Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1484
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1484 ! raeburn 4: # $Id: lonnet.pm,v 1.1483 2022/02/17 22:35:52 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.486 www 74: use HTTP::Date;
1.977 amueller 75: use Image::Magick;
1.1389 raeburn 76: use CGI::Cookie;
1.1182 foxr 77:
1.1173 foxr 78: use Encode;
79:
1.1405 raeburn 80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138 raeburn 81: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1416 raeburn 82: %managerstab $passwdmin);
1.871 albertel 83:
84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
85: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
86: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 87: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 88:
1.1 albertel 89: use IO::Socket;
1.31 www 90: use GDBM_File;
1.208 albertel 91: use HTML::LCParser;
1.88 www 92: use Fcntl qw(:flock);
1.870 albertel 93: use Storable qw(thaw nfreeze);
1.1289 damieng 94: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599 albertel 95: use Cache::Memcached;
1.676 albertel 96: use Digest::MD5;
1.790 albertel 97: use Math::Random;
1.1024 raeburn 98: use File::MMagic;
1.1434 raeburn 99: use Net::CIDR;
1.1456 raeburn 100: use Sys::Hostname::FQDN();
1.807 albertel 101: use LONCAPA qw(:DEFAULT :match);
1.740 www 102: use LONCAPA::Configuration;
1.1160 www 103: use LONCAPA::lonmetadata;
1.1167 droeschl 104: use LONCAPA::Lond;
1.1345 raeburn 105: use LONCAPA::LWPReq;
1.1406 raeburn 106: use LONCAPA::transliterate;
1.1117 foxr 107:
1.1090 raeburn 108: use File::Copy;
1.676 albertel 109:
1.195 www 110: my $readit;
1.1288 damieng 111: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 112:
1.619 albertel 113: require Exporter;
114:
115: our @ISA = qw (Exporter);
116: our @EXPORT = qw(%env);
117:
1.449 matthew 118:
1.1187 raeburn 119: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 120: {
121: my $logid;
1.1187 raeburn 122: sub write_log {
1.1188 raeburn 123: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184 raeburn 124: if ($context eq 'course') {
125: if (($cnum eq '') || ($cdom eq '')) {
126: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
127: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
128: }
1.957 raeburn 129: }
1.1184 raeburn 130: $logid ++;
1.957 raeburn 131: my $now = time();
132: my $id=$now.'00000'.$$.'00000'.$logid;
1.1434 raeburn 133: my $ip = &get_requestor_ip();
1.1184 raeburn 134: my $logentry = {
135: $id => {
136: 'exe_uname' => $env{'user.name'},
137: 'exe_udom' => $env{'user.domain'},
138: 'exe_time' => $now,
1.1434 raeburn 139: 'exe_ip' => $ip,
1.1184 raeburn 140: 'delflag' => $delflag,
141: 'logentry' => $storehash,
142: 'uname' => $uname,
143: 'udom' => $udom,
144: }
145: };
146: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 147: }
148: }
1.1 albertel 149:
1.163 harris41 150: sub logtouch {
151: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 152: unless (-e "$execdir/logs/lonnet.log") {
1.1359 raeburn 153: open(my $fh,">>","$execdir/logs/lonnet.log");
1.163 harris41 154: close $fh;
155: }
156: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
157: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
158: }
159:
1.1 albertel 160: sub logthis {
161: my $message=shift;
162: my $execdir=$perlvar{'lonDaemons'};
163: my $now=time;
164: my $local=localtime($now);
1.1359 raeburn 165: if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986 foxr 166: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
167: print $fh $logstring;
1.448 albertel 168: close($fh);
169: }
1.1 albertel 170: return 1;
171: }
172:
173: sub logperm {
174: my $message=shift;
175: my $execdir=$perlvar{'lonDaemons'};
176: my $now=time;
177: my $local=localtime($now);
1.1359 raeburn 178: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448 albertel 179: print $fh "$now:$message:$local\n";
180: close($fh);
181: }
1.1 albertel 182: return 1;
183: }
184:
1.850 albertel 185: sub create_connection {
1.853 albertel 186: my ($hostname,$lonid) = @_;
1.851 albertel 187: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 188: Type => SOCK_STREAM,
189: Timeout => 10);
190: return 0 if (!$client);
1.1399 raeburn 191: print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
1.850 albertel 192: my $result = <$client>;
193: chomp($result);
194: return 1 if ($result eq 'done');
195: return 0;
196: }
197:
1.983 raeburn 198: sub get_server_timezone {
199: my ($cnum,$cdom) = @_;
200: my $home=&homeserver($cnum,$cdom);
201: if ($home ne 'no_host') {
202: my $cachetime = 24*3600;
203: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
204: if (defined($cached)) {
205: return $timezone;
206: } else {
207: my $timezone = &reply('servertimezone',$home);
208: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
209: }
210: }
211: }
1.850 albertel 212:
1.1106 raeburn 213: sub get_server_distarch {
214: my ($lonhost,$ignore_cache) = @_;
215: if (defined($lonhost)) {
216: if (!defined(&hostname($lonhost))) {
217: return;
218: }
219: my $cachetime = 12*3600;
220: if (!$ignore_cache) {
221: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
222: if (defined($cached)) {
223: return $distarch;
224: }
225: }
226: my $rep = &reply('serverdistarch',$lonhost);
227: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
228: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
229: $rep eq '') {
230: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
231: }
232: }
233: return;
234: }
235:
1.1315 raeburn 236: sub get_servercerts_info {
1.1383 raeburn 237: my ($lonhost,$hostname,$context) = @_;
238: return if ($lonhost eq '');
239: if ($hostname eq '') {
240: $hostname = &hostname($lonhost);
241: }
242: return if ($hostname eq '');
1.1315 raeburn 243: my ($rep,$uselocal);
1.1388 raeburn 244: if ($context eq 'install') {
1.1387 raeburn 245: $uselocal = 1;
246: } elsif (grep { $_ eq $lonhost } ¤t_machine_ids()) {
1.1315 raeburn 247: $uselocal = 1;
248: }
1.1387 raeburn 249: if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
1.1315 raeburn 250: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323 raeburn 251: if ($distro eq '') {
252: $uselocal = 0;
253: } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315 raeburn 254: if ($1 < 6) {
255: $uselocal = 0;
256: }
1.1346 raeburn 257: } elsif ($distro =~ /^(?:sles)(\d+)$/) {
258: if ($1 < 12) {
259: $uselocal = 0;
260: }
1.1315 raeburn 261: }
262: }
263: if ($uselocal) {
1.1383 raeburn 264: $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
1.1315 raeburn 265: } else {
266: $rep=&reply('servercerts',$lonhost);
267: }
268: my ($result,%returnhash);
269: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
270: ($rep eq 'unknown_cmd')) {
271: $result = $rep;
272: } else {
273: $result = 'ok';
274: my @pairs=split(/\&/,$rep);
275: foreach my $item (@pairs) {
276: my ($key,$value)=split(/=/,$item,2);
277: my $what = &unescape($key);
278: $returnhash{$what}=&thaw_unescape($value);
279: }
280: }
281: return ($result,\%returnhash);
282: }
283:
1.993 raeburn 284: sub get_server_loncaparev {
1.1073 raeburn 285: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 286: if (defined($lonhost)) {
287: if (!defined(&hostname($lonhost))) {
288: undef($lonhost);
289: }
290: }
291: if (!defined($lonhost)) {
292: if (defined(&domain($dom,'primary'))) {
293: $lonhost=&domain($dom,'primary');
294: if ($lonhost eq 'no_host') {
295: undef($lonhost);
296: }
297: }
298: }
299: if (defined($lonhost)) {
1.1073 raeburn 300: my $cachetime = 12*3600;
301: if (!$ignore_cache) {
302: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
303: if (defined($cached)) {
304: return $loncaparev;
305: }
306: }
307: my ($answer,$loncaparev);
308: my @ids=¤t_machine_ids();
309: if (grep(/^\Q$lonhost\E$/,@ids)) {
310: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 311: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 312: $loncaparev = $1;
313: }
314: } else {
315: $answer = &reply('serverloncaparev',$lonhost);
316: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
317: if ($caller eq 'loncron') {
1.1397 raeburn 318: my $hostname = &hostname($lonhost);
1.1073 raeburn 319: my $protocol = $protocol{$lonhost};
320: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 321: my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073 raeburn 322: my $request=new HTTP::Request('GET',$url);
1.1345 raeburn 323: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073 raeburn 324: unless ($response->is_error()) {
325: my $content = $response->content;
1.1081 raeburn 326: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 327: $loncaparev = $1;
328: }
329: }
330: } else {
331: $loncaparev = $loncaparevs{$lonhost};
332: }
1.1081 raeburn 333: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 334: $loncaparev = $1;
335: }
1.993 raeburn 336: }
1.1073 raeburn 337: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 338: }
339: }
340:
1.1074 raeburn 341: sub get_server_homeID {
342: my ($hostname,$ignore_cache,$caller) = @_;
343: unless ($ignore_cache) {
344: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
345: if (defined($cached)) {
346: return $serverhomeID;
347: }
348: }
349: my $cachetime = 12*3600;
350: my $serverhomeID;
351: if ($caller eq 'loncron') {
352: my @machine_ids = &machine_ids($hostname);
353: foreach my $id (@machine_ids) {
354: my $response = &reply('serverhomeID',$id);
355: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
356: $serverhomeID = $response;
357: last;
358: }
359: }
360: if ($serverhomeID eq '') {
361: $serverhomeID = $machine_ids[-1];
362: }
363: } else {
364: $serverhomeID = $serverhomeIDs{$hostname};
365: }
366: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
367: }
368:
1.1121 raeburn 369: sub get_remote_globals {
370: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 371: my ($result,%returnhash,%whatneeded);
372: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 373: foreach my $what (sort(keys(%{$whathash}))) {
374: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 375: my ($response,$cached);
1.1121 raeburn 376: unless ($ignore_cache) {
1.1125 raeburn 377: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 378: }
379: if (defined($cached)) {
1.1125 raeburn 380: $returnhash{$what} = $response;
1.1121 raeburn 381: } else {
1.1125 raeburn 382: $whatneeded{$what} = 1;
1.1121 raeburn 383: }
384: }
1.1125 raeburn 385: if (keys(%whatneeded) == 0) {
386: $result = 'ok';
387: } else {
1.1121 raeburn 388: my $requested = &freeze_escape(\%whatneeded);
389: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 390: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
391: ($rep eq 'unknown_cmd')) {
392: $result = $rep;
393: } else {
394: $result = 'ok';
1.1121 raeburn 395: my @pairs=split(/\&/,$rep);
1.1125 raeburn 396: foreach my $item (@pairs) {
397: my ($key,$value)=split(/=/,$item,2);
398: my $what = &unescape($key);
399: my $hashid = $lonhost.'-'.$what;
400: $returnhash{$what}=&thaw_unescape($value);
401: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 402: }
403: }
404: }
405: }
1.1125 raeburn 406: return ($result,\%returnhash);
1.1121 raeburn 407: }
408:
1.1124 raeburn 409: sub remote_devalidate_cache {
1.1241 raeburn 410: my ($lonhost,$cachekeys) = @_;
411: my $items;
412: return unless (ref($cachekeys) eq 'ARRAY');
413: my $cachestr = join('&',@{$cachekeys});
414: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 415: return $response;
416: }
417:
1.1 albertel 418: # -------------------------------------------------- Non-critical communication
419: sub subreply {
420: my ($cmd,$server)=@_;
1.838 albertel 421: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 422: #
423: # With loncnew process trimming, there's a timing hole between lonc server
424: # process exit and the master server picking up the listen on the AF_UNIX
425: # socket. In that time interval, a lock file will exist:
426:
427: my $lockfile=$peerfile.".lock";
428: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1289 damieng 429: sleep(0.1);
1.549 foxr 430: }
431: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 432: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 433: #
1.550 foxr 434: # We'll give the connection a few tries before abandoning it. If
435: # connection is not possible, we'll con_lost back to the client.
436: #
437: my $client;
438: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
439: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
440: Type => SOCK_STREAM,
441: Timeout => 10);
1.869 albertel 442: if ($client) {
1.550 foxr 443: last; # Connected!
1.850 albertel 444: } else {
1.853 albertel 445: &create_connection(&hostname($server),$server);
1.550 foxr 446: }
1.1289 damieng 447: sleep(0.1); # Try again later if failed connection.
1.550 foxr 448: }
449: my $answer;
450: if ($client) {
1.704 albertel 451: print $client "sethost:$server:$cmd\n";
1.550 foxr 452: $answer=<$client>;
453: if (!$answer) { $answer="con_lost"; }
454: chomp($answer);
455: } else {
456: $answer = 'con_lost'; # Failed connection.
457: }
1.1 albertel 458: return $answer;
459: }
460:
461: sub reply {
462: my ($cmd,$server)=@_;
1.838 albertel 463: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 464: my $answer=subreply($cmd,$server);
1.65 www 465: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1396 raeburn 466: my $logged = $cmd;
467: if ($cmd =~ /^encrypt:([^:]+):/) {
468: my $subcmd = $1;
469: if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
470: ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1462 raeburn 471: ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
472: ($subcmd eq 'put')) {
1.1396 raeburn 473: (undef,undef,my @rest) = split(/:/,$cmd);
474: if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
475: splice(@rest,2,1,'Hidden');
476: } elsif ($subcmd eq 'passwd') {
477: splice(@rest,2,2,('Hidden','Hidden'));
478: } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1462 raeburn 479: ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
1.1396 raeburn 480: splice(@rest,3,1,'Hidden');
481: }
482: $logged = join(':',('encrypt:'.$subcmd,@rest));
483: }
484: }
485: &logthis("<font color=\"blue\">WARNING:".
486: " $logged to $server returned $answer</font>");
1.12 www 487: }
1.1 albertel 488: return $answer;
489: }
490:
491: # ----------------------------------------------------------- Send USR1 to lonc
492:
493: sub reconlonc {
1.891 albertel 494: my ($lonid) = @_;
495: if ($lonid) {
1.1295 raeburn 496: my $hostname = &hostname($lonid);
1.891 albertel 497: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
498: if ($hostname && -e $peerfile) {
499: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
500: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
501: Type => SOCK_STREAM,
502: Timeout => 10);
503: if ($client) {
504: print $client ("reset_retries\n");
505: my $answer=<$client>;
506: #reset just this one.
507: }
508: }
509: return;
510: }
511:
1.836 www 512: &logthis("Trying to reconnect lonc");
1.1 albertel 513: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359 raeburn 514: if (open(my $fh,"<",$loncfile)) {
1.1 albertel 515: my $loncpid=<$fh>;
516: chomp($loncpid);
517: if (kill 0 => $loncpid) {
518: &logthis("lonc at pid $loncpid responding, sending USR1");
519: kill USR1 => $loncpid;
520: sleep 1;
1.1295 raeburn 521: } else {
1.12 www 522: &logthis(
1.672 albertel 523: "<font color=\"blue\">WARNING:".
1.12 www 524: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 525: }
526: } else {
1.836 www 527: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 528: }
529: }
530:
531: # ------------------------------------------------------ Critical communication
1.12 www 532:
1.1 albertel 533: sub critical {
534: my ($cmd,$server)=@_;
1.838 albertel 535: unless (&hostname($server)) {
1.672 albertel 536: &logthis("<font color=\"blue\">WARNING:".
1.89 www 537: " Critical message to unknown server ($server)</font>");
538: return 'no_such_host';
539: }
1.1 albertel 540: my $answer=reply($cmd,$server);
541: if ($answer eq 'con_lost') {
1.1295 raeburn 542: &reconlonc($server);
1.589 albertel 543: my $answer=reply($cmd,$server);
1.1 albertel 544: if ($answer eq 'con_lost') {
545: my $now=time;
546: my $middlename=$cmd;
1.5 www 547: $middlename=substr($middlename,0,16);
1.1 albertel 548: $middlename=~s/\W//g;
549: my $dfilename=
1.305 www 550: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
551: $dumpcount++;
1.1 albertel 552: {
1.448 albertel 553: my $dfh;
1.1359 raeburn 554: if (open($dfh,">",$dfilename)) {
1.448 albertel 555: print $dfh "$cmd\n";
556: close($dfh);
557: }
1.1 albertel 558: }
1.1288 damieng 559: sleep 1;
1.1 albertel 560: my $wcmd='';
561: {
1.448 albertel 562: my $dfh;
1.1359 raeburn 563: if (open($dfh,"<",$dfilename)) {
1.448 albertel 564: $wcmd=<$dfh>;
565: close($dfh);
566: }
1.1 albertel 567: }
568: chomp($wcmd);
1.7 www 569: if ($wcmd eq $cmd) {
1.672 albertel 570: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 571: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 572: &logperm("D:$server:$cmd");
573: return 'con_delayed';
574: } else {
1.672 albertel 575: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 576: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 577: &logperm("F:$server:$cmd");
578: return 'con_failed';
579: }
580: }
581: }
582: return $answer;
1.405 albertel 583: }
584:
1.755 albertel 585: # ------------------------------------------- check if return value is an error
586:
587: sub error {
588: my ($result) = @_;
1.756 albertel 589: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 590: if ($2 == 2) { return undef; }
591: return $1;
592: }
593: return undef;
594: }
595:
1.783 albertel 596: sub convert_and_load_session_env {
597: my ($lonidsdir,$handle)=@_;
598: my @profile;
599: {
1.917 albertel 600: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
601: if (!$opened) {
1.915 albertel 602: return 0;
603: }
1.783 albertel 604: flock($idf,LOCK_SH);
605: @profile=<$idf>;
606: close($idf);
607: }
608: my %temp_env;
609: foreach my $line (@profile) {
1.786 albertel 610: if ($line !~ m/=/) {
611: return 0;
612: }
1.783 albertel 613: chomp($line);
614: my ($envname,$envvalue)=split(/=/,$line,2);
615: $temp_env{&unescape($envname)} = &unescape($envvalue);
616: }
617: unlink("$lonidsdir/$handle.id");
618: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
619: 0640)) {
620: %disk_env = %temp_env;
621: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
622: untie(%disk_env);
623: }
1.786 albertel 624: return 1;
1.783 albertel 625: }
626:
1.374 www 627: # ------------------------------------------- Transfer profile into environment
1.780 albertel 628: my $env_loaded;
629: sub transfer_profile_to_env {
1.788 albertel 630: my ($lonidsdir,$handle,$force_transfer) = @_;
631: if (!$force_transfer && $env_loaded) { return; }
1.374 www 632:
1.720 albertel 633: if (!defined($lonidsdir)) {
634: $lonidsdir = $perlvar{'lonIDsDir'};
635: }
636: if (!defined($handle)) {
637: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
638: }
639:
1.786 albertel 640: my $convert;
641: {
1.917 albertel 642: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
643: if (!$opened) {
1.915 albertel 644: return;
645: }
1.786 albertel 646: flock($idf,LOCK_SH);
647: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
648: &GDBM_READER(),0640)) {
649: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
650: untie(%disk_env);
651: } else {
652: $convert = 1;
653: }
654: }
655: if ($convert) {
656: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
657: &logthis("Failed to load session, or convert session.");
658: }
1.374 www 659: }
1.783 albertel 660:
1.786 albertel 661: my %remove;
1.783 albertel 662: while ( my $envname = each(%env) ) {
1.433 matthew 663: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
664: if ($time < time-300) {
1.783 albertel 665: $remove{$key}++;
1.433 matthew 666: }
667: }
668: }
1.783 albertel 669:
1.619 albertel 670: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 671: $env_loaded=1;
1.783 albertel 672: foreach my $expired_key (keys(%remove)) {
1.433 matthew 673: &delenv($expired_key);
1.374 www 674: }
1.1 albertel 675: }
676:
1.916 albertel 677: # ---------------------------------------------------- Check for valid session
678: sub check_for_valid_session {
1.1355 raeburn 679: my ($r,$name,$userhashref,$domref) = @_;
1.916 albertel 680: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1378 raeburn 681: my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
682: if ($name eq 'lonDAV') {
683: $lonidsdir=$r->dir_config('lonDAVsessDir');
684: } else {
685: $lonidsdir=$r->dir_config('lonIDsDir');
686: if ($name eq '') {
687: $name = 'lonID';
688: }
689: }
690: if ($name eq 'lonID') {
691: $secure = 'lonSID';
1.1337 raeburn 692: $linkname = 'lonLinkID';
693: $pubname = 'lonPubID';
1.1378 raeburn 694: if (exists($cookies{$secure})) {
695: $lonid=$cookies{$secure};
696: } elsif (exists($cookies{$name})) {
697: $lonid=$cookies{$name};
1.1400 raeburn 698: } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
1.1337 raeburn 699: $lonid=$cookies{$linkname};
1.1378 raeburn 700: } elsif (exists($cookies{$pubname})) {
701: $lonid=$cookies{$pubname};
1.1337 raeburn 702: }
1.1378 raeburn 703: } else {
704: $lonid=$cookies{$name};
1.1337 raeburn 705: }
1.916 albertel 706: return undef if (!$lonid);
707:
708: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1378 raeburn 709: if (-l "$lonidsdir/$handle.id") {
710: my $link = readlink("$lonidsdir/$handle.id");
711: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
712: $handle = $1;
713: }
1.1155 raeburn 714: }
1.1355 raeburn 715: if (!-e "$lonidsdir/$handle.id") {
716: if ((ref($domref)) && ($name eq 'lonID') &&
717: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
718: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
719: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
720: $$domref = $possudom;
721: }
722: }
723: return undef;
724: }
1.916 albertel 725:
1.917 albertel 726: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
727: return undef if (!$opened);
1.916 albertel 728:
729: flock($idf,LOCK_SH);
730: my %disk_env;
731: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
732: &GDBM_READER(),0640)) {
733: return undef;
734: }
735:
736: if (!defined($disk_env{'user.name'})
737: || !defined($disk_env{'user.domain'})) {
1.1394 raeburn 738: untie(%disk_env);
1.916 albertel 739: return undef;
740: }
1.1245 raeburn 741:
742: if (ref($userhashref) eq 'HASH') {
743: $userhashref->{'name'} = $disk_env{'user.name'};
744: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1448 raeburn 745: if ($disk_env{'request.role'}) {
746: $userhashref->{'role'} = $disk_env{'request.role'};
747: }
1.1361 raeburn 748: $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375 raeburn 749: if ($userhashref->{'lti'}) {
750: $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
751: $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
752: }
1.1212 raeburn 753: }
1.1394 raeburn 754: untie(%disk_env);
1.1245 raeburn 755:
1.916 albertel 756: return $handle;
757: }
758:
1.830 albertel 759: sub timed_flock {
760: my ($file,$lock_type) = @_;
761: my $failed=0;
762: eval {
763: local $SIG{__DIE__}='DEFAULT';
764: local $SIG{ALRM}=sub {
765: $failed=1;
766: die("failed lock");
767: };
768: alarm(13);
769: flock($file,$lock_type);
770: alarm(0);
771: };
772: if ($failed) {
773: return undef;
774: } else {
775: return 1;
776: }
777: }
778:
1.1392 raeburn 779: sub get_sessionfile_vars {
780: my ($handle,$lonidsdir,$storearr) = @_;
781: my %returnhash;
782: unless (ref($storearr) eq 'ARRAY') {
783: return %returnhash;
784: }
785: if (-l "$lonidsdir/$handle.id") {
786: my $link = readlink("$lonidsdir/$handle.id");
787: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
788: $handle = $1;
789: }
790: }
791: if ((-e "$lonidsdir/$handle.id") &&
792: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
793: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
794: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
795: if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
796: flock($idf,LOCK_SH);
797: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
798: &GDBM_READER(),0640)) {
799: foreach my $item (@{$storearr}) {
800: $returnhash{$item} = $disk_env{$item};
801: }
802: untie(%disk_env);
803: }
804: }
805: }
806: }
807: return %returnhash;
808: }
809:
1.5 www 810: # ---------------------------------------------------------- Append Environment
811:
812: sub appenv {
1.949 raeburn 813: my ($newenv,$roles) = @_;
814: if (ref($newenv) eq 'HASH') {
815: foreach my $key (keys(%{$newenv})) {
816: my $refused = 0;
817: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
818: $refused = 1;
819: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 820: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 821: if (grep(/^\Q$role\E$/,@{$roles})) {
822: $refused = 0;
823: }
824: }
825: }
826: if ($refused) {
827: &logthis("<font color=\"blue\">WARNING: ".
828: "Attempt to modify environment ".$key." to ".$newenv->{$key}
829: .'</font>');
830: delete($newenv->{$key});
831: } else {
832: $env{$key}=$newenv->{$key};
833: }
834: }
1.1376 raeburn 835: my $lonids = $perlvar{'lonIDsDir'};
836: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
837: my $opened = open(my $env_file,'+<',$env{'user.environment'});
838: if ($opened
839: && &timed_flock($env_file,LOCK_EX)
840: &&
841: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
842: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
843: while (my ($key,$value) = each(%{$newenv})) {
844: $disk_env{$key} = $value;
845: }
846: untie(%disk_env);
847: }
1.35 www 848: }
1.191 harris41 849: }
1.56 www 850: return 'ok';
851: }
852: # ----------------------------------------------------- Delete from Environment
853:
854: sub delenv {
1.1104 raeburn 855: my ($delthis,$regexp,$roles) = @_;
856: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
857: my $refused = 1;
858: if (ref($roles) eq 'ARRAY') {
859: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
860: if (grep(/^\Q$role\E$/,@{$roles})) {
861: $refused = 0;
862: }
863: }
864: if ($refused) {
865: &logthis("<font color=\"blue\">WARNING: ".
866: "Attempt to delete from environment ".$delthis);
867: return 'error';
868: }
1.56 www 869: }
1.917 albertel 870: my $opened = open(my $env_file,'+<',$env{'user.environment'});
871: if ($opened
1.915 albertel 872: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 873: &&
874: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
875: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 876: foreach my $key (keys(%disk_env)) {
1.987 raeburn 877: if ($regexp) {
878: if ($key=~/^$delthis/) {
879: delete($env{$key});
880: delete($disk_env{$key});
881: }
882: } else {
883: if ($key=~/^\Q$delthis\E/) {
884: delete($env{$key});
885: delete($disk_env{$key});
886: }
887: }
1.448 albertel 888: }
1.783 albertel 889: untie(%disk_env);
1.5 www 890: }
891: return 'ok';
1.369 albertel 892: }
893:
1.790 albertel 894: sub get_env_multiple {
895: my ($name) = @_;
896: my @values;
897: if (defined($env{$name})) {
898: # exists is it an array
899: if (ref($env{$name})) {
900: @values=@{ $env{$name} };
901: } else {
902: $values[0]=$env{$name};
903: }
904: }
905: return(@values);
906: }
907:
1.958 www 908: # ------------------------------------------------------------------- Locking
909:
910: sub set_lock {
911: my ($text)=@_;
912: $locknum++;
913: my $id=$$.'-'.$locknum;
914: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
915: 'session.lock.'.$id => $text});
916: return $id;
917: }
918:
919: sub get_locks {
920: my $num=0;
921: my %texts=();
922: foreach my $lock (split(/\,/,$env{'session.locks'})) {
923: if ($lock=~/\w/) {
924: $num++;
925: $texts{$lock}=$env{'session.lock.'.$lock};
926: }
927: }
928: return ($num,%texts);
929: }
930:
931: sub remove_lock {
932: my ($id)=@_;
933: my $newlocks='';
934: foreach my $lock (split(/\,/,$env{'session.locks'})) {
935: if (($lock=~/\w/) && ($lock ne $id)) {
936: $newlocks.=','.$lock;
937: }
938: }
939: &appenv({'session.locks' => $newlocks});
940: &delenv('session.lock.'.$id);
941: }
942:
943: sub remove_all_locks {
944: my $activelocks=$env{'session.locks'};
945: foreach my $lock (split(/\,/,$env{'session.locks'})) {
946: if ($lock=~/\w/) {
947: &remove_lock($lock);
948: }
949: }
950: }
951:
952:
1.369 albertel 953: # ------------------------------------------ Find out current server userload
954: sub userload {
955: my $numusers=0;
956: {
957: opendir(LONIDS,$perlvar{'lonIDsDir'});
958: my $filename;
959: my $curtime=time;
960: while ($filename=readdir(LONIDS)) {
1.925 albertel 961: next if ($filename eq '.' || $filename eq '..');
962: next if ($filename =~ /publicuser_\d+\.id/);
1.1390 raeburn 963: next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404 albertel 964: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 965: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 966: }
967: closedir(LONIDS);
968: }
969: my $userloadpercent=0;
970: my $maxuserload=$perlvar{'lonUserLoadLim'};
971: if ($maxuserload) {
1.371 albertel 972: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 973: }
1.372 albertel 974: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 975: return $userloadpercent;
1.283 www 976: }
977:
1.1 albertel 978: # ------------------------------ Find server with least workload from spare.tab
1.11 www 979:
1.1 albertel 980: sub spareserver {
1.1451 raeburn 981: my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 982: my $spare_server;
1.370 albertel 983: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 984: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
985: : $userloadpercent;
1.1083 raeburn 986: my ($uint_dom,$remotesessions);
987: if (($udom ne '') && (&domain($udom) ne '')) {
988: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
989: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
990: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
991: $remotesessions = $udomdefaults{'remotesessions'};
992: }
1.1123 raeburn 993: my $spareshash = &this_host_spares($udom);
994: if (ref($spareshash) eq 'HASH') {
995: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
996: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279 raeburn 997: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
998: $try_server));
1.1123 raeburn 999: ($spare_server, $lowest_load) =
1000: &compare_server_load($try_server, $spare_server, $lowest_load);
1001: }
1.1083 raeburn 1002: }
1.784 albertel 1003:
1.1123 raeburn 1004: my $found_server = ($spare_server ne '' && $lowest_load < 100);
1005:
1006: if (!$found_server) {
1007: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1008: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279 raeburn 1009: next unless (&spare_can_host($udom,$uint_dom,
1010: $remotesessions,$try_server));
1.1123 raeburn 1011: ($spare_server, $lowest_load) =
1012: &compare_server_load($try_server, $spare_server, $lowest_load);
1013: }
1014: }
1015: }
1.784 albertel 1016: }
1017:
1018: if (!$want_server_name) {
1.1001 raeburn 1019: if (defined($spare_server)) {
1020: my $hostname = &hostname($spare_server);
1.1083 raeburn 1021: if (defined($hostname)) {
1.1397 raeburn 1022: my $protocol = 'http';
1023: if ($protocol{$spare_server} eq 'https') {
1024: $protocol = $protocol{$spare_server};
1025: }
1.1451 raeburn 1026: my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
1027: $hostname = $alias if ($alias ne '');
1.1001 raeburn 1028: $spare_server = $protocol.'://'.$hostname;
1029: }
1030: }
1.784 albertel 1031: }
1032: return $spare_server;
1033: }
1034:
1035: sub compare_server_load {
1.1253 raeburn 1036: my ($try_server, $spare_server, $lowest_load, $required) = @_;
1037:
1038: if ($required) {
1039: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
1040: my $remoterev = &get_server_loncaparev(undef,$try_server);
1041: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
1042: if (($major eq '' && $minor eq '') ||
1043: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
1044: return ($spare_server,$lowest_load);
1045: }
1046: }
1.784 albertel 1047:
1048: my $loadans = &reply('load', $try_server);
1049: my $userloadans = &reply('userload',$try_server);
1050:
1051: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 1052: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 1053: }
1054:
1055: my $load;
1056: if ($loadans =~ /\d/) {
1057: if ($userloadans =~ /\d/) {
1058: #both are numbers, pick the bigger one
1059: $load = ($loadans > $userloadans) ? $loadans
1060: : $userloadans;
1.411 albertel 1061: } else {
1.784 albertel 1062: $load = $loadans;
1.411 albertel 1063: }
1.784 albertel 1064: } else {
1065: $load = $userloadans;
1066: }
1067:
1068: if (($load =~ /\d/) && ($load < $lowest_load)) {
1069: $spare_server = $try_server;
1070: $lowest_load = $load;
1.370 albertel 1071: }
1.784 albertel 1072: return ($spare_server,$lowest_load);
1.202 matthew 1073: }
1.914 albertel 1074:
1075: # --------------------------- ask offload servers if user already has a session
1076: sub find_existing_session {
1077: my ($udom,$uname) = @_;
1.1123 raeburn 1078: my $spareshash = &this_host_spares($udom);
1079: if (ref($spareshash) eq 'HASH') {
1080: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1081: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1082: return $try_server if (&has_user_session($try_server, $udom, $uname));
1083: }
1084: }
1085: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1086: foreach my $try_server (@{ $spareshash->{'default'} }) {
1087: return $try_server if (&has_user_session($try_server, $udom, $uname));
1088: }
1089: }
1.914 albertel 1090: }
1091: return;
1092: }
1093:
1.1411 raeburn 1094: sub delusersession {
1095: my ($lonid,$udom,$uname) = @_;
1096: my $uprimary_id = &domain($udom,'primary');
1097: my $uintdom = &internet_dom($uprimary_id);
1098: my $intdom = &internet_dom($lonid);
1099: my $serverhomedom = &host_domain($lonid);
1100: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1101: return &reply(join(':','delusersession',
1102: map {&escape($_)} ($udom,$uname)),$lonid);
1103: }
1104: return;
1105: }
1106:
1.1389 raeburn 1107: # check if user's browser sent load balancer cookie and server still has session
1108: # and is not overloaded.
1109: sub check_for_balancer_cookie {
1110: my ($r,$update_mtime) = @_;
1111: my ($otherserver,$cookie);
1112: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1113: if (exists($cookies{'balanceID'})) {
1114: my $balid = $cookies{'balanceID'};
1115: $cookie=&LONCAPA::clean_handle($balid->value);
1116: my $balancedir=$r->dir_config('lonBalanceDir');
1117: if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
1118: if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
1119: my ($possudom,$possuname) = ($1,$2);
1120: my $has_session = 0;
1121: if ((&domain($possudom) ne '') &&
1122: (&homeserver($possuname,$possudom) ne 'no_host')) {
1123: my $try_server;
1124: my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
1125: if ($opened) {
1126: flock($idf,LOCK_SH);
1127: while (my $line = <$idf>) {
1128: chomp($line);
1129: if (&hostname($line) ne '') {
1130: $try_server = $line;
1131: last;
1132: }
1133: }
1134: close($idf);
1135: if (($try_server) &&
1136: (&has_user_session($try_server,$possudom,$possuname))) {
1137: my $lowest_load = 30000;
1138: ($otherserver,$lowest_load) =
1139: &compare_server_load($try_server,undef,$lowest_load);
1140: if ($otherserver ne '' && $lowest_load < 100) {
1141: $has_session = 1;
1142: } else {
1143: undef($otherserver);
1144: }
1145: }
1146: }
1147: }
1148: if ($has_session) {
1149: if ($update_mtime) {
1150: my $atime = my $mtime = time;
1151: utime($atime,$mtime,"$balancedir/$cookie.id");
1152: }
1153: } else {
1154: unlink("$balancedir/$cookie.id");
1155: }
1156: }
1157: }
1158: }
1159: return ($otherserver,$cookie);
1160: }
1161:
1.1431 raeburn 1162: sub updatebalcookie {
1163: my ($cookie,$balancer,$lastentry)=@_;
1164: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1165: my ($udom,$uname) = ($1,$2);
1166: my $uprimary_id = &domain($udom,'primary');
1167: my $uintdom = &internet_dom($uprimary_id);
1168: my $intdom = &internet_dom($balancer);
1169: my $serverhomedom = &host_domain($balancer);
1170: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1171: return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
1172: }
1173: }
1174: return;
1175: }
1176:
1.1389 raeburn 1177: sub delbalcookie {
1178: my ($cookie,$balancer) =@_;
1179: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1180: my ($udom,$uname) = ($1,$2);
1181: my $uprimary_id = &domain($udom,'primary');
1182: my $uintdom = &internet_dom($uprimary_id);
1183: my $intdom = &internet_dom($balancer);
1184: my $serverhomedom = &host_domain($balancer);
1185: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1431 raeburn 1186: return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1389 raeburn 1187: }
1188: }
1189: }
1190:
1.914 albertel 1191: # -------------------------------- ask if server already has a session for user
1192: sub has_user_session {
1193: my ($lonid,$udom,$uname) = @_;
1194: my $result = &reply(join(':','userhassession',
1195: map {&escape($_)} ($udom,$uname)),$lonid);
1196: return 1 if ($result eq 'ok');
1197:
1198: return 0;
1199: }
1200:
1.1076 raeburn 1201: # --------- determine least loaded server in a user's domain which allows login
1202:
1203: sub choose_server {
1.1259 raeburn 1204: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1205: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1206: my %servers = &get_servers($udom);
1.1076 raeburn 1207: my $lowest_load = 30000;
1.1259 raeburn 1208: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1209: if ($skiploadbal) {
1210: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1211: unless (defined($cached)) {
1212: my $cachetime = 60*60*24;
1213: my %domconfig =
1214: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1215: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1216: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1217: $cachetime);
1218: }
1219: }
1220: }
1.1076 raeburn 1221: foreach my $lonhost (keys(%servers)) {
1.1259 raeburn 1222: if ($skiploadbal) {
1223: if (ref($balancers) eq 'HASH') {
1224: next if (exists($balancers->{$lonhost}));
1225: }
1.1389 raeburn 1226: }
1.1115 raeburn 1227: my $loginvia;
1228: if ($checkloginvia) {
1229: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1230: if ($loginvia) {
1231: my ($server,$path) = split(/:/,$loginvia);
1232: ($login_host, $lowest_load) =
1.1253 raeburn 1233: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1234: if ($login_host eq $server) {
1235: $portal_path = $path;
1.1151 raeburn 1236: $isredirect = 1;
1.1116 raeburn 1237: }
1238: } else {
1239: ($login_host, $lowest_load) =
1.1253 raeburn 1240: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1241: if ($login_host eq $lonhost) {
1242: $portal_path = '';
1.1151 raeburn 1243: $isredirect = '';
1.1116 raeburn 1244: }
1245: }
1246: } else {
1.1076 raeburn 1247: ($login_host, $lowest_load) =
1.1253 raeburn 1248: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1249: }
1250: }
1251: if ($login_host ne '') {
1.1116 raeburn 1252: $hostname = &hostname($login_host);
1.1076 raeburn 1253: }
1.1331 raeburn 1254: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1255: }
1256:
1.1420 raeburn 1257: sub get_course_sessions {
1258: my ($cnum,$cdom,$lastactivity) = @_;
1259: my %servers = &internet_dom_servers($cdom);
1260: my %returnhash;
1261: foreach my $server (sort(keys(%servers))) {
1262: my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
1263: my @pairs=split(/\&/,$rep);
1264: unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
1265: foreach my $item (@pairs) {
1266: my ($key,$value)=split(/=/,$item,2);
1267: $key = &unescape($key);
1268: next if ($key =~ /^error: 2 /);
1269: if (exists($returnhash{$key})) {
1270: next if ($value < $returnhash{$key});
1271: }
1272: $returnhash{$key}=$value;
1273: }
1274: }
1275: }
1276: return %returnhash;
1277: }
1278:
1.202 matthew 1279: # --------------------------------------------- Try to change a user's password
1280:
1281: sub changepass {
1.799 raeburn 1282: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1283: $currentpass = &escape($currentpass);
1284: $newpass = &escape($newpass);
1.1030 raeburn 1285: my $lonhost = $perlvar{'lonHostID'};
1286: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1287: $server);
1288: if (! $answer) {
1289: &logthis("No reply on password change request to $server ".
1290: "by $uname in domain $udom.");
1291: } elsif ($answer =~ "^ok") {
1292: &logthis("$uname in $udom successfully changed their password ".
1293: "on $server.");
1294: } elsif ($answer =~ "^pwchange_failure") {
1295: &logthis("$uname in $udom was unable to change their password ".
1296: "on $server. The action was blocked by either lcpasswd ".
1297: "or pwchange");
1298: } elsif ($answer =~ "^non_authorized") {
1299: &logthis("$uname in $udom did not get their password correct when ".
1300: "attempting to change it on $server.");
1301: } elsif ($answer =~ "^auth_mode_error") {
1302: &logthis("$uname in $udom attempted to change their password despite ".
1303: "not being locally or internally authenticated on $server.");
1304: } elsif ($answer =~ "^unknown_user") {
1305: &logthis("$uname in $udom attempted to change their password ".
1306: "on $server but were unable to because $server is not ".
1307: "their home server.");
1308: } elsif ($answer =~ "^refused") {
1309: &logthis("$server refused to change $uname in $udom password because ".
1310: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1311: } elsif ($answer =~ "invalid_client") {
1312: &logthis("$server refused to change $uname in $udom password because ".
1313: "it was a reset by e-mail originating from an invalid server.");
1.1408 raeburn 1314: } elsif ($answer =~ "^prioruse") {
1315: &logthis("$server refused to change $uname in $udom password because ".
1316: "the password had been used before");
1.202 matthew 1317: }
1318: return $answer;
1.1 albertel 1319: }
1320:
1.169 harris41 1321: # ----------------------- Try to determine user's current authentication scheme
1322:
1323: sub queryauthenticate {
1324: my ($uname,$udom)=@_;
1.456 albertel 1325: my $uhome=&homeserver($uname,$udom);
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.1073 raeburn 1381: sub can_host_session {
1.1074 raeburn 1382: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1383: my $canhost = 1;
1.1074 raeburn 1384: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1385: if (ref($remotesessions) eq 'HASH') {
1386: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1387: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1388: $canhost = 0;
1389: } else {
1390: $canhost = 1;
1391: }
1392: }
1393: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1394: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1395: $canhost = 1;
1396: } else {
1397: $canhost = 0;
1398: }
1399: }
1400: if ($canhost) {
1401: if ($remotesessions->{'version'} ne '') {
1402: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1403: if ($reqmajor ne '' && $reqminor ne '') {
1404: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1405: my $major = $1;
1406: my $minor = $2;
1407: if (($major < $reqmajor ) ||
1408: (($major == $reqmajor) && ($minor < $reqminor))) {
1409: $canhost = 0;
1410: }
1411: } else {
1412: $canhost = 0;
1413: }
1414: }
1415: }
1416: }
1417: }
1418: if ($canhost) {
1419: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1420: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1421: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1422: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1423: if (($uint_dom ne '') &&
1424: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1425: $canhost = 0;
1426: } else {
1427: $canhost = 1;
1428: }
1429: }
1430: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1431: if (($uint_dom ne '') &&
1432: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1433: $canhost = 1;
1434: } else {
1435: $canhost = 0;
1436: }
1437: }
1438: }
1439: }
1440: return $canhost;
1441: }
1442:
1.1083 raeburn 1443: sub spare_can_host {
1444: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1445: my $canhost=1;
1.1279 raeburn 1446: my $try_server_hostname = &hostname($try_server);
1447: my $serverhomeID = &get_server_homeID($try_server_hostname);
1448: my $serverhomedom = &host_domain($serverhomeID);
1449: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1450: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1451: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1452: $canhost = 0;
1453: }
1454: }
1.1439 raeburn 1455: if ($canhost) {
1456: if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
1457: if ($defdomdefaults{'offloadoth'}{$try_server}) {
1458: unless (&shared_institution($udom,$try_server)) {
1459: $canhost = 0;
1460: }
1461: }
1462: }
1463: }
1.1279 raeburn 1464: if (($canhost) && ($uint_dom)) {
1465: my @intdoms;
1466: my $internet_names = &get_internet_names($try_server);
1467: if (ref($internet_names) eq 'ARRAY') {
1468: @intdoms = @{$internet_names};
1469: }
1470: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1471: my $remoterev = &get_server_loncaparev(undef,$try_server);
1472: $canhost = &can_host_session($udom,$try_server,$remoterev,
1473: $remotesessions,
1474: $defdomdefaults{'hostedsessions'});
1475: }
1.1083 raeburn 1476: }
1477: return $canhost;
1478: }
1479:
1.1123 raeburn 1480: sub this_host_spares {
1481: my ($dom) = @_;
1.1126 raeburn 1482: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1483: my @hosts = ¤t_machine_ids();
1484: foreach my $lonhost (@hosts) {
1485: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1486: $dom_in_use = $dom;
1487: $lonhost_in_use = $lonhost;
1.1123 raeburn 1488: last;
1489: }
1490: }
1.1126 raeburn 1491: if ($dom_in_use ne '') {
1492: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1493: }
1494: if (ref($result) ne 'HASH') {
1495: $lonhost_in_use = $perlvar{'lonHostID'};
1496: $dom_in_use = &host_domain($lonhost_in_use);
1497: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1498: if (ref($result) ne 'HASH') {
1499: $result = \%spareid;
1500: }
1501: }
1502: return $result;
1503: }
1504:
1505: sub spares_for_offload {
1506: my ($dom_in_use,$lonhost_in_use) = @_;
1507: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1508: if (defined($cached)) {
1509: return $result;
1510: } else {
1.1126 raeburn 1511: my $cachetime = 60*60*24;
1512: my %domconfig =
1513: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1514: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1515: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1516: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1517: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1518: }
1519: }
1520: }
1521: }
1.1126 raeburn 1522: return;
1.1123 raeburn 1523: }
1524:
1.1129 raeburn 1525: sub get_lonbalancer_config {
1526: my ($servers) = @_;
1527: my ($currbalancer,$currtargets);
1528: if (ref($servers) eq 'HASH') {
1529: foreach my $server (keys(%{$servers})) {
1530: my %what = (
1531: spareid => 1,
1532: perlvar => 1,
1533: );
1534: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1535: if ($result eq 'ok') {
1536: if (ref($returnhash) eq 'HASH') {
1537: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1538: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1539: $currbalancer = $server;
1540: $currtargets = {};
1541: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1542: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1543: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1544: }
1545: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1546: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1547: }
1548: }
1549: last;
1550: }
1551: }
1552: }
1553: }
1554: }
1555: }
1556: return ($currbalancer,$currtargets);
1557: }
1558:
1559: sub check_loadbalancing {
1.1331 raeburn 1560: my ($uname,$udom,$caller) = @_;
1.1191 raeburn 1561: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391 raeburn 1562: $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129 raeburn 1563: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1564: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1565: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1566: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1567: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1568: my $serverhomedom = &host_domain($lonhost);
1.1307 raeburn 1569: my $domneedscache;
1.1129 raeburn 1570: my $cachetime = 60*60*24;
1571:
1572: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1573: $dom_in_use = $udom;
1574: $homeintdom = 1;
1575: } else {
1576: $dom_in_use = $serverhomedom;
1577: }
1578: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1579: unless (defined($cached)) {
1580: my %domconfig =
1581: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1582: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1583: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307 raeburn 1584: } else {
1585: $domneedscache = $dom_in_use;
1.1129 raeburn 1586: }
1587: }
1588: if (ref($result) eq 'HASH') {
1.1391 raeburn 1589: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191 raeburn 1590: &check_balancer_result($result,@hosts);
1.1129 raeburn 1591: if ($is_balancer) {
1592: if (ref($currrules) eq 'HASH') {
1593: if ($homeintdom) {
1594: if ($uname ne '') {
1595: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1596: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1597: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1598: $rule_in_effect = $currrules->{'_LC_author'};
1599: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1600: $rule_in_effect = $currrules->{'_LC_adv'}
1601: }
1602: }
1603: if ($rule_in_effect eq '') {
1604: my %userenv = &userenvironment($udom,$uname,'inststatus');
1605: if ($userenv{'inststatus'} ne '') {
1606: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1607: my ($othertitle,$usertypes,$types) =
1608: &Apache::loncommon::sorted_inst_types($udom);
1609: if (ref($types) eq 'ARRAY') {
1610: foreach my $type (@{$types}) {
1611: if (grep(/^\Q$type\E$/,@statuses)) {
1612: if (exists($currrules->{$type})) {
1613: $rule_in_effect = $currrules->{$type};
1614: }
1615: }
1616: }
1617: }
1618: } else {
1619: if (exists($currrules->{'default'})) {
1620: $rule_in_effect = $currrules->{'default'};
1621: }
1622: }
1623: }
1624: } else {
1625: if (exists($currrules->{'default'})) {
1626: $rule_in_effect = $currrules->{'default'};
1627: }
1628: }
1629: } else {
1630: if ($currrules->{'_LC_external'} ne '') {
1631: $rule_in_effect = $currrules->{'_LC_external'};
1632: }
1633: }
1634: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1635: $uname,$udom);
1636: }
1637: }
1638: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1639: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1640: unless (defined($cached)) {
1641: my %domconfig =
1642: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1643: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307 raeburn 1644: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1645: } else {
1646: $domneedscache = $serverhomedom;
1.1129 raeburn 1647: }
1648: }
1649: if (ref($result) eq 'HASH') {
1.1391 raeburn 1650: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191 raeburn 1651: &check_balancer_result($result,@hosts);
1652: if ($is_balancer) {
1.1129 raeburn 1653: if (ref($currrules) eq 'HASH') {
1654: if ($currrules->{'_LC_internetdom'} ne '') {
1655: $rule_in_effect = $currrules->{'_LC_internetdom'};
1656: }
1657: }
1658: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1659: $uname,$udom);
1660: }
1661: } else {
1662: if ($perlvar{'lonBalancer'} eq 'yes') {
1663: $is_balancer = 1;
1664: $offloadto = &this_host_spares($dom_in_use);
1665: }
1.1307 raeburn 1666: unless (defined($cached)) {
1667: $domneedscache = $serverhomedom;
1668: }
1.1129 raeburn 1669: }
1670: } else {
1671: if ($perlvar{'lonBalancer'} eq 'yes') {
1672: $is_balancer = 1;
1673: $offloadto = &this_host_spares($dom_in_use);
1674: }
1.1307 raeburn 1675: unless (defined($cached)) {
1676: $domneedscache = $serverhomedom;
1677: }
1678: }
1679: if ($domneedscache) {
1680: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1681: }
1.1430 raeburn 1682: if (($is_balancer) && ($caller ne 'switchserver')) {
1.1176 raeburn 1683: my $lowest_load = 30000;
1684: if (ref($offloadto) eq 'HASH') {
1685: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1686: foreach my $try_server (@{$offloadto->{'primary'}}) {
1687: ($otherserver,$lowest_load) =
1688: &compare_server_load($try_server,$otherserver,$lowest_load);
1689: }
1.1129 raeburn 1690: }
1.1176 raeburn 1691: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1692:
1.1176 raeburn 1693: if (!$found_server) {
1694: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1695: foreach my $try_server (@{$offloadto->{'default'}}) {
1696: ($otherserver,$lowest_load) =
1697: &compare_server_load($try_server,$otherserver,$lowest_load);
1698: }
1699: }
1700: }
1701: } elsif (ref($offloadto) eq 'ARRAY') {
1702: if (@{$offloadto} == 1) {
1703: $otherserver = $offloadto->[0];
1704: } elsif (@{$offloadto} > 1) {
1705: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1706: ($otherserver,$lowest_load) =
1707: &compare_server_load($try_server,$otherserver,$lowest_load);
1708: }
1709: }
1710: }
1.1331 raeburn 1711: unless ($caller eq 'login') {
1712: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1713: $is_balancer = 0;
1714: if ($uname ne '' && $udom ne '') {
1715: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389 raeburn 1716: &appenv({'user.loadbalexempt' => $lonhost,
1.1331 raeburn 1717: 'user.loadbalcheck.time' => time});
1718: }
1.1176 raeburn 1719: }
1.1129 raeburn 1720: }
1721: }
1.1430 raeburn 1722: }
1723: if (($is_balancer) && (!$homeintdom)) {
1724: undef($setcookie);
1.1129 raeburn 1725: }
1.1391 raeburn 1726: return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129 raeburn 1727: }
1728:
1.1191 raeburn 1729: sub check_balancer_result {
1730: my ($result,@hosts) = @_;
1.1391 raeburn 1731: my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191 raeburn 1732: if (ref($result) eq 'HASH') {
1733: if ($result->{'lonhost'} ne '') {
1734: my $currbalancer = $result->{'lonhost'};
1735: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1736: $is_balancer = 1;
1737: $currtargets = $result->{'targets'};
1738: $currrules = $result->{'rules'};
1739: }
1.1391 raeburn 1740: $dom_balancers = $currbalancer;
1.1191 raeburn 1741: } else {
1.1391 raeburn 1742: if (keys(%{$result})) {
1743: foreach my $key (keys(%{$result})) {
1744: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1745: (ref($result->{$key}) eq 'HASH')) {
1746: $is_balancer = 1;
1747: $currrules = $result->{$key}{'rules'};
1748: $currtargets = $result->{$key}{'targets'};
1749: $setcookie = $result->{$key}{'cookie'};
1750: last;
1751: }
1.1191 raeburn 1752: }
1.1391 raeburn 1753: $dom_balancers = join(',',sort(keys(%{$result})));
1.1191 raeburn 1754: }
1755: }
1756: }
1.1391 raeburn 1757: return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191 raeburn 1758: }
1759:
1.1129 raeburn 1760: sub get_loadbalancer_targets {
1761: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1762: my $offloadto;
1.1175 raeburn 1763: if ($rule_in_effect eq 'none') {
1764: return [$perlvar{'lonHostID'}];
1765: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1766: $offloadto = $currtargets;
1767: } else {
1768: if ($rule_in_effect eq 'homeserver') {
1769: my $homeserver = &homeserver($uname,$udom);
1770: if ($homeserver ne 'no_host') {
1771: $offloadto = [$homeserver];
1772: }
1773: } elsif ($rule_in_effect eq 'externalbalancer') {
1774: my %domconfig =
1775: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1776: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1777: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1778: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1779: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1780: }
1781: }
1782: } else {
1.1178 raeburn 1783: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1784: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1785: if (&hostname($remotebalancer) ne '') {
1786: $offloadto = [$remotebalancer];
1787: }
1788: }
1789: } elsif (&hostname($rule_in_effect) ne '') {
1790: $offloadto = [$rule_in_effect];
1791: }
1792: }
1793: return $offloadto;
1794: }
1795:
1.1127 raeburn 1796: sub internet_dom_servers {
1797: my ($dom) = @_;
1798: my (%uniqservers,%servers);
1799: my $primaryserver = &hostname(&domain($dom,'primary'));
1800: my @machinedoms = &machine_domains($primaryserver);
1801: foreach my $mdom (@machinedoms) {
1802: my %currservers = %servers;
1803: my %server = &get_servers($mdom);
1804: %servers = (%currservers,%server);
1805: }
1806: my %by_hostname;
1807: foreach my $id (keys(%servers)) {
1808: push(@{$by_hostname{$servers{$id}}},$id);
1809: }
1810: foreach my $hostname (sort(keys(%by_hostname))) {
1811: if (@{$by_hostname{$hostname}} > 1) {
1812: my $match = 0;
1813: foreach my $id (@{$by_hostname{$hostname}}) {
1814: if (&host_domain($id) eq $dom) {
1815: $uniqservers{$id} = $hostname;
1816: $match = 1;
1817: }
1818: }
1819: unless ($match) {
1820: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1821: }
1822: } else {
1823: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1824: }
1825: }
1826: return %uniqservers;
1827: }
1828:
1.1347 raeburn 1829: sub trusted_domains {
1830: my ($cmdtype,$calldom) = @_;
1.1349 raeburn 1831: my ($trusted,$untrusted);
1.1347 raeburn 1832: if (&domain($calldom) eq '') {
1.1349 raeburn 1833: return ($trusted,$untrusted);
1.1347 raeburn 1834: }
1.1395 raeburn 1835: unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349 raeburn 1836: return ($trusted,$untrusted);
1.1347 raeburn 1837: }
1838: my $callprimary = &domain($calldom,'primary');
1839: my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
1840: if ($intcalldom eq '') {
1.1349 raeburn 1841: return ($trusted,$untrusted);
1.1347 raeburn 1842: }
1843:
1844: my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
1845: unless (defined($cached)) {
1846: my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
1847: &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
1848: $trustconfig = $domconfig{'trust'};
1849: }
1850: if (ref($trustconfig)) {
1851: my (%possexc,%possinc,@allexc,@allinc);
1852: if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
1853: if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
1854: map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}};
1855: }
1856: if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395 raeburn 1857: $possinc{$intcalldom} = 1;
1.1347 raeburn 1858: map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
1859: }
1860: }
1861: if (keys(%possexc)) {
1862: if (keys(%possinc)) {
1863: foreach my $key (sort(keys(%possexc))) {
1864: next if ($key eq $intcalldom);
1865: unless ($possinc{$key}) {
1866: push(@allexc,$key);
1867: }
1868: }
1869: } else {
1870: @allexc = sort(keys(%possexc));
1871: }
1872: }
1873: if (keys(%possinc)) {
1874: $possinc{$intcalldom} = 1;
1875: @allinc = sort(keys(%possinc));
1876: }
1877: if ((@allexc > 0) || (@allinc > 0)) {
1878: my %doms_by_intdom;
1879: my %allintdoms = &all_host_intdom();
1880: my %alldoms = &all_host_domain();
1881: foreach my $key (%allintdoms) {
1882: if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
1883: unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
1884: push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
1885: }
1886: } else {
1887: $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}];
1888: }
1889: }
1890: foreach my $exc (@allexc) {
1891: if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395 raeburn 1892: push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347 raeburn 1893: }
1894: }
1895: foreach my $inc (@allinc) {
1896: if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395 raeburn 1897: push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347 raeburn 1898: }
1899: }
1900: }
1901: }
1.1349 raeburn 1902: return ($trusted,$untrusted);
1.1347 raeburn 1903: }
1904:
1905: sub will_trust {
1906: my ($cmdtype,$domain,$possdom) = @_;
1907: return 1 if ($domain eq $possdom);
1908: my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
1909: my $willtrust;
1910: if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
1911: if (grep(/^\Q$domain\E$/,@{$trustedref})) {
1912: $willtrust = 1;
1913: }
1914: } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
1915: unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
1916: $willtrust = 1;
1917: }
1918: } else {
1919: $willtrust = 1;
1920: }
1921: return $willtrust;
1922: }
1923:
1.1 albertel 1924: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1925:
1.599 albertel 1926: my %homecache;
1.1 albertel 1927: sub homeserver {
1.230 stredwic 1928: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1929: my $index="$uname:$udom";
1.426 albertel 1930:
1.599 albertel 1931: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1932:
1933: my %servers = &get_servers($udom,'library');
1934: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1935: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1936: exists($badServerCache{$tryserver}));
1.841 albertel 1937:
1938: my $answer=reply("home:$udom:$uname",$tryserver);
1939: if ($answer eq 'found') {
1940: delete($badServerCache{$tryserver});
1941: return $homecache{$index}=$tryserver;
1942: } elsif ($answer eq 'no_host') {
1943: $badServerCache{$tryserver}=1;
1944: }
1.1 albertel 1945: }
1946: return 'no_host';
1.70 www 1947: }
1948:
1.1300 raeburn 1949: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70 www 1950:
1951: sub idget {
1.1300 raeburn 1952: my ($udom,$idsref,$namespace)=@_;
1.70 www 1953: my %returnhash=();
1.1300 raeburn 1954: my @ids=();
1955: if (ref($idsref) eq 'ARRAY') {
1956: @ids = @{$idsref};
1957: } else {
1958: return %returnhash;
1959: }
1960: if ($namespace eq '') {
1961: $namespace = 'ids';
1962: }
1.70 www 1963:
1.841 albertel 1964: my %servers = &get_servers($udom,'library');
1965: foreach my $tryserver (keys(%servers)) {
1.1299 raeburn 1966: my $idlist=join('&', map { &escape($_); } @ids);
1.1300 raeburn 1967: if ($namespace eq 'ids') {
1968: $idlist=~tr/A-Z/a-z/;
1969: }
1970: my $reply;
1971: if ($namespace eq 'ids') {
1972: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1973: } else {
1974: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1975: }
1.841 albertel 1976: my @answer=();
1977: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1978: @answer=split(/\&/,$reply);
1979: } ;
1980: my $i;
1981: for ($i=0;$i<=$#ids;$i++) {
1982: if ($answer[$i]) {
1.1299 raeburn 1983: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300 raeburn 1984: }
1.841 albertel 1985: }
1.1300 raeburn 1986: }
1.70 www 1987: return %returnhash;
1988: }
1989:
1990: # ------------------------------------- Find the IDs behind a list of usernames
1991:
1992: sub idrget {
1993: my ($udom,@unames)=@_;
1994: my %returnhash=();
1.800 albertel 1995: foreach my $uname (@unames) {
1996: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1997: }
1.70 www 1998: return %returnhash;
1999: }
2000:
1.1300 raeburn 2001: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70 www 2002:
2003: sub idput {
1.1300 raeburn 2004: my ($udom,$idsref,$uhom,$namespace)=@_;
1.70 www 2005: my %servers=();
1.1300 raeburn 2006: my %ids=();
2007: my %byid = ();
2008: if (ref($idsref) eq 'HASH') {
2009: %ids=%{$idsref};
2010: }
2011: if ($namespace eq '') {
2012: $namespace = 'ids';
2013: }
1.800 albertel 2014: foreach my $uname (keys(%ids)) {
2015: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300 raeburn 2016: if ($uhom eq '') {
2017: $uhom=&homeserver($uname,$udom);
2018: }
1.70 www 2019: if ($uhom ne 'no_host') {
1.800 albertel 2020: my $esc_unam=&escape($uname);
1.1300 raeburn 2021: if ($namespace eq 'ids') {
2022: my $id=&escape($ids{$uname});
2023: $id=~tr/A-Z/a-z/;
2024: my $esc_unam=&escape($uname);
2025: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70 www 2026: } else {
1.1300 raeburn 2027: my @currids = split(/,/,$ids{$uname});
2028: foreach my $id (@currids) {
2029: $byid{$uhom}{$id} .= $uname.',';
2030: }
2031: }
2032: }
2033: }
2034: if ($namespace eq 'clickers') {
2035: foreach my $server (keys(%byid)) {
2036: if (ref($byid{$server}) eq 'HASH') {
2037: foreach my $id (keys(%{$byid{$server}})) {
2038: $byid{$server} =~ s/,$//;
2039: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
2040: }
1.70 www 2041: }
2042: }
1.191 harris41 2043: }
1.800 albertel 2044: foreach my $server (keys(%servers)) {
1.1300 raeburn 2045: $servers{$server} =~ s/\&$//;
2046: if ($namespace eq 'ids') {
2047: &critical('idput:'.$udom.':'.$servers{$server},$server);
2048: } else {
2049: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
2050: }
1.191 harris41 2051: }
1.344 www 2052: }
2053:
1.1300 raeburn 2054: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231 raeburn 2055:
2056: sub iddel {
1.1300 raeburn 2057: my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231 raeburn 2058: my %result=();
1.1300 raeburn 2059: my %ids=();
2060: my %byid = ();
2061: if (ref($idshashref) eq 'HASH') {
2062: %ids=%{$idshashref};
2063: } else {
1.1231 raeburn 2064: return %result;
2065: }
1.1300 raeburn 2066: if ($namespace eq '') {
2067: $namespace = 'ids';
2068: }
1.1231 raeburn 2069: my %servers=();
1.1300 raeburn 2070: while (my ($id,$unamestr) = each(%ids)) {
2071: if ($namespace eq 'ids') {
2072: my $uhom = $uhome;
2073: if ($uhom eq '') {
2074: $uhom=&homeserver($unamestr,$udom);
2075: }
2076: if ($uhom ne 'no_host') {
2077: $servers{$uhom}.='&'.&escape($id);
2078: }
2079: } else {
2080: my @curritems = split(/,/,$ids{$id});
2081: foreach my $uname (@curritems) {
2082: my $uhom = $uhome;
2083: if ($uhom eq '') {
2084: $uhom=&homeserver($uname,$udom);
2085: }
2086: if ($uhom ne 'no_host') {
2087: $byid{$uhom}{$id} .= $uname.',';
2088: }
2089: }
1.1231 raeburn 2090: }
1.1300 raeburn 2091: }
2092: if ($namespace eq 'clickers') {
2093: foreach my $server (keys(%byid)) {
2094: if (ref($byid{$server}) eq 'HASH') {
2095: foreach my $id (keys(%{$byid{$server}})) {
2096: $byid{$server}{$id} =~ s/,$//;
2097: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
2098: }
1.1231 raeburn 2099: }
2100: }
2101: }
2102: foreach my $server (keys(%servers)) {
1.1300 raeburn 2103: $servers{$server} =~ s/\&$//;
2104: if ($namespace eq 'ids') {
2105: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
2106: } elsif ($namespace eq 'clickers') {
2107: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
2108: }
1.1231 raeburn 2109: }
2110: return %result;
2111: }
2112:
1.1300 raeburn 2113: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
2114:
2115: sub updateclickers {
2116: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
2117: my %clickers;
2118: if (ref($idshashref) eq 'HASH') {
2119: %clickers=%{$idshashref};
2120: } else {
2121: return;
2122: }
2123: my $items='';
2124: foreach my $item (keys(%clickers)) {
2125: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
2126: }
2127: $items=~s/\&$//;
2128: my $request = "updateclickers:$udom:$action:$items";
2129: if ($critical) {
2130: return &critical($request,$uhome);
2131: } else {
2132: return &reply($request,$uhome);
2133: }
2134: }
2135:
1.1023 raeburn 2136: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 2137: sub dump_dom {
1.1165 droeschl 2138: my ($namespace, $udom, $regexp) = @_;
2139:
2140: $udom ||= $env{'user.domain'};
2141:
2142: return () unless $udom;
2143:
2144: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 2145: }
2146:
1.1023 raeburn 2147: # ------------------------------------------ get items from domain db files
1.806 raeburn 2148:
2149: sub get_dom {
1.1462 raeburn 2150: my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
1.1267 raeburn 2151: return if ($udom eq 'public');
1.806 raeburn 2152: my $items='';
2153: foreach my $item (@$storearr) {
2154: $items.=&escape($item).'&';
2155: }
2156: $items=~s/\&$//;
1.860 raeburn 2157: if (!$udom) {
2158: $udom=$env{'user.domain'};
1.1267 raeburn 2159: return if ($udom eq 'public');
1.860 raeburn 2160: if (defined(&domain($udom,'primary'))) {
2161: $uhome=&domain($udom,'primary');
2162: } else {
1.874 albertel 2163: undef($uhome);
1.860 raeburn 2164: }
2165: } else {
2166: if (!$uhome) {
2167: if (defined(&domain($udom,'primary'))) {
2168: $uhome=&domain($udom,'primary');
2169: }
2170: }
2171: }
2172: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344 raeburn 2173: my $rep;
1.1442 raeburn 2174: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
2175: # domain information is hosted on this machine
1.1462 raeburn 2176: $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1.1344 raeburn 2177: } else {
1.1462 raeburn 2178: if ($encrypt) {
1.1442 raeburn 2179: $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
2180: } else {
2181: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
2182: }
1.1344 raeburn 2183: }
1.866 raeburn 2184: my %returnhash;
1.875 albertel 2185: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 2186: return %returnhash;
2187: }
1.806 raeburn 2188: my @pairs=split(/\&/,$rep);
2189: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2190: return @pairs;
2191: }
2192: my $i=0;
2193: foreach my $item (@$storearr) {
2194: $returnhash{$item}=&thaw_unescape($pairs[$i]);
2195: $i++;
2196: }
2197: return %returnhash;
2198: } else {
1.880 banghart 2199: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 2200: }
2201: }
2202:
2203: # -------------------------------------------- put items in domain db files
2204:
2205: sub put_dom {
1.1462 raeburn 2206: my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
1.860 raeburn 2207: if (!$udom) {
2208: $udom=$env{'user.domain'};
2209: if (defined(&domain($udom,'primary'))) {
2210: $uhome=&domain($udom,'primary');
2211: } else {
1.874 albertel 2212: undef($uhome);
1.860 raeburn 2213: }
2214: } else {
2215: if (!$uhome) {
2216: if (defined(&domain($udom,'primary'))) {
2217: $uhome=&domain($udom,'primary');
2218: }
2219: }
2220: }
2221: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 2222: my $items='';
2223: foreach my $item (keys(%$storehash)) {
2224: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
2225: }
2226: $items=~s/\&$//;
1.1462 raeburn 2227: if ($encrypt) {
1.1344 raeburn 2228: return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
2229: } else {
2230: return &reply("putdom:$udom:$namespace:$items",$uhome);
2231: }
1.806 raeburn 2232: } else {
1.860 raeburn 2233: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 2234: }
2235: }
2236:
1.1023 raeburn 2237: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 2238: sub newput_dom {
1.1023 raeburn 2239: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 2240: my $result;
2241: if (!$udom) {
2242: $udom=$env{'user.domain'};
2243: }
1.1023 raeburn 2244: if ($udom) {
2245: my $uname = &get_domainconfiguser($udom);
2246: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 2247: }
2248: return $result;
2249: }
2250:
1.1023 raeburn 2251: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 2252: sub del_dom {
1.1023 raeburn 2253: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 2254: if (ref($storearr) eq 'ARRAY') {
2255: if (!$udom) {
2256: $udom=$env{'user.domain'};
2257: }
1.1023 raeburn 2258: if ($udom) {
2259: my $uname = &get_domainconfiguser($udom);
2260: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 2261: }
2262: }
2263: }
2264:
1.1481 raeburn 2265: sub store_dom {
1.1482 raeburn 2266: my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
1.1481 raeburn 2267: $$storehash{'ip'}=&get_requestor_ip();
2268: $$storehash{'host'}=$perlvar{'lonHostID'};
2269: my $namevalue='';
2270: foreach my $key (keys(%{$storehash})) {
2271: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
2272: }
2273: $namevalue=~s/\&$//;
2274: if (grep { $_ eq $home } current_machine_ids()) {
2275: return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
2276: } else {
2277: if ($namespace eq 'private') {
2278: return 'refused';
1.1482 raeburn 2279: } elsif ($encrypt) {
2280: return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
1.1481 raeburn 2281: } else {
1.1482 raeburn 2282: return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
1.1481 raeburn 2283: }
2284: }
2285: }
2286:
1.1482 raeburn 2287: sub restore_dom {
2288: my ($id,$namespace,$dom,$home,$encrypt) = @_;
2289: my $answer;
2290: if (grep { $_ eq $home } current_machine_ids()) {
2291: $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
2292: } elsif ($namespace ne 'private') {
2293: if ($encrypt) {
2294: $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
2295: } else {
2296: $answer=&reply("restoredom:$dom:$namespace:$id",$home);
2297: }
2298: }
2299: my %returnhash=();
2300: unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') ||
2301: ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
2302: foreach my $line (split(/\&/,$answer)) {
2303: my ($name,$value)=split(/\=/,$line);
2304: $returnhash{&unescape($name)}=&thaw_unescape($value);
2305: }
2306: my $version;
2307: for ($version=1;$version<=$returnhash{'version'};$version++) {
2308: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
2309: $returnhash{$item}=$returnhash{$version.':'.$item};
2310: }
2311: }
2312: }
2313: return %returnhash;
2314: }
2315:
1.1023 raeburn 2316: # ----------------------------------construct domainconfig user for a domain
2317: sub get_domainconfiguser {
2318: my ($udom) = @_;
2319: return $udom.'-domainconfig';
2320: }
2321:
1.837 raeburn 2322: sub retrieve_inst_usertypes {
2323: my ($udom) = @_;
2324: my (%returnhash,@order);
1.989 raeburn 2325: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
2326: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2327: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 2328: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 2329: } else {
2330: if (defined(&domain($udom,'primary'))) {
2331: my $uhome=&domain($udom,'primary');
2332: my $rep=&reply("inst_usertypes:$udom",$uhome);
2333: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 2334: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 2335: return (\%returnhash,\@order);
2336: }
2337: my ($hashitems,$orderitems) = split(/:/,$rep);
2338: my @pairs=split(/\&/,$hashitems);
2339: foreach my $item (@pairs) {
2340: my ($key,$value)=split(/=/,$item,2);
2341: $key = &unescape($key);
2342: next if ($key =~ /^error: 2 /);
2343: $returnhash{$key}=&thaw_unescape($value);
2344: }
2345: my @esc_order = split(/\&/,$orderitems);
2346: foreach my $item (@esc_order) {
2347: push(@order,&unescape($item));
2348: }
2349: } else {
1.1256 raeburn 2350: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 2351: }
1.1256 raeburn 2352: return (\%returnhash,\@order);
1.837 raeburn 2353: }
2354: }
2355:
1.868 raeburn 2356: sub is_domainimage {
2357: my ($url) = @_;
1.1468 raeburn 2358: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868 raeburn 2359: if (&domain($1) ne '') {
2360: return '1';
2361: }
2362: }
2363: return;
2364: }
2365:
1.899 raeburn 2366: sub inst_directory_query {
2367: my ($srch) = @_;
2368: my $udom = $srch->{'srchdomain'};
2369: my %results;
2370: my $homeserver = &domain($udom,'primary');
1.909 raeburn 2371: my $outcome;
1.899 raeburn 2372: if ($homeserver ne '') {
1.1357 raeburn 2373: unless ($homeserver eq $perlvar{'lonHostID'}) {
2374: if ($srch->{'srchby'} eq 'email') {
1.1417 raeburn 2375: my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1357 raeburn 2376: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2377: if (($major eq '' && $minor eq '') || ($major < 2) ||
2378: (($major == 2) && ($minor < 12))) {
2379: return;
2380: }
2381: }
2382: }
1.904 albertel 2383: my $queryid=&reply("querysend:instdirsearch:".
2384: &escape($srch->{'srchby'}).':'.
2385: &escape($srch->{'srchterm'}).':'.
2386: &escape($srch->{'srchtype'}),$homeserver);
2387: my $host=&hostname($homeserver);
2388: if ($queryid !~/^\Q$host\E\_/) {
1.1343 raeburn 2389: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 2390: return;
2391: }
2392: my $response = &get_query_reply($queryid);
2393: my $maxtries = 5;
2394: my $tries = 1;
2395: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2396: $response = &get_query_reply($queryid);
2397: $tries ++;
2398: }
2399:
2400: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2401: if ($response eq 'unavailable') {
2402: $outcome = $response;
2403: } else {
2404: $outcome = 'ok';
2405: my @matches = split(/\n/,$response);
2406: foreach my $match (@matches) {
2407: my ($key,$value) = split(/=/,$match);
2408: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2409: }
1.899 raeburn 2410: }
2411: }
2412: }
1.909 raeburn 2413: return ($outcome,%results);
1.899 raeburn 2414: }
2415:
2416: sub usersearch {
2417: my ($srch) = @_;
2418: my $dom = $srch->{'srchdomain'};
2419: my %results;
2420: my %libserv = &all_library();
2421: my $query = 'usersearch';
2422: foreach my $tryserver (keys(%libserv)) {
2423: if (&host_domain($tryserver) eq $dom) {
1.1357 raeburn 2424: unless ($tryserver eq $perlvar{'lonHostID'}) {
2425: if ($srch->{'srchby'} eq 'email') {
1.1417 raeburn 2426: my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1357 raeburn 2427: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2428: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2429: (($major == 2) && ($minor < 12)));
2430: }
2431: }
1.899 raeburn 2432: my $host=&hostname($tryserver);
2433: my $queryid=
1.911 raeburn 2434: &reply("querysend:".&escape($query).':'.
2435: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2436: &escape($srch->{'srchtype'}).':'.
2437: &escape($srch->{'srchterm'}),$tryserver);
2438: if ($queryid !~/^\Q$host\E\_/) {
2439: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2440: next;
1.899 raeburn 2441: }
2442: my $reply = &get_query_reply($queryid);
2443: my $maxtries = 1;
2444: my $tries = 1;
2445: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2446: $reply = &get_query_reply($queryid);
2447: $tries ++;
2448: }
2449: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2450: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2451: } else {
1.911 raeburn 2452: my @matches;
2453: if ($reply =~ /\n/) {
2454: @matches = split(/\n/,$reply);
2455: } else {
2456: @matches = split(/\&/,$reply);
2457: }
1.899 raeburn 2458: foreach my $match (@matches) {
2459: my ($uname,$udom,%userhash);
1.911 raeburn 2460: foreach my $entry (split(/:/,$match)) {
2461: my ($key,$value) =
2462: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2463: $userhash{$key} = $value;
2464: if ($key eq 'username') {
2465: $uname = $value;
2466: } elsif ($key eq 'domain') {
2467: $udom = $value;
1.911 raeburn 2468: }
1.899 raeburn 2469: }
2470: $results{$uname.':'.$udom} = \%userhash;
2471: }
2472: }
2473: }
2474: }
2475: return %results;
2476: }
2477:
1.912 raeburn 2478: sub get_instuser {
2479: my ($udom,$uname,$id) = @_;
2480: my $homeserver = &domain($udom,'primary');
2481: my ($outcome,%results);
2482: if ($homeserver ne '') {
2483: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2484: &escape($id).':'.&escape($udom),$homeserver);
2485: my $host=&hostname($homeserver);
2486: if ($queryid !~/^\Q$host\E\_/) {
2487: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2488: return;
2489: }
2490: my $response = &get_query_reply($queryid);
2491: my $maxtries = 5;
2492: my $tries = 1;
2493: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2494: $response = &get_query_reply($queryid);
2495: $tries ++;
2496: }
2497: if (!&error($response) && $response ne 'refused') {
2498: if ($response eq 'unavailable') {
2499: $outcome = $response;
2500: } else {
2501: $outcome = 'ok';
2502: my @matches = split(/\n/,$response);
2503: foreach my $match (@matches) {
2504: my ($key,$value) = split(/=/,$match);
2505: $results{&unescape($key)} = &thaw_unescape($value);
2506: }
2507: }
2508: }
2509: }
2510: my %userinfo;
2511: if (ref($results{$uname}) eq 'HASH') {
2512: %userinfo = %{$results{$uname}};
2513: }
2514: return ($outcome,%userinfo);
2515: }
2516:
1.1290 raeburn 2517: sub get_multiple_instusers {
2518: my ($udom,$users,$caller) = @_;
2519: my ($outcome,$results);
2520: if (ref($users) eq 'HASH') {
2521: my $count = keys(%{$users});
2522: my $requested = &freeze_escape($users);
2523: my $homeserver = &domain($udom,'primary');
2524: if ($homeserver ne '') {
2525: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2526: my $host=&hostname($homeserver);
2527: if ($queryid !~/^\Q$host\E\_/) {
2528: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2529: ' for host: '.$homeserver.'in domain '.$udom);
2530: return ($outcome,$results);
2531: }
2532: my $response = &get_query_reply($queryid);
2533: my $maxtries = 5;
2534: if ($count > 100) {
2535: $maxtries = 1+int($count/20);
2536: }
2537: my $tries = 1;
2538: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2539: $response = &get_query_reply($queryid);
2540: $tries ++;
2541: }
2542: if ($response eq '') {
2543: $results = {};
2544: foreach my $key (keys(%{$users})) {
2545: my ($uname,$id);
2546: if ($caller eq 'id') {
2547: $id = $key;
2548: } else {
2549: $uname = $key;
2550: }
2551: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291 raeburn 2552: $outcome = $resp;
1.1290 raeburn 2553: if ($resp eq 'ok') {
2554: %{$results} = (%{$results}, %info);
2555: } else {
2556: last;
2557: }
2558: }
2559: } elsif(!&error($response) && ($response ne 'refused')) {
2560: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2561: $outcome = $response;
2562: } else {
1.1291 raeburn 2563: ($outcome,my $userdata) = split(/=/,$response,2);
1.1290 raeburn 2564: if ($outcome eq 'ok') {
2565: $results = &thaw_unescape($userdata);
2566: }
2567: }
2568: }
2569: }
2570: }
2571: return ($outcome,$results);
2572: }
2573:
1.912 raeburn 2574: sub inst_rulecheck {
1.923 raeburn 2575: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2576: my %returnhash;
2577: if ($udom ne '') {
2578: if (ref($rules) eq 'ARRAY') {
2579: @{$rules} = map {&escape($_);} (@{$rules});
2580: my $rulestr = join(':',@{$rules});
2581: my $homeserver=&domain($udom,'primary');
2582: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2583: my $response;
2584: if ($item eq 'username') {
2585: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2586: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2587: $homeserver));
1.923 raeburn 2588: } elsif ($item eq 'id') {
2589: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2590: ':'.&escape($id).':'.$rulestr,
2591: $homeserver));
1.945 raeburn 2592: } elsif ($item eq 'selfcreate') {
2593: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2594: &escape($udom).':'.&escape($uname).
2595: ':'.$rulestr,$homeserver));
1.1484 ! raeburn 2596: } elsif ($item eq 'unamemap') {
! 2597: $response=&unescape(&reply('instunamemapcheck:'.
! 2598: &escape($udom).':'.&escape($uname).
! 2599: ':'.$rulestr,$homeserver));
1.923 raeburn 2600: }
1.912 raeburn 2601: if ($response ne 'refused') {
2602: my @pairs=split(/\&/,$response);
2603: foreach my $item (@pairs) {
2604: my ($key,$value)=split(/=/,$item,2);
2605: $key = &unescape($key);
2606: next if ($key =~ /^error: 2 /);
2607: $returnhash{$key}=&thaw_unescape($value);
2608: }
2609: }
2610: }
2611: }
2612: }
2613: return %returnhash;
2614: }
2615:
2616: sub inst_userrules {
1.923 raeburn 2617: my ($udom,$check) = @_;
1.912 raeburn 2618: my (%ruleshash,@ruleorder);
2619: if ($udom ne '') {
2620: my $homeserver=&domain($udom,'primary');
2621: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2622: my $response;
2623: if ($check eq 'id') {
2624: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2625: $homeserver);
1.943 raeburn 2626: } elsif ($check eq 'email') {
2627: $response=&reply('instemailrules:'.&escape($udom),
2628: $homeserver);
1.1484 ! raeburn 2629: } elsif ($check eq 'unamemap') {
! 2630: $response=&reply('unamemaprules:'.&escape($udom),
! 2631: $homeserver);
1.923 raeburn 2632: } else {
2633: $response=&reply('instuserrules:'.&escape($udom),
2634: $homeserver);
2635: }
1.912 raeburn 2636: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2637: ($response ne 'unknown_cmd') &&
1.912 raeburn 2638: ($response ne 'no_such_host')) {
2639: my ($hashitems,$orderitems) = split(/:/,$response);
2640: my @pairs=split(/\&/,$hashitems);
2641: foreach my $item (@pairs) {
2642: my ($key,$value)=split(/=/,$item,2);
2643: $key = &unescape($key);
2644: next if ($key =~ /^error: 2 /);
2645: $ruleshash{$key}=&thaw_unescape($value);
2646: }
2647: my @esc_order = split(/\&/,$orderitems);
2648: foreach my $item (@esc_order) {
2649: push(@ruleorder,&unescape($item));
2650: }
2651: }
2652: }
2653: }
2654: return (\%ruleshash,\@ruleorder);
2655: }
2656:
1.976 raeburn 2657: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2658:
2659: sub get_domain_defaults {
1.1240 raeburn 2660: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2661: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2662: my $cachetime = 60*60*24;
1.1240 raeburn 2663: unless ($ignore_cache) {
2664: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2665: if (defined($cached)) {
2666: if (ref($result) eq 'HASH') {
2667: return %{$result};
2668: }
1.943 raeburn 2669: }
2670: }
2671: my %domdefaults;
2672: my %domconfig =
1.989 raeburn 2673: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2674: 'requestcourses','inststatus',
1.1183 raeburn 2675: 'coursedefaults','usersessions',
1.1258 raeburn 2676: 'requestauthor','selfenrollment',
1.1320 raeburn 2677: 'coursecategories','ssl','autoenroll',
1.1482 raeburn 2678: 'trust','helpsettings','wafproxy','ltisec'],$domain);
1.1305 raeburn 2679: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2680: if (ref($domconfig{'defaults'}) eq 'HASH') {
2681: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2682: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2683: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2684: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2685: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2686: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340 raeburn 2687: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2688: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2689: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.1484 ! raeburn 2690: $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
1.943 raeburn 2691: } else {
2692: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2693: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2694: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2695: }
1.976 raeburn 2696: if (ref($domconfig{'quotas'}) eq 'HASH') {
2697: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2698: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2699: } else {
2700: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2701: }
1.1177 raeburn 2702: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2703: foreach my $item (@usertools) {
2704: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2705: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2706: }
2707: }
1.1229 raeburn 2708: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2709: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2710: }
1.976 raeburn 2711: }
1.985 raeburn 2712: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 raeburn 2713: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2714: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2715: }
2716: }
1.1183 raeburn 2717: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2718: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2719: }
1.989 raeburn 2720: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2721: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2722: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2723: }
2724: }
1.1047 raeburn 2725: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2726: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2727: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1476 raeburn 2728: $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1277 raeburn 2729: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2730: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2731: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2732: }
1.1254 raeburn 2733: foreach my $type (@coursetypes) {
2734: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2735: unless ($type eq 'community') {
2736: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2737: }
2738: }
2739: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2740: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2741: }
1.1277 raeburn 2742: if ($domdefaults{'postsubmit'} eq 'on') {
2743: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2744: $domdefaults{$type.'postsubtimeout'} =
2745: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2746: }
2747: }
1.1230 raeburn 2748: }
1.1286 raeburn 2749: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2750: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2751: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2752: if (@clonecodes) {
2753: $domdefaults{'canclone'} = join('+',@clonecodes);
2754: }
2755: }
2756: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2757: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2758: }
1.1356 raeburn 2759: if ($domconfig{'coursedefaults'}{'texengine'}) {
2760: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
1.1480 raeburn 2761: }
2762: if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
2763: $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
2764: }
1.1047 raeburn 2765: }
1.1073 raeburn 2766: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2767: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2768: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2769: }
2770: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2771: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2772: }
1.1279 raeburn 2773: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2774: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2775: }
1.1440 raeburn 2776: if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1439 raeburn 2777: $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
2778: }
1.1073 raeburn 2779: }
1.1254 raeburn 2780: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2781: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2782: my @settings = ('types','registered','enroll_dates','access_dates','section',
2783: 'approval','limit');
2784: foreach my $type (@coursetypes) {
2785: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2786: my @mgrdc = ();
2787: foreach my $item (@settings) {
2788: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2789: push(@mgrdc,$item);
2790: }
2791: }
2792: if (@mgrdc) {
2793: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2794: }
2795: }
2796: }
2797: }
2798: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2799: foreach my $type (@coursetypes) {
2800: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2801: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2802: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2803: }
2804: }
2805: }
2806: }
2807: }
1.1258 raeburn 2808: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2809: $domdefaults{'catauth'} = 'std';
2810: $domdefaults{'catunauth'} = 'std';
1.1413 raeburn 2811: if ($domconfig{'coursecategories'}{'auth'}) {
1.1258 raeburn 2812: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2813: }
2814: if ($domconfig{'coursecategories'}{'unauth'}) {
2815: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2816: }
2817: }
1.1315 raeburn 2818: if (ref($domconfig{'ssl'}) eq 'HASH') {
2819: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2820: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2821: }
1.1338 raeburn 2822: if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
2823: $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
2824: }
2825: if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
2826: $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315 raeburn 2827: }
2828: }
1.1320 raeburn 2829: if (ref($domconfig{'trust'}) eq 'HASH') {
2830: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2831: foreach my $prefix (@prefixes) {
2832: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2833: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2834: }
2835: }
2836: }
1.1314 raeburn 2837: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2838: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1477 raeburn 2839: $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1314 raeburn 2840: }
1.1332 raeburn 2841: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2842: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2843: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2844: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2845: }
2846: }
1.1434 raeburn 2847: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
1.1449 raeburn 2848: foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
1.1434 raeburn 2849: if ($domconfig{'wafproxy'}{$item}) {
2850: $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
2851: }
2852: }
1.1482 raeburn 2853: }
2854: if (ref($domconfig{'ltisec'}) eq 'HASH') {
2855: if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
2856: $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
2857: $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
2858: $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
2859: }
2860: if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
2861: if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
2862: $domdefaults{'privhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
2863: }
2864: }
2865: }
1.1219 raeburn 2866: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2867: return %domdefaults;
2868: }
2869:
1.1412 raeburn 2870: sub get_dom_cats {
2871: my ($dom) = @_;
2872: return unless (&domain($dom));
2873: my ($cats,$cached)=&is_cached_new('cats',$dom);
2874: unless (defined($cached)) {
2875: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2876: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2877: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2878: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2879: } else {
2880: $cats = {};
2881: }
2882: } else {
2883: $cats = {};
2884: }
2885: &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
2886: }
1.1413 raeburn 2887: return $cats;
2888: }
2889:
2890: sub get_dom_instcats {
2891: my ($dom) = @_;
2892: return unless (&domain($dom));
2893: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2894: unless (defined($cached)) {
2895: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2896: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2897: if ($totcodes > 0) {
2898: my $caller = 'global';
2899: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2900: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2901: $instcats = {
2902: codes => \%codes,
2903: codetitles => \@codetitles,
2904: cat_titles => \%cat_titles,
2905: cat_order => \%cat_order,
2906: };
2907: &do_cache_new('instcats',$dom,$instcats,3600);
2908: }
2909: }
2910: }
2911: return $instcats;
2912: }
2913:
2914: sub retrieve_instcodes {
2915: my ($coursecodes,$dom) = @_;
2916: my $totcodes;
2917: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2918: foreach my $course (keys(%courses)) {
2919: if (ref($courses{$course}) eq 'HASH') {
2920: if ($courses{$course}{'inst_code'} ne '') {
2921: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2922: $totcodes ++;
2923: }
2924: }
2925: }
2926: return $totcodes;
1.1412 raeburn 2927: }
2928:
1.1311 raeburn 2929: sub course_portal_url {
1.1451 raeburn 2930: my ($cnum,$cdom,$r) = @_;
1.1311 raeburn 2931: my $chome = &homeserver($cnum,$cdom);
2932: my $hostname = &hostname($chome);
2933: my $protocol = $protocol{$chome};
2934: $protocol = 'http' if ($protocol ne 'https');
2935: my %domdefaults = &get_domain_defaults($cdom);
2936: my $firsturl;
2937: if ($domdefaults{'portal_def'}) {
2938: $firsturl = $domdefaults{'portal_def'};
2939: } else {
1.1451 raeburn 2940: my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
2941: $hostname = $alias if ($alias ne '');
1.1311 raeburn 2942: $firsturl = $protocol.'://'.$hostname;
2943: }
2944: return $firsturl;
2945: }
2946:
1.1407 raeburn 2947: # --------------------------------------------- Get domain config for passwords
2948:
2949: sub get_passwdconf {
2950: my ($dom) = @_;
2951: my (%passwdconf,$gotconf,$lookup);
2952: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2953: if (defined($cached)) {
2954: if (ref($result) eq 'HASH') {
2955: %passwdconf = %{$result};
2956: $gotconf = 1;
2957: }
2958: }
2959: unless ($gotconf) {
2960: my %domconfig = &get_dom('configuration',['passwords'],$dom);
2961: if (ref($domconfig{'passwords'}) eq 'HASH') {
2962: %passwdconf = %{$domconfig{'passwords'}};
2963: }
2964: my $cachetime = 24*60*60;
2965: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
2966: }
2967: return %passwdconf;
2968: }
2969:
1.344 www 2970: # --------------------------------------------------- Assign a key to a student
2971:
2972: sub assign_access_key {
1.364 www 2973: #
2974: # a valid key looks like uname:udom#comments
2975: # comments are being appended
2976: #
1.498 www 2977: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2978: $kdom=
1.620 albertel 2979: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2980: $knum=
1.620 albertel 2981: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2982: $cdom=
1.620 albertel 2983: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2984: $cnum=
1.620 albertel 2985: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2986: $udom=$env{'user.name'} unless (defined($udom));
2987: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2988: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2989: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2990: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2991: # assigned to this person
2992: # - this should not happen,
1.345 www 2993: # unless something went wrong
2994: # the first time around
2995: # ready to assign
1.364 www 2996: $logentry=$1.'; '.$logentry;
1.496 www 2997: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2998: $kdom,$knum) eq 'ok') {
1.345 www 2999: # key now belongs to user
1.346 www 3000: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 3001: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 3002: &appenv({'environment.'.$envkey => $ckey});
1.345 www 3003: return 'ok';
3004: } else {
3005: return
3006: 'error: Count not permanently assign key, will need to be re-entered later.';
3007: }
3008: } else {
3009: return 'error: Could not assign key, try again later.';
3010: }
1.364 www 3011: } elsif (!$existing{$ckey}) {
1.345 www 3012: # the key does not exist
3013: return 'error: The key does not exist';
3014: } else {
3015: # the key is somebody else's
3016: return 'error: The key is already in use';
3017: }
1.344 www 3018: }
3019:
1.364 www 3020: # ------------------------------------------ put an additional comment on a key
3021:
3022: sub comment_access_key {
3023: #
3024: # a valid key looks like uname:udom#comments
3025: # comments are being appended
3026: #
3027: my ($ckey,$cdom,$cnum,$logentry)=@_;
3028: $cdom=
1.620 albertel 3029: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 3030: $cnum=
1.620 albertel 3031: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 3032: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
3033: if ($existing{$ckey}) {
3034: $existing{$ckey}.='; '.$logentry;
3035: # ready to assign
1.367 www 3036: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 3037: $cdom,$cnum) eq 'ok') {
3038: return 'ok';
3039: } else {
3040: return 'error: Count not store comment.';
3041: }
3042: } else {
3043: # the key does not exist
3044: return 'error: The key does not exist';
3045: }
3046: }
3047:
1.344 www 3048: # ------------------------------------------------------ Generate a set of keys
3049:
3050: sub generate_access_keys {
1.364 www 3051: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 3052: $cdom=
1.620 albertel 3053: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 3054: $cnum=
1.620 albertel 3055: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 3056: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 3057: unless (($cdom) && ($cnum)) { return 0; }
3058: if ($number>10000) { return 0; }
3059: sleep(2); # make sure don't get same seed twice
3060: srand(time()^($$+($$<<15))); # from "Programming Perl"
3061: my $total=0;
3062: for (my $i=1;$i<=$number;$i++) {
3063: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
3064: sprintf("%lx",int(100000*rand)).'-'.
3065: sprintf("%lx",int(100000*rand));
3066: $newkey=~s/1/g/g; # folks mix up 1 and l
3067: $newkey=~s/0/h/g; # and also 0 and O
3068: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
3069: if ($existing{$newkey}) {
3070: $i--;
3071: } else {
1.364 www 3072: if (&put('accesskeys',
3073: { $newkey => '# generated '.localtime().
1.620 albertel 3074: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 3075: '; '.$logentry },
3076: $cdom,$cnum) eq 'ok') {
1.344 www 3077: $total++;
3078: }
3079: }
3080: }
1.620 albertel 3081: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 3082: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
3083: return $total;
3084: }
3085:
3086: # ------------------------------------------------------- Validate an accesskey
3087:
3088: sub validate_access_key {
3089: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
3090: $cdom=
1.620 albertel 3091: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 3092: $cnum=
1.620 albertel 3093: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
3094: $udom=$env{'user.domain'} unless (defined($udom));
3095: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 3096: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 3097: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 3098: }
3099:
3100: # ------------------------------------- Find the section of student in a course
1.652 albertel 3101: sub devalidate_getsection_cache {
3102: my ($udom,$unam,$courseid)=@_;
3103: my $hashid="$udom:$unam:$courseid";
3104: &devalidate_cache_new('getsection',$hashid);
3105: }
1.298 matthew 3106:
1.815 albertel 3107: sub courseid_to_courseurl {
3108: my ($courseid) = @_;
3109: #already url style courseid
3110: return $courseid if ($courseid =~ m{^/});
3111:
3112: if (exists($env{'course.'.$courseid.'.num'})) {
3113: my $cnum = $env{'course.'.$courseid.'.num'};
3114: my $cdom = $env{'course.'.$courseid.'.domain'};
3115: return "/$cdom/$cnum";
3116: }
3117:
3118: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
3119: if (exists($courseinfo{'num'})) {
3120: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
3121: }
3122:
3123: return undef;
3124: }
3125:
1.298 matthew 3126: sub getsection {
3127: my ($udom,$unam,$courseid)=@_;
1.599 albertel 3128: my $cachetime=1800;
1.551 albertel 3129:
3130: my $hashid="$udom:$unam:$courseid";
1.599 albertel 3131: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 3132: if (defined($cached)) { return $result; }
3133:
1.298 matthew 3134: my %Pending;
3135: my %Expired;
3136: #
3137: # Each role can either have not started yet (pending), be active,
3138: # or have expired.
3139: #
3140: # If there is an active role, we are done.
3141: #
3142: # If there is more than one role which has not started yet,
3143: # choose the one which will start sooner
3144: # If there is one role which has not started yet, return it.
3145: #
3146: # If there is more than one expired role, choose the one which ended last.
3147: # If there is a role which has expired, return it.
3148: #
1.815 albertel 3149: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 3150: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 3151: foreach my $key (keys(%roleshash)) {
1.479 albertel 3152: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 3153: my $section=$1;
3154: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 3155: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 3156: my $now=time;
1.548 albertel 3157: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 3158: $Expired{$end}=$section;
3159: next;
3160: }
1.548 albertel 3161: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 3162: $Pending{$start}=$section;
3163: next;
3164: }
1.599 albertel 3165: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 3166: }
3167: #
3168: # Presumedly there will be few matching roles from the above
3169: # loop and the sorting time will be negligible.
3170: if (scalar(keys(%Pending))) {
3171: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 3172: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 3173: }
3174: if (scalar(keys(%Expired))) {
3175: my @sorted = sort {$a <=> $b} keys(%Expired);
3176: my $time = pop(@sorted);
1.599 albertel 3177: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 3178: }
1.599 albertel 3179: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 3180: }
1.70 www 3181:
1.599 albertel 3182: sub save_cache {
3183: &purge_remembered();
1.722 albertel 3184: #&Apache::loncommon::validate_page();
1.620 albertel 3185: undef(%env);
1.780 albertel 3186: undef($env_loaded);
1.599 albertel 3187: }
1.452 albertel 3188:
1.599 albertel 3189: my $to_remember=-1;
3190: my %remembered;
3191: my %accessed;
3192: my $kicks=0;
3193: my $hits=0;
1.849 albertel 3194: sub make_key {
3195: my ($name,$id) = @_;
1.872 albertel 3196: if (length($id) > 65
3197: && length(&escape($id)) > 200) {
3198: $id=length($id).':'.&Digest::MD5::md5_hex($id);
3199: }
1.849 albertel 3200: return &escape($name.':'.$id);
3201: }
3202:
1.599 albertel 3203: sub devalidate_cache_new {
3204: my ($name,$id,$debug) = @_;
3205: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319 damieng 3206: my $remembered_id=$name.':'.$id;
1.849 albertel 3207: $id=&make_key($name,$id);
1.599 albertel 3208: $memcache->delete($id);
1.1319 damieng 3209: delete($remembered{$remembered_id});
3210: delete($accessed{$remembered_id});
1.599 albertel 3211: }
3212:
3213: sub is_cached_new {
3214: my ($name,$id,$debug) = @_;
1.1319 damieng 3215: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
3216: if (exists($remembered{$remembered_id})) {
3217: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
3218: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3219: $hits++;
1.1319 damieng 3220: return ($remembered{$remembered_id},1);
1.599 albertel 3221: }
1.1319 damieng 3222: $id=&make_key($name,$id);
1.599 albertel 3223: my $value = $memcache->get($id);
3224: if (!(defined($value))) {
3225: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 3226: return (undef,undef);
1.416 albertel 3227: }
1.599 albertel 3228: if ($value eq '__undef__') {
3229: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
3230: $value=undef;
3231: }
1.1319 damieng 3232: &make_room($remembered_id,$value,$debug);
1.599 albertel 3233: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
3234: return ($value,1);
3235: }
3236:
3237: sub do_cache_new {
3238: my ($name,$id,$value,$time,$debug) = @_;
1.1319 damieng 3239: my $remembered_id=$name.':'.$id;
1.849 albertel 3240: $id=&make_key($name,$id);
1.599 albertel 3241: my $setvalue=$value;
3242: if (!defined($setvalue)) {
3243: $setvalue='__undef__';
3244: }
1.623 albertel 3245: if (!defined($time) ) {
3246: $time=600;
3247: }
1.599 albertel 3248: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 3249: my $result = $memcache->set($id,$setvalue,$time);
3250: if (! $result) {
1.872 albertel 3251: &logthis("caching of id -> $id failed");
1.910 albertel 3252: $memcache->disconnect_all();
1.872 albertel 3253: }
1.600 albertel 3254: # need to make a copy of $value
1.1319 damieng 3255: &make_room($remembered_id,$value,$debug);
1.599 albertel 3256: return $value;
3257: }
3258:
3259: sub make_room {
1.1319 damieng 3260: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 3261:
1.1319 damieng 3262: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 3263: : $value;
1.599 albertel 3264: if ($to_remember<0) { return; }
1.1319 damieng 3265: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3266: if (scalar(keys(%remembered)) <= $to_remember) { return; }
3267: my $to_kick;
3268: my $max_time=0;
3269: foreach my $other (keys(%accessed)) {
3270: if (&tv_interval($accessed{$other}) > $max_time) {
3271: $to_kick=$other;
3272: $max_time=&tv_interval($accessed{$other});
3273: }
3274: }
3275: delete($remembered{$to_kick});
3276: delete($accessed{$to_kick});
3277: $kicks++;
3278: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 3279: return;
3280: }
3281:
1.599 albertel 3282: sub purge_remembered {
1.604 albertel 3283: #&logthis("Tossing ".scalar(keys(%remembered)));
3284: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 3285: undef(%remembered);
3286: undef(%accessed);
1.428 albertel 3287: }
1.70 www 3288: # ------------------------------------- Read an entry from a user's environment
3289:
3290: sub userenvironment {
3291: my ($udom,$unam,@what)=@_;
1.976 raeburn 3292: my $items;
3293: foreach my $item (@what) {
3294: $items.=&escape($item).'&';
3295: }
3296: $items=~s/\&$//;
1.70 www 3297: my %returnhash=();
1.1009 raeburn 3298: my $uhome = &homeserver($unam,$udom);
3299: unless ($uhome eq 'no_host') {
3300: my @answer=split(/\&/,
3301: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 3302: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
3303: return %returnhash;
3304: }
1.1009 raeburn 3305: my $i;
3306: for ($i=0;$i<=$#what;$i++) {
3307: $returnhash{$what[$i]}=&unescape($answer[$i]);
3308: }
1.70 www 3309: }
3310: return %returnhash;
1.1 albertel 3311: }
3312:
1.617 albertel 3313: # ---------------------------------------------------------- Get a studentphoto
3314: sub studentphoto {
3315: my ($udom,$unam,$ext) = @_;
3316: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 3317: if (defined($env{'request.course.id'})) {
1.708 raeburn 3318: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 3319: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
3320: return(&retrievestudentphoto($udom,$unam,$ext));
3321: } else {
3322: my ($result,$perm_reqd)=
1.707 albertel 3323: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 3324: if ($result eq 'ok') {
3325: if (!($perm_reqd eq 'yes')) {
3326: return(&retrievestudentphoto($udom,$unam,$ext));
3327: }
3328: }
3329: }
3330: }
3331: } else {
3332: my ($result,$perm_reqd) =
1.707 albertel 3333: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 3334: if ($result eq 'ok') {
3335: if (!($perm_reqd eq 'yes')) {
3336: return(&retrievestudentphoto($udom,$unam,$ext));
3337: }
3338: }
3339: }
3340: return '/adm/lonKaputt/lonlogo_broken.gif';
3341: }
3342:
3343: sub retrievestudentphoto {
3344: my ($udom,$unam,$ext,$type) = @_;
3345: my $home=&Apache::lonnet::homeserver($unam,$udom);
3346: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
3347: if ($ret eq 'ok') {
3348: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
3349: if ($type eq 'thumbnail') {
3350: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
3351: }
3352: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
3353: return $tokenurl;
3354: } else {
3355: if ($type eq 'thumbnail') {
3356: return '/adm/lonKaputt/genericstudent_tn.gif';
3357: } else {
3358: return '/adm/lonKaputt/lonlogo_broken.gif';
3359: }
1.617 albertel 3360: }
3361: }
3362:
1.263 www 3363: # -------------------------------------------------------------------- New chat
3364:
3365: sub chatsend {
1.724 raeburn 3366: my ($newentry,$anon,$group)=@_;
1.620 albertel 3367: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
3368: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3369: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 3370: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 3371: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 3372: &escape($newentry)).':'.$group,$chome);
1.292 www 3373: }
3374:
3375: # ------------------------------------------ Find current version of a resource
3376:
3377: sub getversion {
3378: my $fname=&clutter(shift);
1.1189 raeburn 3379: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 3380: return ¤tversion(&filelocation('',$fname));
3381: }
3382:
3383: sub currentversion {
3384: my $fname=shift;
3385: my $author=$fname;
3386: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3387: my ($udom,$uname)=split(/\//,$author);
1.1112 www 3388: my $home=&homeserver($uname,$udom);
1.292 www 3389: if ($home eq 'no_host') {
3390: return -1;
3391: }
1.1112 www 3392: my $answer=&reply("currentversion:$fname",$home);
1.292 www 3393: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3394: return -1;
3395: }
1.1112 www 3396: return $answer;
1.263 www 3397: }
3398:
1.1111 www 3399: #
3400: # Return special version number of resource if set by override, empty otherwise
3401: #
3402: sub usedversion {
3403: my $fname=shift;
3404: unless ($fname) { $fname=$env{'request.uri'}; }
3405: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3406: if ($urlversion) { return $urlversion; }
3407: return '';
3408: }
3409:
1.1 albertel 3410: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 3411:
1.1 albertel 3412: sub subscribe {
3413: my $fname=shift;
1.761 raeburn 3414: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 3415: $fname=~s/[\n\r]//g;
1.1 albertel 3416: my $author=$fname;
3417: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3418: my ($udom,$uname)=split(/\//,$author);
3419: my $home=homeserver($uname,$udom);
1.335 albertel 3420: if ($home eq 'no_host') {
3421: return 'not_found';
1.1 albertel 3422: }
3423: my $answer=reply("sub:$fname",$home);
1.64 www 3424: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3425: $answer.=' by '.$home;
3426: }
1.1 albertel 3427: return $answer;
3428: }
3429:
1.8 www 3430: # -------------------------------------------------------------- Replicate file
3431:
3432: sub repcopy {
3433: my $filename=shift;
1.23 www 3434: $filename=~s/\/+/\//g;
1.1142 raeburn 3435: my $londocroot = $perlvar{'lonDocRoot'};
3436: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3437: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3438: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3439: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3440: return &repcopy_userfile($filename);
3441: }
1.532 albertel 3442: $filename=~s/[\n\r]//g;
1.8 www 3443: my $transname="$filename.in.transfer";
1.828 www 3444: # FIXME: this should flock
1.607 raeburn 3445: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3446: my $remoteurl=subscribe($filename);
1.64 www 3447: if ($remoteurl =~ /^con_lost by/) {
3448: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3449: return 'unavailable';
1.8 www 3450: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3451: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3452: return 'not_found';
1.64 www 3453: } elsif ($remoteurl =~ /^rejected by/) {
3454: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3455: return 'forbidden';
1.20 www 3456: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3457: return 'ok';
1.8 www 3458: } else {
1.290 www 3459: my $author=$filename;
3460: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3461: my ($udom,$uname)=split(/\//,$author);
3462: my $home=homeserver($uname,$udom);
3463: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3464: my @parts=split(/\//,$filename);
3465: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3466: if ($path ne "$londocroot/res") {
1.8 www 3467: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3468: return 'bad_request';
1.8 www 3469: }
3470: my $count;
3471: for ($count=5;$count<$#parts;$count++) {
3472: $path.="/$parts[$count]";
3473: if ((-e $path)!=1) {
3474: mkdir($path,0777);
3475: }
3476: }
3477: my $request=new HTTP::Request('GET',"$remoteurl");
1.1345 raeburn 3478: my $response;
3479: if ($remoteurl =~ m{/raw/}) {
3480: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
3481: } else {
3482: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
3483: }
1.8 www 3484: if ($response->is_error()) {
3485: unlink($transname);
3486: my $message=$response->status_line;
1.672 albertel 3487: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3488: ." LWP get: $message: $filename</font>");
1.607 raeburn 3489: return 'unavailable';
1.8 www 3490: } else {
1.16 www 3491: if ($remoteurl!~/\.meta$/) {
3492: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345 raeburn 3493: my $mresponse;
3494: if ($remoteurl =~ m{/raw/}) {
3495: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
3496: } else {
3497: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
3498: }
1.16 www 3499: if ($mresponse->is_error()) {
3500: unlink($filename.'.meta');
3501: &logthis(
1.672 albertel 3502: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3503: }
3504: }
1.8 www 3505: rename($transname,$filename);
1.607 raeburn 3506: return 'ok';
1.8 www 3507: }
1.290 www 3508: }
1.8 www 3509: }
1.330 www 3510: }
3511:
1.1422 raeburn 3512: # ------------------------------------------------- Unsubscribe from a resource
3513:
3514: sub unsubscribe {
3515: my ($fname) = @_;
3516: my $answer;
3517: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3518: $fname=~s/[\n\r]//g;
3519: my $author=$fname;
3520: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3521: my ($udom,$uname)=split(/\//,$author);
3522: my $home=homeserver($uname,$udom);
3523: if ($home eq 'no_host') {
3524: $answer = 'no_host';
3525: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3526: $answer = 'home';
3527: } else {
3528: my $defdom = $perlvar{'lonDefDomain'};
3529: if (&will_trust('content',$defdom,$udom)) {
3530: $answer = reply("unsub:$fname",$home);
3531: } else {
3532: $answer = 'untrusted';
3533: }
3534: }
3535: return $answer;
3536: }
3537:
1.330 www 3538: # ------------------------------------------------ Get server side include body
3539: sub ssi_body {
1.381 albertel 3540: my ($filelink,%form)=@_;
1.606 matthew 3541: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3542: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3543: }
1.953 www 3544: my $output='';
3545: my $response;
1.980 raeburn 3546: if ($filelink=~/^https?\:/) {
1.954 raeburn 3547: ($output,$response)=&externalssi($filelink);
1.953 www 3548: } else {
1.1004 droeschl 3549: $filelink .= $filelink=~/\?/ ? '&' : '?';
3550: $filelink .= 'inhibitmenu=yes';
1.953 www 3551: ($output,$response)=&ssi($filelink,%form);
3552: }
1.778 albertel 3553: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3554: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3555: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3556: if (wantarray) {
3557: return ($output, $response);
3558: } else {
3559: return $output;
3560: }
1.8 www 3561: }
3562:
1.15 www 3563: # --------------------------------------------------------- Server Side Include
3564:
1.782 albertel 3565: sub absolute_url {
1.1447 raeburn 3566: my ($host_name,$unalias,$keep_proto) = @_;
1.782 albertel 3567: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3568: if ($host_name eq '') {
3569: $host_name = $ENV{'SERVER_NAME'};
3570: }
1.1447 raeburn 3571: if ($unalias) {
3572: my $alias = &get_proxy_alias();
3573: if ($alias eq $host_name) {
3574: my $lonhost = $perlvar{'lonHostID'};
3575: my $hostname = &hostname($lonhost);
3576: my $lcproto;
3577: if (($keep_proto) || ($hostname eq '')) {
3578: $lcproto = $protocol;
3579: } else {
3580: $lcproto = $protocol{$lonhost};
3581: $lcproto = 'http' if ($lcproto ne 'https');
3582: $lcproto .= '://';
3583: }
3584: unless ($hostname eq '') {
3585: return $lcproto.$hostname;
3586: }
3587: }
3588: }
1.782 albertel 3589: return $protocol.$host_name;
3590: }
3591:
1.942 foxr 3592: #
3593: # Server side include.
3594: # Parameters:
3595: # fn Possibly encrypted resource name/id.
3596: # form Hash that describes how the rendering should be done
3597: # and other things.
1.944 foxr 3598: # Returns:
1.950 raeburn 3599: # Scalar context: The content of the response.
3600: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3601: #
1.15 www 3602: sub ssi {
3603:
1.944 foxr 3604: my ($fn,%form)=@_;
1.1447 raeburn 3605: my ($host,$request,$response);
3606: $host = &absolute_url('',1);
1.711 albertel 3607:
3608: $form{'no_update_last_known'}=1;
1.895 albertel 3609: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3610: if (%form) {
1.1447 raeburn 3611: $request=new HTTP::Request('POST',$host.$fn);
1.1272 droeschl 3612: $request->content(join('&',map {
3613: my $name = escape($_);
3614: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3615: ? join("&$name=", map {escape($_) } @{$form{$_}})
3616: : &escape($form{$_}) );
3617: } keys(%form)));
1.23 www 3618: } else {
1.1447 raeburn 3619: $request=new HTTP::Request('GET',$host.$fn);
1.23 www 3620: }
3621:
1.15 www 3622: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345 raeburn 3623: my $lonhost = $perlvar{'lonHostID'};
1.1385 raeburn 3624: my $islocal;
3625: if (($env{'request.course.id'}) &&
3626: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3627: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3628: ($form{'grade_symb'} ne '') &&
3629: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3630: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
3631: $islocal = 1;
3632: }
1.1447 raeburn 3633: $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
3634: '','','',$islocal);
1.1182 foxr 3635:
1.944 foxr 3636: if (wantarray) {
1.1345 raeburn 3637: return ($response->content, $response);
1.944 foxr 3638: } else {
1.1345 raeburn 3639: return $response->content;
1.942 foxr 3640: }
1.324 www 3641: }
3642:
3643: sub externalssi {
3644: my ($url)=@_;
3645: my $request=new HTTP::Request('GET',$url);
1.1345 raeburn 3646: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954 raeburn 3647: if (wantarray) {
3648: return ($response->content, $response);
3649: } else {
3650: return $response->content;
3651: }
1.15 www 3652: }
1.254 www 3653:
1.1354 raeburn 3654:
3655: # If the local copy of a replicated resource is outdated, trigger a
3656: # connection from the homeserver to flush the delayed queue. If no update
3657: # happens, remove local copies of outdated resource (and corresponding
3658: # metadata file).
3659:
1.1352 raeburn 3660: sub remove_stale_resfile {
3661: my ($url) = @_;
1.1354 raeburn 3662: my $removed;
1.1352 raeburn 3663: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3664: my $audom = $1;
3665: my $auname = $2;
1.1353 raeburn 3666: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352 raeburn 3667: my $homeserver = &homeserver($auname,$audom);
3668: unless (($homeserver eq 'no_host') ||
3669: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3670: my $fname = &filelocation('',$url);
3671: if (-e $fname) {
3672: my $hostname = &hostname($homeserver);
3673: if ($hostname) {
1.1397 raeburn 3674: my $protocol = $protocol{$homeserver};
3675: $protocol = 'http' if ($protocol ne 'https');
1.1352 raeburn 3676: my $uri = &declutter($url);
3677: my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
3678: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
3679: if ($response->is_success()) {
3680: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3681: my $locmodtime = (stat($fname))[9];
3682: if ($locmodtime < $remmodtime) {
1.1354 raeburn 3683: my $stale;
3684: my $answer = &reply('pong',$homeserver);
3685: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3686: sleep(0.2);
3687: $locmodtime = (stat($fname))[9];
3688: if ($locmodtime < $remmodtime) {
3689: my $posstransfer = $fname.'.in.transfer';
3690: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3691: $removed = 1;
3692: } else {
3693: $stale = 1;
3694: }
3695: } else {
3696: $removed = 1;
3697: }
3698: } else {
3699: $stale = 1;
3700: }
3701: if ($stale) {
1.1421 raeburn 3702: if (unlink($fname)) {
3703: if ($uri!~/\.meta$/) {
3704: if (-e $fname.'.meta') {
3705: unlink($fname.'.meta');
3706: }
3707: }
1.1422 raeburn 3708: my $unsubresult = &unsubscribe($fname);
3709: unless ($unsubresult eq 'ok') {
3710: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3711: }
1.1421 raeburn 3712: $removed = 1;
1.1354 raeburn 3713: }
1.1352 raeburn 3714: }
3715: }
3716: }
3717: }
3718: }
3719: }
3720: }
3721: }
1.1354 raeburn 3722: return $removed;
1.1352 raeburn 3723: }
3724:
1.492 albertel 3725: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3726:
3727: sub allowuploaded {
3728: my ($srcurl,$url)=@_;
3729: $url=&clutter(&declutter($url));
3730: my $dir=$url;
3731: $dir=~s/\/[^\/]+$//;
3732: my %httpref=();
3733: my $httpurl=&hreflocation('',$url);
3734: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3735: &Apache::lonnet::appenv(\%httpref);
1.254 www 3736: }
1.477 raeburn 3737:
1.1193 raeburn 3738: #
3739: # Determine if the current user should be able to edit a particular resource,
3740: # when viewing in course context.
3741: # (a) When viewing resource used to determine if "Edit" item is included in
3742: # Functions.
3743: # (b) When displaying folder contents in course editor, used to determine if
3744: # "Edit" link will be displayed alongside resource.
3745: #
1.1196 raeburn 3746: # input: six args -- filename (decluttered), course number, course domain,
3747: # url, symb (if registered) and group (if this is a group
3748: # item -- e.g., bulletin board, group page etc.).
3749: # output: array of five scalars --
1.1193 raeburn 3750: # $cfile -- url for file editing if editable on current server
3751: # $home -- homeserver of resource (i.e., for author if published,
3752: # or course if uploaded.).
3753: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 3754: # $forceedit -- 1 if icon/link should be to go to edit mode
3755: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 3756: #
3757:
3758: sub can_edit_resource {
1.1194 raeburn 3759: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3760: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3761: #
3762: # For aboutme pages user can only edit his/her own.
3763: #
1.1199 raeburn 3764: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 3765: my ($sdom,$sname) = ($1,$2);
3766: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3767: $home = $env{'user.home'};
3768: $cfile = $resurl;
3769: if ($env{'form.forceedit'}) {
3770: $forceview = 1;
3771: } else {
3772: $forceedit = 1;
3773: }
3774: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3775: } else {
3776: return;
3777: }
3778: }
3779:
3780: if ($env{'request.course.id'}) {
3781: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3782: if ($group ne '') {
3783: # if this is a group homepage or group bulletin board, check group privs
3784: my $allowed = 0;
1.1197 raeburn 3785: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3786: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3787: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3788: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3789: $allowed = 1;
3790: }
1.1197 raeburn 3791: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3792: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3793: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3794: $allowed = 1;
3795: }
3796: }
3797: if ($allowed) {
3798: $home=&homeserver($cnum,$cdom);
3799: if ($env{'form.forceedit'}) {
3800: $forceview = 1;
3801: } else {
3802: $forceedit = 1;
3803: }
3804: $cfile = $resurl;
3805: } else {
3806: return;
3807: }
3808: } else {
1.1208 raeburn 3809: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3810: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3811: return;
3812: }
3813: } elsif (!$crsedit) {
1.1194 raeburn 3814: #
3815: # No edit allowed where CC has switched to student role.
3816: #
3817: return;
3818: }
3819: }
3820: }
3821:
1.1193 raeburn 3822: if ($file ne '') {
3823: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3824: if (&is_course_upload($file,$cnum,$cdom)) {
3825: $uploaded = 1;
3826: $incourse = 1;
1.1193 raeburn 3827: if ($file =~/\.(htm|html|css|js|txt)$/) {
3828: $cfile = &hreflocation('',$file);
1.1201 raeburn 3829: if ($env{'form.forceedit'}) {
3830: $forceview = 1;
3831: } else {
3832: $forceedit = 1;
3833: }
1.1194 raeburn 3834: }
3835: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3836: $incourse = 1;
3837: if ($env{'form.forceedit'}) {
3838: $forceview = 1;
3839: } else {
3840: $forceedit = 1;
3841: }
3842: $cfile = $resurl;
3843: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3844: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3845: $incourse = 1;
3846: if ($env{'form.forceedit'}) {
3847: $forceview = 1;
3848: } else {
3849: $forceedit = 1;
3850: }
3851: $cfile = $resurl;
1.1199 raeburn 3852: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3853: $incourse = 1;
3854: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3855: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3856: $incourse = 1;
1.1199 raeburn 3857: if ($env{'form.forceedit'}) {
3858: $forceview = 1;
3859: } else {
3860: $forceedit = 1;
3861: }
3862: $cfile = $resurl;
1.1419 raeburn 3863: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3864: my ($map,$id,$res) = &decode_symb($symb);
3865: if ($map =~ /\.page$/) {
3866: $incourse = 1;
3867: if ($env{'form.forceedit'}) {
3868: $forceview = 1;
3869: $cfile = $map;
3870: } else {
3871: $forceedit = 1;
3872: $cfile = '/adm/wrapper'.$resurl;
3873: }
3874: }
1.1343 raeburn 3875: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3876: $incourse = 1;
3877: if ($env{'form.forceedit'}) {
3878: $forceview = 1;
3879: } else {
3880: $forceedit = 1;
3881: }
3882: $cfile = $resurl;
1.1208 raeburn 3883: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3884: $incourse = 1;
3885: if ($env{'form.forceedit'}) {
3886: $forceview = 1;
3887: } else {
3888: $forceedit = 1;
3889: }
3890: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3891: }
3892: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3893: my $template = '/res/lib/templates/simpleproblem.problem';
3894: if (&is_on_map($template)) {
3895: $incourse = 1;
3896: $forceview = 1;
3897: $cfile = $template;
1.1193 raeburn 3898: }
1.1199 raeburn 3899: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1418 raeburn 3900: $incourse = 1;
3901: if ($env{'form.forceedit'}) {
3902: $forceview = 1;
3903: } else {
3904: $forceedit = 1;
3905: }
3906: $cfile = $resurl;
1.1343 raeburn 3907: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298 raeburn 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 '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3916: $incourse = 1;
3917: $forceview = 1;
3918: if ($symb) {
3919: my ($map,$id,$res)=&decode_symb($symb);
3920: $env{'request.symb'} = $symb;
3921: $cfile = &clutter($res);
3922: } else {
3923: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3924: my $escfile = &unescape($cfile);
1.1343 raeburn 3925: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3926: $cfile = '/adm/wrapper'.$escfile;
3927: } else {
3928: $escfile =~ s{^http://}{};
3929: $cfile = &escape("/adm/wrapper/ext/$escfile");
3930: }
1.1199 raeburn 3931: }
1.1234 raeburn 3932: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3933: if ($env{'form.forceedit'}) {
3934: $forceview = 1;
3935: } else {
3936: $forceedit = 1;
3937: }
3938: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 3939: }
3940: }
1.1194 raeburn 3941: if ($uploaded || $incourse) {
3942: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 3943: } elsif ($file !~ m{/$}) {
1.1193 raeburn 3944: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3945: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3946: # Check that the user has permission to edit this resource
3947: my $setpriv = 1;
3948: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3949: if (defined($cfudom)) {
3950: $home=&homeserver($cfuname,$cfudom);
3951: $cfile=$file;
3952: }
3953: }
1.1194 raeburn 3954: if (($cfile ne '') && (!$incourse || $uploaded) &&
3955: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 3956: my @ids=¤t_machine_ids();
3957: unless (grep(/^\Q$home\E$/,@ids)) {
3958: $switchserver=1;
3959: }
3960: }
3961: }
1.1194 raeburn 3962: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 3963: }
3964:
3965: sub is_course_upload {
3966: my ($file,$cnum,$cdom) = @_;
3967: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3968: $uploadpath =~ s{^\/}{};
1.1201 raeburn 3969: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3970: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 3971: return 1;
3972: }
3973: return;
3974: }
3975:
1.1194 raeburn 3976: sub in_course {
1.1195 raeburn 3977: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3978: if ($hideprivileged) {
3979: my $skipuser;
1.1219 raeburn 3980: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3981: my @possdoms = ($cdom);
3982: if ($coursehash{'checkforpriv'}) {
3983: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3984: }
3985: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3986: $skipuser = 1;
3987: if ($coursehash{'nothideprivileged'}) {
3988: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3989: my $user;
3990: if ($item =~ /:/) {
3991: $user = $item;
3992: } else {
3993: $user = join(':',split(/[\@]/,$item));
3994: }
3995: if ($user eq $uname.':'.$udom) {
3996: undef($skipuser);
3997: last;
3998: }
3999: }
4000: }
4001: if ($skipuser) {
4002: return 0;
4003: }
4004: }
4005: }
1.1194 raeburn 4006: $type ||= 'any';
4007: if (!defined($cdom) || !defined($cnum)) {
4008: my $cid = $env{'request.course.id'};
4009: $cdom = $env{'course.'.$cid.'.domain'};
4010: $cnum = $env{'course.'.$cid.'.num'};
4011: }
4012: my $typesref;
1.1195 raeburn 4013: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 4014: $typesref = ['active','previous','future'];
4015: } elsif ($type eq 'previous' || $type eq 'future') {
4016: $typesref = [$type];
4017: }
4018: my %roles = &get_my_roles($uname,$udom,'userroles',
4019: $typesref,undef,[$cdom]);
4020: my ($tmp) = keys(%roles);
4021: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
4022: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
4023: if (@course_roles > 0) {
4024: return 1;
4025: }
4026: return 0;
4027: }
4028:
1.478 albertel 4029: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 4030: # input: action, courseID, current domain, intended
1.637 raeburn 4031: # path to file, source of file, instruction to parse file for objects,
4032: # ref to hash for embedded objects,
4033: # ref to hash for codebase of java objects.
1.1095 raeburn 4034: # reference to scalar to accommodate mime type determined
4035: # from File::MMagic if $parser = parse.
1.637 raeburn 4036: #
1.485 raeburn 4037: # output: url to file (if action was uploaddoc),
4038: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 4039: #
1.478 albertel 4040: # Allows directory structure to be used within lonUsers/../userfiles/ for a
4041: # course.
1.477 raeburn 4042: #
1.478 albertel 4043: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
4044: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
4045: # course's home server.
1.477 raeburn 4046: #
1.478 albertel 4047: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
4048: # be copied from $source (current location) to
4049: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
4050: # and will then be copied to
4051: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
4052: # course's home server.
1.485 raeburn 4053: #
1.481 raeburn 4054: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 4055: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 4056: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
4057: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
4058: # in course's home server.
1.637 raeburn 4059: #
1.477 raeburn 4060:
4061: sub process_coursefile {
1.1095 raeburn 4062: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
4063: $mimetype)=@_;
1.477 raeburn 4064: my $fetchresult;
1.638 albertel 4065: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 4066: if ($action eq 'propagate') {
1.638 albertel 4067: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
4068: $home);
1.481 raeburn 4069: } else {
1.477 raeburn 4070: my $fpath = '';
4071: my $fname = $file;
1.478 albertel 4072: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 4073: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 4074: my $filepath = &build_filepath($fpath);
1.481 raeburn 4075: if ($action eq 'copy') {
4076: if ($source eq '') {
4077: $fetchresult = 'no source file';
4078: return $fetchresult;
4079: } else {
4080: my $destination = $filepath.'/'.$fname;
4081: rename($source,$destination);
4082: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4083: $home);
1.481 raeburn 4084: }
4085: } elsif ($action eq 'uploaddoc') {
1.1359 raeburn 4086: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 4087: print $fh $env{'form.'.$source};
1.481 raeburn 4088: close($fh);
1.637 raeburn 4089: if ($parser eq 'parse') {
1.1024 raeburn 4090: my $mm = new File::MMagic;
1.1095 raeburn 4091: my $type = $mm->checktype_filename($filepath.'/'.$fname);
4092: if ($type eq 'text/html') {
1.1024 raeburn 4093: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
4094: unless ($parse_result eq 'ok') {
4095: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
4096: }
1.637 raeburn 4097: }
1.1095 raeburn 4098: if (ref($mimetype)) {
4099: $$mimetype = $type;
4100: }
1.637 raeburn 4101: }
1.477 raeburn 4102: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4103: $home);
1.481 raeburn 4104: if ($fetchresult eq 'ok') {
4105: return '/uploaded/'.$fpath.'/'.$fname;
4106: } else {
4107: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 4108: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 4109: return '/adm/notfound.html';
4110: }
1.477 raeburn 4111: }
4112: }
1.485 raeburn 4113: unless ( $fetchresult eq 'ok') {
1.477 raeburn 4114: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 4115: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 4116: }
4117: return $fetchresult;
4118: }
4119:
1.637 raeburn 4120: sub build_filepath {
4121: my ($fpath) = @_;
4122: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
4123: unless ($fpath eq '') {
4124: my @parts=split('/',$fpath);
4125: foreach my $part (@parts) {
4126: $filepath.= '/'.$part;
4127: if ((-e $filepath)!=1) {
4128: mkdir($filepath,0777);
4129: }
4130: }
4131: }
4132: return $filepath;
4133: }
4134:
4135: sub store_edited_file {
1.638 albertel 4136: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 4137: my $file = $primary_url;
4138: $file =~ s#^/uploaded/$docudom/$docuname/##;
4139: my $fpath = '';
4140: my $fname = $file;
4141: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
4142: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
4143: my $filepath = &build_filepath($fpath);
1.1359 raeburn 4144: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 4145: print $fh $content;
4146: close($fh);
1.638 albertel 4147: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 4148: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4149: $home);
1.637 raeburn 4150: if ($$fetchresult eq 'ok') {
4151: return '/uploaded/'.$fpath.'/'.$fname;
4152: } else {
1.638 albertel 4153: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
4154: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 4155: return '/adm/notfound.html';
4156: }
4157: }
4158:
1.531 albertel 4159: sub clean_filename {
1.831 albertel 4160: my ($fname,$args)=@_;
1.315 www 4161: # Replace Windows backslashes by forward slashes
1.257 www 4162: $fname=~s/\\/\//g;
1.831 albertel 4163: if (!$args->{'keep_path'}) {
4164: # Get rid of everything but the actual filename
4165: $fname=~s/^.*\/([^\/]+)$/$1/;
4166: }
1.315 www 4167: # Replace spaces by underscores
4168: $fname=~s/\s+/\_/g;
1.1406 raeburn 4169: # Transliterate non-ascii text to ascii
4170: my $lang = &Apache::lonlocal::current_language();
4171: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 4172: # Replace all other weird characters by nothing
1.831 albertel 4173: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 4174: # Replace all .\d. sequences with _\d. so they no longer look like version
4175: # numbers
4176: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1443 raeburn 4177: # Replace three or more adjacent underscores with one for consistency
4178: # with loncfile::filename_check() so complete url can be extracted by
4179: # lonnet::decode_symb()
4180: $fname=~s/_{3,}/_/g;
1.531 albertel 4181: return $fname;
4182: }
1.1406 raeburn 4183:
1.1051 raeburn 4184: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
4185: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
4186: # image with the same aspect ratio as the original, but with dimensions which do
4187: # not exceed $resizewidth and $resizeheight.
4188:
1.984 neumanie 4189: sub resizeImage {
1.1051 raeburn 4190: my ($img_path,$resizewidth,$resizeheight) = @_;
4191: my $ima = Image::Magick->new;
4192: my $resized;
4193: if (-e $img_path) {
4194: $ima->Read($img_path);
4195: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
4196: my $width = $ima->Get('width');
4197: my $height = $ima->Get('height');
4198: if ($width > $resizewidth) {
4199: my $factor = $width/$resizewidth;
4200: my $newheight = $height/$factor;
4201: $ima->Scale(width=>$resizewidth,height=>$newheight);
4202: $resized = 1;
4203: }
4204: }
4205: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
4206: my $width = $ima->Get('width');
4207: my $height = $ima->Get('height');
4208: if ($height > $resizeheight) {
4209: my $factor = $height/$resizeheight;
4210: my $newwidth = $width/$factor;
4211: $ima->Scale(width=>$newwidth,height=>$resizeheight);
4212: $resized = 1;
4213: }
4214: }
4215: if ($resized) {
4216: $ima->Write($img_path);
4217: }
4218: }
4219: return;
1.977 amueller 4220: }
4221:
1.608 albertel 4222: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 4223: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 4224: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 4225: # $context - possible values: coursedoc, existingfile, overwrite,
1.1401 raeburn 4226: # canceloverwrite, scantron or ''.
1.1090 raeburn 4227: # if 'coursedoc': upload to the current course
4228: # if 'existingfile': write file to tmp/overwrites directory
4229: # if 'canceloverwrite': delete file written to tmp/overwrites directory
4230: # $context is passed as argument to &finishuserfileupload
1.686 albertel 4231: # $subdir - directory in userfile to store the file into
1.1401 raeburn 4232: # $parser - instruction to parse file for objects ($parser = parse) or
4233: # if context is 'scantron', $parser is hashref of csv column mapping
4234: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
4235: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 4236: # $allfiles - reference to hash for embedded objects
4237: # $codebase - reference to hash for codebase of java objects
4238: # $desuname - username for permanent storage of uploaded file
4239: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 4240: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
4241: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 4242: # $resizewidth - width (pixels) to which to resize uploaded image
4243: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 4244: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 4245: # from File::MMagic.
1.858 raeburn 4246: #
1.686 albertel 4247: # output: url of file in userspace, or error: <message>
4248: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 4249:
1.531 albertel 4250: sub userfileupload {
1.1090 raeburn 4251: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 4252: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 4253: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 4254: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 4255: $fname=&clean_filename($fname);
1.1090 raeburn 4256: # See if there is anything left
1.257 www 4257: unless ($fname) { return 'error: no uploaded file'; }
1.1406 raeburn 4258: # If filename now begins with a . prepend unix timestamp _ milliseconds
4259: if ($fname =~ /^\./) {
4260: my ($s,$usec) = &gettimeofday();
4261: while (length($usec) < 6) {
4262: $usec = '0'.$usec;
4263: }
4264: $fname = $s.'_'.substr($usec,0,3).$fname;
4265: }
1.1090 raeburn 4266: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
4267: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
4268: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
4269: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 4270: my $now = time;
1.1090 raeburn 4271: my $filepath;
1.1095 raeburn 4272: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 4273: $filepath = 'tmp/helprequests/'.$now;
4274: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
4275: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
4276: '_'.$env{'user.domain'}.'/pending';
4277: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
4278: my ($docuname,$docudom);
1.1350 raeburn 4279: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 4280: $docudom = $destudom;
4281: } else {
4282: $docudom = $env{'user.domain'};
4283: }
1.1350 raeburn 4284: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 4285: $docuname = $destuname;
4286: } else {
4287: $docuname = $env{'user.name'};
4288: }
4289: if (exists($env{'form.group'})) {
4290: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4291: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4292: }
4293: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
4294: if ($context eq 'canceloverwrite') {
4295: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
4296: if (-e $tempfile) {
4297: my @info = stat($tempfile);
4298: if ($info[9] eq $env{'form.timestamp'}) {
4299: unlink($tempfile);
4300: }
4301: }
4302: return;
1.523 raeburn 4303: }
4304: }
1.1090 raeburn 4305: # Create the directory if not present
1.741 raeburn 4306: my @parts=split(/\//,$filepath);
4307: my $fullpath = $perlvar{'lonDaemons'};
4308: for (my $i=0;$i<@parts;$i++) {
4309: $fullpath .= '/'.$parts[$i];
4310: if ((-e $fullpath)!=1) {
4311: mkdir($fullpath,0777);
4312: }
4313: }
1.1359 raeburn 4314: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 4315: print $fh $env{'form.'.$formname};
4316: close($fh);
1.1090 raeburn 4317: if ($context eq 'existingfile') {
4318: my @info = stat($fullpath.'/'.$fname);
4319: return ($fullpath.'/'.$fname,$info[9]);
4320: } else {
4321: return $fullpath.'/'.$fname;
4322: }
1.523 raeburn 4323: }
1.995 raeburn 4324: if ($subdir eq 'scantron') {
4325: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 4326: } else {
1.995 raeburn 4327: $fname="$subdir/$fname";
4328: }
1.1090 raeburn 4329: if ($context eq 'coursedoc') {
1.638 albertel 4330: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4331: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 4332: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 4333: return &finishuserfileupload($docuname,$docudom,
4334: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 4335: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 4336: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 4337: } else {
1.1218 raeburn 4338: if ($env{'form.folder'}) {
4339: $fname=$env{'form.folder'}.'/'.$fname;
4340: }
1.638 albertel 4341: return &process_coursefile('uploaddoc',$docuname,$docudom,
4342: $fname,$formname,$parser,
1.1095 raeburn 4343: $allfiles,$codebase,$mimetype);
1.481 raeburn 4344: }
1.719 banghart 4345: } elsif (defined($destuname)) {
4346: my $docuname=$destuname;
4347: my $docudom=$destudom;
1.860 raeburn 4348: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4349: $parser,$allfiles,$codebase,
1.1051 raeburn 4350: $thumbwidth,$thumbheight,
1.1095 raeburn 4351: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4352: } else {
1.638 albertel 4353: my $docuname=$env{'user.name'};
4354: my $docudom=$env{'user.domain'};
1.1220 raeburn 4355: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 4356: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4357: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4358: }
1.860 raeburn 4359: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4360: $parser,$allfiles,$codebase,
1.1051 raeburn 4361: $thumbwidth,$thumbheight,
1.1095 raeburn 4362: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4363: }
1.271 www 4364: }
4365:
4366: sub finishuserfileupload {
1.860 raeburn 4367: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 4368: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 4369: my $path=$docudom.'/'.$docuname.'/';
1.258 www 4370: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 4371:
1.860 raeburn 4372: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 4373: $file=$fname;
4374: if ($fname=~m|/|) {
4375: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
4376: $path.=$fnamepath.'/';
4377: }
1.259 www 4378: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 4379: my $count;
4380: for ($count=4;$count<=$#parts;$count++) {
4381: $filepath.="/$parts[$count]";
4382: if ((-e $filepath)!=1) {
4383: mkdir($filepath,0777);
4384: }
4385: }
1.984 neumanie 4386:
1.258 www 4387: # Save the file
4388: {
1.1359 raeburn 4389: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 4390: &logthis('Failed to create '.$filepath.'/'.$file);
4391: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
4392: return '/adm/notfound.html';
4393: }
1.1090 raeburn 4394: if ($context eq 'overwrite') {
1.1117 foxr 4395: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 4396: my $target = $filepath.'/'.$file;
4397: if (-e $source) {
4398: my @info = stat($source);
4399: if ($info[9] eq $env{'form.timestamp'}) {
4400: unless (&File::Copy::move($source,$target)) {
4401: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4402: return "Moving from $source failed";
4403: }
4404: } else {
4405: return "Temporary file: $source had unexpected date/time for last modification";
4406: }
4407: } else {
4408: return "Temporary file: $source missing";
4409: }
4410: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 4411: &logthis('Failed to write to '.$filepath.'/'.$file);
4412: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4413: return '/adm/notfound.html';
4414: }
1.570 albertel 4415: close(FH);
1.1051 raeburn 4416: if ($resizewidth && $resizeheight) {
4417: my $mm = new File::MMagic;
4418: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4419: if ($mime_type =~ m{^image/}) {
4420: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4421: }
1.977 amueller 4422: }
1.258 www 4423: }
1.1152 raeburn 4424: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4425: if (ref($mimetype)) {
4426: if ($$mimetype eq '') {
4427: my $mm = new File::MMagic;
4428: my $type = $mm->checktype_filename($filepath.'/'.$file);
4429: $$mimetype = $type;
4430: }
4431: }
4432: }
1.1401 raeburn 4433: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 4434: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 4435: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4436: $allfiles,$codebase);
4437: unless ($parse_result eq 'ok') {
4438: &logthis('Failed to parse '.$filepath.$file.
4439: ' for embedded media: '.$parse_result);
4440: }
1.637 raeburn 4441: }
1.1401 raeburn 4442: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4443: my $format = $env{'form.scantron_format'};
4444: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 4445: }
1.860 raeburn 4446: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4447: my $input = $filepath.'/'.$file;
4448: my $output = $filepath.'/'.'tn-'.$file;
4449: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359 raeburn 4450: my @args = ('convert','-sample',$thumbsize,$input,$output);
4451: system({$args[0]} @args);
1.860 raeburn 4452: if (-e $filepath.'/'.'tn-'.$file) {
4453: $fetchthumb = 1;
4454: }
4455: }
1.858 raeburn 4456:
1.259 www 4457: # Notify homeserver to grep it
4458: #
1.984 neumanie 4459: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 4460: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 4461: if ($fetchresult eq 'ok') {
1.860 raeburn 4462: if ($fetchthumb) {
4463: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4464: if ($thumbresult ne 'ok') {
4465: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4466: $docuhome.': '.$thumbresult);
4467: }
4468: }
1.259 www 4469: #
1.258 www 4470: # Return the URL to it
1.494 albertel 4471: return '/uploaded/'.$path.$file;
1.263 www 4472: } else {
1.494 albertel 4473: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4474: ': '.$fetchresult);
1.263 www 4475: return '/adm/notfound.html';
1.858 raeburn 4476: }
1.493 albertel 4477: }
4478:
1.637 raeburn 4479: sub extract_embedded_items {
1.961 raeburn 4480: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4481: my @state = ();
1.1164 raeburn 4482: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4483: my %javafiles = (
4484: codebase => '',
4485: code => '',
4486: archive => ''
4487: );
4488: my %mediafiles = (
4489: src => '',
4490: movie => '',
4491: );
1.648 raeburn 4492: my $p;
4493: if ($content) {
4494: $p = HTML::LCParser->new($content);
4495: } else {
1.961 raeburn 4496: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4497: }
1.641 albertel 4498: while (my $t=$p->get_token()) {
1.640 albertel 4499: if ($t->[0] eq 'S') {
4500: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4501: push(@state, $tagname);
1.648 raeburn 4502: if (lc($tagname) eq 'allow') {
4503: &add_filetype($allfiles,$attr->{'src'},'src');
4504: }
1.640 albertel 4505: if (lc($tagname) eq 'img') {
4506: &add_filetype($allfiles,$attr->{'src'},'src');
4507: }
1.886 albertel 4508: if (lc($tagname) eq 'a') {
1.1222 raeburn 4509: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 4510: &add_filetype($allfiles,$attr->{'href'},'href');
4511: }
1.886 albertel 4512: }
1.645 raeburn 4513: if (lc($tagname) eq 'script') {
1.1164 raeburn 4514: my $src;
1.645 raeburn 4515: if ($attr->{'archive'} =~ /\.jar$/i) {
4516: &add_filetype($allfiles,$attr->{'archive'},'archive');
4517: } else {
1.1164 raeburn 4518: if ($attr->{'src'} ne '') {
4519: $src = $attr->{'src'};
4520: &add_filetype($allfiles,$src,'src');
4521: }
4522: }
4523: my $text = $p->get_trimmed_text();
4524: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4525: my @swfargs = split(/,/,$1);
4526: foreach my $item (@swfargs) {
4527: $item =~ s/["']//g;
4528: $item =~ s/^\s+//;
4529: $item =~ s/\s+$//;
4530: }
4531: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4532: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4533: push(@{$related{$swfargs[0]}},$swfargs[2]);
4534: } else {
4535: $related{$swfargs[0]} = [$swfargs[2]];
4536: }
4537: }
1.645 raeburn 4538: }
4539: }
4540: if (lc($tagname) eq 'link') {
4541: if (lc($attr->{'rel'}) eq 'stylesheet') {
4542: &add_filetype($allfiles,$attr->{'href'},'href');
4543: }
4544: }
1.640 albertel 4545: if (lc($tagname) eq 'object' ||
4546: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4547: foreach my $item (keys(%javafiles)) {
4548: $javafiles{$item} = '';
4549: }
1.1164 raeburn 4550: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4551: $lastids{lc($tagname)} = $attr->{'id'};
4552: }
1.640 albertel 4553: }
4554: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4555: my $name = lc($attr->{'name'});
4556: foreach my $item (keys(%javafiles)) {
4557: if ($name eq $item) {
4558: $javafiles{$item} = $attr->{'value'};
4559: last;
4560: }
4561: }
1.1164 raeburn 4562: my $pathfrom;
1.640 albertel 4563: foreach my $item (keys(%mediafiles)) {
4564: if ($name eq $item) {
1.1164 raeburn 4565: $pathfrom = $attr->{'value'};
4566: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4567: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4568: last;
4569: }
4570: }
1.1164 raeburn 4571: if ($name eq 'flashvars') {
4572: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4573: }
4574: if ($pathfrom ne '') {
4575: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4576: $pathfrom);
4577: }
1.640 albertel 4578: }
4579: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4580: foreach my $item (keys(%javafiles)) {
4581: if ($attr->{$item}) {
4582: $javafiles{$item} = $attr->{$item};
4583: last;
4584: }
4585: }
4586: foreach my $item (keys(%mediafiles)) {
4587: if ($attr->{$item}) {
4588: &add_filetype($allfiles,$attr->{$item},$item);
4589: last;
4590: }
4591: }
1.1164 raeburn 4592: if (lc($tagname) eq 'embed') {
4593: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4594: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4595: $attr->{'src'});
4596: }
4597: }
1.640 albertel 4598: }
1.1243 raeburn 4599: if (lc($tagname) eq 'iframe') {
4600: my $src = $attr->{'src'} ;
4601: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4602: &add_filetype($allfiles,$src,'src');
4603: } elsif ($src =~ m{^/}) {
4604: if ($env{'request.course.id'}) {
4605: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4606: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4607: my $url = &hreflocation('',$fullpath);
4608: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4609: my $relpath = $1;
4610: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4611: &add_filetype($allfiles,$1,'src');
4612: }
4613: }
4614: }
4615: }
4616: }
1.1164 raeburn 4617: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 4618: pop(@state);
1.1164 raeburn 4619: }
1.640 albertel 4620: } elsif ($t->[0] eq 'E') {
4621: my ($tagname) = ($t->[1]);
4622: if ($javafiles{'codebase'} ne '') {
4623: $javafiles{'codebase'} .= '/';
4624: }
4625: if (lc($tagname) eq 'applet' ||
4626: lc($tagname) eq 'object' ||
4627: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4628: ) {
4629: foreach my $item (keys(%javafiles)) {
4630: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4631: my $file=$javafiles{'codebase'}.$javafiles{$item};
4632: &add_filetype($allfiles,$file,$item);
4633: }
4634: }
4635: }
4636: pop @state;
4637: }
4638: }
1.1164 raeburn 4639: foreach my $id (sort(keys(%flashvars))) {
4640: if ($shockwave{$id} ne '') {
4641: my @pairs = split(/\&/,$flashvars{$id});
4642: foreach my $pair (@pairs) {
4643: my ($key,$value) = split(/\=/,$pair);
4644: if ($key eq 'thumb') {
4645: &add_filetype($allfiles,$value,$key);
4646: } elsif ($key eq 'content') {
4647: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4648: my ($ext) = ($value =~ /\.([^.]+)$/);
4649: if ($ext ne '') {
4650: &add_filetype($allfiles,$path.$value,$ext);
4651: }
4652: }
4653: }
4654: }
4655: }
1.637 raeburn 4656: return 'ok';
4657: }
4658:
1.639 albertel 4659: sub add_filetype {
4660: my ($allfiles,$file,$type)=@_;
4661: if (exists($allfiles->{$file})) {
4662: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4663: push(@{$allfiles->{$file}}, &escape($type));
4664: }
4665: } else {
4666: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4667: }
4668: }
4669:
1.1164 raeburn 4670: sub embedded_dependency {
4671: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4672: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4673: if (($identifier ne '') &&
4674: (ref($related->{$identifier}) eq 'ARRAY') &&
4675: ($pathfrom ne '')) {
4676: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4677: foreach my $dep (@{$related->{$identifier}}) {
4678: &add_filetype($allfiles,$path.$dep,'object');
4679: }
4680: }
4681: }
4682: return;
4683: }
4684:
1.1401 raeburn 4685: sub bubblesheet_converter {
4686: my ($cdom,$fullpath,$config,$format) = @_;
4687: if ((&domain($cdom) ne '') &&
1.1403 raeburn 4688: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401 raeburn 4689: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404 raeburn 4690: my (%csvcols,%csvoptions);
4691: if (ref($config->{'fields'}) eq 'HASH') {
4692: %csvcols = %{$config->{'fields'}};
4693: }
4694: if (ref($config->{'options'}) eq 'HASH') {
4695: %csvoptions = %{$config->{'options'}};
4696: }
1.1401 raeburn 4697: my %csvbynum = reverse(%csvcols);
4698: my %scantronconf = &get_scantron_config($format,$cdom);
4699: if (keys(%scantronconf)) {
4700: my %bynum = (
4701: $scantronconf{CODEstart} => 'CODEstart',
4702: $scantronconf{IDstart} => 'IDstart',
4703: $scantronconf{PaperID} => 'PaperID',
4704: $scantronconf{FirstName} => 'FirstName',
4705: $scantronconf{LastName} => 'LastName',
4706: $scantronconf{Qstart} => 'Qstart',
4707: );
4708: my @ordered;
4709: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403 raeburn 4710: push(@ordered,$bynum{$item});
1.1401 raeburn 4711: }
4712: my %mapstart = (
4713: CODEstart => 'CODE',
4714: IDstart => 'ID',
4715: PaperID => 'PaperID',
4716: FirstName => 'FirstName',
4717: LastName => 'LastName',
4718: Qstart => 'FirstQuestion',
4719: );
4720: my %maplength = (
4721: CODEstart => 'CODElength',
4722: IDstart => 'IDlength',
4723: PaperID => 'PaperIDlength',
4724: FirstName => 'FirstNamelength',
4725: LastName => 'LastNamelength',
4726: );
4727: if (open(my $fh,'<',$fullpath)) {
4728: my $output;
1.1403 raeburn 4729: my %lettdig = &letter_to_digits();
4730: my %diglett = reverse(%lettdig);
4731: my $numletts = scalar(keys(%lettdig));
1.1404 raeburn 4732: my $num = 0;
1.1401 raeburn 4733: while (my $line=<$fh>) {
1.1404 raeburn 4734: $num ++;
4735: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401 raeburn 4736: $line =~ s{[\r\n]+$}{};
4737: my %found;
1.1475 raeburn 4738: my @values = split(/,/,$line,-1);
1.1401 raeburn 4739: my ($qstart,$record);
4740: for (my $i=0; $i<@values; $i++) {
1.1403 raeburn 4741: if ((($qstart ne '') && ($i > $qstart)) ||
4742: ($csvbynum{$i} eq 'FirstQuestion')) {
4743: if ($values[$i] eq '') {
4744: $values[$i] = $scantronconf{'Qoff'};
4745: } elsif ($scantronconf{'Qon'} eq 'number') {
4746: if ($values[$i] =~ /^[A-Ja-j]$/) {
4747: $values[$i] = $lettdig{uc($values[$i])};
4748: }
4749: } elsif ($scantronconf{'Qon'} eq 'letter') {
4750: if ($values[$i] =~ /^[0-9]$/) {
4751: $values[$i] = $diglett{$values[$i]};
4752: }
4753: } else {
4754: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4755: my $digit;
4756: if ($values[$i] =~ /^[A-Ja-j]$/) {
4757: $digit = $lettdig{uc($values[$i])}-1;
4758: if ($values[$i] eq 'J') {
4759: $digit += $numletts;
4760: }
4761: } elsif ($values[$i] =~ /^[0-9]$/) {
4762: $digit = $values[$i]-1;
4763: if ($values[$i] eq '0') {
4764: $digit += $numletts;
4765: }
4766: }
4767: my $qval='';
4768: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4769: if ($j == $digit) {
4770: $qval .= $scantronconf{'Qon'};
4771: } else {
4772: $qval .= $scantronconf{'Qoff'};
4773: }
4774: }
4775: $values[$i] = $qval;
4776: }
4777: }
4778: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4779: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4780: }
4781: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4782: if ($numblank > 0) {
4783: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4784: }
1.1401 raeburn 4785: if ($csvbynum{$i} eq 'FirstQuestion') {
4786: $qstart = $i;
1.1403 raeburn 4787: $found{$csvbynum{$i}} = $values[$i];
1.1401 raeburn 4788: } else {
1.1403 raeburn 4789: $found{'FirstQuestion'} .= $values[$i];
4790: }
4791: } elsif (exists($csvbynum{$i})) {
1.1404 raeburn 4792: if ($csvoptions{'rem'}) {
4793: $values[$i] =~ s/^\s+//;
4794: }
4795: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403 raeburn 4796: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4797: $values[$i] = '0'.$values[$i];
1.1401 raeburn 4798: }
4799: }
4800: $found{$csvbynum{$i}} = $values[$i];
4801: }
4802: }
4803: foreach my $item (@ordered) {
4804: my $currlength = 1+length($record);
4805: my $numspaces = $scantronconf{$item} - $currlength;
4806: if ($numspaces > 0) {
4807: $record .= (' ' x $numspaces);
4808: }
4809: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4810: unless ($item eq 'Qstart') {
4811: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4812: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4813: }
4814: }
4815: $record .= $found{$mapstart{$item}};
4816: }
4817: }
4818: $output .= "$record\n";
4819: }
4820: close($fh);
4821: if ($output) {
4822: if (open(my $fh,'>',$fullpath)) {
4823: print $fh $output;
4824: close($fh);
4825: }
4826: }
4827: }
4828: }
4829: return;
4830: }
4831: }
4832:
1.1403 raeburn 4833: sub letter_to_digits {
4834: my %lettdig = (
4835: A => 1,
4836: B => 2,
4837: C => 3,
4838: D => 4,
4839: E => 5,
4840: F => 6,
4841: G => 7,
4842: H => 8,
4843: I => 9,
4844: J => 0,
4845: );
4846: return %lettdig;
4847: }
4848:
1.1401 raeburn 4849: sub get_scantron_config {
4850: my ($which,$cdom) = @_;
4851: my @lines = &get_scantronformat_file($cdom);
4852: my %config;
4853: #FIXME probably should move to XML it has already gotten a bit much now
4854: foreach my $line (@lines) {
4855: my ($name,$descrip)=split(/:/,$line);
4856: if ($name ne $which ) { next; }
4857: chomp($line);
4858: my @config=split(/:/,$line);
4859: $config{'name'}=$config[0];
4860: $config{'description'}=$config[1];
4861: $config{'CODElocation'}=$config[2];
4862: $config{'CODEstart'}=$config[3];
4863: $config{'CODElength'}=$config[4];
4864: $config{'IDstart'}=$config[5];
4865: $config{'IDlength'}=$config[6];
4866: $config{'Qstart'}=$config[7];
4867: $config{'Qlength'}=$config[8];
4868: $config{'Qoff'}=$config[9];
4869: $config{'Qon'}=$config[10];
4870: $config{'PaperID'}=$config[11];
4871: $config{'PaperIDlength'}=$config[12];
4872: $config{'FirstName'}=$config[13];
4873: $config{'FirstNamelength'}=$config[14];
4874: $config{'LastName'}=$config[15];
4875: $config{'LastNamelength'}=$config[16];
4876: $config{'BubblesPerRow'}=$config[17];
4877: last;
4878: }
4879: return %config;
4880: }
4881:
4882: sub get_scantronformat_file {
4883: my ($cdom) = @_;
4884: if ($cdom eq '') {
4885: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4886: }
4887: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4888: my $gottab = 0;
4889: my @lines;
4890: if (ref($domconfig{'scantron'}) eq 'HASH') {
4891: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4892: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4893: if ($formatfile ne '-1') {
4894: @lines = split("\n",$formatfile,-1);
4895: $gottab = 1;
4896: }
4897: }
4898: }
4899: if (!$gottab) {
4900: my $confname = $cdom.'-domainconfig';
4901: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4902: my $formatfile = &getfile($default);
4903: if ($formatfile ne '-1') {
4904: @lines = split("\n",$formatfile,-1);
4905: $gottab = 1;
4906: }
4907: }
4908: if (!$gottab) {
4909: my @domains = ¤t_machine_domains();
4910: if (grep(/^\Q$cdom\E$/,@domains)) {
4911: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4912: @lines = <$fh>;
4913: close($fh);
1.1403 raeburn 4914: }
1.1401 raeburn 4915: } else {
4916: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4917: @lines = <$fh>;
4918: close($fh);
4919: }
4920: }
4921: }
4922: return @lines;
4923: }
4924:
1.493 albertel 4925: sub removeuploadedurl {
1.984 neumanie 4926: my ($url)=@_;
4927: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4928: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4929: }
4930:
4931: sub removeuserfile {
4932: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4933: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4934: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4935: if ($result eq 'ok') {
1.798 raeburn 4936: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4937: my $metafile = $fname.'.meta';
4938: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4939: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4940: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4941: my $sqlresult =
1.823 albertel 4942: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4943: 'portfolio_metadata',$group,
4944: 'delete');
1.798 raeburn 4945: }
4946: }
4947: return $result;
1.257 www 4948: }
1.15 www 4949:
1.530 albertel 4950: sub mkdiruserfile {
4951: my ($docuname,$docudom,$dir)=@_;
4952: my $home=&homeserver($docuname,$docudom);
4953: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4954: }
4955:
1.531 albertel 4956: sub renameuserfile {
4957: my ($docuname,$docudom,$old,$new)=@_;
4958: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4959: my $result = &reply("renameuserfile:$docudom:$docuname:".
4960: &escape("$old").':'.&escape("$new"),$home);
4961: if ($result eq 'ok') {
4962: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4963: my $oldmeta = $old.'.meta';
4964: my $newmeta = $new.'.meta';
4965: my $metaresult =
4966: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4967: my $url = "/uploaded/$docudom/$docuname/$old";
4968: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4969: my $sqlresult =
1.823 albertel 4970: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4971: 'portfolio_metadata',$group,
4972: 'delete');
1.798 raeburn 4973: }
4974: }
4975: return $result;
1.531 albertel 4976: }
4977:
1.14 www 4978: # ------------------------------------------------------------------------- Log
4979:
4980: sub log {
4981: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4982: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4983: }
4984:
4985: # ------------------------------------------------------------------ Course Log
1.352 www 4986: #
4987: # This routine flushes several buffers of non-mission-critical nature
4988: #
1.157 www 4989:
4990: sub flushcourselogs {
1.352 www 4991: &logthis('Flushing log buffers');
4992: #
4993: # course logs
4994: # This is a log of all transactions in a course, which can be used
4995: # for data mining purposes
4996: #
4997: # It also collects the courseid database, which lists last transaction
4998: # times and course titles for all courseids
4999: #
5000: my %courseidbuffer=();
1.921 raeburn 5001: foreach my $crsid (keys(%courselogs)) {
1.352 www 5002: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 5003: &escape($courselogs{$crsid}),
5004: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 5005: delete $courselogs{$crsid};
5006: } else {
5007: &logthis('Failed to flush log buffer for '.$crsid);
5008: if (length($courselogs{$crsid})>40000) {
1.672 albertel 5009: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 5010: " exceeded maximum size, deleting.</font>");
5011: delete $courselogs{$crsid};
5012: }
1.352 www 5013: }
1.920 raeburn 5014: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 5015: 'description' => $coursedescrbuf{$crsid},
5016: 'inst_code' => $courseinstcodebuf{$crsid},
5017: 'type' => $coursetypebuf{$crsid},
5018: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 5019: };
1.191 harris41 5020: }
1.352 www 5021: #
5022: # Write course id database (reverse lookup) to homeserver of courses
5023: # Is used in pickcourse
5024: #
1.840 albertel 5025: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 5026: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 5027: $courseidbuffer{$crs_home},
5028: $crs_home,'timeonly');
1.352 www 5029: }
5030: #
5031: # File accesses
5032: # Writes to the dynamic metadata of resources to get hit counts, etc.
5033: #
1.449 matthew 5034: foreach my $entry (keys(%accesshash)) {
1.458 matthew 5035: if ($entry =~ /___count$/) {
5036: my ($dom,$name);
1.807 albertel 5037: ($dom,$name,undef)=
1.811 albertel 5038: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 5039: if (! defined($dom) || $dom eq '' ||
5040: ! defined($name) || $name eq '') {
1.620 albertel 5041: my $cid = $env{'request.course.id'};
1.1472 raeburn 5042: #
5043: # FIXME 11/29/2021
5044: # Typo in rev. 1.458 (2003/12/09)??
5045: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
5046: #
5047: # While these ramain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
5048: # $dom and $name will always be null, so the &inc() call will default to storing this data
5049: # in a nohist_accesscount.db file for the user rather than the course.
5050: #
5051: # That said there is a lot of noise in the data being stored.
5052: # So counts for prtspool/ and adm/ etc. are recorded.
5053: #
5054: # A review of which items ending '___count' are written to %accesshash should likely be
5055: # made before deciding whether to set these to 'course.' instead of 'request.'
5056: #
5057: # Under the current scheme each user receives a nohist_accesscount.db file listing
5058: # accesses for things which are not published resources, regardless of course, and
5059: # there is not a nohist_accesscount.db file in a course, which might log accesses from
5060: # anyone in the course for things which are not published resources.
5061: #
5062: # For an author, nohist_accesscount.db ends up having records for other items
5063: # mixed up with the legitimate access counts for the author's published resources.
5064: #
1.620 albertel 5065: $dom = $env{'request.'.$cid.'.domain'};
5066: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 5067: }
1.450 matthew 5068: my $value = $accesshash{$entry};
5069: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
5070: my %temphash=($url => $value);
1.449 matthew 5071: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
5072: if ($result eq 'ok') {
5073: delete $accesshash{$entry};
5074: }
5075: } else {
1.811 albertel 5076: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 5077: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 5078: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 5079: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
5080: delete $accesshash{$entry};
5081: }
1.185 www 5082: }
1.191 harris41 5083: }
1.352 www 5084: #
5085: # Roles
5086: # Reverse lookup of user roles for course faculty/staff and co-authorship
5087: #
1.800 albertel 5088: foreach my $entry (keys(%userrolehash)) {
1.351 www 5089: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 5090: split(/\:/,$entry);
5091: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 5092: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 5093: $rudom,$runame) eq 'ok') {
5094: delete $userrolehash{$entry};
5095: }
5096: }
1.662 raeburn 5097: #
1.1334 raeburn 5098: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 5099: #
5100: my %domrolebuffer = ();
1.1000 raeburn 5101: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 5102: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 5103: if ($domrolebuffer{$rudom}) {
5104: $domrolebuffer{$rudom}.='&'.&escape($entry).
5105: '='.&escape($domainrolehash{$entry});
5106: } else {
5107: $domrolebuffer{$rudom}.=&escape($entry).
5108: '='.&escape($domainrolehash{$entry});
5109: }
5110: delete $domainrolehash{$entry};
5111: }
5112: foreach my $dom (keys(%domrolebuffer)) {
1.1324 raeburn 5113: my %servers;
5114: if (defined(&domain($dom,'primary'))) {
5115: my $primary=&domain($dom,'primary');
5116: my $hostname=&hostname($primary);
5117: $servers{$primary} = $hostname;
5118: } else {
5119: %servers = &get_servers($dom,'library');
5120: }
1.841 albertel 5121: foreach my $tryserver (keys(%servers)) {
1.1324 raeburn 5122: if (&reply('domroleput:'.$dom.':'.
5123: $domrolebuffer{$dom},$tryserver) eq 'ok') {
5124: last;
5125: } else {
1.841 albertel 5126: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
5127: }
1.662 raeburn 5128: }
5129: }
1.186 www 5130: $dumpcount++;
1.157 www 5131: }
5132:
5133: sub courselog {
5134: my $what=shift;
1.158 www 5135: $what=time.':'.$what;
1.620 albertel 5136: unless ($env{'request.course.id'}) { return ''; }
5137: $coursedombuf{$env{'request.course.id'}}=
5138: $env{'course.'.$env{'request.course.id'}.'.domain'};
5139: $coursenumbuf{$env{'request.course.id'}}=
5140: $env{'course.'.$env{'request.course.id'}.'.num'};
5141: $coursehombuf{$env{'request.course.id'}}=
5142: $env{'course.'.$env{'request.course.id'}.'.home'};
5143: $coursedescrbuf{$env{'request.course.id'}}=
5144: $env{'course.'.$env{'request.course.id'}.'.description'};
5145: $courseinstcodebuf{$env{'request.course.id'}}=
5146: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
5147: $courseownerbuf{$env{'request.course.id'}}=
5148: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 5149: $coursetypebuf{$env{'request.course.id'}}=
5150: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 5151: if (defined $courselogs{$env{'request.course.id'}}) {
5152: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 5153: } else {
1.620 albertel 5154: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 5155: }
1.620 albertel 5156: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 5157: &flushcourselogs();
5158: }
1.158 www 5159: }
5160:
5161: sub courseacclog {
5162: my $fnsymb=shift;
1.620 albertel 5163: unless ($env{'request.course.id'}) { return ''; }
5164: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 5165: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 5166: $what.=':POST';
1.583 matthew 5167: # FIXME: Probably ought to escape things....
1.800 albertel 5168: foreach my $key (keys(%env)) {
5169: if ($key=~/^form\.(.*)/) {
1.975 raeburn 5170: my $formitem = $1;
5171: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
5172: $what.=':'.$formitem.'='.$env{$key};
5173: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1432 raeburn 5174: if ($formitem eq 'proctorpassword') {
1.1433 raeburn 5175: $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1432 raeburn 5176: } else {
5177: $what.=':'.$formitem.'='.$env{$key};
5178: }
1.975 raeburn 5179: }
1.158 www 5180: }
1.191 harris41 5181: }
1.583 matthew 5182: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
5183: # FIXME: We should not be depending on a form parameter that someone
5184: # editing lonsearchcat.pm might change in the future.
1.620 albertel 5185: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 5186: $what.= ':POST';
5187: # FIXME: Probably ought to escape things....
5188: foreach my $element ('courseexp','crsfulltext','crsrelated',
5189: 'crsdiscuss') {
1.620 albertel 5190: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 5191: }
5192: }
1.158 www 5193: }
5194: &courselog($what);
1.149 www 5195: }
5196:
1.185 www 5197: sub countacc {
5198: my $url=&declutter(shift);
1.458 matthew 5199: return if (! defined($url) || $url eq '');
1.620 albertel 5200: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 5201: #
5202: # Mark that this url was used in this course
5203: #
1.620 albertel 5204: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 5205: #
5206: # Increase the access count for this resource in this child process
5207: #
1.281 www 5208: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 5209: $accesshash{$key}++;
1.185 www 5210: }
1.349 www 5211:
1.361 www 5212: sub linklog {
5213: my ($from,$to)=@_;
5214: $from=&declutter($from);
5215: $to=&declutter($to);
5216: $accesshash{$from.'___'.$to.'___comefrom'}=1;
5217: $accesshash{$to.'___'.$from.'___goto'}=1;
5218: }
1.1160 www 5219:
5220: sub statslog {
5221: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
5222: if ($users<2) { return; }
5223: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
5224: 'course' => $env{'request.course.id'},
5225: 'sections' => '"all"',
5226: 'num_students' => $users,
5227: 'part' => $part,
5228: 'symb' => $symb,
5229: 'mean_tries' => $av_attempts,
5230: 'deg_of_diff' => $degdiff});
5231: foreach my $key (keys(%dynstore)) {
5232: $accesshash{$key}=$dynstore{$key};
5233: }
5234: }
1.361 www 5235:
1.349 www 5236: sub userrolelog {
5237: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 5238: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 5239: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5240: $userrolehash
5241: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 5242: =$tend.':'.$tstart;
1.662 raeburn 5243: }
1.1169 droeschl 5244: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 5245: $userrolehash
5246: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
5247: =$tend.':'.$tstart;
5248: }
1.1334 raeburn 5249: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 5250: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5251: $domainrolehash
5252: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
5253: = $tend.':'.$tstart;
5254: }
1.351 www 5255: }
5256:
1.957 raeburn 5257: sub courserolelog {
5258: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 5259: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
5260: my $cdom = $1;
5261: my $cnum = $2;
5262: my $sec = $3;
5263: my $namespace = 'rolelog';
5264: my %storehash = (
5265: role => $trole,
5266: start => $tstart,
5267: end => $tend,
5268: selfenroll => $selfenroll,
5269: context => $context,
5270: );
5271: if ($trole eq 'gr') {
5272: $namespace = 'groupslog';
5273: $storehash{'group'} = $sec;
5274: } else {
5275: $storehash{'section'} = $sec;
5276: }
1.1188 raeburn 5277: &write_log('course',$namespace,\%storehash,$delflag,$username,
5278: $domain,$cnum,$cdom);
1.1184 raeburn 5279: if (($trole ne 'st') || ($sec ne '')) {
5280: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 5281: }
5282: }
5283: return;
5284: }
5285:
1.1184 raeburn 5286: sub domainrolelog {
5287: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5288: if ($area =~ m{^/($match_domain)/$}) {
5289: my $cdom = $1;
5290: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
5291: my $namespace = 'rolelog';
5292: my %storehash = (
5293: role => $trole,
5294: start => $tstart,
5295: end => $tend,
5296: context => $context,
5297: );
1.1188 raeburn 5298: &write_log('domain',$namespace,\%storehash,$delflag,$username,
5299: $domain,$domconfiguser,$cdom);
1.1184 raeburn 5300: }
5301: return;
5302:
5303: }
5304:
5305: sub coauthorrolelog {
5306: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5307: if ($area =~ m{^/($match_domain)/($match_username)$}) {
5308: my $audom = $1;
5309: my $auname = $2;
5310: my $namespace = 'rolelog';
5311: my %storehash = (
5312: role => $trole,
5313: start => $tstart,
5314: end => $tend,
5315: context => $context,
5316: );
1.1188 raeburn 5317: &write_log('author',$namespace,\%storehash,$delflag,$username,
5318: $domain,$auname,$audom);
1.1184 raeburn 5319: }
5320: return;
5321: }
5322:
1.351 www 5323: sub get_course_adv_roles {
1.948 raeburn 5324: my ($cid,$codes) = @_;
1.620 albertel 5325: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 5326: my %coursehash=&coursedescription($cid);
1.988 raeburn 5327: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 5328: my %nothide=();
1.800 albertel 5329: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 5330: if ($user !~ /:/) {
5331: $nothide{join(':',split(/[\@]/,$user))}=1;
5332: } else {
5333: $nothide{$user}=1;
5334: }
1.470 www 5335: }
1.1219 raeburn 5336: my @possdoms = ($coursehash{'domain'});
5337: if ($coursehash{'checkforpriv'}) {
5338: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
5339: }
1.351 www 5340: my %returnhash=();
5341: my %dumphash=
5342: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
5343: my $now=time;
1.997 raeburn 5344: my %privileged;
1.1000 raeburn 5345: foreach my $entry (keys(%dumphash)) {
1.800 albertel 5346: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 5347: if (($tstart) && ($tstart<0)) { next; }
5348: if (($tend) && ($tend<$now)) { next; }
5349: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 5350: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 5351: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 5352: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 5353: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 5354: if ($role eq 'cr') { next; }
1.948 raeburn 5355: if ($codes) {
5356: if ($section) { $role .= ':'.$section; }
5357: if ($returnhash{$role}) {
5358: $returnhash{$role}.=','.$username.':'.$domain;
5359: } else {
5360: $returnhash{$role}=$username.':'.$domain;
5361: }
1.351 www 5362: } else {
1.988 raeburn 5363: my $key=&plaintext($role,$crstype);
1.973 bisitz 5364: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 5365: if ($returnhash{$key}) {
5366: $returnhash{$key}.=','.$username.':'.$domain;
5367: } else {
5368: $returnhash{$key}=$username.':'.$domain;
5369: }
1.351 www 5370: }
1.948 raeburn 5371: }
1.400 www 5372: return %returnhash;
5373: }
5374:
5375: sub get_my_roles {
1.937 raeburn 5376: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 5377: unless (defined($uname)) { $uname=$env{'user.name'}; }
5378: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 5379: my (%dumphash,%nothide);
1.1086 raeburn 5380: if ($context eq 'userroles') {
1.1166 raeburn 5381: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 5382: } else {
1.1219 raeburn 5383: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 5384: if ($hidepriv) {
5385: my %coursehash=&coursedescription($udom.'_'.$uname);
5386: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5387: if ($user !~ /:/) {
5388: $nothide{join(':',split(/[\@]/,$user))} = 1;
5389: } else {
5390: $nothide{$user} = 1;
5391: }
5392: }
5393: }
1.858 raeburn 5394: }
1.400 www 5395: my %returnhash=();
5396: my $now=time;
1.999 raeburn 5397: my %privileged;
1.800 albertel 5398: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 5399: my ($role,$tend,$tstart);
5400: if ($context eq 'userroles') {
1.1149 raeburn 5401: next if ($entry =~ /^rolesdef/);
1.867 raeburn 5402: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5403: } else {
5404: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5405: }
1.400 www 5406: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 5407: my $status = 'active';
1.939 raeburn 5408: if (($tend) && ($tend<=$now)) {
1.832 raeburn 5409: $status = 'previous';
5410: }
5411: if (($tstart) && ($now<$tstart)) {
5412: $status = 'future';
5413: }
5414: if (ref($types) eq 'ARRAY') {
5415: if (!grep(/^\Q$status\E$/,@{$types})) {
5416: next;
5417: }
5418: } else {
5419: if ($status ne 'active') {
5420: next;
5421: }
5422: }
1.867 raeburn 5423: my ($rolecode,$username,$domain,$section,$area);
5424: if ($context eq 'userroles') {
1.1186 raeburn 5425: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 5426: (undef,$domain,$username,$section) = split(/\//,$area);
5427: } else {
5428: ($role,$username,$domain,$section) = split(/\:/,$entry);
5429: }
1.832 raeburn 5430: if (ref($roledoms) eq 'ARRAY') {
5431: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5432: next;
5433: }
5434: }
5435: if (ref($roles) eq 'ARRAY') {
5436: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 5437: if ($role =~ /^cr\//) {
5438: if (!grep(/^cr$/,@{$roles})) {
5439: next;
5440: }
1.1104 raeburn 5441: } elsif ($role =~ /^gr\//) {
5442: if (!grep(/^gr$/,@{$roles})) {
5443: next;
5444: }
1.922 raeburn 5445: } else {
5446: next;
5447: }
1.832 raeburn 5448: }
1.867 raeburn 5449: }
1.937 raeburn 5450: if ($hidepriv) {
1.1219 raeburn 5451: my @privroles = ('dc','su');
1.999 raeburn 5452: if ($context eq 'userroles') {
1.1219 raeburn 5453: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 5454: } else {
1.1219 raeburn 5455: my $possdoms = [$domain];
5456: if (ref($roledoms) eq 'ARRAY') {
5457: push(@{$possdoms},@{$roledoms});
1.999 raeburn 5458: }
1.1219 raeburn 5459: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 5460: if (!$nothide{$username.':'.$domain}) {
5461: next;
5462: }
5463: }
1.937 raeburn 5464: }
5465: }
1.933 raeburn 5466: if ($withsec) {
5467: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5468: $tstart.':'.$tend;
5469: } else {
5470: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5471: }
1.832 raeburn 5472: }
1.373 www 5473: return %returnhash;
1.399 www 5474: }
5475:
1.1333 raeburn 5476: sub get_all_adhocroles {
5477: my ($dom) = @_;
5478: my @roles_by_num = ();
5479: my %domdefaults = &get_domain_defaults($dom);
5480: my (%description,%access_in_dom,%access_info);
5481: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5482: my $count = 0;
5483: my %domcurrent = %{$domdefaults{'adhocroles'}};
5484: my %ordered;
5485: foreach my $role (sort(keys(%domcurrent))) {
5486: my ($order,$desc,$access_in_dom);
5487: if (ref($domcurrent{$role}) eq 'HASH') {
5488: $order = $domcurrent{$role}{'order'};
5489: $desc = $domcurrent{$role}{'desc'};
5490: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5491: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5492: }
5493: if ($order eq '') {
5494: $order = $count;
5495: }
5496: $ordered{$order} = $role;
5497: if ($desc ne '') {
5498: $description{$role} = $desc;
5499: } else {
5500: $description{$role}= $role;
5501: }
5502: $count++;
5503: }
5504: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5505: push(@roles_by_num,$ordered{$item});
5506: }
5507: }
5508: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5509: }
5510:
1.1332 raeburn 5511: sub get_my_adhocroles {
1.1333 raeburn 5512: my ($cid,$checkreg) = @_;
5513: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5514: if ($env{'request.course.id'} eq $cid) {
5515: $cdom = $env{'course.'.$cid.'.domain'};
5516: $cnum = $env{'course.'.$cid.'.num'};
5517: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5518: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5519: $cdom = $1;
5520: $cnum = $2;
5521: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5522: $cdom,$cnum);
5523: }
5524: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5525: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5526: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5527: if ($rosterhash{$user} ne '') {
5528: my $type = (split(/:/,$rosterhash{$user}))[5];
5529: return ([],{}) if ($type eq 'auto');
5530: }
5531: }
5532: if (($cdom ne '') && ($cnum ne '')) {
1.1334 raeburn 5533: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332 raeburn 5534: my $then=$env{'user.login.time'};
5535: my $update=$env{'user.update.time'};
1.1335 raeburn 5536: if (!$update) {
5537: $update = $then;
5538: }
5539: my @liveroles;
1.1334 raeburn 5540: foreach my $role ('dh','da') {
5541: if ($env{"user.role.$role./$cdom/"}) {
1.1335 raeburn 5542: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334 raeburn 5543: my $limit = $update;
5544: if ($env{'request.role'} eq "$role./$cdom/") {
5545: $limit = $then;
5546: }
1.1335 raeburn 5547: my $activerole = 1;
5548: if ($tstart && $tstart>$limit) { $activerole = 0; }
5549: if ($tend && $tend <$limit) { $activerole = 0; }
5550: if ($activerole) {
5551: push(@liveroles,$role);
5552: }
1.1334 raeburn 5553: }
1.1332 raeburn 5554: }
1.1335 raeburn 5555: if (@liveroles) {
1.1332 raeburn 5556: if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333 raeburn 5557: my ($accessref,$accessinfo,%access_in_dom);
5558: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5559: if (ref($roles_by_num) eq 'ARRAY') {
5560: if (@{$roles_by_num}) {
1.1332 raeburn 5561: my %settings;
5562: if ($env{'request.course.id'} eq $cid) {
5563: foreach my $envkey (keys(%env)) {
5564: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5565: $settings{$1} = $env{$envkey};
5566: }
5567: }
5568: } else {
5569: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5570: }
5571: my %setincrs;
5572: if ($settings{'internal.adhocaccess'}) {
5573: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5574: }
5575: my @statuses;
5576: if ($env{'environment.inststatus'}) {
5577: @statuses = split(/,/,$env{'environment.inststatus'});
5578: }
5579: my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333 raeburn 5580: if (ref($accessref) eq 'HASH') {
5581: %access_in_dom = %{$accessref};
5582: }
5583: foreach my $role (@{$roles_by_num}) {
1.1332 raeburn 5584: my ($curraccess,@okstatus,@personnel);
5585: if ($setincrs{$role}) {
5586: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5587: if ($curraccess eq 'status') {
5588: @okstatus = split(/\&/,$rest);
5589: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5590: @personnel = split(/\&/,$rest);
5591: }
5592: } else {
5593: $curraccess = $access_in_dom{$role};
1.1333 raeburn 5594: if (ref($accessinfo) eq 'HASH') {
5595: if ($curraccess eq 'status') {
5596: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5597: @okstatus = @{$accessinfo->{$role}};
5598: }
5599: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5600: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5601: @personnel = @{$accessinfo->{$role}};
5602: }
1.1332 raeburn 5603: }
5604: }
5605: }
5606: if ($curraccess eq 'none') {
5607: next;
5608: } elsif ($curraccess eq 'all') {
5609: push(@possroles,$role);
1.1336 raeburn 5610: } elsif ($curraccess eq 'dh') {
1.1335 raeburn 5611: if (grep(/^dh$/,@liveroles)) {
5612: push(@possroles,$role);
5613: } else {
5614: next;
5615: }
1.1336 raeburn 5616: } elsif ($curraccess eq 'da') {
1.1335 raeburn 5617: if (grep(/^da$/,@liveroles)) {
5618: push(@possroles,$role);
5619: } else {
5620: next;
5621: }
1.1332 raeburn 5622: } elsif ($curraccess eq 'status') {
5623: if (@okstatus) {
5624: if (!@statuses) {
5625: if (grep(/^default$/,@okstatus)) {
5626: push(@possroles,$role);
5627: }
5628: } else {
5629: foreach my $status (@okstatus) {
5630: if (grep(/^\Q$status\E$/,@statuses)) {
5631: push(@possroles,$role);
5632: last;
5633: }
5634: }
5635: }
5636: }
5637: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5638: if (grep(/^\Q$user\E$/,@personnel)) {
5639: if ($curraccess eq 'exc') {
5640: push(@possroles,$role);
5641: }
5642: } elsif ($curraccess eq 'inc') {
5643: push(@possroles,$role);
5644: }
5645: }
5646: }
5647: }
5648: }
5649: }
5650: }
5651: }
5652: }
1.1333 raeburn 5653: unless (ref($description) eq 'HASH') {
5654: if (ref($roles_by_num) eq 'ARRAY') {
5655: my %desc;
5656: map { $desc{$_} = $_; } (@{$roles_by_num});
5657: $description = \%desc;
5658: } else {
5659: $description = {};
5660: }
5661: }
5662: return (\@possroles,$description);
1.1332 raeburn 5663: }
5664:
1.399 www 5665: # ----------------------------------------------------- Frontpage Announcements
5666: #
5667: #
5668:
5669: sub postannounce {
5670: my ($server,$text)=@_;
1.844 albertel 5671: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5672: unless ($text=~/\w/) { $text=''; }
5673: return &reply('setannounce:'.&escape($text),$server);
5674: }
5675:
5676: sub getannounce {
1.448 albertel 5677:
1.1359 raeburn 5678: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5679: my $announcement='';
1.800 albertel 5680: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5681: close($fh);
1.399 www 5682: if ($announcement=~/\w/) {
5683: return
5684: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5685: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5686: } else {
5687: return '';
5688: }
5689: } else {
5690: return '';
5691: }
1.351 www 5692: }
1.353 www 5693:
5694: # ---------------------------------------------------------- Course ID routines
5695: # Deal with domain's nohist_courseid.db files
5696: #
5697:
5698: sub courseidput {
1.921 raeburn 5699: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5700: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5701: my $outcome;
5702: if ($caller eq 'timeonly') {
5703: my $cids = '';
5704: foreach my $item (keys(%$storehash)) {
5705: $cids.=&escape($item).'&';
5706: }
5707: $cids=~s/\&$//;
5708: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5709: $coursehome);
5710: } else {
5711: my $items = '';
5712: foreach my $item (keys(%$storehash)) {
5713: $items.= &escape($item).'='.
5714: &freeze_escape($$storehash{$item}).'&';
5715: }
5716: $items=~s/\&$//;
5717: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5718: $coursehome);
1.918 raeburn 5719: }
5720: if ($outcome eq 'unknown_cmd') {
5721: my $what;
5722: foreach my $cid (keys(%$storehash)) {
5723: $what .= &escape($cid).'=';
1.921 raeburn 5724: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5725: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5726: }
5727: $what =~ s/\:$/&/;
5728: }
5729: $what =~ s/\&$//;
5730: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5731: } else {
5732: return $outcome;
5733: }
1.353 www 5734: }
5735:
5736: sub courseiddump {
1.921 raeburn 5737: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5738: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5739: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 5740: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 5741: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5742: my $as_hash = 1;
5743: my %returnhash;
5744: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5745: my %libserv = &all_library();
5746: foreach my $tryserver (keys(%libserv)) {
5747: if ( ( $hostidflag == 1
5748: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5749: || (!defined($hostidflag)) ) {
5750:
1.918 raeburn 5751: if (($domfilter eq '') ||
5752: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 5753: my $rep;
5754: if (grep { $_ eq $tryserver } current_machine_ids()) {
5755: $rep = LONCAPA::Lond::dump_course_id_handler(
5756: join(":", (&host_domain($tryserver), $sincefilter,
5757: &escape($descfilter), &escape($instcodefilter),
5758: &escape($ownerfilter), &escape($coursefilter),
5759: &escape($typefilter), &escape($regexp_ok),
5760: $as_hash, &escape($selfenrollonly),
5761: &escape($catfilter), $showhidden, $caller,
5762: &escape($cloner), &escape($cc_clone), $cloneonly,
5763: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 5764: &escape($creationcontext),$domcloner,$hasuniquecode,
5765: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 5766: } else {
5767: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5768: $sincefilter.':'.&escape($descfilter).':'.
5769: &escape($instcodefilter).':'.&escape($ownerfilter).
5770: ':'.&escape($coursefilter).':'.&escape($typefilter).
5771: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5772: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5773: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5774: &escape($cc_clone).':'.$cloneonly.':'.
5775: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 5776: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5777: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 5778: }
5779:
1.918 raeburn 5780: my @pairs=split(/\&/,$rep);
5781: foreach my $item (@pairs) {
5782: my ($key,$value)=split(/\=/,$item,2);
5783: $key = &unescape($key);
5784: next if ($key =~ /^error: 2 /);
5785: my $result = &thaw_unescape($value);
5786: if (ref($result) eq 'HASH') {
5787: $returnhash{$key}=$result;
5788: } else {
1.921 raeburn 5789: my @responses = split(/:/,$value);
5790: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5791: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5792: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5793: }
1.1008 raeburn 5794: }
1.353 www 5795: }
5796: }
5797: }
5798: }
5799: return %returnhash;
5800: }
5801:
1.1055 raeburn 5802: sub courselastaccess {
5803: my ($cdom,$cnum,$hostidref) = @_;
5804: my %returnhash;
5805: if ($cdom && $cnum) {
5806: my $chome = &homeserver($cnum,$cdom);
5807: if ($chome ne 'no_host') {
5808: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5809: &extract_lastaccess(\%returnhash,$rep);
5810: }
5811: } else {
5812: if (!$cdom) { $cdom=''; }
5813: my %libserv = &all_library();
5814: foreach my $tryserver (keys(%libserv)) {
5815: if (ref($hostidref) eq 'ARRAY') {
5816: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5817: }
5818: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5819: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5820: &extract_lastaccess(\%returnhash,$rep);
5821: }
5822: }
5823: }
5824: return %returnhash;
5825: }
5826:
5827: sub extract_lastaccess {
5828: my ($returnhash,$rep) = @_;
5829: if (ref($returnhash) eq 'HASH') {
5830: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5831: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5832: $rep eq '') {
5833: my @pairs=split(/\&/,$rep);
5834: foreach my $item (@pairs) {
5835: my ($key,$value)=split(/\=/,$item,2);
5836: $key = &unescape($key);
5837: next if ($key =~ /^error: 2 /);
5838: $returnhash->{$key} = &thaw_unescape($value);
5839: }
5840: }
5841: }
5842: return;
5843: }
5844:
1.658 raeburn 5845: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5846:
5847: sub dcmailput {
1.685 raeburn 5848: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 5849: my $status = &Apache::lonnet::critical(
1.740 www 5850: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5851: &escape($message),$server);
1.662 raeburn 5852: return $status;
5853: }
5854:
1.658 raeburn 5855: sub dcmaildump {
5856: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5857: my %returnhash=();
1.846 albertel 5858:
5859: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5860: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5861: &escape($enddate).':';
5862: my @esc_senders=map { &escape($_)} @$senders;
5863: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5864: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5865: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5866: if (($key) && ($value)) {
5867: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5868: }
5869: }
5870: }
5871: return %returnhash;
5872: }
1.662 raeburn 5873: # ---------------------------------------------------------- Domain roles
5874:
5875: sub get_domain_roles {
5876: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5877: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5878: $startdate = '.';
5879: }
1.1018 raeburn 5880: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5881: $enddate = '.';
5882: }
1.922 raeburn 5883: my $rolelist;
5884: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 5885: $rolelist = join('&',@{$roles});
1.922 raeburn 5886: }
1.662 raeburn 5887: my %personnel = ();
1.841 albertel 5888:
5889: my %servers = &get_servers($dom,'library');
5890: foreach my $tryserver (keys(%servers)) {
5891: %{$personnel{$tryserver}}=();
5892: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5893: &escape($startdate).':'.
5894: &escape($enddate).':'.
5895: &escape($rolelist), $tryserver))) {
5896: my ($key,$value) = split(/\=/,$line,2);
5897: if (($key) && ($value)) {
5898: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5899: }
5900: }
1.662 raeburn 5901: }
5902: return %personnel;
5903: }
1.658 raeburn 5904:
1.1332 raeburn 5905: sub get_active_domroles {
5906: my ($dom,$roles) = @_;
5907: return () unless (ref($roles) eq 'ARRAY');
5908: my $now = time;
5909: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5910: my %domroles;
5911: foreach my $server (keys(%dompersonnel)) {
5912: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5913: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5914: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5915: }
5916: }
5917: return %domroles;
5918: }
5919:
1.1057 www 5920: # ----------------------------------------------------------- Interval timing
1.149 www 5921:
1.1153 www 5922: {
5923: # Caches needed for speedup of navmaps
5924: # We don't want to cache this for very long at all (5 seconds at most)
5925: #
5926: # The user for whom we cache
5927: my $cachedkey='';
5928: # The cached times for this user
5929: my %cachedtimes=();
5930: # When this was last done
1.1282 raeburn 5931: my $cachedtime='';
1.1153 www 5932:
5933: sub load_all_first_access {
1.1308 raeburn 5934: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 5935: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 raeburn 5936: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5937: (!$ignorecache)) {
1.1154 raeburn 5938: return;
5939: }
5940: $cachedtime=time;
5941: $cachedkey=$uname.':'.$udom;
5942: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5943: }
5944:
1.504 albertel 5945: sub get_first_access {
1.1308 raeburn 5946: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 5947: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5948: if ($argsymb) { $symb=$argsymb; }
5949: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5950: if ($argmap) { $map = $argmap; }
1.926 albertel 5951: if ($type eq 'course') {
5952: $res='course';
5953: } elsif ($type eq 'map') {
1.588 albertel 5954: $res=&symbread($map);
5955: } else {
5956: $res=$symb;
5957: }
1.1308 raeburn 5958: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 5959: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5960: }
5961:
5962: sub set_first_access {
1.1162 raeburn 5963: my ($type,$interval)=@_;
1.790 albertel 5964: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5965: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5966: if ($type eq 'course') {
5967: $res='course';
5968: } elsif ($type eq 'map') {
1.588 albertel 5969: $res=&symbread($map);
5970: } else {
5971: $res=$symb;
5972: }
1.1153 www 5973: $cachedkey='';
1.1162 raeburn 5974: my $firstaccess=&get_first_access($type,$symb,$map);
1.1386 raeburn 5975: if ($firstaccess) {
5976: &logthis("First access time already set ($firstaccess) when attempting ".
1.1393 raeburn 5977: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5978: "in $courseid");
1.1386 raeburn 5979: return 'already_set';
5980: } else {
1.1162 raeburn 5981: my $start = time;
5982: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5983: $udom,$uname);
5984: if ($putres eq 'ok') {
5985: &put('timerinterval',{"$courseid\0$res"=>$interval},
5986: $udom,$uname);
5987: &appenv(
5988: {
5989: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5990: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5991: }
5992: );
1.1365 raeburn 5993: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5994: $cachedtimes{"$courseid\0$res"} = $start;
5995: }
1.1386 raeburn 5996: } elsif ($putres ne 'refused') {
5997: &logthis("Result: $putres when attempting to set first access time ".
5998: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 5999: }
6000: return $putres;
1.505 albertel 6001: }
6002: return 'already_set';
1.504 albertel 6003: }
1.1153 www 6004: }
1.1282 raeburn 6005:
1.110 www 6006: # --------------------------------------------- Set Expire Date for Spreadsheet
6007:
6008: sub expirespread {
6009: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 6010: my $cid=$env{'request.course.id'};
1.110 www 6011: if ($cid) {
6012: my $now=time;
6013: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 6014: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
6015: $env{'course.'.$cid.'.num'}.
1.110 www 6016: ':nohist_expirationdates:'.
6017: &escape($key).'='.$now,
1.620 albertel 6018: $env{'course.'.$cid.'.home'})
1.110 www 6019: }
6020: return 'ok';
1.14 www 6021: }
6022:
1.109 www 6023: # ----------------------------------------------------- Devalidate Spreadsheets
6024:
6025: sub devalidate {
1.325 www 6026: my ($symb,$uname,$udom)=@_;
1.620 albertel 6027: my $cid=$env{'request.course.id'};
1.109 www 6028: if ($cid) {
1.391 matthew 6029: # delete the stored spreadsheets for
6030: # - the student level sheet of this user in course's homespace
6031: # - the assessment level sheet for this resource
6032: # for this user in user's homespace
1.553 albertel 6033: # - current conditional state info
1.325 www 6034: my $key=$uname.':'.$udom.':';
1.109 www 6035: my $status=
1.299 matthew 6036: &del('nohist_calculatedsheets',
1.391 matthew 6037: [$key.'studentcalc:'],
1.620 albertel 6038: $env{'course.'.$cid.'.domain'},
6039: $env{'course.'.$cid.'.num'})
1.133 albertel 6040: .' '.
6041: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 6042: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 6043: unless ($status eq 'ok ok') {
6044: &logthis('Could not devalidate spreadsheet '.
1.325 www 6045: $uname.' at '.$udom.' for '.
1.109 www 6046: $symb.': '.$status);
1.133 albertel 6047: }
1.553 albertel 6048: &delenv('user.state.'.$cid);
1.109 www 6049: }
6050: }
6051:
1.265 albertel 6052: sub get_scalar {
6053: my ($string,$end) = @_;
6054: my $value;
6055: if ($$string =~ s/^([^&]*?)($end)/$2/) {
6056: $value = $1;
6057: } elsif ($$string =~ s/^([^&]*?)&//) {
6058: $value = $1;
6059: }
6060: return &unescape($value);
6061: }
6062:
6063: sub array2str {
6064: my (@array) = @_;
6065: my $result=&arrayref2str(\@array);
6066: $result=~s/^__ARRAY_REF__//;
6067: $result=~s/__END_ARRAY_REF__$//;
6068: return $result;
6069: }
6070:
1.204 albertel 6071: sub arrayref2str {
6072: my ($arrayref) = @_;
1.265 albertel 6073: my $result='__ARRAY_REF__';
1.204 albertel 6074: foreach my $elem (@$arrayref) {
1.265 albertel 6075: if(ref($elem) eq 'ARRAY') {
6076: $result.=&arrayref2str($elem).'&';
6077: } elsif(ref($elem) eq 'HASH') {
6078: $result.=&hashref2str($elem).'&';
6079: } elsif(ref($elem)) {
6080: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 6081: } else {
6082: $result.=&escape($elem).'&';
6083: }
6084: }
6085: $result=~s/\&$//;
1.265 albertel 6086: $result .= '__END_ARRAY_REF__';
1.204 albertel 6087: return $result;
6088: }
6089:
1.168 albertel 6090: sub hash2str {
1.204 albertel 6091: my (%hash) = @_;
6092: my $result=&hashref2str(\%hash);
1.265 albertel 6093: $result=~s/^__HASH_REF__//;
6094: $result=~s/__END_HASH_REF__$//;
1.204 albertel 6095: return $result;
6096: }
6097:
6098: sub hashref2str {
6099: my ($hashref)=@_;
1.265 albertel 6100: my $result='__HASH_REF__';
1.800 albertel 6101: foreach my $key (sort(keys(%$hashref))) {
6102: if (ref($key) eq 'ARRAY') {
6103: $result.=&arrayref2str($key).'=';
6104: } elsif (ref($key) eq 'HASH') {
6105: $result.=&hashref2str($key).'=';
6106: } elsif (ref($key)) {
1.265 albertel 6107: $result.='=';
1.800 albertel 6108: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 6109: } else {
1.1132 raeburn 6110: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 6111: }
6112:
1.800 albertel 6113: if(ref($hashref->{$key}) eq 'ARRAY') {
6114: $result.=&arrayref2str($hashref->{$key}).'&';
6115: } elsif(ref($hashref->{$key}) eq 'HASH') {
6116: $result.=&hashref2str($hashref->{$key}).'&';
6117: } elsif(ref($hashref->{$key})) {
1.265 albertel 6118: $result.='&';
1.800 albertel 6119: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 6120: } else {
1.800 albertel 6121: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 6122: }
6123: }
1.168 albertel 6124: $result=~s/\&$//;
1.265 albertel 6125: $result .= '__END_HASH_REF__';
1.168 albertel 6126: return $result;
6127: }
6128:
6129: sub str2hash {
1.265 albertel 6130: my ($string)=@_;
6131: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
6132: return %$hash;
6133: }
6134:
6135: sub str2hashref {
1.168 albertel 6136: my ($string) = @_;
1.265 albertel 6137:
6138: my %hash;
6139:
6140: if($string !~ /^__HASH_REF__/) {
6141: if (! ($string eq '' || !defined($string))) {
6142: $hash{'error'}='Not hash reference';
6143: }
6144: return (\%hash, $string);
6145: }
6146:
6147: $string =~ s/^__HASH_REF__//;
6148:
6149: while($string !~ /^__END_HASH_REF__/) {
6150: #key
6151: my $key='';
6152: if($string =~ /^__HASH_REF__/) {
6153: ($key, $string)=&str2hashref($string);
6154: if(defined($key->{'error'})) {
6155: $hash{'error'}='Bad data';
6156: return (\%hash, $string);
6157: }
6158: } elsif($string =~ /^__ARRAY_REF__/) {
6159: ($key, $string)=&str2arrayref($string);
6160: if($key->[0] eq 'Array reference error') {
6161: $hash{'error'}='Bad data';
6162: return (\%hash, $string);
6163: }
6164: } else {
6165: $string =~ s/^(.*?)=//;
1.267 albertel 6166: $key=&unescape($1);
1.265 albertel 6167: }
6168: $string =~ s/^=//;
6169:
6170: #value
6171: my $value='';
6172: if($string =~ /^__HASH_REF__/) {
6173: ($value, $string)=&str2hashref($string);
6174: if(defined($value->{'error'})) {
6175: $hash{'error'}='Bad data';
6176: return (\%hash, $string);
6177: }
6178: } elsif($string =~ /^__ARRAY_REF__/) {
6179: ($value, $string)=&str2arrayref($string);
6180: if($value->[0] eq 'Array reference error') {
6181: $hash{'error'}='Bad data';
6182: return (\%hash, $string);
6183: }
6184: } else {
6185: $value=&get_scalar(\$string,'__END_HASH_REF__');
6186: }
6187: $string =~ s/^&//;
6188:
6189: $hash{$key}=$value;
1.204 albertel 6190: }
1.265 albertel 6191:
6192: $string =~ s/^__END_HASH_REF__//;
6193:
6194: return (\%hash, $string);
1.204 albertel 6195: }
6196:
6197: sub str2array {
1.265 albertel 6198: my ($string)=@_;
6199: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
6200: return @$array;
6201: }
6202:
6203: sub str2arrayref {
1.204 albertel 6204: my ($string) = @_;
1.265 albertel 6205: my @array;
6206:
6207: if($string !~ /^__ARRAY_REF__/) {
6208: if (! ($string eq '' || !defined($string))) {
6209: $array[0]='Array reference error';
6210: }
6211: return (\@array, $string);
6212: }
6213:
6214: $string =~ s/^__ARRAY_REF__//;
6215:
6216: while($string !~ /^__END_ARRAY_REF__/) {
6217: my $value='';
6218: if($string =~ /^__HASH_REF__/) {
6219: ($value, $string)=&str2hashref($string);
6220: if(defined($value->{'error'})) {
6221: $array[0] ='Array reference error';
6222: return (\@array, $string);
6223: }
6224: } elsif($string =~ /^__ARRAY_REF__/) {
6225: ($value, $string)=&str2arrayref($string);
6226: if($value->[0] eq 'Array reference error') {
6227: $array[0] ='Array reference error';
6228: return (\@array, $string);
6229: }
6230: } else {
6231: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
6232: }
6233: $string =~ s/^&//;
6234:
6235: push(@array, $value);
1.191 harris41 6236: }
1.265 albertel 6237:
6238: $string =~ s/^__END_ARRAY_REF__//;
6239:
6240: return (\@array, $string);
1.168 albertel 6241: }
6242:
1.167 albertel 6243: # -------------------------------------------------------------------Temp Store
6244:
1.168 albertel 6245: sub tmpreset {
6246: my ($symb,$namespace,$domain,$stuname) = @_;
6247: if (!$symb) {
6248: $symb=&symbread();
1.620 albertel 6249: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6250: }
6251: $symb=escape($symb);
6252:
1.620 albertel 6253: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 6254: $namespace=~s/\//\_/g;
6255: $namespace=~s/\W//g;
6256:
1.620 albertel 6257: if (!$domain) { $domain=$env{'user.domain'}; }
6258: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6259: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6260: $stuname=&get_requestor_ip();
1.591 albertel 6261: }
1.1117 foxr 6262: my $path=LONCAPA::tempdir();
1.168 albertel 6263: my %hash;
6264: if (tie(%hash,'GDBM_File',
6265: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6266: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 6267: foreach my $key (keys(%hash)) {
1.180 albertel 6268: if ($key=~ /:$symb/) {
1.168 albertel 6269: delete($hash{$key});
6270: }
6271: }
6272: }
6273: }
6274:
1.167 albertel 6275: sub tmpstore {
1.168 albertel 6276: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
6277:
6278: if (!$symb) {
6279: $symb=&symbread();
1.620 albertel 6280: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6281: }
6282: $symb=escape($symb);
6283:
6284: if (!$namespace) {
6285: # I don't think we would ever want to store this for a course.
6286: # it seems this will only be used if we don't have a course.
1.620 albertel 6287: #$namespace=$env{'request.course.id'};
1.168 albertel 6288: #if (!$namespace) {
1.620 albertel 6289: $namespace=$env{'request.state'};
1.168 albertel 6290: #}
6291: }
6292: $namespace=~s/\//\_/g;
6293: $namespace=~s/\W//g;
1.620 albertel 6294: if (!$domain) { $domain=$env{'user.domain'}; }
6295: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6296: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6297: $stuname=&get_requestor_ip();
1.591 albertel 6298: }
1.168 albertel 6299: my $now=time;
6300: my %hash;
1.1117 foxr 6301: my $path=LONCAPA::tempdir();
1.168 albertel 6302: if (tie(%hash,'GDBM_File',
6303: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6304: &GDBM_WRCREAT(),0640)) {
1.168 albertel 6305: $hash{"version:$symb"}++;
6306: my $version=$hash{"version:$symb"};
6307: my $allkeys='';
6308: foreach my $key (keys(%$storehash)) {
6309: $allkeys.=$key.':';
1.591 albertel 6310: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 6311: }
6312: $hash{"$version:$symb:timestamp"}=$now;
6313: $allkeys.='timestamp';
6314: $hash{"$version:keys:$symb"}=$allkeys;
6315: if (untie(%hash)) {
6316: return 'ok';
6317: } else {
6318: return "error:$!";
6319: }
6320: } else {
6321: return "error:$!";
6322: }
6323: }
1.167 albertel 6324:
1.168 albertel 6325: # -----------------------------------------------------------------Temp Restore
1.167 albertel 6326:
1.168 albertel 6327: sub tmprestore {
6328: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 6329:
1.168 albertel 6330: if (!$symb) {
6331: $symb=&symbread();
1.620 albertel 6332: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6333: }
6334: $symb=escape($symb);
6335:
1.620 albertel 6336: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 6337:
1.620 albertel 6338: if (!$domain) { $domain=$env{'user.domain'}; }
6339: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6340: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6341: $stuname=&get_requestor_ip();
1.591 albertel 6342: }
1.168 albertel 6343: my %returnhash;
6344: $namespace=~s/\//\_/g;
6345: $namespace=~s/\W//g;
6346: my %hash;
1.1117 foxr 6347: my $path=LONCAPA::tempdir();
1.168 albertel 6348: if (tie(%hash,'GDBM_File',
6349: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6350: &GDBM_READER(),0640)) {
1.168 albertel 6351: my $version=$hash{"version:$symb"};
6352: $returnhash{'version'}=$version;
6353: my $scope;
6354: for ($scope=1;$scope<=$version;$scope++) {
6355: my $vkeys=$hash{"$scope:keys:$symb"};
6356: my @keys=split(/:/,$vkeys);
6357: my $key;
6358: $returnhash{"$scope:keys"}=$vkeys;
6359: foreach $key (@keys) {
1.591 albertel 6360: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6361: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 6362: }
6363: }
1.168 albertel 6364: if (!(untie(%hash))) {
6365: return "error:$!";
6366: }
6367: } else {
6368: return "error:$!";
6369: }
6370: return %returnhash;
1.167 albertel 6371: }
6372:
1.9 www 6373: # ----------------------------------------------------------------------- Store
6374:
6375: sub store {
1.1269 raeburn 6376: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6377: my $home='';
6378:
1.168 albertel 6379: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6380:
1.213 www 6381: $symb=&symbclean($symb);
1.122 albertel 6382: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6383:
1.620 albertel 6384: if (!$domain) { $domain=$env{'user.domain'}; }
6385: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6386:
6387: &devalidate($symb,$stuname,$domain);
1.109 www 6388:
6389: $symb=escape($symb);
1.187 www 6390: if (!$namespace) {
1.620 albertel 6391: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6392: return '';
6393: }
6394: }
1.620 albertel 6395: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6396:
1.1434 raeburn 6397: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6398: $$storehash{'host'}=$perlvar{'lonHostID'};
6399:
1.12 www 6400: my $namevalue='';
1.800 albertel 6401: foreach my $key (keys(%$storehash)) {
6402: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6403: }
1.12 www 6404: $namevalue=~s/\&$//;
1.187 www 6405: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 6406: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6407: }
6408:
1.47 www 6409: # -------------------------------------------------------------- Critical Store
6410:
6411: sub cstore {
1.1269 raeburn 6412: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6413: my $home='';
6414:
1.168 albertel 6415: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6416:
1.213 www 6417: $symb=&symbclean($symb);
1.122 albertel 6418: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6419:
1.620 albertel 6420: if (!$domain) { $domain=$env{'user.domain'}; }
6421: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6422:
6423: &devalidate($symb,$stuname,$domain);
1.109 www 6424:
6425: $symb=escape($symb);
1.187 www 6426: if (!$namespace) {
1.620 albertel 6427: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6428: return '';
6429: }
6430: }
1.620 albertel 6431: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6432:
1.1434 raeburn 6433: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6434: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6435:
1.47 www 6436: my $namevalue='';
1.800 albertel 6437: foreach my $key (keys(%$storehash)) {
6438: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6439: }
1.47 www 6440: $namevalue=~s/\&$//;
1.187 www 6441: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6442: return critical
1.1269 raeburn 6443: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6444: }
6445:
1.9 www 6446: # --------------------------------------------------------------------- Restore
6447:
6448: sub restore {
1.124 www 6449: my ($symb,$namespace,$domain,$stuname) = @_;
6450: my $home='';
6451:
1.168 albertel 6452: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6453:
1.122 albertel 6454: if (!$symb) {
1.1224 raeburn 6455: return if ($namespace eq 'courserequests');
6456: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6457: } else {
1.1224 raeburn 6458: unless ($namespace eq 'courserequests') {
6459: $symb=&escape(&symbclean($symb));
6460: }
1.122 albertel 6461: }
1.188 www 6462: if (!$namespace) {
1.620 albertel 6463: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6464: return '';
6465: }
6466: }
1.620 albertel 6467: if (!$domain) { $domain=$env{'user.domain'}; }
6468: if (!$stuname) { $stuname=$env{'user.name'}; }
6469: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6470: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6471:
1.12 www 6472: my %returnhash=();
1.800 albertel 6473: foreach my $line (split(/\&/,$answer)) {
6474: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6475: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6476: }
1.75 www 6477: my $version;
6478: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6479: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6480: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6481: }
1.75 www 6482: }
1.13 www 6483: return %returnhash;
1.34 www 6484: }
6485:
6486: # ---------------------------------------------------------- Course Description
1.1118 foxr 6487: #
6488: #
1.34 www 6489:
6490: sub coursedescription {
1.731 albertel 6491: my ($courseid,$args)=@_;
1.34 www 6492: $courseid=~s/^\///;
1.49 www 6493: $courseid=~s/\_/\//g;
1.34 www 6494: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6495: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6496: my $normalid=$cdomain.'_'.$cnum;
6497: # need to always cache even if we get errors otherwise we keep
6498: # trying and trying and trying to get the course description.
6499: my %envhash=();
6500: my %returnhash=();
1.731 albertel 6501:
6502: my $expiretime=600;
6503: if ($env{'request.course.id'} eq $normalid) {
6504: $expiretime=120;
6505: }
6506:
6507: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6508: if (!$args->{'freshen_cache'}
6509: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6510: foreach my $key (keys(%env)) {
6511: next if ($key !~ /^\Q$prefix\E(.*)/);
6512: my ($setting) = $1;
6513: $returnhash{$setting} = $env{$key};
6514: }
6515: return %returnhash;
6516: }
6517:
1.1118 foxr 6518: # get the data again
6519:
1.731 albertel 6520: if (!$args->{'one_time'}) {
6521: $envhash{'course.'.$normalid.'.last_cache'}=time;
6522: }
1.811 albertel 6523:
1.34 www 6524: if ($chome ne 'no_host') {
1.302 albertel 6525: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6526: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6527: my $username = $env{'user.name'}; # Defult username
6528: if(defined $args->{'user'}) {
6529: $username = $args->{'user'};
6530: }
1.129 albertel 6531: $returnhash{'home'}= $chome;
6532: $returnhash{'domain'} = $cdomain;
6533: $returnhash{'num'} = $cnum;
1.741 raeburn 6534: if (!defined($returnhash{'type'})) {
6535: $returnhash{'type'} = 'Course';
6536: }
1.130 albertel 6537: while (my ($name,$value) = each %returnhash) {
1.53 www 6538: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6539: }
1.270 www 6540: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6541: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6542: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6543: $envhash{'course.'.$normalid.'.home'}=$chome;
6544: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6545: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6546: }
6547: }
1.731 albertel 6548: if (!$args->{'one_time'}) {
1.949 raeburn 6549: &appenv(\%envhash);
1.731 albertel 6550: }
1.302 albertel 6551: return %returnhash;
1.461 www 6552: }
6553:
1.1080 raeburn 6554: sub update_released_required {
6555: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6556: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6557: $cid = $env{'request.course.id'};
6558: $cdom = $env{'course.'.$cid.'.domain'};
6559: $cnum = $env{'course.'.$cid.'.num'};
6560: $chome = $env{'course.'.$cid.'.home'};
6561: }
6562: if ($needsrelease) {
6563: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6564: my $needsupdate;
6565: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6566: $needsupdate = 1;
6567: } else {
6568: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6569: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6570: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6571: $needsupdate = 1;
6572: }
6573: }
6574: if ($needsupdate) {
6575: my %needshash = (
6576: 'internal.releaserequired' => $needsrelease,
6577: );
6578: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6579: if ($putresult eq 'ok') {
6580: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6581: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6582: if (ref($crsinfo{$cid}) eq 'HASH') {
6583: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6584: &courseidput($cdom,\%crsinfo,$chome,'notime');
6585: }
6586: }
6587: }
6588: }
6589: return;
6590: }
6591:
1.461 www 6592: # -------------------------------------------------See if a user is privileged
6593:
6594: sub privileged {
1.1219 raeburn 6595: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6596: my $now = time;
1.1219 raeburn 6597: my $roles;
6598: if (ref($possroles) eq 'ARRAY') {
6599: $roles = $possroles;
6600: } else {
6601: $roles = ['dc','su'];
6602: }
6603: if (ref($possdomains) eq 'ARRAY') {
6604: my %privileged = &privileged_by_domain($possdomains,$roles);
6605: foreach my $dom (@{$possdomains}) {
6606: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6607: (ref($privileged{$dom}) eq 'HASH')) {
6608: foreach my $role (@{$roles}) {
6609: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6610: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6611: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6612: return 1 unless (($end && $end < $now) ||
6613: ($start && $start > $now));
6614: }
6615: }
6616: }
6617: }
6618: }
6619: } else {
6620: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6621: my $now = time;
1.1170 droeschl 6622:
1.1275 musolffc 6623: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6624: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 6625: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 6626: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 6627: or ($tstart && $tstart > $now);
1.1170 droeschl 6628: }
1.1219 raeburn 6629: }
6630: }
6631: return 0;
6632: }
1.1170 droeschl 6633:
1.1219 raeburn 6634: sub privileged_by_domain {
6635: my ($domains,$roles) = @_;
6636: my %privileged = ();
6637: my $cachetime = 60*60*24;
6638: my $now = time;
6639: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6640: return %privileged;
6641: }
6642: foreach my $dom (@{$domains}) {
6643: next if (ref($privileged{$dom}) eq 'HASH');
6644: my $needroles;
6645: foreach my $role (@{$roles}) {
6646: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6647: if (defined($cached)) {
6648: if (ref($result) eq 'HASH') {
6649: $privileged{$dom}{$role} = $result;
6650: }
6651: } else {
6652: $needroles = 1;
6653: }
6654: }
6655: if ($needroles) {
6656: my %dompersonnel = &get_domain_roles($dom,$roles);
6657: $privileged{$dom} = {};
6658: foreach my $server (keys(%dompersonnel)) {
6659: if (ref($dompersonnel{$server}) eq 'HASH') {
6660: foreach my $item (keys(%{$dompersonnel{$server}})) {
6661: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6662: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6663: next if ($end && $end < $now);
6664: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6665: $dompersonnel{$server}{$item};
6666: }
6667: }
6668: }
6669: if (ref($privileged{$dom}) eq 'HASH') {
6670: foreach my $role (@{$roles}) {
6671: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6672: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6673: } else {
6674: my %hash = ();
6675: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6676: }
6677: }
6678: }
6679: }
6680: }
6681: return %privileged;
1.9 www 6682: }
1.1 albertel 6683:
1.103 harris41 6684: # -------------------------------------------------------- Get user privileges
1.11 www 6685:
6686: sub rolesinit {
1.1169 droeschl 6687: my ($domain, $username) = @_;
6688: my %userroles = ('user.login.time' => time);
6689: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6690:
6691: # firstaccess and timerinterval are related to timed maps/resources.
6692: # also, blocking can be triggered by an activating timer
6693: # it's saved in the user's %env.
6694: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6695: my %timerinterval = &dump('timerinterval', $domain, $username);
6696: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6697: %timerintchk, %timerintenv);
6698:
1.1162 raeburn 6699: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6700: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6701: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6702: }
1.1169 droeschl 6703:
1.1162 raeburn 6704: foreach my $key (keys(%timerinterval)) {
6705: my ($cid,$rest) = split(/\0/,$key);
6706: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6707: }
1.1169 droeschl 6708:
1.11 www 6709: my %allroles=();
1.1162 raeburn 6710: my %allgroups=();
1.11 www 6711:
1.1274 raeburn 6712: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6713: my $role = $rolesdump{$area};
6714: $area =~ s/\_\w\w$//;
6715:
6716: my ($trole, $tend, $tstart, $group_privs);
6717:
6718: if ($role =~ /^cr/) {
6719: # Custom role, defined by a user
6720: # e.g., user.role.cr/msu/smith/mynewrole
6721: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6722: $trole = $1;
6723: ($tend, $tstart) = split('_', $2);
6724: } else {
6725: $trole = $role;
6726: }
6727: } elsif ($role =~ m|^gr/|) {
6728: # Role of member in a group, defined within a course/community
6729: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6730: ($trole, $tend, $tstart) = split(/_/, $role);
6731: next if $tstart eq '-1';
6732: ($trole, $group_privs) = split(/\//, $trole);
6733: $group_privs = &unescape($group_privs);
6734: } else {
6735: # Just a normal role, defined in roles.tab
6736: ($trole, $tend, $tstart) = split(/_/,$role);
6737: }
6738:
6739: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6740: $username);
6741: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6742:
6743: # role expired or not available yet?
6744: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6745: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6746:
6747: next if $area eq '' or $trole eq '';
6748:
6749: my $spec = "$trole.$area";
6750: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6751:
6752: if ($trole =~ /^cr\//) {
6753: # Custom role, defined by a user
6754: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6755: } elsif ($trole eq 'gr') {
6756: # Role of a member in a group, defined within a course/community
6757: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6758: next;
6759: } else {
6760: # Normal role, defined in roles.tab
6761: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6762: }
6763:
6764: my $cid = $tdomain.'_'.$trest;
6765: unless ($firstaccchk{$cid}) {
6766: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6767: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6768: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6769: $coursetimerstarts{$cid}{$item};
6770: }
6771: }
6772: $firstaccchk{$cid} = 1;
6773: }
6774: unless ($timerintchk{$cid}) {
6775: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6776: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6777: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6778: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6779: }
1.12 www 6780: }
1.1169 droeschl 6781: $timerintchk{$cid} = 1;
1.191 harris41 6782: }
1.11 www 6783: }
1.1169 droeschl 6784:
1.1341 raeburn 6785: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6786: \%allroles, \%allgroups);
1.1169 droeschl 6787: $env{'user.adv'} = $userroles{'user.adv'};
1.1341 raeburn 6788: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6789:
1.1162 raeburn 6790: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6791: }
6792:
1.567 raeburn 6793: sub set_arearole {
1.1215 raeburn 6794: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6795: unless ($nolog) {
1.567 raeburn 6796: # log the associated role with the area
1.1215 raeburn 6797: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6798: }
1.743 albertel 6799: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6800: }
6801:
6802: sub custom_roleprivs {
6803: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6804: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 6805: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6806: if (&hostname($homsvr) ne '') {
1.567 raeburn 6807: my ($rdummy,$roledef)=
6808: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6809: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6810: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6811: if (defined($syspriv)) {
1.1043 raeburn 6812: if ($trest =~ /^$match_community$/) {
6813: $syspriv =~ s/bre\&S//;
6814: }
1.567 raeburn 6815: $$allroles{'cm./'}.=':'.$syspriv;
6816: $$allroles{$spec.'./'}.=':'.$syspriv;
6817: }
6818: if ($tdomain ne '') {
6819: if (defined($dompriv)) {
6820: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6821: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6822: }
6823: if (($trest ne '') && (defined($coursepriv))) {
1.1332 raeburn 6824: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6825: my $rolename = $1;
6826: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6827: }
1.567 raeburn 6828: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6829: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6830: }
6831: }
6832: }
6833: }
6834: }
6835:
1.1332 raeburn 6836: sub course_adhocrole_privs {
6837: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6838: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6839: if ($overrides{"internal.adhocpriv.$rolename"}) {
6840: my (%currprivs,%storeprivs);
6841: foreach my $item (split(/:/,$coursepriv)) {
6842: my ($priv,$restrict) = split(/\&/,$item);
6843: $currprivs{$priv} = $restrict;
6844: }
6845: my (%possadd,%possremove,%full);
6846: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6847: my ($priv,$restrict)=split(/\&/,$item);
6848: $full{$priv} = $restrict;
6849: }
6850: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6851: next if ($item eq '');
6852: my ($rule,$rest) = split(/=/,$item);
6853: next unless (($rule eq 'off') || ($rule eq 'on'));
6854: foreach my $priv (split(/:/,$rest)) {
6855: if ($priv ne '') {
6856: if ($rule eq 'off') {
6857: $possremove{$priv} = 1;
6858: } else {
6859: $possadd{$priv} = 1;
6860: }
6861: }
6862: }
6863: }
6864: foreach my $priv (sort(keys(%full))) {
6865: if (exists($currprivs{$priv})) {
6866: unless (exists($possremove{$priv})) {
6867: $storeprivs{$priv} = $currprivs{$priv};
6868: }
6869: } elsif (exists($possadd{$priv})) {
6870: $storeprivs{$priv} = $full{$priv};
6871: }
6872: }
6873: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6874: }
6875: return $coursepriv;
6876: }
6877:
1.678 raeburn 6878: sub group_roleprivs {
6879: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6880: my $access = 1;
6881: my $now = time;
6882: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6883: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6884: if ($access) {
1.811 albertel 6885: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6886: $$allgroups{$course}{$group} .=':'.$group_privs;
6887: }
6888: }
1.567 raeburn 6889:
6890: sub standard_roleprivs {
6891: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6892: if (defined($pr{$trole.':s'})) {
6893: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6894: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6895: }
6896: if ($tdomain ne '') {
6897: if (defined($pr{$trole.':d'})) {
6898: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6899: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6900: }
6901: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6902: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6903: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6904: }
6905: }
6906: }
6907:
6908: sub set_userprivs {
1.1064 raeburn 6909: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6910: my $author=0;
6911: my $adv=0;
1.1341 raeburn 6912: my $rar=0;
1.678 raeburn 6913: my %grouproles = ();
6914: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6915: my @groupkeys;
1.1000 raeburn 6916: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6917: push(@groupkeys,$role);
6918: }
6919: if (ref($groups_roles) eq 'HASH') {
6920: foreach my $key (keys(%{$groups_roles})) {
6921: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6922: push(@groupkeys,$key);
6923: }
6924: }
6925: }
6926: if (@groupkeys > 0) {
6927: foreach my $role (@groupkeys) {
6928: my ($trole,$area,$sec,$extendedarea);
6929: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6930: $trole = $1;
6931: $area = $2;
6932: $sec = $3;
6933: $extendedarea = $area.$sec;
6934: if (exists($$allgroups{$area})) {
6935: foreach my $group (keys(%{$$allgroups{$area}})) {
6936: my $spec = $trole.'.'.$extendedarea;
6937: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6938: $$allgroups{$area}{$group};
1.1064 raeburn 6939: }
1.678 raeburn 6940: }
6941: }
6942: }
6943: }
6944: }
1.800 albertel 6945: foreach my $group (keys(%grouproles)) {
6946: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6947: }
1.800 albertel 6948: foreach my $role (keys(%{$allroles})) {
6949: my %thesepriv;
1.941 raeburn 6950: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6951: foreach my $item (split(/:/,$$allroles{$role})) {
6952: if ($item ne '') {
6953: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 6954: if ($restrictions eq '') {
6955: $thesepriv{$privilege}='F';
6956: } elsif ($thesepriv{$privilege} ne 'F') {
6957: $thesepriv{$privilege}.=$restrictions;
6958: }
6959: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341 raeburn 6960: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 6961: }
6962: }
6963: my $thesestr='';
1.1104 raeburn 6964: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 6965: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6966: }
6967: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 6968: }
1.1341 raeburn 6969: return ($author,$adv,$rar);
1.567 raeburn 6970: }
6971:
1.994 raeburn 6972: sub role_status {
1.1104 raeburn 6973: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 6974: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 6975: my ($one,$two) = split(m{\./},$rolekey,2);
6976: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 6977: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 6978: $$where = '/'.$two;
1.994 raeburn 6979: $$trolecode=$$role.'.'.$$where;
6980: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6981: $$tstatus='is';
1.1104 raeburn 6982: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6983: $$tstatus='future';
1.1034 raeburn 6984: if ($$tstart<$now) {
6985: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6986: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6987: my (%allroles,%allgroups,$group_privs,
6988: %groups_roles,@rolecodes);
1.1002 raeburn 6989: my %userroles = (
6990: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6991: );
1.1064 raeburn 6992: @rolecodes = ('cm');
1.1002 raeburn 6993: my $spec=$$role.'.'.$$where;
6994: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6995: if ($$role =~ /^cr\//) {
6996: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6997: push(@rolecodes,'cr');
1.1002 raeburn 6998: } elsif ($$role eq 'gr') {
1.1064 raeburn 6999: push(@rolecodes,$$role);
1.1002 raeburn 7000: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
7001: $env{'user.name'});
1.1064 raeburn 7002: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 7003: (undef,my $group_privs) = split(/\//,$trole);
7004: $group_privs = &unescape($group_privs);
7005: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 7006: 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 7007: &get_groups_roles($tdomain,$trest,
7008: \%course_roles,\@rolecodes,
7009: \%groups_roles);
1.1002 raeburn 7010: } else {
1.1064 raeburn 7011: push(@rolecodes,$$role);
1.1002 raeburn 7012: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
7013: }
1.1341 raeburn 7014: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
7015: \%groups_roles);
1.1064 raeburn 7016: &appenv(\%userroles,\@rolecodes);
1.1342 raeburn 7017: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 7018: }
7019: }
1.1034 raeburn 7020: $$tstatus = 'is';
1.1002 raeburn 7021: }
1.994 raeburn 7022: }
7023: if ($$tend) {
1.1104 raeburn 7024: if ($$tend<$update) {
1.994 raeburn 7025: $$tstatus='expired';
7026: } elsif ($$tend<$now) {
7027: $$tstatus='will_not';
7028: }
7029: }
7030: }
7031: }
7032: }
7033:
1.1104 raeburn 7034: sub get_groups_roles {
7035: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
7036: return unless((ref($cdom_courseroles) eq 'HASH') &&
7037: (ref($rolecodes) eq 'ARRAY') &&
7038: (ref($groups_roles) eq 'HASH'));
7039: if (keys(%{$cdom_courseroles}) > 0) {
7040: my ($cnum) = ($rest =~ /^($match_courseid)/);
7041: if ($cdom ne '' && $cnum ne '') {
7042: foreach my $key (keys(%{$cdom_courseroles})) {
7043: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
7044: my $crsrole = $1;
7045: my $crssec = $2;
7046: if ($crsrole =~ /^cr/) {
7047: unless (grep(/^cr$/,@{$rolecodes})) {
7048: push(@{$rolecodes},'cr');
7049: }
7050: } else {
7051: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
7052: push(@{$rolecodes},$crsrole);
7053: }
7054: }
7055: my $rolekey = "$crsrole./$cdom/$cnum";
7056: if ($crssec ne '') {
7057: $rolekey .= "/$crssec";
7058: }
7059: $rolekey .= './';
7060: $groups_roles->{$rolekey} = $rolecodes;
7061: }
7062: }
7063: }
7064: }
7065: return;
7066: }
7067:
7068: sub delete_env_groupprivs {
7069: my ($where,$courseroles,$possroles) = @_;
7070: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
7071: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
7072: unless (ref($courseroles->{$udom}) eq 'HASH') {
7073: %{$courseroles->{$udom}} =
7074: &get_my_roles('','','userroles',['active'],
7075: $possroles,[$udom],1);
7076: }
7077: if (ref($courseroles->{$udom}) eq 'HASH') {
7078: foreach my $item (keys(%{$courseroles->{$udom}})) {
7079: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
7080: my $area = '/'.$cdom.'/'.$cnum;
7081: my $privkey = "user.priv.$crsrole.$area";
7082: if ($crssec ne '') {
7083: $privkey .= '/'.$crssec;
7084: }
7085: $privkey .= ".$area/$group";
7086: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
7087: }
7088: }
7089: return;
7090: }
7091:
1.994 raeburn 7092: sub check_adhoc_privs {
1.1329 raeburn 7093: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 7094: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329 raeburn 7095: if ($sec) {
7096: $cckey .= '/'.$sec;
7097: }
1.1185 raeburn 7098: my $setprivs;
1.994 raeburn 7099: if ($env{$cckey}) {
7100: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 7101: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 7102: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329 raeburn 7103: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 7104: $setprivs = 1;
1.994 raeburn 7105: }
7106: } else {
1.1330 raeburn 7107: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 7108: $setprivs = 1;
1.994 raeburn 7109: }
1.1185 raeburn 7110: return $setprivs;
1.994 raeburn 7111: }
7112:
7113: sub set_adhoc_privileges {
1.1326 raeburn 7114: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329 raeburn 7115: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 7116: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329 raeburn 7117: if ($sec ne '') {
7118: $area .= '/'.$sec;
7119: }
1.994 raeburn 7120: my $spec = $role.'.'.$area;
7121: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 7122: $env{'user.name'},1);
1.1326 raeburn 7123: my %rolehash = ();
1.1332 raeburn 7124: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
7125: my $rolename = $1;
1.1326 raeburn 7126: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332 raeburn 7127: my %domdef = &get_domain_defaults($dcdom);
7128: if (ref($domdef{'adhocroles'}) eq 'HASH') {
7129: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
7130: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
7131: }
7132: }
1.1326 raeburn 7133: } else {
7134: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
7135: }
1.1341 raeburn 7136: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 7137: &appenv(\%userroles,[$role,'cm']);
1.1342 raeburn 7138: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402 raeburn 7139: unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
7140: ($caller eq 'tiny')) {
1.1088 raeburn 7141: &appenv( {'request.role' => $spec,
7142: 'request.role.domain' => $dcdom,
1.1332 raeburn 7143: 'request.course.sec' => $sec,
1.1088 raeburn 7144: }
7145: );
7146: my $tadv=0;
7147: if (&allowed('adv') eq 'F') { $tadv=1; }
7148: &appenv({'request.role.adv' => $tadv});
7149: }
1.994 raeburn 7150: }
7151:
1.12 www 7152: # --------------------------------------------------------------- get interface
7153:
7154: sub get {
1.131 albertel 7155: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7156: my $items='';
1.800 albertel 7157: foreach my $item (@$storearr) {
7158: $items.=&escape($item).'&';
1.191 harris41 7159: }
1.12 www 7160: $items=~s/\&$//;
1.620 albertel 7161: if (!$udomain) { $udomain=$env{'user.domain'}; }
7162: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 7163: my $uhome=&homeserver($uname,$udomain);
7164:
1.133 albertel 7165: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7166: my @pairs=split(/\&/,$rep);
1.273 albertel 7167: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
7168: return @pairs;
7169: }
1.15 www 7170: my %returnhash=();
1.42 www 7171: my $i=0;
1.800 albertel 7172: foreach my $item (@$storearr) {
7173: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7174: $i++;
1.191 harris41 7175: }
1.15 www 7176: return %returnhash;
1.27 www 7177: }
7178:
7179: # --------------------------------------------------------------- del interface
7180:
7181: sub del {
1.133 albertel 7182: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 7183: my $items='';
1.800 albertel 7184: foreach my $item (@$storearr) {
7185: $items.=&escape($item).'&';
1.191 harris41 7186: }
1.984 neumanie 7187:
1.27 www 7188: $items=~s/\&$//;
1.620 albertel 7189: if (!$udomain) { $udomain=$env{'user.domain'}; }
7190: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7191: my $uhome=&homeserver($uname,$udomain);
7192: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7193: }
7194:
7195: # -------------------------------------------------------------- dump interface
7196:
1.1180 droeschl 7197: sub unserialize {
7198: my ($rep, $escapedkeys) = @_;
7199:
7200: return {} if $rep =~ /^error/;
7201:
7202: my %returnhash=();
1.1252 raeburn 7203: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 7204: my ($key, $value) = split(/=/, $item, 2);
7205: $key = unescape($key) unless $escapedkeys;
7206: next if $key =~ /^error: 2 /;
1.1252 raeburn 7207: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 7208: }
7209: #return %returnhash;
7210: return \%returnhash;
7211: }
7212:
7213: # see Lond::dump_with_regexp
7214: # if $escapedkeys hash keys won't get unescaped.
1.15 www 7215: sub dump {
1.1462 raeburn 7216: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755 albertel 7217: if (!$udomain) { $udomain=$env{'user.domain'}; }
7218: if (!$uname) { $uname=$env{'user.name'}; }
7219: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 7220:
1.1266 raeburn 7221: if ($regexp) {
7222: $regexp=&escape($regexp);
7223: } else {
7224: $regexp='.';
7225: }
1.1180 droeschl 7226: if (grep { $_ eq $uhome } current_machine_ids()) {
7227: # user is hosted on this machine
1.1266 raeburn 7228: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 7229: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 7230: return %{unserialize($reply, $escapedkeys)};
7231: }
1.1462 raeburn 7232: my $rep;
7233: if ($encrypt) {
7234: $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.1463 raeburn 7235: } else {
1.1462 raeburn 7236: $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
7237: }
1.755 albertel 7238: my @pairs=split(/\&/,$rep);
7239: my %returnhash=();
1.1098 foxr 7240: if (!($rep =~ /^error/ )) {
7241: foreach my $item (@pairs) {
7242: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 7243: $key = unescape($key) unless $escapedkeys;
7244: #$key = &unescape($key);
1.1098 foxr 7245: next if ($key =~ /^error: 2 /);
7246: $returnhash{$key}=&thaw_unescape($value);
7247: }
1.755 albertel 7248: }
7249: return %returnhash;
1.407 www 7250: }
7251:
1.1098 foxr 7252:
1.717 albertel 7253: # --------------------------------------------------------- dumpstore interface
7254:
7255: sub dumpstore {
7256: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 7257: # same as dump but keys must be escaped. They may contain colon separated
7258: # lists of values that may themself contain colons (e.g. symbs).
7259: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 7260: }
7261:
1.407 www 7262: # -------------------------------------------------------------- keys interface
7263:
7264: sub getkeys {
7265: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 7266: if (!$udomain) { $udomain=$env{'user.domain'}; }
7267: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 7268: my $uhome=&homeserver($uname,$udomain);
7269: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
7270: my @keyarray=();
1.800 albertel 7271: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 7272: next if ($key =~ /^error: 2 /);
1.800 albertel 7273: push(@keyarray,&unescape($key));
1.407 www 7274: }
7275: return @keyarray;
1.318 matthew 7276: }
7277:
1.319 matthew 7278: # --------------------------------------------------------------- currentdump
7279: sub currentdump {
1.328 matthew 7280: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 7281: $courseid = $env{'request.course.id'} if (! defined($courseid));
7282: $sdom = $env{'user.domain'} if (! defined($sdom));
7283: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 7284: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 7285: my $rep;
7286:
7287: if (grep { $_ eq $uhome } current_machine_ids()) {
7288: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
7289: $courseid)));
7290: } else {
7291: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
7292: }
7293:
1.318 matthew 7294: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 7295: #
1.318 matthew 7296: my %returnhash=();
1.319 matthew 7297: #
1.1343 raeburn 7298: if ($rep eq 'unknown_cmd') {
1.319 matthew 7299: # an old lond will not know currentdump
7300: # Do a dump and make it look like a currentdump
1.822 albertel 7301: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 7302: return if ($tmp[0] =~ /^(error:|no_such_host)/);
7303: my %hash = @tmp;
7304: @tmp=();
1.424 matthew 7305: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 7306: } else {
7307: my @pairs=split(/\&/,$rep);
1.800 albertel 7308: foreach my $pair (@pairs) {
7309: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 7310: my ($symb,$param) = split(/:/,$key);
7311: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 7312: &thaw_unescape($value);
1.319 matthew 7313: }
1.191 harris41 7314: }
1.12 www 7315: return %returnhash;
1.424 matthew 7316: }
7317:
7318: sub convert_dump_to_currentdump{
7319: my %hash = %{shift()};
7320: my %returnhash;
7321: # Code ripped from lond, essentially. The only difference
7322: # here is the unescaping done by lonnet::dump(). Conceivably
7323: # we might run in to problems with parameter names =~ /^v\./
7324: while (my ($key,$value) = each(%hash)) {
7325: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 7326: $symb = &unescape($symb);
7327: $param = &unescape($param);
1.424 matthew 7328: next if ($v eq 'version' || $symb eq 'keys');
7329: next if (exists($returnhash{$symb}) &&
7330: exists($returnhash{$symb}->{$param}) &&
7331: $returnhash{$symb}->{'v.'.$param} > $v);
7332: $returnhash{$symb}->{$param}=$value;
7333: $returnhash{$symb}->{'v.'.$param}=$v;
7334: }
7335: #
7336: # Remove all of the keys in the hashes which keep track of
7337: # the version of the parameter.
7338: while (my ($symb,$param_hash) = each(%returnhash)) {
7339: # use a foreach because we are going to delete from the hash.
7340: foreach my $key (keys(%$param_hash)) {
7341: delete($param_hash->{$key}) if ($key =~ /^v\./);
7342: }
7343: }
7344: return \%returnhash;
1.12 www 7345: }
7346:
1.627 albertel 7347: # ------------------------------------------------------ critical inc interface
7348:
7349: sub cinc {
7350: return &inc(@_,'critical');
7351: }
7352:
1.449 matthew 7353: # --------------------------------------------------------------- inc interface
7354:
7355: sub inc {
1.627 albertel 7356: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 7357: if (!$udomain) { $udomain=$env{'user.domain'}; }
7358: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 7359: my $uhome=&homeserver($uname,$udomain);
7360: my $items='';
7361: if (! ref($store)) {
7362: # got a single value, so use that instead
7363: $items = &escape($store).'=&';
7364: } elsif (ref($store) eq 'SCALAR') {
7365: $items = &escape($$store).'=&';
7366: } elsif (ref($store) eq 'ARRAY') {
7367: $items = join('=&',map {&escape($_);} @{$store});
7368: } elsif (ref($store) eq 'HASH') {
7369: while (my($key,$value) = each(%{$store})) {
7370: $items.= &escape($key).'='.&escape($value).'&';
7371: }
7372: }
7373: $items=~s/\&$//;
1.627 albertel 7374: if ($critical) {
7375: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7376: } else {
7377: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7378: }
1.449 matthew 7379: }
7380:
1.12 www 7381: # --------------------------------------------------------------- put interface
7382:
7383: sub put {
1.1462 raeburn 7384: my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620 albertel 7385: if (!$udomain) { $udomain=$env{'user.domain'}; }
7386: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7387: my $uhome=&homeserver($uname,$udomain);
1.12 www 7388: my $items='';
1.800 albertel 7389: foreach my $item (keys(%$storehash)) {
7390: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7391: }
1.12 www 7392: $items=~s/\&$//;
1.1462 raeburn 7393: if ($encrypt) {
7394: return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
7395: } else {
7396: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
7397: }
1.47 www 7398: }
7399:
1.631 albertel 7400: # ------------------------------------------------------------ newput interface
7401:
7402: sub newput {
7403: my ($namespace,$storehash,$udomain,$uname)=@_;
7404: if (!$udomain) { $udomain=$env{'user.domain'}; }
7405: if (!$uname) { $uname=$env{'user.name'}; }
7406: my $uhome=&homeserver($uname,$udomain);
7407: my $items='';
7408: foreach my $key (keys(%$storehash)) {
7409: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7410: }
7411: $items=~s/\&$//;
7412: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7413: }
7414:
7415: # --------------------------------------------------------- putstore interface
7416:
1.524 raeburn 7417: sub putstore {
1.1269 raeburn 7418: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7419: if (!$udomain) { $udomain=$env{'user.domain'}; }
7420: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7421: my $uhome=&homeserver($uname,$udomain);
7422: my $items='';
1.715 albertel 7423: foreach my $key (keys(%$storehash)) {
7424: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7425: }
1.715 albertel 7426: $items=~s/\&$//;
1.716 albertel 7427: my $esc_symb=&escape($symb);
7428: my $esc_v=&escape($version);
1.715 albertel 7429: my $reply =
1.716 albertel 7430: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7431: $uhome);
1.1269 raeburn 7432: if (($tolog) && ($reply eq 'ok')) {
7433: my $namevalue='';
7434: foreach my $key (keys(%{$storehash})) {
7435: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7436: }
1.1434 raeburn 7437: my $ip = &get_requestor_ip();
7438: $namevalue .= 'ip='.&escape($ip).
1.1269 raeburn 7439: '&host='.&escape($perlvar{'lonHostID'}).
7440: '&version='.$esc_v.
7441: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7442: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7443: }
1.715 albertel 7444: if ($reply eq 'unknown_cmd') {
1.716 albertel 7445: # gfall back to way things use to be done
1.715 albertel 7446: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7447: $uname);
1.524 raeburn 7448: }
1.715 albertel 7449: return $reply;
7450: }
7451:
7452: sub old_putstore {
1.716 albertel 7453: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7454: if (!$udomain) { $udomain=$env{'user.domain'}; }
7455: if (!$uname) { $uname=$env{'user.name'}; }
7456: my $uhome=&homeserver($uname,$udomain);
7457: my %newstorehash;
1.800 albertel 7458: foreach my $item (keys(%$storehash)) {
7459: my $key = $version.':'.&escape($symb).':'.$item;
7460: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7461: }
7462: my $items='';
7463: my %allitems = ();
1.800 albertel 7464: foreach my $item (keys(%newstorehash)) {
7465: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7466: my $key = $1.':keys:'.$2;
7467: $allitems{$key} .= $3.':';
7468: }
1.800 albertel 7469: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7470: }
1.800 albertel 7471: foreach my $item (keys(%allitems)) {
7472: $allitems{$item} =~ s/\:$//;
7473: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7474: }
7475: $items=~s/\&$//;
7476: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7477: }
7478:
1.47 www 7479: # ------------------------------------------------------ critical put interface
7480:
7481: sub cput {
1.134 albertel 7482: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7483: if (!$udomain) { $udomain=$env{'user.domain'}; }
7484: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7485: my $uhome=&homeserver($uname,$udomain);
1.47 www 7486: my $items='';
1.800 albertel 7487: foreach my $item (keys(%$storehash)) {
7488: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7489: }
1.47 www 7490: $items=~s/\&$//;
1.134 albertel 7491: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7492: }
7493:
7494: # -------------------------------------------------------------- eget interface
7495:
7496: sub eget {
1.133 albertel 7497: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7498: my $items='';
1.800 albertel 7499: foreach my $item (@$storearr) {
7500: $items.=&escape($item).'&';
1.191 harris41 7501: }
1.12 www 7502: $items=~s/\&$//;
1.620 albertel 7503: if (!$udomain) { $udomain=$env{'user.domain'}; }
7504: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7505: my $uhome=&homeserver($uname,$udomain);
7506: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7507: my @pairs=split(/\&/,$rep);
7508: my %returnhash=();
1.42 www 7509: my $i=0;
1.800 albertel 7510: foreach my $item (@$storearr) {
7511: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7512: $i++;
1.191 harris41 7513: }
1.12 www 7514: return %returnhash;
7515: }
7516:
1.667 albertel 7517: # ------------------------------------------------------------ tmpput interface
7518: sub tmpput {
1.802 raeburn 7519: my ($storehash,$server,$context)=@_;
1.667 albertel 7520: my $items='';
1.800 albertel 7521: foreach my $item (keys(%$storehash)) {
7522: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7523: }
7524: $items=~s/\&$//;
1.802 raeburn 7525: if (defined($context)) {
7526: $items .= ':'.&escape($context);
7527: }
1.667 albertel 7528: return &reply("tmpput:$items",$server);
7529: }
7530:
7531: # ------------------------------------------------------------ tmpget interface
7532: sub tmpget {
1.688 albertel 7533: my ($token,$server)=@_;
7534: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7535: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7536: my %returnhash;
1.1328 raeburn 7537: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7538: return %returnhash;
7539: }
1.667 albertel 7540: foreach my $item (split(/\&/,$rep)) {
7541: my ($key,$value)=split(/=/,$item);
7542: $returnhash{&unescape($key)}=&thaw_unescape($value);
7543: }
7544: return %returnhash;
7545: }
7546:
1.1113 raeburn 7547: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7548: sub tmpdel {
7549: my ($token,$server)=@_;
7550: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7551: return &reply("tmpdel:$token",$server);
7552: }
7553:
1.1198 raeburn 7554: # ------------------------------------------------------------ get_timebased_id
7555:
7556: sub get_timebased_id {
7557: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7558: $maxtries) = @_;
7559: my ($newid,$error,$dellock);
7560: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7561: return ('','ok','invalid call to get suffix');
7562: }
7563:
7564: # set defaults for any optional args for which values were not supplied
7565: if ($who eq '') {
7566: $who = $env{'user.name'}.':'.$env{'user.domain'};
7567: }
7568: if (!$locktries) {
7569: $locktries = 3;
7570: }
7571: if (!$maxtries) {
7572: $maxtries = 10;
7573: }
7574:
7575: if (($cdom eq '') || ($cnum eq '')) {
7576: if ($env{'request.course.id'}) {
7577: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7578: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7579: }
7580: if (($cdom eq '') || ($cnum eq '')) {
7581: return ('','ok','call to get suffix not in course context');
7582: }
7583: }
7584:
7585: # construct locking item
7586: my $lockhash = {
7587: $prefix."\0".'locked_'.$keyid => $who,
7588: };
7589: my $tries = 0;
7590:
7591: # attempt to get lock on nohist_$namespace file
7592: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7593: while (($gotlock ne 'ok') && $tries <$locktries) {
7594: $tries ++;
7595: sleep 1;
7596: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7597: }
7598:
7599: # attempt to get unique identifier, based on current timestamp
7600: if ($gotlock eq 'ok') {
7601: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7602: my $id = time;
7603: $newid = $id;
1.1268 raeburn 7604: if ($idtype eq 'addcode') {
7605: $newid .= &sixnum_code();
7606: }
1.1198 raeburn 7607: my $idtries = 0;
7608: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7609: if ($idtype eq 'concat') {
7610: $newid = $id.$idtries;
1.1268 raeburn 7611: } elsif ($idtype eq 'addcode') {
7612: $newid = $newid.&sixnum_code();
1.1198 raeburn 7613: } else {
7614: $newid ++;
7615: }
7616: $idtries ++;
7617: }
7618: if (!exists($inuse{$prefix."\0".$newid})) {
7619: my %new_item = (
7620: $prefix."\0".$newid => $who,
7621: );
7622: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7623: $cdom,$cnum);
7624: if ($putresult ne 'ok') {
7625: undef($newid);
7626: $error = 'error saving new item: '.$putresult;
7627: }
7628: } else {
1.1268 raeburn 7629: undef($newid);
1.1198 raeburn 7630: $error = ('error: no unique suffix available for the new item ');
7631: }
7632: # remove lock
7633: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7634: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7635: } else {
7636: $error = "error: could not obtain lockfile\n";
7637: $dellock = 'ok';
1.1276 raeburn 7638: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7639: $dellock = 'nolock';
7640: }
1.1198 raeburn 7641: }
7642: return ($newid,$dellock,$error);
7643: }
7644:
1.1268 raeburn 7645: sub sixnum_code {
7646: my $code;
7647: for (0..6) {
7648: $code .= int( rand(9) );
7649: }
7650: return $code;
7651: }
7652:
1.765 albertel 7653: # -------------------------------------------------- portfolio access checking
7654:
7655: sub portfolio_access {
1.1270 raeburn 7656: my ($requrl,$clientip) = @_;
1.765 albertel 7657: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 7658: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7659: if ($result) {
7660: my %setters;
7661: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1473 raeburn 7662: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7663: &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
7664: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7665: return 'B';
7666: }
7667: } else {
1.1473 raeburn 7668: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
7669: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
7670: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 7671: return 'B';
7672: }
7673: }
7674: }
1.765 albertel 7675: if ($result eq 'ok') {
1.766 albertel 7676: return 'F';
1.765 albertel 7677: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7678: return 'A';
1.765 albertel 7679: }
1.766 albertel 7680: return '';
1.765 albertel 7681: }
7682:
7683: sub get_portfolio_access {
1.1270 raeburn 7684: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7685:
7686: if (!ref($access_hash)) {
7687: my $current_perms = &get_portfile_permissions($udom,$unum);
7688: my %access_controls = &get_access_controls($current_perms,$group,
7689: $file_name);
7690: $access_hash = $access_controls{$file_name};
7691: }
7692:
1.1270 raeburn 7693: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7694: my $now = time;
7695: if (ref($access_hash) eq 'HASH') {
7696: foreach my $key (keys(%{$access_hash})) {
7697: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7698: if ($start > $now) {
7699: next;
7700: }
7701: if ($end && $end<$now) {
7702: next;
7703: }
7704: if ($scope eq 'public') {
7705: $public = $key;
7706: last;
7707: } elsif ($scope eq 'guest') {
7708: $guest = $key;
7709: } elsif ($scope eq 'domains') {
7710: push(@domains,$key);
7711: } elsif ($scope eq 'users') {
7712: push(@users,$key);
7713: } elsif ($scope eq 'course') {
7714: push(@courses,$key);
7715: } elsif ($scope eq 'group') {
7716: push(@groups,$key);
1.1270 raeburn 7717: } elsif ($scope eq 'ip') {
7718: push(@ips,$key);
1.765 albertel 7719: }
7720: }
7721: if ($public) {
7722: return 'ok';
1.1270 raeburn 7723: } elsif (@ips > 0) {
7724: my $allowed;
7725: foreach my $ipkey (@ips) {
7726: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7727: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7728: $allowed = 1;
7729: last;
7730: }
7731: }
7732: }
7733: if ($allowed) {
7734: return 'ok';
7735: }
1.765 albertel 7736: }
7737: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7738: if ($guest) {
7739: return $guest;
7740: }
7741: } else {
7742: if (@domains > 0) {
7743: foreach my $domkey (@domains) {
7744: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7745: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7746: return 'ok';
7747: }
7748: }
7749: }
7750: }
7751: if (@users > 0) {
7752: foreach my $userkey (@users) {
1.865 raeburn 7753: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7754: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7755: if (ref($item) eq 'HASH') {
7756: if (($item->{'uname'} eq $env{'user.name'}) &&
7757: ($item->{'udom'} eq $env{'user.domain'})) {
7758: return 'ok';
7759: }
7760: }
7761: }
7762: }
1.765 albertel 7763: }
7764: }
7765: my %roleshash;
7766: my @courses_and_groups = @courses;
7767: push(@courses_and_groups,@groups);
7768: if (@courses_and_groups > 0) {
7769: my (%allgroups,%allroles);
7770: my ($start,$end,$role,$sec,$group);
7771: foreach my $envkey (%env) {
1.1060 raeburn 7772: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7773: my $cid = $2.'_'.$3;
7774: if ($1 eq 'gr') {
7775: $group = $4;
7776: $allgroups{$cid}{$group} = $env{$envkey};
7777: } else {
7778: if ($4 eq '') {
7779: $sec = 'none';
7780: } else {
7781: $sec = $4;
7782: }
7783: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7784: }
1.811 albertel 7785: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7786: my $cid = $2.'_'.$3;
7787: if ($4 eq '') {
7788: $sec = 'none';
7789: } else {
7790: $sec = $4;
7791: }
7792: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7793: }
7794: }
7795: if (keys(%allroles) == 0) {
7796: return;
7797: }
7798: foreach my $key (@courses_and_groups) {
7799: my %content = %{$$access_hash{$key}};
7800: my $cnum = $content{'number'};
7801: my $cdom = $content{'domain'};
7802: my $cid = $cdom.'_'.$cnum;
7803: if (!exists($allroles{$cid})) {
7804: next;
7805: }
7806: foreach my $role_id (keys(%{$content{'roles'}})) {
7807: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7808: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7809: my @status = @{$content{'roles'}{$role_id}{'access'}};
7810: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7811: foreach my $role (keys(%{$allroles{$cid}})) {
7812: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7813: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7814: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7815: if (grep/^all$/,@sections) {
7816: return 'ok';
7817: } else {
7818: if (grep/^$sec$/,@sections) {
7819: return 'ok';
7820: }
7821: }
7822: }
7823: }
7824: if (keys(%{$allgroups{$cid}}) == 0) {
7825: if (grep/^none$/,@groups) {
7826: return 'ok';
7827: }
7828: } else {
7829: if (grep/^all$/,@groups) {
7830: return 'ok';
7831: }
7832: foreach my $group (keys(%{$allgroups{$cid}})) {
7833: if (grep/^$group$/,@groups) {
7834: return 'ok';
7835: }
7836: }
7837: }
7838: }
7839: }
7840: }
7841: }
7842: }
7843: if ($guest) {
7844: return $guest;
7845: }
7846: }
7847: }
7848: return;
7849: }
7850:
7851: sub course_group_datechecker {
7852: my ($dates,$now,$status) = @_;
7853: my ($start,$end) = split(/\./,$dates);
7854: if (!$start && !$end) {
7855: return 'ok';
7856: }
7857: if (grep/^active$/,@{$status}) {
7858: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7859: return 'ok';
7860: }
7861: }
7862: if (grep/^previous$/,@{$status}) {
7863: if ($end > $now ) {
7864: return 'ok';
7865: }
7866: }
7867: if (grep/^future$/,@{$status}) {
7868: if ($start > $now) {
7869: return 'ok';
7870: }
7871: }
7872: return;
7873: }
7874:
7875: sub parse_portfolio_url {
7876: my ($url) = @_;
7877:
7878: my ($type,$udom,$unum,$group,$file_name);
7879:
1.823 albertel 7880: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7881: $type = 1;
7882: $udom = $1;
7883: $unum = $2;
7884: $file_name = $3;
1.823 albertel 7885: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7886: $type = 2;
7887: $udom = $1;
7888: $unum = $2;
7889: $group = $3;
7890: $file_name = $3.'/'.$4;
7891: }
7892: if (wantarray) {
7893: return ($type,$udom,$unum,$file_name,$group);
7894: }
7895: return $type;
7896: }
7897:
7898: sub is_portfolio_url {
7899: my ($url) = @_;
7900: return scalar(&parse_portfolio_url($url));
7901: }
7902:
1.798 raeburn 7903: sub is_portfolio_file {
7904: my ($file) = @_;
1.820 raeburn 7905: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7906: return 1;
7907: }
7908: return;
7909: }
7910:
1.976 raeburn 7911: sub usertools_access {
1.1084 raeburn 7912: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7913: my ($access,%tools);
7914: if ($context eq '') {
7915: $context = 'tools';
7916: }
7917: if ($context eq 'requestcourses') {
7918: %tools = (
7919: official => 1,
7920: unofficial => 1,
1.1006 raeburn 7921: community => 1,
1.1246 raeburn 7922: textbook => 1,
1.1305 raeburn 7923: placement => 1,
1.1368 raeburn 7924: lti => 1,
1.985 raeburn 7925: );
1.1183 raeburn 7926: } elsif ($context eq 'requestauthor') {
7927: %tools = (
7928: requestauthor => 1,
7929: );
1.985 raeburn 7930: } else {
7931: %tools = (
7932: aboutme => 1,
7933: blog => 1,
1.1177 raeburn 7934: webdav => 1,
1.985 raeburn 7935: portfolio => 1,
7936: );
7937: }
1.976 raeburn 7938: return if (!defined($tools{$tool}));
7939:
1.1242 raeburn 7940: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7941: $udom = $env{'user.domain'};
7942: $uname = $env{'user.name'};
7943: }
7944:
1.978 raeburn 7945: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7946: if ($action ne 'reload') {
1.985 raeburn 7947: if ($context eq 'requestcourses') {
7948: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 7949: } elsif ($context eq 'requestauthor') {
7950: return $env{'environment.canrequest.author'};
1.985 raeburn 7951: } else {
7952: return $env{'environment.availabletools.'.$tool};
7953: }
7954: }
1.976 raeburn 7955: }
7956:
1.1183 raeburn 7957: my ($toolstatus,$inststatus,$envkey);
7958: if ($context eq 'requestauthor') {
7959: $envkey = $context;
7960: } else {
7961: $envkey = $context.'.'.$tool;
7962: }
1.976 raeburn 7963:
1.985 raeburn 7964: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7965: ($action ne 'reload')) {
1.1183 raeburn 7966: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 7967: $inststatus = $env{'environment.inststatus'};
7968: } else {
1.1084 raeburn 7969: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 7970: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 7971: $inststatus = $userenvref->{'inststatus'};
7972: } else {
1.1183 raeburn 7973: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7974: $toolstatus = $userenv{$envkey};
1.1084 raeburn 7975: $inststatus = $userenv{'inststatus'};
7976: }
1.976 raeburn 7977: }
7978:
7979: if ($toolstatus ne '') {
7980: if ($toolstatus) {
7981: $access = 1;
7982: } else {
7983: $access = 0;
7984: }
7985: return $access;
7986: }
7987:
1.1084 raeburn 7988: my ($is_adv,%domdef);
7989: if (ref($is_advref) eq 'HASH') {
7990: $is_adv = $is_advref->{'is_adv'};
7991: } else {
7992: $is_adv = &is_advanced_user($udom,$uname);
7993: }
7994: if (ref($domdefref) eq 'HASH') {
7995: %domdef = %{$domdefref};
7996: } else {
7997: %domdef = &get_domain_defaults($udom);
7998: }
1.976 raeburn 7999: if (ref($domdef{$tool}) eq 'HASH') {
8000: if ($is_adv) {
8001: if ($domdef{$tool}{'_LC_adv'} ne '') {
8002: if ($domdef{$tool}{'_LC_adv'}) {
8003: $access = 1;
8004: } else {
8005: $access = 0;
8006: }
8007: return $access;
8008: }
8009: }
8010: if ($inststatus ne '') {
8011: my ($hasaccess,$hasnoaccess);
8012: foreach my $affiliation (split(/:/,$inststatus)) {
8013: if ($domdef{$tool}{$affiliation} ne '') {
8014: if ($domdef{$tool}{$affiliation}) {
8015: $hasaccess = 1;
8016: } else {
8017: $hasnoaccess = 1;
8018: }
8019: }
8020: }
8021: if ($hasaccess || $hasnoaccess) {
8022: if ($hasaccess) {
8023: $access = 1;
8024: } elsif ($hasnoaccess) {
8025: $access = 0;
8026: }
8027: return $access;
8028: }
8029: } else {
8030: if ($domdef{$tool}{'default'} ne '') {
8031: if ($domdef{$tool}{'default'}) {
8032: $access = 1;
8033: } elsif ($domdef{$tool}{'default'} == 0) {
8034: $access = 0;
8035: }
8036: return $access;
8037: }
8038: }
8039: } else {
1.1177 raeburn 8040: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 8041: $access = 1;
8042: } else {
8043: $access = 0;
8044: }
1.976 raeburn 8045: return $access;
8046: }
8047: }
8048:
1.1050 raeburn 8049: sub is_course_owner {
8050: my ($cdom,$cnum,$udom,$uname) = @_;
8051: if (($udom eq '') || ($uname eq '')) {
8052: $udom = $env{'user.domain'};
8053: $uname = $env{'user.name'};
8054: }
8055: unless (($udom eq '') || ($uname eq '')) {
8056: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
8057: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
8058: return 1;
8059: } else {
8060: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
8061: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
8062: return 1;
8063: }
8064: }
8065: }
8066: }
8067: return;
8068: }
8069:
1.976 raeburn 8070: sub is_advanced_user {
8071: my ($udom,$uname) = @_;
1.1085 raeburn 8072: if ($udom ne '' && $uname ne '') {
8073: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 8074: if (wantarray) {
8075: return ($env{'user.adv'},$env{'user.author'});
8076: } else {
8077: return $env{'user.adv'};
8078: }
1.1085 raeburn 8079: }
8080: }
1.976 raeburn 8081: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
8082: my %allroles;
1.1128 raeburn 8083: my ($is_adv,$is_author);
1.976 raeburn 8084: foreach my $role (keys(%roleshash)) {
8085: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
8086: my $area = '/'.$tdomain.'/'.$trest;
8087: if ($sec ne '') {
8088: $area .= '/'.$sec;
8089: }
8090: if (($area ne '') && ($trole ne '')) {
8091: my $spec=$trole.'.'.$area;
8092: if ($trole =~ /^cr\//) {
8093: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
8094: } elsif ($trole ne 'gr') {
8095: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
8096: }
1.1128 raeburn 8097: if ($trole eq 'au') {
8098: $is_author = 1;
8099: }
1.976 raeburn 8100: }
8101: }
8102: foreach my $role (keys(%allroles)) {
8103: last if ($is_adv);
8104: foreach my $item (split(/:/,$allroles{$role})) {
8105: if ($item ne '') {
8106: my ($privilege,$restrictions)=split(/&/,$item);
8107: if ($privilege eq 'adv') {
8108: $is_adv = 1;
8109: last;
8110: }
8111: }
8112: }
8113: }
1.1128 raeburn 8114: if (wantarray) {
8115: return ($is_adv,$is_author);
8116: }
1.976 raeburn 8117: return $is_adv;
8118: }
1.798 raeburn 8119:
1.1035 raeburn 8120: sub check_can_request {
1.1368 raeburn 8121: my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035 raeburn 8122: my $canreq = 0;
1.1368 raeburn 8123: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8124: $uname = $env{'user.name'};
8125: $udom = $env{'user.domain'};
8126: }
1.1035 raeburn 8127: my ($types,$typename) = &Apache::loncommon::course_types();
8128: my @options = ('approval','validate','autolimit');
8129: my $optregex = join('|',@options);
8130: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
8131: foreach my $type (@{$types}) {
1.1368 raeburn 8132: if (&usertools_access($uname,$udom,$type,undef,
8133: 'requestcourses')) {
1.1035 raeburn 8134: $canreq ++;
1.1036 raeburn 8135: if (ref($request_domains) eq 'HASH') {
1.1368 raeburn 8136: push(@{$request_domains->{$type}},$udom);
1.1036 raeburn 8137: }
1.1368 raeburn 8138: if ($dom eq $udom) {
1.1035 raeburn 8139: $can_request->{$type} = 1;
8140: }
8141: }
1.1368 raeburn 8142: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
8143: ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035 raeburn 8144: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
8145: if (@curr > 0) {
1.1036 raeburn 8146: foreach my $item (@curr) {
8147: if (ref($request_domains) eq 'HASH') {
8148: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
8149: if ($otherdom ne '') {
8150: if (ref($request_domains->{$type}) eq 'ARRAY') {
8151: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
8152: push(@{$request_domains->{$type}},$otherdom);
8153: }
8154: } else {
8155: push(@{$request_domains->{$type}},$otherdom);
8156: }
8157: }
8158: }
8159: }
1.1368 raeburn 8160: unless ($dom eq $env{'user.domain'}) {
1.1036 raeburn 8161: $canreq ++;
1.1035 raeburn 8162: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
8163: $can_request->{$type} = 1;
8164: }
8165: }
8166: }
8167: }
8168: }
8169: }
8170: return $canreq;
8171: }
8172:
1.341 www 8173: # ---------------------------------------------- Custom access rule evaluation
8174:
8175: sub customaccess {
8176: my ($priv,$uri)=@_;
1.807 albertel 8177: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 8178: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 8179: $udom = &LONCAPA::clean_domain($udom);
8180: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 8181: my $access=0;
1.800 albertel 8182: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 8183: my ($effect,$realm,$role,$type)=split(/\:/,$right);
8184: if ($type eq 'user') {
8185: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 8186: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 8187: if ($tdom) {
8188: if ($tdom ne $env{'user.domain'}) { next; }
8189: }
1.896 albertel 8190: if ($tuname) {
8191: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 8192: }
8193: $access=($effect eq 'allow');
8194: last;
8195: }
8196: } else {
8197: if ($role) {
8198: if ($role ne $urole) { next; }
8199: }
8200: foreach my $scope (split(/\s*\,\s*/,$realm)) {
8201: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
8202: if ($tdom) {
8203: if ($tdom ne $udom) { next; }
8204: }
8205: if ($tcrs) {
8206: if ($tcrs ne $ucrs) { next; }
8207: }
8208: if ($tsec) {
8209: if ($tsec ne $usec) { next; }
8210: }
8211: $access=($effect eq 'allow');
8212: last;
8213: }
8214: if ($realm eq '' && $role eq '') {
8215: $access=($effect eq 'allow');
8216: }
1.402 bowersj2 8217: }
1.341 www 8218: }
8219: return $access;
8220: }
8221:
1.103 harris41 8222: # ------------------------------------------------- Check for a user privilege
1.12 www 8223:
8224: sub allowed {
1.1461 raeburn 8225: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705 albertel 8226: my $ver_orguri=$uri;
1.439 www 8227: $uri=&deversion($uri);
1.152 www 8228: my $orguri=$uri;
1.52 www 8229: $uri=&declutter($uri);
1.809 raeburn 8230:
1.810 raeburn 8231: if ($priv eq 'evb') {
1.1478 raeburn 8232: # Evade communication block restrictions for specified role in a course or domain
1.810 raeburn 8233: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
8234: return $1;
8235: } else {
8236: return;
8237: }
8238: }
8239:
1.620 albertel 8240: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 8241: # Free bre access to adm and meta resources
1.1436 raeburn 8242: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$}))
1.769 albertel 8243: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
8244: && ($priv eq 'bre')) {
1.14 www 8245: return 'F';
1.159 www 8246: }
8247:
1.545 banghart 8248: # Free bre access to user's own portfolio contents
1.714 raeburn 8249: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 8250: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 8251: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 8252: my %setters;
1.1473 raeburn 8253: my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
8254: &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
8255: if (($startblock && $endblock) || ($by_ip)) {
1.814 raeburn 8256: return 'B';
8257: } else {
8258: return 'F';
8259: }
1.545 banghart 8260: }
8261:
1.762 raeburn 8262: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 8263: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
8264: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
8265: if (exists($env{'request.course.id'})) {
8266: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8267: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8268: if (($domain eq $cdom) && ($name eq $cnum)) {
8269: my $courseprivid=$env{'request.course.id'};
8270: $courseprivid=~s/\_/\//;
8271: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
8272: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
8273: return $1;
1.762 raeburn 8274: } else {
8275: if ($env{'request.course.sec'}) {
8276: $courseprivid.='/'.$env{'request.course.sec'};
8277: }
8278: if ($env{'user.priv.'.$env{'request.role'}.'./'.
8279: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
8280: return $2;
8281: }
1.714 raeburn 8282: }
8283: }
8284: }
8285: }
8286:
1.159 www 8287: # Free bre to public access
8288:
8289: if ($priv eq 'bre') {
1.1362 raeburn 8290: my $copyright;
8291: unless ($uri =~ /ext\.tool/) {
8292: $copyright=&metadata($uri,'copyright');
8293: }
1.620 albertel 8294: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 8295: return 'F';
8296: }
1.238 www 8297: if ($copyright eq 'priv') {
8298: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8299: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 8300: return '';
8301: }
8302: }
8303: if ($copyright eq 'domain') {
8304: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8305: unless (($env{'user.domain'} eq $1) ||
8306: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 8307: return '';
8308: }
1.262 matthew 8309: }
1.620 albertel 8310: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 8311: # Library role, so allow browsing of resources in this domain.
8312: return 'F';
1.238 www 8313: }
1.341 www 8314: if ($copyright eq 'custom') {
8315: unless (&customaccess($priv,$uri)) { return ''; }
8316: }
1.14 www 8317: }
1.264 matthew 8318: # Domain coordinator is trying to create a course
1.620 albertel 8319: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 8320: # uri is the requested domain in this case.
8321: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 8322: # a role of dc for the domain in question.
1.620 albertel 8323: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 8324: }
1.29 www 8325:
1.52 www 8326: my $thisallowed='';
8327: my $statecond=0;
8328: my $courseprivid='';
8329:
1.1039 raeburn 8330: my $ownaccess;
1.1043 raeburn 8331: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 8332: if (($priv eq 'bro') && ($env{'user.author'})) {
8333: if ($uri eq '') {
8334: $ownaccess = 1;
8335: } else {
8336: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8337: my $udom = $env{'user.domain'};
8338: my $uname = $env{'user.name'};
8339: if ($uri =~ m{^\Q$udom\E/?$}) {
8340: $ownaccess = 1;
1.1040 raeburn 8341: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 8342: unless ($uri =~ m{\.\./}) {
8343: $ownaccess = 1;
8344: }
8345: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8346: my $now = time;
8347: if ($uri =~ m{^([^/]+)/?$}) {
8348: my $adom = $1;
8349: foreach my $key (keys(%env)) {
1.1042 raeburn 8350: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1452 raeburn 8351: my ($start,$end) = split(/\./,$env{$key});
8352: if (($now >= $start) && (!$end || $end > $now)) {
1.1039 raeburn 8353: $ownaccess = 1;
8354: last;
8355: }
8356: }
8357: }
8358: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8359: my $adom = $1;
8360: my $aname = $2;
1.1042 raeburn 8361: foreach my $role ('ca','aa') {
8362: if ($env{"user.role.$role./$adom/$aname"}) {
8363: my ($start,$end) =
1.1452 raeburn 8364: split(/\./,$env{"user.role.$role./$adom/$aname"});
8365: if (($now >= $start) && (!$end || $end > $now)) {
1.1042 raeburn 8366: $ownaccess = 1;
8367: last;
8368: }
1.1039 raeburn 8369: }
8370: }
8371: }
8372: }
8373: }
8374: }
8375: }
8376:
1.52 www 8377: # Course
8378:
1.620 albertel 8379: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8380: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8381: $thisallowed.=$1;
8382: }
1.52 www 8383: }
1.29 www 8384:
1.52 www 8385: # Domain
8386:
1.620 albertel 8387: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 8388: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8389: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8390: $thisallowed.=$1;
8391: }
1.12 www 8392: }
1.52 www 8393:
1.1141 raeburn 8394: # User who is not author or co-author might still be able to edit
8395: # resource of an author in the domain (e.g., if Domain Coordinator).
8396: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8397: (&allowed('mdc',$env{'request.course.id'}))) {
8398: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8399: $thisallowed.=$1;
8400: }
8401: }
8402:
1.52 www 8403: # Course: uri itself is a course
1.66 www 8404: my $courseuri=$uri;
8405: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8406: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8407:
1.620 albertel 8408: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8409: =~/\Q$priv\E\&([^\:]*)/) {
1.1409 raeburn 8410: if ($priv eq 'mip') {
8411: my $rem = $1;
8412: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8413: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8414: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8415: if ($cdom ne '') {
1.1410 raeburn 8416: my %passwdconf = &get_passwdconf($cdom);
8417: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8418: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8419: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8420: my @inststatuses = split(':',$env{'environment.inststatus'});
8421: unless (@inststatuses) {
8422: @inststatuses = ('default');
8423: }
8424: foreach my $status (@inststatuses) {
8425: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8426: $thisallowed.=$rem;
8427: }
8428: }
8429: }
8430: }
1.1409 raeburn 8431: }
8432: }
8433: }
8434: } else {
8435: unless (($priv eq 'bro') && (!$ownaccess)) {
8436: $thisallowed.=$1;
8437: }
1.1039 raeburn 8438: }
1.12 www 8439: }
1.29 www 8440:
1.665 albertel 8441: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8442: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8443: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8444: $thisallowed='';
1.671 raeburn 8445: my ($match)=&is_on_map($uri);
8446: if ($match) {
8447: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8448: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 8449: my $value = $1;
1.1461 raeburn 8450: my $deeplinkblock;
8451: unless ($nodeeplinkcheck) {
8452: $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8453: }
1.1402 raeburn 8454: if ($deeplinkblock) {
8455: $thisallowed='D';
8456: } elsif ($noblockcheck) {
1.1281 raeburn 8457: $thisallowed.=$value;
1.1162 raeburn 8458: } else {
1.1424 raeburn 8459: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281 raeburn 8460: if (@blockers > 0) {
8461: $thisallowed = 'B';
8462: } else {
8463: $thisallowed.=$value;
8464: }
1.1162 raeburn 8465: }
1.671 raeburn 8466: }
8467: } else {
1.705 albertel 8468: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8469: if ($refuri) {
8470: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8471: $thisallowed='F';
1.671 raeburn 8472: } else {
8473: $refuri=&declutter($refuri);
8474: my ($match) = &is_on_map($refuri);
8475: if ($match) {
1.1461 raeburn 8476: my $deeplinkblock;
8477: unless ($nodeeplinkcheck) {
8478: $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8479: }
1.1402 raeburn 8480: if ($deeplinkblock) {
8481: $thisallowed='D';
8482: } elsif ($noblockcheck) {
1.1281 raeburn 8483: $thisallowed='F';
1.1162 raeburn 8484: } else {
1.1426 raeburn 8485: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281 raeburn 8486: if (@blockers > 0) {
8487: $thisallowed = 'B';
8488: } else {
8489: $thisallowed='F';
8490: }
1.1162 raeburn 8491: }
1.671 raeburn 8492: }
1.669 raeburn 8493: }
1.671 raeburn 8494: }
8495: }
1.314 www 8496: }
1.492 albertel 8497:
1.766 albertel 8498: if ($priv eq 'bre'
8499: && $thisallowed ne 'F'
8500: && $thisallowed ne '2'
8501: && &is_portfolio_url($uri)) {
1.1270 raeburn 8502: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8503: }
1.1250 raeburn 8504:
1.52 www 8505: # Full access at system, domain or course-wide level? Exit.
1.29 www 8506: if ($thisallowed=~/F/) {
8507: return 'F';
8508: }
8509:
1.52 www 8510: # If this is generating or modifying users, exit with special codes
1.29 www 8511:
1.643 www 8512: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8513: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8514: my ($audom,$auname)=split('/',$uri);
1.643 www 8515: # no author name given, so this just checks on the general right to make a co-author in this domain
8516: unless ($auname) { return $thisallowed; }
8517: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8518: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8519: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8520: ($audom ne $env{'request.role.domain'}))) { return ''; }
8521: }
1.52 www 8522: return $thisallowed;
8523: }
8524: #
1.103 harris41 8525: # Gathered so far: system, domain and course wide privileges
1.52 www 8526: #
8527: # Course: See if uri or referer is an individual resource that is part of
8528: # the course
8529:
1.620 albertel 8530: if ($env{'request.course.id'}) {
1.232 www 8531:
1.1409 raeburn 8532: # If this is modifying password (internal auth) domains must match for user and user's role.
8533:
8534: if ($priv eq 'mip') {
8535: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8536: return $thisallowed;
8537: } else {
8538: return '';
8539: }
8540: }
8541:
1.620 albertel 8542: $courseprivid=$env{'request.course.id'};
8543: if ($env{'request.course.sec'}) {
8544: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8545: }
8546: $courseprivid=~s/\_/\//;
8547: my $checkreferer=1;
1.232 www 8548: my ($match,$cond)=&is_on_map($uri);
8549: if ($match) {
8550: $statecond=$cond;
1.620 albertel 8551: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8552: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8553: my $value = $1;
8554: if ($priv eq 'bre') {
1.1461 raeburn 8555: my $deeplinkblock;
8556: unless ($nodeeplinkcheck) {
8557: $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8558: }
1.1458 raeburn 8559: if ($deeplinkblock) {
8560: $thisallowed = 'D';
8561: } elsif ($noblockcheck) {
1.1281 raeburn 8562: $thisallowed.=$value;
1.1162 raeburn 8563: } else {
1.1424 raeburn 8564: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281 raeburn 8565: if (@blockers > 0) {
8566: $thisallowed = 'B';
8567: } else {
8568: $thisallowed.=$value;
8569: }
1.1162 raeburn 8570: }
8571: } else {
8572: $thisallowed.=$value;
8573: }
1.52 www 8574: $checkreferer=0;
8575: }
1.29 www 8576: }
1.1424 raeburn 8577:
1.148 www 8578: if ($checkreferer) {
1.620 albertel 8579: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8580: unless ($refuri) {
1.800 albertel 8581: foreach my $key (keys(%env)) {
8582: if ($key=~/^httpref\..*\*/) {
8583: my $pattern=$key;
1.156 www 8584: $pattern=~s/^httpref\.\/res\///;
1.148 www 8585: $pattern=~s/\*/\[\^\/\]\+/g;
8586: $pattern=~s/\//\\\//g;
1.152 www 8587: if ($orguri=~/$pattern/) {
1.800 albertel 8588: $refuri=$env{$key};
1.148 www 8589: }
8590: }
1.191 harris41 8591: }
1.148 www 8592: }
1.232 www 8593:
1.148 www 8594: if ($refuri) {
1.152 www 8595: $refuri=&declutter($refuri);
1.232 www 8596: my ($match,$cond)=&is_on_map($refuri);
8597: if ($match) {
8598: my $refstatecond=$cond;
1.620 albertel 8599: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8600: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8601: my $value = $1;
8602: if ($priv eq 'bre') {
1.1461 raeburn 8603: my $deeplinkblock;
8604: unless ($nodeeplinkcheck) {
8605: $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8606: }
1.1402 raeburn 8607: if ($deeplinkblock) {
8608: $thisallowed = 'D';
8609: } elsif ($noblockcheck) {
1.1281 raeburn 8610: $thisallowed.=$value;
1.1162 raeburn 8611: } else {
1.1426 raeburn 8612: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281 raeburn 8613: if (@blockers > 0) {
8614: $thisallowed = 'B';
8615: } else {
8616: $thisallowed.=$value;
8617: }
1.1162 raeburn 8618: }
8619: } else {
8620: $thisallowed.=$value;
8621: }
1.53 www 8622: $uri=$refuri;
8623: $statecond=$refstatecond;
1.52 www 8624: }
8625: }
1.148 www 8626: }
1.29 www 8627: }
1.52 www 8628: }
1.29 www 8629:
1.52 www 8630: #
1.103 harris41 8631: # Gathered now: all privileges that could apply, and condition number
1.52 www 8632: #
8633: #
8634: # Full or no access?
8635: #
1.29 www 8636:
1.52 www 8637: if ($thisallowed=~/F/) {
8638: return 'F';
8639: }
1.29 www 8640:
1.52 www 8641: unless ($thisallowed) {
8642: return '';
8643: }
1.29 www 8644:
1.52 www 8645: # Restrictions exist, deal with them
8646: #
8647: # C:according to course preferences
8648: # R:according to resource settings
8649: # L:unless locked
8650: # X:according to user session state
8651: #
8652:
8653: # Possibly locked functionality, check all courses
1.1454 raeburn 8654: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54 www 8655: # Locks might take effect only after 10 minutes cache expiration for other
1.1454 raeburn 8656: # courses, and 2 minutes for current course, in which user has st or ta role
8657: # which is neither expired nor a future role (unless current course).
1.52 www 8658:
1.1454 raeburn 8659: my ($needlockcheck,$now,$crsonly);
1.52 www 8660: if ($thisallowed=~/L/) {
1.1454 raeburn 8661: $now = time;
8662: if ($priv eq 'bre') {
8663: if ($uri ne '') {
8664: if ($orguri =~ m{^/+res/}) {
8665: if ($uri =~ m{^lib/templates/}) {
8666: if ($env{'request.course.id'}) {
8667: $crsonly = 1;
8668: $needlockcheck = 1;
8669: }
8670: } else {
8671: $needlockcheck = 1;
8672: }
8673: } elsif ($env{'request.course.id'}) {
8674: my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
8675: if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
8676: ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
8677: $crsonly = 1;
8678: }
8679: $needlockcheck = 1;
8680: }
8681: }
8682: } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
8683: $needlockcheck = 1;
8684: }
8685: }
8686: if ($needlockcheck) {
1.1453 raeburn 8687: foreach my $envkey (keys(%env)) {
1.54 www 8688: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8689: my $courseid=$2;
8690: my $roleid=$1.'.'.$2;
1.92 www 8691: $courseid=~s/^\///;
1.1453 raeburn 8692: unless ($env{'request.role'} eq $roleid) {
8693: my ($start,$end) = split(/\./,$env{$envkey});
8694: next unless (($now >= $start) && (!$end || $end > $now));
8695: }
1.54 www 8696: my $expiretime=600;
1.620 albertel 8697: if ($env{'request.role'} eq $roleid) {
1.54 www 8698: $expiretime=120;
8699: }
8700: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8701: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8702: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8703: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8704: }
1.620 albertel 8705: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8706: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8707: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8708: &log($env{'user.domain'},$env{'user.name'},
8709: $env{'user.home'},
1.57 www 8710: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8711: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8712: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8713: return '';
8714: }
8715: }
1.620 albertel 8716: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8717: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1455 raeburn 8718: if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620 albertel 8719: &log($env{'user.domain'},$env{'user.name'},
8720: $env{'user.home'},
1.57 www 8721: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8722: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8723: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8724: return '';
8725: }
8726: }
8727: }
1.29 www 8728: }
1.52 www 8729: }
1.1424 raeburn 8730:
1.52 www 8731: #
8732: # Rest of the restrictions depend on selected course
8733: #
8734:
1.620 albertel 8735: unless ($env{'request.course.id'}) {
1.766 albertel 8736: if ($thisallowed eq 'A') {
8737: return 'A';
1.814 raeburn 8738: } elsif ($thisallowed eq 'B') {
8739: return 'B';
1.766 albertel 8740: } else {
8741: return '1';
8742: }
1.52 www 8743: }
1.29 www 8744:
1.52 www 8745: #
8746: # Now user is definitely in a course
8747: #
1.53 www 8748:
8749:
8750: # Course preferences
8751:
8752: if ($thisallowed=~/C/) {
1.620 albertel 8753: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8754: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8755: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8756: =~/\Q$rolecode\E/) {
1.1304 raeburn 8757: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8758: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8759: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8760: $env{'request.course.id'});
8761: }
1.237 www 8762: return '';
8763: }
8764:
1.620 albertel 8765: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8766: =~/\Q$unamedom\E/) {
1.1304 raeburn 8767: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8768: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8769: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8770: $env{'request.course.id'});
8771: }
1.54 www 8772: return '';
8773: }
1.53 www 8774: }
8775:
8776: # Resource preferences
8777:
8778: if ($thisallowed=~/R/) {
1.620 albertel 8779: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8780: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8781: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8782: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8783: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8784: }
8785: return '';
1.54 www 8786: }
1.53 www 8787: }
1.30 www 8788:
1.1461 raeburn 8789: # Restricted for deeplinked session?
8790:
8791: if ($env{'request.deeplink.login'}) {
8792: if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
8793: if (!$symb) { $symb=&symbread($uri,1); }
8794: if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
8795: return '';
8796: }
8797: }
8798: }
8799:
1.246 www 8800: # Restricted by state or randomout?
1.30 www 8801:
1.52 www 8802: if ($thisallowed=~/X/) {
1.620 albertel 8803: if ($env{'acc.randomout'}) {
1.579 albertel 8804: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8805: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8806: return '';
8807: }
1.247 www 8808: }
8809: if (&condval($statecond)) {
1.52 www 8810: return '2';
8811: } else {
8812: return '';
8813: }
8814: }
1.30 www 8815:
1.766 albertel 8816: if ($thisallowed eq 'A') {
8817: return 'A';
1.814 raeburn 8818: } elsif ($thisallowed eq 'B') {
8819: return 'B';
1.1402 raeburn 8820: } elsif ($thisallowed eq 'D') {
8821: return 'D';
1.766 albertel 8822: }
1.52 www 8823: return 'F';
1.232 www 8824: }
1.1162 raeburn 8825:
1.1192 raeburn 8826: # ------------------------------------------- Check construction space access
8827:
8828: sub constructaccess {
8829: my ($url,$setpriv)=@_;
8830:
8831: # We do not allow editing of previous versions of files
8832: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8833:
8834: # Get username and domain from URL
8835: my ($ownername,$ownerdomain,$ownerhome);
8836:
8837: ($ownerdomain,$ownername) =
1.1325 raeburn 8838: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192 raeburn 8839:
8840: # The URL does not really point to any authorspace, forget it
8841: unless (($ownername) && ($ownerdomain)) { return ''; }
8842:
8843: # Now we need to see if the user has access to the authorspace of
8844: # $ownername at $ownerdomain
8845:
8846: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8847: # Real author for this?
8848: $ownerhome = $env{'user.home'};
8849: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8850: return ($ownername,$ownerdomain,$ownerhome);
8851: }
8852: } else {
8853: # Co-author for this?
8854: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8855: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8856: $ownerhome = &homeserver($ownername,$ownerdomain);
8857: return ($ownername,$ownerdomain,$ownerhome);
8858: }
1.1312 raeburn 8859: if ($env{'request.course.id'}) {
8860: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
8861: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
8862: if (&allowed('mdc',$env{'request.course.id'})) {
8863: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
8864: return ($ownername,$ownerdomain,$ownerhome);
8865: }
8866: }
8867: }
1.1192 raeburn 8868: }
8869:
8870: # We don't have any access right now. If we are not possibly going to do anything about this,
8871: # we might as well leave
8872: unless ($setpriv) { return ''; }
8873:
8874: # Backdoor access?
8875: my $allowed=&allowed('eco',$ownerdomain);
8876: # Nope
8877: unless ($allowed) { return ''; }
8878: # Looks like we may have access, but could be locked by the owner of the construction space
8879: if ($allowed eq 'U') {
8880: my %blocked=&get('environment',['domcoord.author'],
8881: $ownerdomain,$ownername);
8882: # Is blocked by owner
8883: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8884: }
8885: if (($allowed eq 'F') || ($allowed eq 'U')) {
8886: # Grant temporary access
8887: my $then=$env{'user.login.time'};
1.1209 raeburn 8888: my $update=$env{'user.update.time'};
1.1192 raeburn 8889: if (!$update) { $update = $then; }
8890: my $refresh=$env{'user.refresh.time'};
8891: if (!$refresh) { $refresh = $update; }
8892: my $now = time;
8893: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8894: $now,'ca','constructaccess');
8895: $ownerhome = &homeserver($ownername,$ownerdomain);
8896: return($ownername,$ownerdomain,$ownerhome);
8897: }
8898: # No business here
8899: return '';
8900: }
8901:
1.1282 raeburn 8902: # ----------------------------------------------------------- Content Blocking
8903:
8904: {
8905: # Caches for faster Course Contents display where content blocking
8906: # is in operation (i.e., interval param set) for timed quiz.
8907: #
8908: # User for whom data are being temporarily cached.
8909: my $cacheduser='';
1.1424 raeburn 8910: # Course for which data are being temporarily cached.
8911: my $cachedcid='';
1.1282 raeburn 8912: # Cached blockers for this user (a hash of blocking items).
8913: my %cachedblockers=();
8914: # When the data were last cached.
8915: my $cachedlast='';
8916:
8917: sub load_all_blockers {
1.1427 raeburn 8918: my ($uname,$udom)=@_;
1.1282 raeburn 8919: if (($uname ne '') && ($udom ne '')) {
8920: if (($cacheduser eq $uname.':'.$udom) &&
1.1424 raeburn 8921: ($cachedcid eq $env{'request.course.id'}) &&
1.1427 raeburn 8922: (abs($cachedlast-time)<5)) {
1.1282 raeburn 8923: return;
8924: }
8925: }
8926: $cachedlast=time;
8927: $cacheduser=$uname.':'.$udom;
1.1424 raeburn 8928: $cachedcid=$env{'request.course.id'};
1.1427 raeburn 8929: %cachedblockers = &get_commblock_resources();
1.1424 raeburn 8930: return;
1.1282 raeburn 8931: }
8932:
1.1162 raeburn 8933: sub get_comm_blocks {
8934: my ($cdom,$cnum) = @_;
8935: if ($cdom eq '' || $cnum eq '') {
8936: return unless ($env{'request.course.id'});
8937: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8938: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8939: }
8940: my %commblocks;
8941: my $hashid=$cdom.'_'.$cnum;
8942: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8943: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8944: %commblocks = %{$blocksref};
8945: } else {
8946: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8947: my $cachetime = 600;
8948: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8949: }
8950: return %commblocks;
8951: }
8952:
1.1282 raeburn 8953: sub get_commblock_resources {
8954: my ($blocks) = @_;
8955: my %blockers = ();
8956: return %blockers unless ($env{'request.course.id'});
1.1470 raeburn 8957: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
8958: if ($env{'request.course.sec'}) {
8959: $courseurl .= '/'.$env{'request.course.sec'};
8960: }
8961: return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162 raeburn 8962: my %commblocks;
8963: if (ref($blocks) eq 'HASH') {
8964: %commblocks = %{$blocks};
8965: } else {
8966: %commblocks = &get_comm_blocks();
8967: }
1.1282 raeburn 8968: return %blockers unless (keys(%commblocks) > 0);
8969: my $navmap = Apache::lonnavmaps::navmap->new();
8970: return %blockers unless (ref($navmap));
1.1162 raeburn 8971: my $now = time;
8972: foreach my $block (keys(%commblocks)) {
8973: if ($block =~ /^(\d+)____(\d+)$/) {
8974: my ($start,$end) = ($1,$2);
8975: if ($start <= $now && $end >= $now) {
8976: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8977: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8978: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 8979: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8980: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 8981: }
8982: }
8983: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 8984: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8985: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 8986: }
8987: }
8988: }
8989: }
8990: }
8991: } elsif ($block =~ /^firstaccess____(.+)$/) {
8992: my $item = $1;
8993: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8994: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1471 raeburn 8995: my (@interval,$mapname);
1.1282 raeburn 8996: my $type = 'map';
8997: if ($item eq 'course') {
8998: $type = 'course';
8999: @interval=&EXT("resource.0.interval");
9000: } else {
9001: if ($item =~ /___\d+___/) {
9002: $type = 'resource';
9003: @interval=&EXT("resource.0.interval",$item);
1.1162 raeburn 9004: } else {
1.1471 raeburn 9005: $mapname = &deversion($item);
9006: if (ref($navmap)) {
9007: my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
9008: @interval = ($timelimit,'map');
1.1162 raeburn 9009: }
9010: }
1.1282 raeburn 9011: }
1.1310 raeburn 9012: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 9013: my $timelimit = $1;
1.1282 raeburn 9014: my $first_access;
9015: if ($type eq 'resource') {
9016: $first_access=&get_first_access($interval[1],$item);
9017: } elsif ($type eq 'map') {
9018: $first_access=&get_first_access($interval[1],undef,$item);
9019: } else {
9020: $first_access=&get_first_access($interval[1]);
9021: }
9022: if ($first_access) {
1.1292 raeburn 9023: my $timesup = $first_access+$timelimit;
1.1282 raeburn 9024: if ($timesup > $now) {
9025: my $activeblock;
1.1471 raeburn 9026: if ($type eq 'resource') {
9027: if (ref($navmap)) {
9028: my $res = $navmap->getBySymb($item);
9029: if ($res->answerable()) {
9030: $activeblock = 1;
9031: }
9032: }
9033: } elsif ($type eq 'map') {
9034: my $mapsymb = &symbread($mapname,1);
9035: if (($mapsymb) && (ref($navmap))) {
9036: my $mapres = $navmap->getBySymb($mapsymb);
9037: if (ref($mapres)) {
9038: my $first = $mapres->map_start();
9039: my $finish = $mapres->map_finish();
9040: my $it = $navmap->getIterator($first,$finish,undef,0,0);
9041: if (ref($it)) {
9042: my $res;
9043: while ($res = $it->next(undef,1)) {
9044: next unless (ref($res));
9045: my $symb = $res->symb();
9046: next if (($symb eq $mapsymb) || ($symb eq ''));
9047: @interval=&EXT("resource.0.interval",$symb);
9048: if ($interval[1] eq 'map') {
9049: if ($res->answerable()) {
9050: $activeblock = 1;
9051: last;
9052: }
9053: }
9054: }
9055: }
9056: }
1.1282 raeburn 9057: }
9058: }
9059: if ($activeblock) {
9060: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
9061: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
9062: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
9063: }
9064: }
9065: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
9066: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
9067: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 9068: }
1.1162 raeburn 9069: }
9070: }
9071: }
9072: }
9073: }
9074: }
9075: }
9076: }
9077: }
1.1282 raeburn 9078: return %blockers;
1.1162 raeburn 9079: }
9080:
1.1282 raeburn 9081: sub has_comm_blocking {
1.1427 raeburn 9082: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1282 raeburn 9083: my @blockers;
9084: return unless ($env{'request.course.id'});
9085: return unless ($priv eq 'bre');
9086: return if ($env{'request.state'} eq 'construct');
1.1470 raeburn 9087: my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
9088: if ($env{'request.course.sec'}) {
9089: $courseurl .= '/'.$env{'request.course.sec'};
9090: }
9091: return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1427 raeburn 9092: my %blockinfo;
9093: if (ref($blocks) eq 'HASH') {
9094: %blockinfo = &get_commblock_resources($blocks);
9095: } else {
9096: &load_all_blockers($env{'user.name'},$env{'user.domain'});
9097: %blockinfo = %cachedblockers;
9098: }
9099: return unless (keys(%blockinfo) > 0);
1.1282 raeburn 9100: my (%possibles,@symbs);
9101: if (!$symb) {
1.1427 raeburn 9102: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162 raeburn 9103: }
1.1282 raeburn 9104: if ($symb) {
9105: @symbs = ($symb);
9106: } elsif (keys(%possibles)) {
9107: @symbs = keys(%possibles);
9108: }
9109: my $noblock;
9110: foreach my $symb (@symbs) {
9111: last if ($noblock);
9112: my ($map,$resid,$resurl)=&decode_symb($symb);
1.1427 raeburn 9113: foreach my $block (keys(%blockinfo)) {
1.1282 raeburn 9114: if ($block =~ /^firstaccess____(.+)$/) {
9115: my $item = $1;
1.1424 raeburn 9116: unless ($blocked) {
9117: if (($item eq $map) || ($item eq $symb)) {
9118: $noblock = 1;
9119: last;
9120: }
1.1282 raeburn 9121: }
9122: }
1.1427 raeburn 9123: if (ref($blockinfo{$block}) eq 'HASH') {
9124: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
9125: if ($blockinfo{$block}{'resources'}{$symb}) {
1.1282 raeburn 9126: unless (grep(/^\Q$block\E$/,@blockers)) {
9127: push(@blockers,$block);
9128: }
9129: }
9130: }
1.1427 raeburn 9131: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
9132: if ($blockinfo{$block}{'maps'}{$map}) {
1.1424 raeburn 9133: unless (grep(/^\Q$block\E$/,@blockers)) {
9134: push(@blockers,$block);
9135: }
1.1282 raeburn 9136: }
9137: }
1.1162 raeburn 9138: }
9139: }
9140: }
1.1424 raeburn 9141: unless ($noblock) {
9142: return @blockers;
9143: }
9144: return;
1.1282 raeburn 9145: }
1.1162 raeburn 9146: }
9147:
1.1402 raeburn 9148: sub deeplink_check {
9149: my ($priv,$symb,$uri) = @_;
9150: return unless ($env{'request.course.id'});
9151: return unless ($priv eq 'bre');
9152: return if ($env{'request.state'} eq 'construct');
9153: return if ($env{'request.role.adv'});
9154: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9155: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9156: my (%possibles,@symbs);
9157: if (!$symb) {
9158: $symb = &symbread($uri,1,1,1,\%possibles);
9159: }
9160: if ($symb) {
9161: @symbs = ($symb);
9162: } elsif (keys(%possibles)) {
9163: @symbs = keys(%possibles);
9164: }
9165:
1.1461 raeburn 9166: my ($deeplink_symb,$allow);
9167: if ($env{'request.deeplink.login'}) {
9168: $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
1.1402 raeburn 9169: }
9170: foreach my $symb (@symbs) {
9171: last if ($allow);
9172: my $deeplink = &EXT("resource.0.deeplink",$symb);
9173: if ($deeplink eq '') {
9174: $allow = 1;
9175: } else {
1.1463 raeburn 9176: my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
9177: if ($state ne 'only') {
1.1402 raeburn 9178: $allow = 1;
1.1463 raeburn 9179: } else {
9180: my $check_deeplink_entry;
9181: if ($protect ne 'none') {
9182: my ($acctype,$item) = split(/:/,$protect);
9183: if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
9184: if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
9185: $check_deeplink_entry = 1
9186: }
9187: } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
9188: if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
9189: $check_deeplink_entry = 1;
9190: }
9191: } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
9192: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
9193: $check_deeplink_entry = 1;
9194: }
9195: }
9196: }
9197: if (($protect eq 'none') || ($check_deeplink_entry)) {
1.1402 raeburn 9198: if ($scope eq 'res') {
1.1461 raeburn 9199: if ($symb eq $deeplink_symb) {
1.1402 raeburn 9200: $allow = 1;
9201: }
1.1459 raeburn 9202: } elsif (($scope eq 'map') || ($scope eq 'rec')) {
1.1463 raeburn 9203: my ($map_from_symb,$map_from_login);
1.1461 raeburn 9204: $map_from_symb = &deversion((&decode_symb($symb))[0]);
9205: if ($deeplink_symb =~ /\.(page|sequence)$/) {
9206: $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
9207: } else {
9208: $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
9209: }
1.1459 raeburn 9210: if (($map_from_symb) && ($map_from_login)) {
9211: if ($map_from_symb eq $map_from_login) {
9212: $allow = 1;
9213: } elsif ($scope eq 'rec') {
9214: my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
9215: if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
9216: $allow = 1;
9217: }
9218: }
9219: }
1.1402 raeburn 9220: }
9221: }
9222: }
9223: }
9224: }
9225: return if ($allow);
9226: return 1;
9227: }
9228:
1.1282 raeburn 9229: # -------------------------------- Deversion and split uri into path an filename
9230:
1.1133 foxr 9231: #
1.1282 raeburn 9232: # Removes the version from a URI and
1.1133 foxr 9233: # splits it in to its filename and path to the filename.
9234: # Seems like File::Basename could have done this more clearly.
9235: # Parameters:
9236: # $uri - input URI
9237: # Returns:
9238: # Two element list consisting of
9239: # $pathname - the URI up to and excluding the trailing /
9240: # $filename - The part of the URI following the last /
9241: # NOTE:
9242: # Another realization of this is simply:
9243: # use File::Basename;
9244: # ...
9245: # $uri = shift;
9246: # $filename = basename($uri);
9247: # $path = dirname($uri);
9248: # return ($filename, $path);
9249: #
9250: # The implementation below is probably faster however.
9251: #
1.710 albertel 9252: sub split_uri_for_cond {
9253: my $uri=&deversion(&declutter(shift));
9254: my @uriparts=split(/\//,$uri);
9255: my $filename=pop(@uriparts);
9256: my $pathname=join('/',@uriparts);
9257: return ($pathname,$filename);
9258: }
1.232 www 9259: # --------------------------------------------------- Is a resource on the map?
9260:
9261: sub is_on_map {
1.710 albertel 9262: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 9263: #Trying to find the conditional for the file
1.620 albertel 9264: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 9265: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 9266: if ($match) {
1.289 bowersj2 9267: return (1,$1);
9268: } else {
1.434 www 9269: return (0,0);
1.289 bowersj2 9270: }
1.12 www 9271: }
9272:
1.427 www 9273: # --------------------------------------------------------- Get symb from alias
9274:
9275: sub get_symb_from_alias {
9276: my $symb=shift;
9277: my ($map,$resid,$url)=&decode_symb($symb);
9278: # Already is a symb
9279: if ($url) { return $symb; }
9280: # Must be an alias
9281: my $aliassymb='';
9282: my %bighash;
1.620 albertel 9283: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 9284: &GDBM_READER(),0640)) {
9285: my $rid=$bighash{'mapalias_'.$symb};
9286: if ($rid) {
9287: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 9288: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
9289: $resid,$bighash{'src_'.$rid});
1.427 www 9290: }
9291: untie %bighash;
9292: }
9293: return $aliassymb;
9294: }
9295:
1.12 www 9296: # ----------------------------------------------------------------- Define Role
9297:
9298: sub definerole {
9299: if (allowed('mcr','/')) {
1.1326 raeburn 9300: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 9301: foreach my $role (split(':',$sysrole)) {
9302: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9303: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
9304: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
9305: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9306: return "refused:s:$crole&$cqual";
9307: }
9308: }
1.191 harris41 9309: }
1.800 albertel 9310: foreach my $role (split(':',$domrole)) {
9311: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9312: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
9313: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
9314: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 9315: return "refused:d:$crole&$cqual";
9316: }
9317: }
1.191 harris41 9318: }
1.800 albertel 9319: foreach my $role (split(':',$courole)) {
9320: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9321: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
9322: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
9323: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9324: return "refused:c:$crole&$cqual";
9325: }
9326: }
1.191 harris41 9327: }
1.1326 raeburn 9328: my $uhome;
9329: if (($uname ne '') && ($udom ne '')) {
9330: $uhome = &homeserver($uname,$udom);
9331: return $uhome if ($uhome eq 'no_host');
9332: } else {
9333: $uname = $env{'user.name'};
9334: $udom = $env{'user.domain'};
9335: $uhome = $env{'user.home'};
9336: }
1.620 albertel 9337: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326 raeburn 9338: "$udom:$uname:rolesdef_$rolename=".
1.21 www 9339: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326 raeburn 9340: return reply($command,$uhome);
1.12 www 9341: } else {
9342: return 'refused';
9343: }
1.105 harris41 9344: }
9345:
9346: # ---------------- Make a metadata query against the network of library servers
9347:
9348: sub metadata_query {
1.1237 raeburn 9349: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 9350: my %rhash;
1.845 albertel 9351: my %libserv = &all_library();
1.244 matthew 9352: my @server_list = (defined($server_array) ? @$server_array
9353: : keys(%libserv) );
9354: for my $server (@server_list) {
1.1237 raeburn 9355: my $domains = '';
9356: if (ref($domains_hash) eq 'HASH') {
9357: $domains = $domains_hash->{$server};
9358: }
1.118 harris41 9359: unless ($custom or $customshow) {
1.1237 raeburn 9360: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 9361: $rhash{$server}=$reply;
9362: }
9363: else {
9364: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 9365: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 9366: $server);
9367: $rhash{$server}=$reply;
9368: }
1.112 harris41 9369: }
1.118 harris41 9370: return \%rhash;
1.240 www 9371: }
9372:
9373: # ----------------------------------------- Send log queries and wait for reply
9374:
9375: sub log_query {
9376: my ($uname,$udom,$query,%filters)=@_;
9377: my $uhome=&homeserver($uname,$udom);
9378: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 9379: my $uhost=&hostname($uhome);
1.800 albertel 9380: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 9381: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
9382: $uhome);
1.479 albertel 9383: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 9384: return get_query_reply($queryid);
9385: }
9386:
1.818 raeburn 9387: # -------------------------- Update MySQL table for portfolio file
9388:
9389: sub update_portfolio_table {
1.821 raeburn 9390: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 9391: if ($group ne '') {
9392: $file_name =~s /^\Q$group\E//;
9393: }
1.818 raeburn 9394: my $homeserver = &homeserver($uname,$udom);
9395: my $queryid=
1.821 raeburn 9396: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
9397: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 9398: my $reply = &get_query_reply($queryid);
9399: return $reply;
9400: }
9401:
1.899 raeburn 9402: # -------------------------- Update MySQL allusers table
9403:
9404: sub update_allusers_table {
9405: my ($uname,$udom,$names) = @_;
9406: my $homeserver = &homeserver($uname,$udom);
9407: my $queryid=
9408: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
9409: 'lastname='.&escape($names->{'lastname'}).'%%'.
9410: 'firstname='.&escape($names->{'firstname'}).'%%'.
9411: 'middlename='.&escape($names->{'middlename'}).'%%'.
9412: 'generation='.&escape($names->{'generation'}).'%%'.
9413: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
9414: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 9415: return;
1.899 raeburn 9416: }
9417:
1.508 raeburn 9418: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 9419:
9420: sub fetch_enrollment_query {
1.511 raeburn 9421: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 raeburn 9422: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 9423: my $maxtries = 1;
1.508 raeburn 9424: if ($context eq 'automated') {
9425: $homeserver = $perlvar{'lonHostID'};
1.1317 raeburn 9426: $sleep = 2;
9427: $loopmax = 100;
1.547 raeburn 9428: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 9429: } else {
9430: $homeserver = &homeserver($cnum,$dom);
9431: }
1.838 albertel 9432: my $host=&hostname($homeserver);
1.506 raeburn 9433: my $cmd = '';
1.1000 raeburn 9434: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 9435: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 9436: }
9437: $cmd =~ s/%%$//;
9438: $cmd = &escape($cmd);
9439: my $query = 'fetchenrollment';
1.620 albertel 9440: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 9441: unless ($queryid=~/^\Q$host\E\_/) {
9442: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
9443: return 'error: '.$queryid;
9444: }
1.1317 raeburn 9445: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9446: my $tries = 1;
9447: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 raeburn 9448: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9449: $tries ++;
9450: }
1.526 raeburn 9451: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 9452: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 9453: } else {
1.901 albertel 9454: my @responses = split(/:/,$reply);
1.1322 raeburn 9455: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 9456: foreach my $line (@responses) {
9457: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 9458: $$replyref{$key} = $value;
9459: }
9460: } else {
1.1117 foxr 9461: my $pathname = LONCAPA::tempdir();
1.800 albertel 9462: foreach my $line (@responses) {
9463: my ($key,$value) = split(/=/,$line);
1.506 raeburn 9464: $$replyref{$key} = $value;
9465: if ($value > 0) {
1.800 albertel 9466: foreach my $item (@{$$affiliatesref{$key}}) {
9467: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 9468: my $destname = $pathname.'/'.$filename;
9469: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 9470: if ($xml_classlist =~ /^error/) {
9471: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9472: } else {
1.1359 raeburn 9473: if ( open(FILE,">",$destname) ) {
1.506 raeburn 9474: print FILE &unescape($xml_classlist);
9475: close(FILE);
1.526 raeburn 9476: } else {
9477: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 9478: }
9479: }
9480: }
9481: }
9482: }
9483: }
9484: return 'ok';
9485: }
9486: return 'error';
9487: }
9488:
1.242 www 9489: sub get_query_reply {
1.1471 raeburn 9490: my ($queryid,$sleep,$loopmax) = @_;
1.1317 raeburn 9491: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9492: $sleep = 0.2;
9493: }
9494: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9495: $loopmax = 100;
9496: }
1.1117 foxr 9497: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 9498: my $reply='';
1.1317 raeburn 9499: for (1..$loopmax) {
9500: sleep($sleep);
1.240 www 9501: if (-e $replyfile.'.end') {
1.1359 raeburn 9502: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 9503: $reply = join('',<$fh>);
9504: close($fh);
1.240 www 9505: } else { return 'error: reply_file_error'; }
1.242 www 9506: return &unescape($reply);
9507: }
1.240 www 9508: }
1.242 www 9509: return 'timeout:'.$queryid;
1.240 www 9510: }
9511:
9512: sub courselog_query {
1.241 www 9513: #
9514: # possible filters:
9515: # url: url or symb
9516: # username
9517: # domain
9518: # action: view, submit, grade
9519: # start: timestamp
9520: # end: timestamp
9521: #
1.240 www 9522: my (%filters)=@_;
1.620 albertel 9523: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 9524: if ($filters{'url'}) {
9525: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9526: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9527: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9528: }
1.620 albertel 9529: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9530: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 9531: return &log_query($cname,$cdom,'courselog',%filters);
9532: }
9533:
9534: sub userlog_query {
1.858 raeburn 9535: #
9536: # possible filters:
9537: # action: log check role
9538: # start: timestamp
9539: # end: timestamp
9540: #
1.240 www 9541: my ($uname,$udom,%filters)=@_;
9542: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 9543: }
9544:
1.506 raeburn 9545: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9546:
9547: sub auto_run {
1.508 raeburn 9548: my ($cnum,$cdom) = @_;
1.876 raeburn 9549: my $response = 0;
9550: my $settings;
9551: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9552: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9553: $settings = $domconfig{'autoenroll'};
9554: if ($settings->{'run'} eq '1') {
9555: $response = 1;
9556: }
9557: } else {
1.934 raeburn 9558: my $homeserver;
9559: if (&is_course($cdom,$cnum)) {
9560: $homeserver = &homeserver($cnum,$cdom);
9561: } else {
9562: $homeserver = &domain($cdom,'primary');
9563: }
9564: if ($homeserver ne 'no_host') {
9565: $response = &reply('autorun:'.$cdom,$homeserver);
9566: }
1.876 raeburn 9567: }
1.506 raeburn 9568: return $response;
9569: }
1.776 albertel 9570:
1.506 raeburn 9571: sub auto_get_sections {
1.508 raeburn 9572: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 9573: my $homeserver;
9574: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9575: $homeserver = &homeserver($cnum,$cdom);
9576: }
9577: if (!defined($homeserver)) {
9578: if ($cdom =~ /^$match_domain$/) {
9579: $homeserver = &domain($cdom,'primary');
9580: }
9581: }
9582: my @secs;
9583: if (defined($homeserver)) {
9584: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9585: unless ($response eq 'refused') {
9586: @secs = split(/:/,$response);
9587: }
1.506 raeburn 9588: }
9589: return @secs;
9590: }
1.776 albertel 9591:
1.506 raeburn 9592: sub auto_new_course {
1.1099 raeburn 9593: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 9594: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 9595: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 9596: return $response;
9597: }
1.776 albertel 9598:
1.506 raeburn 9599: sub auto_validate_courseID {
1.508 raeburn 9600: my ($cnum,$cdom,$inst_course_id) = @_;
9601: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 9602: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 9603: return $response;
9604: }
1.776 albertel 9605:
1.1007 raeburn 9606: sub auto_validate_instcode {
1.1020 raeburn 9607: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 9608: my ($homeserver,$response);
9609: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9610: $homeserver = &homeserver($cnum,$cdom);
9611: }
9612: if (!defined($homeserver)) {
9613: if ($cdom =~ /^$match_domain$/) {
9614: $homeserver = &domain($cdom,'primary');
9615: }
9616: }
1.1065 raeburn 9617: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9618: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 9619: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9620: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9621: }
9622:
1.1444 raeburn 9623: sub auto_validate_inst_crosslist {
9624: my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
9625: my ($homeserver,$response);
9626: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9627: $homeserver = &homeserver($cnum,$cdom);
9628: }
9629: if (!defined($homeserver)) {
9630: if ($cdom =~ /^$match_domain$/) {
9631: $homeserver = &domain($cdom,'primary');
9632: }
9633: }
9634: unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
9635: $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
9636: &escape($instcode).':'.&escape($inst_xlist).':'.
1.1445 raeburn 9637: &escape($coowner),$homeserver);
1.1444 raeburn 9638: }
9639: return $response;
9640: }
9641:
1.506 raeburn 9642: sub auto_create_password {
1.873 raeburn 9643: my ($cnum,$cdom,$authparam,$udom) = @_;
9644: my ($homeserver,$response);
1.506 raeburn 9645: my $create_passwd = 0;
9646: my $authchk = '';
1.873 raeburn 9647: if ($udom =~ /^$match_domain$/) {
9648: $homeserver = &domain($udom,'primary');
9649: }
9650: if ($homeserver eq '') {
9651: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9652: $homeserver = &homeserver($cnum,$cdom);
9653: }
9654: }
9655: if ($homeserver eq '') {
9656: $authchk = 'nodomain';
1.506 raeburn 9657: } else {
1.873 raeburn 9658: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9659: if ($response eq 'refused') {
9660: $authchk = 'refused';
9661: } else {
1.901 albertel 9662: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9663: }
1.506 raeburn 9664: }
9665: return ($authparam,$create_passwd,$authchk);
9666: }
9667:
1.706 raeburn 9668: sub auto_photo_permission {
9669: my ($cnum,$cdom,$students) = @_;
9670: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9671: my ($outcome,$perm_reqd,$conditions) =
9672: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9673: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9674: return (undef,undef);
9675: }
1.706 raeburn 9676: return ($outcome,$perm_reqd,$conditions);
9677: }
9678:
9679: sub auto_checkphotos {
9680: my ($uname,$udom,$pid) = @_;
9681: my $homeserver = &homeserver($uname,$udom);
9682: my ($result,$resulttype);
9683: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9684: &escape($uname).':'.&escape($pid),
9685: $homeserver));
1.709 albertel 9686: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9687: return (undef,undef);
9688: }
1.706 raeburn 9689: if ($outcome) {
9690: ($result,$resulttype) = split(/:/,$outcome);
9691: }
9692: return ($result,$resulttype);
9693: }
9694:
9695: sub auto_photochoice {
9696: my ($cnum,$cdom) = @_;
9697: my $homeserver = &homeserver($cnum,$cdom);
9698: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9699: &escape($cdom),
9700: $homeserver)));
1.709 albertel 9701: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9702: return (undef,undef);
9703: }
1.706 raeburn 9704: return ($update,$comment);
9705: }
9706:
9707: sub auto_photoupdate {
9708: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9709: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9710: my $host=&hostname($homeserver);
1.706 raeburn 9711: my $cmd = '';
9712: my $maxtries = 1;
1.800 albertel 9713: foreach my $affiliate (keys(%{$affiliatesref})) {
9714: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9715: }
9716: $cmd =~ s/%%$//;
9717: $cmd = &escape($cmd);
9718: my $query = 'institutionalphotos';
9719: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9720: unless ($queryid=~/^\Q$host\E\_/) {
9721: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9722: return 'error: '.$queryid;
9723: }
9724: my $reply = &get_query_reply($queryid);
9725: my $tries = 1;
9726: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9727: $reply = &get_query_reply($queryid);
9728: $tries ++;
9729: }
9730: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9731: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9732: } else {
9733: my @responses = split(/:/,$reply);
9734: my $outcome = shift(@responses);
9735: foreach my $item (@responses) {
9736: my ($key,$value) = split(/=/,$item);
9737: $$photo{$key} = $value;
9738: }
9739: return $outcome;
9740: }
9741: return 'error';
9742: }
9743:
1.521 raeburn 9744: sub auto_instcode_format {
1.793 albertel 9745: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9746: $cat_order) = @_;
1.521 raeburn 9747: my $courses = '';
1.772 raeburn 9748: my @homeservers;
1.521 raeburn 9749: if ($caller eq 'global') {
1.841 albertel 9750: my %servers = &get_servers($codedom,'library');
9751: foreach my $tryserver (keys(%servers)) {
9752: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9753: push(@homeservers,$tryserver);
9754: }
1.584 raeburn 9755: }
1.1022 raeburn 9756: } elsif ($caller eq 'requests') {
9757: if ($codedom =~ /^$match_domain$/) {
9758: my $chome = &domain($codedom,'primary');
9759: unless ($chome eq 'no_host') {
9760: push(@homeservers,$chome);
9761: }
9762: }
1.521 raeburn 9763: } else {
1.772 raeburn 9764: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9765: }
1.793 albertel 9766: foreach my $code (keys(%{$instcodes})) {
9767: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9768: }
9769: chop($courses);
1.772 raeburn 9770: my $ok_response = 0;
9771: my $response;
9772: while (@homeservers > 0 && $ok_response == 0) {
9773: my $server = shift(@homeservers);
9774: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9775: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9776: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9777: split(/:/,$response);
1.772 raeburn 9778: %{$codes} = (%{$codes},&str2hash($codes_str));
9779: push(@{$codetitles},&str2array($codetitles_str));
9780: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9781: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9782: $ok_response = 1;
9783: }
9784: }
9785: if ($ok_response) {
1.521 raeburn 9786: return 'ok';
1.772 raeburn 9787: } else {
9788: return $response;
1.521 raeburn 9789: }
9790: }
9791:
1.792 raeburn 9792: sub auto_instcode_defaults {
9793: my ($domain,$returnhash,$code_order) = @_;
9794: my @homeservers;
1.841 albertel 9795:
9796: my %servers = &get_servers($domain,'library');
9797: foreach my $tryserver (keys(%servers)) {
9798: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9799: push(@homeservers,$tryserver);
9800: }
1.792 raeburn 9801: }
1.841 albertel 9802:
1.792 raeburn 9803: my $response;
1.841 albertel 9804: foreach my $server (@homeservers) {
1.792 raeburn 9805: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9806: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9807:
9808: foreach my $pair (split(/\&/,$response)) {
9809: my ($name,$value)=split(/\=/,$pair);
9810: if ($name eq 'code_order') {
9811: @{$code_order} = split(/\&/,&unescape($value));
9812: } else {
9813: $returnhash->{&unescape($name)}=&unescape($value);
9814: }
9815: }
9816: return 'ok';
1.792 raeburn 9817: }
1.841 albertel 9818:
9819: return $response;
1.1003 raeburn 9820: }
9821:
9822: sub auto_possible_instcodes {
1.1007 raeburn 9823: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9824: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9825: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9826: return;
9827: }
1.1003 raeburn 9828: my (@homeservers,$uhome);
9829: if (defined(&domain($domain,'primary'))) {
9830: $uhome=&domain($domain,'primary');
9831: push(@homeservers,&domain($domain,'primary'));
9832: } else {
9833: my %servers = &get_servers($domain,'library');
9834: foreach my $tryserver (keys(%servers)) {
9835: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9836: push(@homeservers,$tryserver);
9837: }
9838: }
9839: }
9840: my $response;
9841: foreach my $server (@homeservers) {
9842: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9843: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9844: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9845: split(':',$response);
9846: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9847: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9848: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9849: my ($name,$value)=split('=',$item);
9850: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9851: }
9852: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9853: my ($name,$value)=split('=',$item);
9854: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9855: }
9856: return 'ok';
9857: }
9858: return $response;
9859: }
1.792 raeburn 9860:
1.1010 raeburn 9861: sub auto_courserequest_checks {
9862: my ($dom) = @_;
1.1020 raeburn 9863: my ($homeserver,%validations);
9864: if ($dom =~ /^$match_domain$/) {
9865: $homeserver = &domain($dom,'primary');
9866: }
9867: unless ($homeserver eq 'no_host') {
9868: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9869: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9870: my @items = split(/&/,$response);
9871: foreach my $item (@items) {
9872: my ($key,$value) = split('=',$item);
9873: $validations{&unescape($key)} = &thaw_unescape($value);
9874: }
9875: }
9876: }
1.1010 raeburn 9877: return %validations;
9878: }
9879:
1.1020 raeburn 9880: sub auto_courserequest_validation {
1.1255 raeburn 9881: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 9882: my ($homeserver,$response);
9883: if ($dom =~ /^$match_domain$/) {
9884: $homeserver = &domain($dom,'primary');
9885: }
1.1255 raeburn 9886: unless ($homeserver eq 'no_host') {
9887: my $customdata;
9888: if (ref($custominfo) eq 'HASH') {
9889: $customdata = &freeze_escape($custominfo);
9890: }
1.1020 raeburn 9891: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 9892: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 9893: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9894: $customdata,$homeserver));
1.1020 raeburn 9895: }
9896: return $response;
9897: }
9898:
1.777 albertel 9899: sub auto_validate_class_sec {
1.918 raeburn 9900: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 9901: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 9902: my $ownerlist;
9903: if (ref($owners) eq 'ARRAY') {
9904: $ownerlist = join(',',@{$owners});
9905: } else {
9906: $ownerlist = $owners;
9907: }
1.773 raeburn 9908: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 9909: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 9910: return $response;
9911: }
9912:
1.1460 raeburn 9913: sub auto_instsec_reformat {
9914: my ($cdom,$action,$instsecref) = @_;
9915: return unless(($action eq 'clutter') || ($action eq 'declutter'));
9916: my @homeservers;
9917: if (defined(&domain($cdom,'primary'))) {
9918: push(@homeservers,&domain($cdom,'primary'));
9919: } else {
9920: my %servers = &get_servers($cdom,'library');
9921: foreach my $tryserver (keys(%servers)) {
9922: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9923: push(@homeservers,$tryserver);
9924: }
9925: }
9926: }
9927: my $response;
9928: my %reformatted = %{$instsecref};
9929: foreach my $server (@homeservers) {
9930: if (ref($instsecref) eq 'HASH') {
9931: my $info = &freeze_escape($instsecref);
9932: my $response=&reply('autoinstsecreformat:'.$cdom.':'.
9933: $action.':'.$info,$server);
9934: next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
9935: my @items = split(/&/,$response);
9936: foreach my $item (@items) {
9937: my ($key,$value) = split(/=/,$item);
9938: $reformatted{&unescape($key)} = &thaw_unescape($value);
9939: }
9940: }
9941: }
9942: return %reformatted;
9943: }
9944:
1.1367 raeburn 9945: sub auto_validate_instclasses {
9946: my ($cdom,$cnum,$owners,$classesref) = @_;
9947: my ($homeserver,%validations);
9948: $homeserver = &homeserver($cnum,$cdom);
9949: unless ($homeserver eq 'no_host') {
9950: my $ownerlist;
9951: if (ref($owners) eq 'ARRAY') {
9952: $ownerlist = join(',',@{$owners});
9953: } else {
9954: $ownerlist = $owners;
9955: }
9956: if (ref($classesref) eq 'HASH') {
9957: my $classes = &freeze_escape($classesref);
9958: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9959: ':'.$cdom.':'.$classes,$homeserver);
9960: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9961: my @items = split(/&/,$response);
9962: foreach my $item (@items) {
9963: my ($key,$value) = split('=',$item);
9964: $validations{&unescape($key)} = &thaw_unescape($value);
9965: }
9966: }
9967: }
9968: }
9969: return %validations;
9970: }
9971:
1.1248 raeburn 9972: sub auto_crsreq_update {
9973: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 9974: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 9975: my ($homeserver,%crsreqresponse);
9976: if ($cdom =~ /^$match_domain$/) {
9977: $homeserver = &domain($cdom,'primary');
9978: }
9979: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9980: my $info;
9981: if (ref($inbound) eq 'HASH') {
9982: $info = &freeze_escape($inbound);
9983: }
9984: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9985: ':'.&escape($action).':'.&escape($ownername).':'.
9986: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 9987: &escape($title).':'.&escape($code).':'.
9988: &escape($accessstart).':'.&escape($accessend).':'.$info,
9989: $homeserver);
1.1248 raeburn 9990: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9991: my @items = split(/&/,$response);
9992: foreach my $item (@items) {
9993: my ($key,$value) = split('=',$item);
9994: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9995: }
9996: }
9997: }
9998: return \%crsreqresponse;
9999: }
10000:
1.1305 raeburn 10001: sub auto_export_grades {
1.1309 raeburn 10002: my ($cdom,$cnum,$inforef,$gradesref) = @_;
10003: my ($homeserver,%exportresponse);
10004: if ($cdom =~ /^$match_domain$/) {
10005: $homeserver = &domain($cdom,'primary');
10006: }
10007: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10008: my $info;
10009: if (ref($inforef) eq 'HASH') {
10010: $info = &freeze_escape($inforef);
10011: }
10012: if (ref($gradesref) eq 'HASH') {
10013: my $grades = &freeze_escape($gradesref);
10014: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10015: $info.':'.$grades,$homeserver);
10016: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
10017: my @items = split(/&/,$response);
10018: foreach my $item (@items) {
10019: my ($key,$value) = split('=',$item);
10020: $exportresponse{&unescape($key)} = &thaw_unescape($value);
10021: }
10022: }
10023: }
10024: }
10025: return \%exportresponse;
1.1305 raeburn 10026: }
10027:
1.1287 raeburn 10028: sub check_instcode_cloning {
10029: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10030: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10031: return;
10032: }
10033: my $canclone;
10034: if (@{$code_order} > 0) {
10035: my $instcoderegexp ='^';
10036: my @clonecodes = split(/\&/,$cloner);
10037: foreach my $item (@{$code_order}) {
10038: if (grep(/^\Q$item\E=/,@clonecodes)) {
10039: foreach my $pair (@clonecodes) {
10040: my ($key,$val) = split(/\=/,$pair,2);
10041: $val = &unescape($val);
10042: if ($key eq $item) {
10043: $instcoderegexp .= '('.$val.')';
10044: last;
10045: }
10046: }
10047: } else {
10048: $instcoderegexp .= $codedefaults->{$item};
10049: }
10050: }
10051: $instcoderegexp .= '$';
10052: my (@from,@to);
10053: eval {
10054: (@from) = ($clonefromcode =~ /$instcoderegexp/);
10055: (@to) = ($clonetocode =~ /$instcoderegexp/);
10056: };
10057: if ((@from > 0) && (@to > 0)) {
10058: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10059: if (!@diffs) {
10060: $canclone = 1;
10061: }
10062: }
10063: }
10064: return $canclone;
10065: }
10066:
10067: sub default_instcode_cloning {
10068: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10069: my (%codedefaults,@code_order,$canclone);
10070: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10071: %codedefaults = %{$codedefaultsref};
10072: @code_order = @{$codeorderref};
10073: } elsif ($clonedom) {
10074: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10075: }
10076: if (($domdefclone) && (@code_order)) {
10077: my @clonecodes = split(/\+/,$domdefclone);
10078: my $instcoderegexp ='^';
10079: foreach my $item (@code_order) {
10080: if (grep(/^\Q$item\E$/,@clonecodes)) {
10081: $instcoderegexp .= '('.$codedefaults{$item}.')';
10082: } else {
10083: $instcoderegexp .= $codedefaults{$item};
10084: }
10085: }
10086: $instcoderegexp .= '$';
10087: my (@from,@to);
10088: eval {
10089: (@from) = ($clonefromcode =~ /$instcoderegexp/);
10090: (@to) = ($clonetocode =~ /$instcoderegexp/);
10091: };
10092: if ((@from > 0) && (@to > 0)) {
10093: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10094: if (!@diffs) {
10095: $canclone = 1;
10096: }
10097: }
10098: }
10099: return $canclone;
10100: }
10101:
1.679 raeburn 10102: # ------------------------------------------------------- Course Group routines
10103:
10104: sub get_coursegroups {
1.809 raeburn 10105: my ($cdom,$cnum,$group,$namespace) = @_;
10106: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 10107: }
10108:
1.679 raeburn 10109: sub modify_coursegroup {
10110: my ($cdom,$cnum,$groupsettings) = @_;
10111: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10112: }
10113:
1.809 raeburn 10114: sub toggle_coursegroup_status {
10115: my ($cdom,$cnum,$group,$action) = @_;
10116: my ($from_namespace,$to_namespace);
10117: if ($action eq 'delete') {
10118: $from_namespace = 'coursegroups';
10119: $to_namespace = 'deleted_groups';
10120: } else {
10121: $from_namespace = 'deleted_groups';
10122: $to_namespace = 'coursegroups';
10123: }
10124: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 10125: if (my $tmp = &error(%curr_group)) {
10126: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10127: return ('read error',$tmp);
10128: } else {
10129: my %savedsettings = %curr_group;
1.809 raeburn 10130: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 10131: my $deloutcome;
10132: if ($result eq 'ok') {
1.809 raeburn 10133: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 10134: } else {
10135: return ('write error',$result);
10136: }
10137: if ($deloutcome eq 'ok') {
10138: return 'ok';
10139: } else {
10140: return ('delete error',$deloutcome);
10141: }
10142: }
10143: }
10144:
1.679 raeburn 10145: sub modify_group_roles {
1.957 raeburn 10146: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 10147: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10148: my $role = 'gr/'.&escape($userprivs);
10149: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 10150: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 10151: if ($result eq 'ok') {
10152: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10153: }
1.679 raeburn 10154: return $result;
10155: }
10156:
10157: sub modify_coursegroup_membership {
10158: my ($cdom,$cnum,$membership) = @_;
10159: my $result = &put('groupmembership',$membership,$cdom,$cnum);
10160: return $result;
10161: }
10162:
1.682 raeburn 10163: sub get_active_groups {
10164: my ($udom,$uname,$cdom,$cnum) = @_;
10165: my $now = time;
10166: my %groups = ();
10167: foreach my $key (keys(%env)) {
1.811 albertel 10168: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 10169: my ($start,$end) = split(/\./,$env{$key});
10170: if (($end!=0) && ($end<$now)) { next; }
10171: if (($start!=0) && ($start>$now)) { next; }
10172: if ($1 eq $cdom && $2 eq $cnum) {
10173: $groups{$3} = $env{$key} ;
10174: }
10175: }
10176: }
10177: return %groups;
10178: }
10179:
1.683 raeburn 10180: sub get_group_membership {
10181: my ($cdom,$cnum,$group) = @_;
10182: return(&dump('groupmembership',$cdom,$cnum,$group));
10183: }
10184:
10185: sub get_users_groups {
10186: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 10187: my @usersgroups;
1.683 raeburn 10188: my $cachetime=1800;
10189:
10190: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 10191: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10192: if (defined($cached)) {
1.734 albertel 10193: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 10194: } else {
10195: $grouplist = '';
1.816 raeburn 10196: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 10197: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 10198: my $access_end = $env{'course.'.$courseid.
10199: '.default_enrollment_end_date'};
10200: my $now = time;
10201: foreach my $key (keys(%roleshash)) {
10202: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10203: my $group = $1;
10204: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10205: my $start = $2;
10206: my $end = $1;
10207: if ($start == -1) { next; } # deleted from group
10208: if (($start!=0) && ($start>$now)) { next; }
10209: if (($end!=0) && ($end<$now)) {
10210: if ($access_end && $access_end < $now) {
10211: if ($access_end - $end < 86400) {
10212: push(@usersgroups,$group);
1.733 raeburn 10213: }
10214: }
1.817 raeburn 10215: next;
1.733 raeburn 10216: }
1.817 raeburn 10217: push(@usersgroups,$group);
1.683 raeburn 10218: }
10219: }
10220: }
1.817 raeburn 10221: @usersgroups = &sort_course_groups($courseid,@usersgroups);
10222: $grouplist = join(':',@usersgroups);
10223: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 10224: }
1.733 raeburn 10225: return @usersgroups;
1.683 raeburn 10226: }
10227:
10228: sub devalidate_getgroups_cache {
10229: my ($udom,$uname,$cdom,$cnum)=@_;
10230: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 10231:
1.683 raeburn 10232: my $hashid="$udom:$uname:$courseid";
10233: &devalidate_cache_new('getgroups',$hashid);
10234: }
10235:
1.12 www 10236: # ------------------------------------------------------------------ Plain Text
10237:
10238: sub plaintext {
1.988 raeburn 10239: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 10240: if ($short =~ m{^cr/}) {
1.758 albertel 10241: return (split('/',$short))[-1];
10242: }
1.742 raeburn 10243: if (!defined($cid)) {
10244: $cid = $env{'request.course.id'};
10245: }
10246: my %rolenames = (
1.1008 raeburn 10247: Course => 'std',
10248: Community => 'alt1',
1.1305 raeburn 10249: Placement => 'std',
1.742 raeburn 10250: );
1.1037 raeburn 10251: if ($cid ne '') {
10252: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10253: unless ($forcedefault) {
10254: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
10255: &Apache::lonlocal::mt_escape(\$roletext);
10256: return &Apache::lonlocal::mt($roletext);
10257: }
10258: }
10259: }
10260: if ((defined($type)) && (defined($rolenames{$type})) &&
10261: (defined($rolenames{$type})) &&
10262: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 10263: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 10264: } elsif ($cid ne '') {
10265: my $crstype = $env{'course.'.$cid.'.type'};
10266: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10267: (defined($prp{$short}{$rolenames{$crstype}}))) {
10268: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10269: }
1.742 raeburn 10270: }
1.1037 raeburn 10271: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 10272: }
10273:
10274: # ----------------------------------------------------------------- Assign Role
10275:
10276: sub assignrole {
1.957 raeburn 10277: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10278: $context)=@_;
1.21 www 10279: my $mrole;
10280: if ($role =~ /^cr\//) {
1.393 www 10281: my $cwosec=$url;
1.811 albertel 10282: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 10283: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 10284: my $refused = 1;
10285: if ($context eq 'requestcourses') {
10286: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10287: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10288: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10289: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10290: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10291: if ($crsenv{'internal.courseowner'} eq
10292: $env{'user.name'}.':'.$env{'user.domain'}) {
10293: $refused = '';
10294: }
10295: }
10296: }
10297: }
10298: }
10299: if ($refused) {
10300: &logthis('Refused custom assignrole: '.
10301: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10302: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10303: return 'refused';
10304: }
1.104 www 10305: }
1.21 www 10306: $mrole='cr';
1.678 raeburn 10307: } elsif ($role =~ /^gr\//) {
10308: my $cwogrp=$url;
1.811 albertel 10309: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 10310: unless (&allowed('mdg',$cwogrp)) {
10311: &logthis('Refused group assignrole: '.
10312: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10313: $env{'user.name'}.' at '.$env{'user.domain'});
10314: return 'refused';
10315: }
10316: $mrole='gr';
1.21 www 10317: } else {
1.82 www 10318: my $cwosec=$url;
1.811 albertel 10319: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 10320: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10321: my $refused;
10322: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
10323: if (!(&allowed('c'.$role,$url))) {
10324: $refused = 1;
10325: }
10326: } else {
10327: $refused = 1;
10328: }
1.947 raeburn 10329: if ($refused) {
1.1045 raeburn 10330: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377 raeburn 10331: if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045 raeburn 10332: my %crsenv;
10333: if ($role eq 'cc' || $role eq 'co') {
10334: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10335: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10336: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10337: if ($crsenv{'internal.courseowner'} eq
10338: $env{'user.name'}.':'.$env{'user.domain'}) {
10339: $refused = '';
10340: }
10341: }
10342: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
10343: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10344: if ($crsenv{'internal.courseowner'} eq
10345: $env{'user.name'}.':'.$env{'user.domain'}) {
10346: $refused = '';
10347: }
10348: }
10349: }
10350: }
1.1368 raeburn 10351: } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10352: if ($role eq 'st') {
10353: $refused = '';
1.1377 raeburn 10354: } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368 raeburn 10355: $refused = '';
10356: }
1.1017 raeburn 10357: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 10358: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 10359: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 10360: my $wrongcc;
10361: if ($cnum =~ /^$match_community$/) {
10362: $wrongcc = 1 if ($role eq 'cc');
10363: } else {
10364: $wrongcc = 1 if ($role eq 'co');
10365: }
10366: unless ($wrongcc) {
10367: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10368: if ($crsenv{'internal.courseowner'} eq
10369: $env{'user.name'}.':'.$env{'user.domain'}) {
10370: $refused = '';
10371: }
1.1017 raeburn 10372: }
10373: }
1.1183 raeburn 10374: } elsif ($context eq 'requestauthor') {
10375: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
10376: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10377: if ($env{'environment.requestauthor'} eq 'automatic') {
10378: $refused = '';
10379: } else {
10380: my %domdefaults = &get_domain_defaults($udom);
10381: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10382: my $checkbystatus;
10383: if ($env{'user.adv'}) {
10384: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10385: if ($disposition eq 'automatic') {
10386: $refused = '';
10387: } elsif ($disposition eq '') {
10388: $checkbystatus = 1;
10389: }
10390: } else {
10391: $checkbystatus = 1;
10392: }
10393: if ($checkbystatus) {
10394: if ($env{'environment.inststatus'}) {
10395: my @inststatuses = split(/,/,$env{'environment.inststatus'});
10396: foreach my $type (@inststatuses) {
10397: if (($type ne '') &&
10398: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10399: $refused = '';
10400: }
10401: }
10402: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10403: $refused = '';
10404: }
10405: }
10406: }
10407: }
10408: }
1.1017 raeburn 10409: }
10410: if ($refused) {
1.947 raeburn 10411: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10412: ' '.$role.' '.$end.' '.$start.' by '.
10413: $env{'user.name'}.' at '.$env{'user.domain'});
10414: return 'refused';
10415: }
1.932 raeburn 10416: }
1.1131 raeburn 10417: } elsif ($role eq 'au') {
10418: if ($url ne '/'.$udom.'/') {
10419: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10420: ' to assign author role for '.$uname.':'.$udom.
10421: ' in domain: '.$url.' refused (wrong domain).');
10422: return 'refused';
10423: }
1.104 www 10424: }
1.21 www 10425: $mrole=$role;
10426: }
1.620 albertel 10427: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 10428: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 10429: if ($end) { $command.='_'.$end; }
1.21 www 10430: if ($start) {
10431: if ($end) {
1.81 www 10432: $command.='_'.$start;
1.21 www 10433: } else {
1.81 www 10434: $command.='_0_'.$start;
1.21 www 10435: }
10436: }
1.739 raeburn 10437: my $origstart = $start;
10438: my $origend = $end;
1.957 raeburn 10439: my $delflag;
1.357 www 10440: # actually delete
10441: if ($deleteflag) {
1.373 www 10442: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 10443: # modify command to delete the role
1.620 albertel 10444: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 10445: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 10446: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 10447: # set start and finish to negative values for userrolelog
10448: $start=-1;
10449: $end=-1;
1.957 raeburn 10450: $delflag = 1;
1.357 www 10451: }
10452: }
10453: # send command
1.349 www 10454: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 10455: # log new user role if status is ok
1.349 www 10456: if ($answer eq 'ok') {
1.663 raeburn 10457: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 10458: if (($role eq 'cc') || ($role eq 'in') ||
10459: ($role eq 'ep') || ($role eq 'ad') ||
10460: ($role eq 'ta') || ($role eq 'st') ||
10461: ($role=~/^cr/) || ($role eq 'gr') ||
10462: ($role eq 'co')) {
1.1200 raeburn 10463: # for course roles, perform group memberships changes triggered by role change.
10464: unless ($role =~ /^gr/) {
10465: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10466: $origstart,$selfenroll,$context);
10467: }
1.1184 raeburn 10468: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10469: $selfenroll,$context);
10470: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334 raeburn 10471: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10472: ($role eq 'da')) {
1.1184 raeburn 10473: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10474: $context);
10475: } elsif (($role eq 'ca') || ($role eq 'aa')) {
10476: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10477: $context);
10478: }
1.1053 raeburn 10479: if ($role eq 'cc') {
10480: &autoupdate_coowners($url,$end,$start,$uname,$udom);
10481: }
1.349 www 10482: }
10483: return $answer;
1.169 harris41 10484: }
10485:
1.1053 raeburn 10486: sub autoupdate_coowners {
10487: my ($url,$end,$start,$uname,$udom) = @_;
10488: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10489: if (($cdom ne '') && ($cnum ne '')) {
10490: my $now = time;
10491: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10492: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10493: my %coursehash = &coursedescription($cdom.'_'.$cnum);
10494: my $instcode = $coursehash{'internal.coursecode'};
1.1444 raeburn 10495: my $xlists = $coursehash{'internal.crosslistings'};
1.1053 raeburn 10496: if ($instcode ne '') {
1.1056 raeburn 10497: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10498: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 10499: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 10500: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1444 raeburn 10501: unless ($result eq 'valid') {
10502: if ($xlists ne '') {
10503: foreach my $xlist (split(',',$xlists)) {
10504: my ($inst_crosslist,$lcsec) = split(':',$xlist);
10505: $result =
1.1446 raeburn 10506: &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10507: $inst_crosslist,$uname.':'.$udom);
10508: last if ($result eq 'valid');
1.1444 raeburn 10509: }
10510: }
10511: }
1.1056 raeburn 10512: if ($result eq 'valid') {
10513: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 10514: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10515: push(@newcoowners,$coowner);
10516: }
10517: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10518: push(@newcoowners,$uname.':'.$udom);
10519: }
10520: @newcoowners = sort(@newcoowners);
10521: } else {
10522: push(@newcoowners,$uname.':'.$udom);
10523: }
1.1444 raeburn 10524: } elsif ($coursehash{'internal.co-owners'}) {
10525: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10526: unless ($coowner eq $uname.':'.$udom) {
10527: push(@newcoowners,$coowner);
1.1053 raeburn 10528: }
1.1444 raeburn 10529: }
10530: unless (@newcoowners > 0) {
10531: $delcoowners = 1;
10532: $coowners = '';
1.1053 raeburn 10533: }
10534: }
10535: if (@newcoowners || $delcoowners) {
10536: &store_coowners($cdom,$cnum,$coursehash{'home'},
10537: $delcoowners,@newcoowners);
10538: }
10539: }
10540: }
10541: }
10542: }
10543: }
10544: }
10545:
10546: sub store_coowners {
10547: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10548: my $cid = $cdom.'_'.$cnum;
10549: my ($coowners,$delresult,$putresult);
10550: if (@newcoowners) {
10551: $coowners = join(',',@newcoowners);
10552: my %coownershash = (
10553: 'internal.co-owners' => $coowners,
10554: );
10555: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10556: if ($putresult eq 'ok') {
10557: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10558: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10559: }
10560: }
10561: }
10562: if ($delcoowners) {
10563: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10564: if ($delresult eq 'ok') {
10565: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10566: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10567: }
10568: }
10569: }
10570: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10571: my %crsinfo =
10572: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10573: if (ref($crsinfo{$cid}) eq 'HASH') {
10574: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10575: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10576: }
10577: }
10578: }
10579:
1.169 harris41 10580: # -------------------------------------------------- Modify user authentication
1.197 www 10581: # Overrides without validation
10582:
1.169 harris41 10583: sub modifyuserauth {
10584: my ($udom,$uname,$umode,$upass)=@_;
10585: my $uhome=&homeserver($uname,$udom);
1.1409 raeburn 10586: my $allowed;
10587: if (&allowed('mau',$udom)) {
10588: $allowed = 1;
10589: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10590: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10591: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10592: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10593: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10594: if (($cdom ne '') && ($cnum ne '')) {
10595: my $is_owner = &is_course_owner($cdom,$cnum);
10596: if ($is_owner) {
10597: $allowed = 1;
10598: }
10599: }
10600: }
10601: unless ($allowed) { return 'refused'; }
1.197 www 10602: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 10603: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10604: ' in domain '.$env{'request.role.domain'});
1.169 harris41 10605: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10606: &escape($upass),$uhome);
1.1434 raeburn 10607: my $ip = &get_requestor_ip();
1.620 albertel 10608: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 10609: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1434 raeburn 10610: '(Remote '.$ip.'): '.$reply);
1.197 www 10611: &log($udom,,$uname,$uhome,
1.620 albertel 10612: 'Authentication changed by '.$env{'user.domain'}.', '.
10613: $env{'user.name'}.', '.$umode.
1.1435 raeburn 10614: '(Remote '.$ip.'): '.$reply);
1.169 harris41 10615: unless ($reply eq 'ok') {
1.197 www 10616: &logthis('Authentication mode error: '.$reply);
1.169 harris41 10617: return 'error: '.$reply;
10618: }
1.170 harris41 10619: return 'ok';
1.80 www 10620: }
10621:
1.81 www 10622: # --------------------------------------------------------------- Modify a user
1.80 www 10623:
1.81 www 10624: sub modifyuser {
1.206 matthew 10625: my ($udom, $uname, $uid,
10626: $umode, $upass, $first,
10627: $middle, $last, $gene,
1.1058 raeburn 10628: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 10629: $udom= &LONCAPA::clean_domain($udom);
10630: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 10631: my $showcandelete = 'none';
10632: if (ref($candelete) eq 'ARRAY') {
10633: if (@{$candelete} > 0) {
10634: $showcandelete = join(', ',@{$candelete});
10635: }
10636: }
1.81 www 10637: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 10638: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 10639: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 10640: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10641: ' desiredhome not specified').
1.620 albertel 10642: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10643: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 10644: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 10645: my $newuser;
10646: if ($uhome eq 'no_host') {
10647: $newuser = 1;
1.1368 raeburn 10648: unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10649: ($umode eq 'lti')) {
10650: return 'error: more information needed to create new user';
10651: }
1.1075 raeburn 10652: }
1.80 www 10653: # ----------------------------------------------------------------- Create User
1.406 albertel 10654: if (($uhome eq 'no_host') &&
1.1368 raeburn 10655: (($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80 www 10656: my $unhome='';
1.844 albertel 10657: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 10658: $unhome = $desiredhome;
1.620 albertel 10659: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10660: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 10661: } else { # load balancing routine for determining $unhome
1.81 www 10662: my $loadm=10000000;
1.841 albertel 10663: my %servers = &get_servers($udom,'library');
10664: foreach my $tryserver (keys(%servers)) {
10665: my $answer=reply('load',$tryserver);
10666: if (($answer=~/\d+/) && ($answer<$loadm)) {
10667: $loadm=$answer;
10668: $unhome=$tryserver;
10669: }
1.80 www 10670: }
10671: }
10672: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 10673: return 'error: unable to find a home server for '.$uname.
10674: ' in domain '.$udom;
1.80 www 10675: }
10676: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10677: &escape($upass),$unhome);
10678: unless ($reply eq 'ok') {
10679: return 'error: '.$reply;
10680: }
1.230 stredwic 10681: $uhome=&homeserver($uname,$udom,'true');
1.80 www 10682: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 10683: return 'error: unable verify users home machine.';
1.80 www 10684: }
1.209 matthew 10685: } # End of creation of new user
1.80 www 10686: # ---------------------------------------------------------------------- Add ID
10687: if ($uid) {
10688: $uid=~tr/A-Z/a-z/;
10689: my %uidhash=&idrget($udom,$uname);
1.196 www 10690: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10691: && (!$forceid)) {
1.80 www 10692: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10693: return 'error: user id "'.$uid.'" does not match '.
10694: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10695: }
10696: } else {
1.1300 raeburn 10697: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 10698: }
10699: }
10700: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10701: my @tmp=&get('environment',
1.899 raeburn 10702: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10703: 'permanentemail','inststatus'],
1.134 albertel 10704: $udom,$uname);
1.1075 raeburn 10705: my (%names,%oldnames);
1.313 matthew 10706: if ($tmp[0] =~ m/^error:.*/) {
10707: %names=();
10708: } else {
10709: %names = @tmp;
1.1075 raeburn 10710: %oldnames = %names;
1.313 matthew 10711: }
1.388 www 10712: #
1.1058 raeburn 10713: # If name, email and/or uid are blank (e.g., because an uploaded file
10714: # of users did not contain them), do not overwrite existing values
10715: # unless field is in $candelete array ref.
10716: #
10717:
10718: my @fields = ('firstname','middlename','lastname','generation',
10719: 'permanentemail','id');
10720: my %newvalues;
10721: if (ref($candelete) eq 'ARRAY') {
10722: foreach my $field (@fields) {
10723: if (grep(/^\Q$field\E$/,@{$candelete})) {
10724: if ($field eq 'firstname') {
10725: $names{$field} = $first;
10726: } elsif ($field eq 'middlename') {
10727: $names{$field} = $middle;
10728: } elsif ($field eq 'lastname') {
10729: $names{$field} = $last;
10730: } elsif ($field eq 'generation') {
10731: $names{$field} = $gene;
10732: } elsif ($field eq 'permanentemail') {
10733: $names{$field} = $email;
10734: } elsif ($field eq 'id') {
10735: $names{$field} = $uid;
10736: }
10737: }
10738: }
10739: }
1.388 www 10740: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10741: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10742: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10743: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10744: if ($email) {
10745: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10746: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10747: }
1.899 raeburn 10748: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10749: if (defined($inststatus)) {
10750: $names{'inststatus'} = '';
10751: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10752: if (ref($usertypes) eq 'HASH') {
10753: my @okstatuses;
10754: foreach my $item (split(/:/,$inststatus)) {
10755: if (defined($usertypes->{$item})) {
10756: push(@okstatuses,$item);
10757: }
10758: }
10759: if (@okstatuses) {
10760: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10761: }
10762: }
10763: }
1.1075 raeburn 10764: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10765: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10766: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10767: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10768: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10769: } else {
10770: $logmsg .= ' during self creation';
10771: }
1.1075 raeburn 10772: my $changed;
10773: if ($newuser) {
10774: $changed = 1;
10775: } else {
10776: foreach my $field (@fields) {
10777: if ($names{$field} ne $oldnames{$field}) {
10778: $changed = 1;
10779: last;
10780: }
10781: }
10782: }
10783: unless ($changed) {
10784: $logmsg = 'No changes in user information needed for: '.$logmsg;
10785: &logthis($logmsg);
10786: return 'ok';
10787: }
10788: my $reply = &put('environment', \%names, $udom,$uname);
10789: if ($reply ne 'ok') {
10790: return 'error: '.$reply;
10791: }
1.1087 raeburn 10792: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10793: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10794: }
1.1075 raeburn 10795: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10796: &devalidate_cache_new('namescache',$uname.':'.$udom);
10797: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10798: &logthis($logmsg);
1.134 albertel 10799: return 'ok';
1.80 www 10800: }
10801:
1.81 www 10802: # -------------------------------------------------------------- Modify student
1.80 www 10803:
1.81 www 10804: sub modifystudent {
10805: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10806: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 10807: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10808: if (!$cid) {
1.620 albertel 10809: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10810: return 'not_in_class';
10811: }
1.80 www 10812: }
10813: # --------------------------------------------------------------- Make the user
1.81 www 10814: my $reply=&modifyuser
1.209 matthew 10815: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10816: $desiredhome,$email,$inststatus);
1.80 www 10817: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10818: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 10819: # student's environment
1.297 matthew 10820: $uid = undef if (!$forceid);
1.455 albertel 10821: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 10822: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 10823: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10824: return $reply;
10825: }
10826:
10827: sub modify_student_enrollment {
1.1216 raeburn 10828: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314 raeburn 10829: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10830: my ($cdom,$cnum,$chome);
10831: if (!$cid) {
1.620 albertel 10832: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10833: return 'not_in_class';
10834: }
1.620 albertel 10835: $cdom=$env{'course.'.$cid.'.domain'};
10836: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10837: } else {
10838: ($cdom,$cnum)=split(/_/,$cid);
10839: }
1.620 albertel 10840: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10841: if (!$chome) {
1.457 raeburn 10842: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10843: }
1.455 albertel 10844: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10845: # Make sure the user exists
1.81 www 10846: my $uhome=&homeserver($uname,$udom);
10847: if (($uhome eq '') || ($uhome eq 'no_host')) {
10848: return 'error: no such user';
10849: }
1.297 matthew 10850: # Get student data if we were not given enough information
10851: if (!defined($first) || $first eq '' ||
10852: !defined($last) || $last eq '' ||
10853: !defined($uid) || $uid eq '' ||
10854: !defined($middle) || $middle eq '' ||
10855: !defined($gene) || $gene eq '') {
1.294 matthew 10856: # They did not supply us with enough data to enroll the student, so
10857: # we need to pick up more information.
1.297 matthew 10858: my %tmp = &get('environment',
1.294 matthew 10859: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10860: ,$udom,$uname);
10861:
1.800 albertel 10862: #foreach my $key (keys(%tmp)) {
10863: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10864: #}
1.294 matthew 10865: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10866: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10867: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10868: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10869: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10870: }
1.556 albertel 10871: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10872: my $user = "$uname:$udom";
10873: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10874: my $reply=cput('classlist',
1.1148 raeburn 10875: {$user =>
1.1314 raeburn 10876: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 10877: $cdom,$cnum);
1.1148 raeburn 10878: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10879: &devalidate_getsection_cache($udom,$uname,$cid);
10880: } else {
1.81 www 10881: return 'error: '.$reply;
10882: }
1.297 matthew 10883: # Add student role to user
1.83 www 10884: my $uurl='/'.$cid;
1.81 www 10885: $uurl=~s/\_/\//g;
10886: if ($usec) {
10887: $uurl.='/'.$usec;
10888: }
1.1148 raeburn 10889: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10890: $selfenroll,$context);
10891: if ($result ne 'ok') {
10892: if ($old_entry{$user} ne '') {
10893: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10894: } else {
10895: $reply = &del('classlist',[$user],$cdom,$cnum);
10896: }
10897: }
10898: return $result;
1.21 www 10899: }
10900:
1.556 albertel 10901: sub format_name {
10902: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10903: my $name;
10904: if ($first ne 'lastname') {
10905: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10906: } else {
10907: if ($lastname=~/\S/) {
10908: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10909: $name=~s/\s+,/,/;
10910: } else {
10911: $name.= $firstname.' '.$middlename.' '.$generation;
10912: }
10913: }
10914: $name=~s/^\s+//;
10915: $name=~s/\s+$//;
10916: $name=~s/\s+/ /g;
10917: return $name;
10918: }
10919:
1.84 www 10920: # ------------------------------------------------- Write to course preferences
10921:
10922: sub writecoursepref {
10923: my ($courseid,%prefs)=@_;
10924: $courseid=~s/^\///;
10925: $courseid=~s/\_/\//g;
10926: my ($cdomain,$cnum)=split(/\//,$courseid);
10927: my $chome=homeserver($cnum,$cdomain);
10928: if (($chome eq '') || ($chome eq 'no_host')) {
10929: return 'error: no such course';
10930: }
10931: my $cstring='';
1.800 albertel 10932: foreach my $pref (keys(%prefs)) {
10933: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 10934: }
1.84 www 10935: $cstring=~s/\&$//;
10936: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10937: }
10938:
10939: # ---------------------------------------------------------- Make/modify course
10940:
10941: sub createcourse {
1.741 raeburn 10942: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1423 raeburn 10943: $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84 www 10944: $url=&declutter($url);
10945: my $cid='';
1.1028 raeburn 10946: if ($context eq 'requestcourses') {
10947: my $can_create = 0;
10948: my ($ownername,$ownerdom) = split(':',$course_owner);
10949: if ($udom eq $ownerdom) {
1.1423 raeburn 10950: my $reload;
10951: if (($callercontext eq 'auto') &&
10952: ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10953: $reload = 'reload';
10954: }
10955: if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028 raeburn 10956: $context)) {
10957: $can_create = 1;
10958: }
10959: } else {
10960: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10961: $category);
10962: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10963: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10964: if (@curr > 0) {
10965: my @options = qw(approval validate autolimit);
10966: my $optregex = join('|',@options);
10967: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10968: $can_create = 1;
10969: }
10970: }
10971: }
10972: }
10973: if ($can_create) {
10974: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10975: unless (&allowed('ccc',$udom)) {
10976: return 'refused';
10977: }
1.1017 raeburn 10978: }
10979: } else {
10980: return 'refused';
10981: }
1.1028 raeburn 10982: } elsif (!&allowed('ccc',$udom)) {
10983: return 'refused';
1.84 www 10984: }
1.1011 raeburn 10985: # --------------------------------------------------------------- Get Unique ID
10986: my $uname;
10987: if ($cnum =~ /^$match_courseid$/) {
10988: my $chome=&homeserver($cnum,$udom,'true');
10989: if (($chome eq '') || ($chome eq 'no_host')) {
10990: $uname = $cnum;
10991: } else {
1.1038 raeburn 10992: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10993: }
10994: } else {
1.1038 raeburn 10995: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10996: }
10997: return $uname if ($uname =~ /^error/);
10998: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 10999: if (!defined($course_server)) {
11000: if (defined(&domain($udom,'primary'))) {
11001: $course_server = &domain($udom,'primary');
11002: } else {
11003: $course_server = $env{'user.home'};
11004: }
11005: }
11006: my %host_servers =
11007: &Apache::lonnet::get_servers($udom,'library');
11008: unless ($host_servers{$course_server}) {
11009: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 11010: }
1.84 www 11011: # ------------------------------------------------------------- Make the course
11012: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 11013: $course_server);
1.84 www 11014: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 11015: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 11016: if (($uhome eq '') || ($uhome eq 'no_host')) {
11017: return 'error: no such course';
11018: }
1.271 www 11019: # ----------------------------------------------------------------- Course made
1.516 raeburn 11020: # log existence
1.1029 raeburn 11021: my $now = time;
1.918 raeburn 11022: my $newcourse = {
11023: $udom.'_'.$uname => {
1.921 raeburn 11024: description => $description,
11025: inst_code => $inst_code,
11026: owner => $course_owner,
11027: type => $crstype,
1.1029 raeburn 11028: creator => $env{'user.name'}.':'.
11029: $env{'user.domain'},
11030: created => $now,
11031: context => $context,
1.918 raeburn 11032: },
11033: };
1.921 raeburn 11034: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 11035: # set toplevel url
1.271 www 11036: my $topurl=$url;
11037: unless ($nonstandard) {
11038: # ------------------------------------------ For standard courses, make top url
11039: my $mapurl=&clutter($url);
1.278 www 11040: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 11041: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 11042: <map>
11043: <resource id="1" type="start"></resource>
11044: <resource id="2" src="$mapurl"></resource>
11045: <resource id="3" type="finish"></resource>
11046: <link index="1" from="1" to="2"></link>
11047: <link index="2" from="2" to="3"></link>
11048: </map>
11049: ENDINITMAP
11050: $topurl=&declutter(
1.638 albertel 11051: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 11052: );
11053: }
11054: # ----------------------------------------------------------- Write preferences
1.84 www 11055: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 11056: ('description' => $description,
11057: 'url' => $topurl,
11058: 'internal.creator' => $env{'user.name'}.':'.
11059: $env{'user.domain'},
11060: 'internal.created' => $now,
11061: 'internal.creationcontext' => $context)
11062: );
1.84 www 11063: return '/'.$udom.'/'.$uname;
11064: }
11065:
1.1011 raeburn 11066: # ------------------------------------------------------------------- Create ID
11067: sub generate_coursenum {
1.1038 raeburn 11068: my ($udom,$crstype) = @_;
1.1011 raeburn 11069: my $domdesc = &domain($udom);
11070: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 11071: my $first;
11072: if ($crstype eq 'Community') {
11073: $first = '0';
11074: } else {
11075: $first = int(1+rand(9));
11076: }
11077: my $uname=$first.
1.1011 raeburn 11078: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11079: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11080: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11081: # ----------------------------------------------- Make sure that does not exist
11082: my $uhome=&homeserver($uname,$udom,'true');
11083: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 11084: if ($crstype eq 'Community') {
11085: $first = '0';
11086: } else {
11087: $first = int(1+rand(9));
11088: }
11089: $uname=$first.
1.1011 raeburn 11090: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11091: substr($$.time,0,5).unpack("H8",pack("I32",time)).
11092: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11093: $uhome=&homeserver($uname,$udom,'true');
11094: unless (($uhome eq '') || ($uhome eq 'no_host')) {
11095: return 'error: unable to generate unique course-ID';
11096: }
11097: }
11098: return $uname;
11099: }
11100:
1.813 albertel 11101: sub is_course {
1.1167 droeschl 11102: my ($cdom, $cnum) = scalar(@_) == 1 ?
11103: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
11104:
1.1381 raeburn 11105: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11106: my $uhome=&homeserver($cnum,$cdom);
11107: my $iscourse;
11108: if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382 raeburn 11109: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381 raeburn 11110: } else {
11111: my $hashid = $cdom.':'.$cnum;
11112: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11113: unless (defined($cached)) {
11114: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11115: $cnum,undef,undef,'.');
11116: $iscourse = 0;
11117: if (exists($courses{$cdom.'_'.$cnum})) {
11118: $iscourse = 1;
11119: }
11120: &do_cache_new('iscourse',$hashid,$iscourse,3600);
11121: }
11122: }
11123: return unless ($iscourse);
1.1167 droeschl 11124: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 11125: }
11126:
1.1015 raeburn 11127: sub store_userdata {
11128: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 11129: my $result;
1.1016 raeburn 11130: if ($datakey ne '') {
1.1013 raeburn 11131: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 11132: if ($udom eq '' || $uname eq '') {
11133: $udom = $env{'user.domain'};
11134: $uname = $env{'user.name'};
11135: }
11136: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 11137: if (($uhome eq '') || ($uhome eq 'no_host')) {
11138: $result = 'error: no_host';
11139: } else {
1.1434 raeburn 11140: $storehash->{'ip'} = &get_requestor_ip();
1.1013 raeburn 11141: $storehash->{'host'} = $perlvar{'lonHostID'};
11142:
11143: my $namevalue='';
11144: foreach my $key (keys(%{$storehash})) {
11145: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11146: }
11147: $namevalue=~s/\&$//;
1.1224 raeburn 11148: unless ($namespace eq 'courserequests') {
11149: $datakey = &escape($datakey);
11150: }
1.1105 raeburn 11151: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
11152: $namevalue,$uhome);
1.1013 raeburn 11153: }
11154: } else {
11155: $result = 'error: data to store was not a hash reference';
11156: }
11157: } else {
11158: $result= 'error: invalid requestkey';
11159: }
11160: return $result;
11161: }
11162:
1.21 www 11163: # ---------------------------------------------------------- Assign Custom Role
11164:
11165: sub assigncustomrole {
1.957 raeburn 11166: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11167: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 11168: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 11169: }
11170:
11171: # ----------------------------------------------------------------- Revoke Role
11172:
11173: sub revokerole {
1.957 raeburn 11174: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11175: my $now=time;
1.965 raeburn 11176: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 11177: }
11178:
11179: # ---------------------------------------------------------- Revoke Custom Role
11180:
11181: sub revokecustomrole {
1.957 raeburn 11182: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11183: my $now=time;
1.357 www 11184: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 11185: $deleteflag,$selfenroll,$context);
1.17 www 11186: }
11187:
1.533 banghart 11188: # ------------------------------------------------------------ Disk usage
1.535 albertel 11189: sub diskusage {
1.955 raeburn 11190: my ($udom,$uname,$directorypath,$getpropath)=@_;
11191: $directorypath =~ s/\/$//;
11192: my $listing=&reply('du2:'.&escape($directorypath).':'
11193: .&escape($getpropath).':'.&escape($uname).':'
11194: .&escape($udom),homeserver($uname,$udom));
11195: if ($listing eq 'unknown_cmd') {
11196: if ($getpropath) {
11197: $directorypath = &propath($udom,$uname).'/'.$directorypath;
11198: }
11199: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11200: }
1.514 albertel 11201: return $listing;
1.512 banghart 11202: }
11203:
1.566 banghart 11204: sub is_locked {
1.1096 raeburn 11205: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 11206: my @check;
11207: my $is_locked;
1.1093 raeburn 11208: push (@check,$file_name);
1.613 albertel 11209: my %locked = &get('file_permissions',\@check,
1.620 albertel 11210: $env{'user.domain'},$env{'user.name'});
1.615 albertel 11211: my ($tmp)=keys(%locked);
11212: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 11213:
1.566 banghart 11214: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 11215: $is_locked = 'false';
11216: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 11217: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 11218: $is_locked = 'true';
1.1096 raeburn 11219: if (ref($which) eq 'ARRAY') {
11220: push(@{$which},$entry);
11221: } else {
11222: last;
11223: }
1.745 raeburn 11224: }
11225: }
1.566 banghart 11226: } else {
11227: $is_locked = 'false';
11228: }
1.1093 raeburn 11229: return $is_locked;
1.566 banghart 11230: }
11231:
1.759 albertel 11232: sub declutter_portfile {
11233: my ($file) = @_;
1.833 albertel 11234: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 11235: return $file;
11236: }
11237:
1.559 banghart 11238: # ------------------------------------------------------------- Mark as Read Only
11239:
11240: sub mark_as_readonly {
11241: my ($domain,$user,$files,$what) = @_;
1.613 albertel 11242: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11243: my ($tmp)=keys(%current_permissions);
11244: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 11245: foreach my $file (@{$files}) {
1.759 albertel 11246: $file = &declutter_portfile($file);
1.561 banghart 11247: push(@{$current_permissions{$file}},$what);
1.559 banghart 11248: }
1.613 albertel 11249: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11250: return;
11251: }
11252:
1.572 banghart 11253: # ------------------------------------------------------------Save Selected Files
11254:
11255: sub save_selected_files {
11256: my ($user, $path, @files) = @_;
11257: my $filename = $user."savedfiles";
1.573 banghart 11258: my @other_files = &files_not_in_path($user, $path);
1.1359 raeburn 11259: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 11260: foreach my $file (@files) {
1.620 albertel 11261: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 11262: }
11263: foreach my $file (@other_files) {
1.574 banghart 11264: print (OUT $file."\n");
1.572 banghart 11265: }
1.574 banghart 11266: close (OUT);
1.572 banghart 11267: return 'ok';
11268: }
11269:
1.574 banghart 11270: sub clear_selected_files {
11271: my ($user) = @_;
11272: my $filename = $user."savedfiles";
1.1359 raeburn 11273: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 11274: print (OUT undef);
11275: close (OUT);
11276: return ("ok");
11277: }
11278:
1.572 banghart 11279: sub files_in_path {
11280: my ($user, $path) = @_;
11281: my $filename = $user."savedfiles";
11282: my %return_files;
1.1359 raeburn 11283: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 11284: while (my $line_in = <IN>) {
1.574 banghart 11285: chomp ($line_in);
11286: my @paths_and_file = split (m!/!, $line_in);
11287: my $file_part = pop (@paths_and_file);
11288: my $path_part = join ('/', @paths_and_file);
1.573 banghart 11289: $path_part.='/';
11290: my $path_and_file = $path_part.$file_part;
11291: if ($path_part eq $path) {
11292: $return_files{$file_part}= 'selected';
11293: }
11294: }
1.574 banghart 11295: close (IN);
11296: return (\%return_files);
1.572 banghart 11297: }
11298:
11299: # called in portfolio select mode, to show files selected NOT in current directory
11300: sub files_not_in_path {
11301: my ($user, $path) = @_;
11302: my $filename = $user."savedfiles";
11303: my @return_files;
11304: my $path_part;
1.1359 raeburn 11305: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 11306: while (my $line = <IN>) {
1.572 banghart 11307: #ok, I know it's clunky, but I want it to work
1.800 albertel 11308: my @paths_and_file = split(m|/|, $line);
11309: my $file_part = pop(@paths_and_file);
11310: chomp($file_part);
11311: my $path_part = join('/', @paths_and_file);
1.572 banghart 11312: $path_part .= '/';
11313: my $path_and_file = $path_part.$file_part;
11314: if ($path_part ne $path) {
1.800 albertel 11315: push(@return_files, ($path_and_file));
1.572 banghart 11316: }
11317: }
1.800 albertel 11318: close(OUT);
1.574 banghart 11319: return (@return_files);
1.572 banghart 11320: }
11321:
1.1273 raeburn 11322: #------------------------------Submitted/Handedback Portfolio Files Versioning
11323:
11324: sub portfiles_versioning {
11325: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11326: my $portfolio_root = '/userfiles/portfolio';
11327: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11328: foreach my $file (@{$portfiles}) {
11329: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11330: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11331: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11332: my $getpropath = 1;
11333: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11334: $stu_name,$getpropath);
11335: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11336: my $new_answer =
11337: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11338: if ($new_answer ne 'problem getting file') {
11339: push(@{$versioned_portfiles}, $directory.$new_answer);
11340: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11341: [$symb,$env{'request.course.id'},'graded']);
11342: }
11343: }
11344: }
11345:
11346: sub get_next_version {
11347: my ($answer_name, $answer_ext, $dir_list) = @_;
11348: my $version;
11349: if (ref($dir_list) eq 'ARRAY') {
11350: foreach my $row (@{$dir_list}) {
11351: my ($file) = split(/\&/,$row,2);
11352: my ($file_name,$file_version,$file_ext) =
11353: &file_name_version_ext($file);
11354: if (($file_name eq $answer_name) &&
11355: ($file_ext eq $answer_ext)) {
11356: # gets here if filename and extension match,
11357: # regardless of version
11358: if ($file_version ne '') {
11359: # a versioned file is found so save it for later
11360: if ($file_version > $version) {
11361: $version = $file_version;
11362: }
11363: }
11364: }
11365: }
11366: }
11367: $version ++;
11368: return($version);
11369: }
11370:
11371: sub version_selected_portfile {
11372: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11373: my ($answer_name,$answer_ver,$answer_ext) =
11374: &file_name_version_ext($file_name);
11375: my $new_answer;
11376: $env{'form.copy'} =
11377: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11378: if($env{'form.copy'} eq '-1') {
11379: $new_answer = 'problem getting file';
11380: } else {
11381: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11382: my $copy_result =
11383: &finishuserfileupload($stu_name,$domain,'copy',
11384: '/portfolio'.$directory.$new_answer);
11385: }
11386: undef($env{'form.copy'});
11387: return ($new_answer);
11388: }
11389:
11390: sub file_name_version_ext {
11391: my ($file)=@_;
11392: my @file_parts = split(/\./, $file);
11393: my ($name,$version,$ext);
11394: if (@file_parts > 1) {
11395: $ext=pop(@file_parts);
11396: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11397: $version=pop(@file_parts);
11398: }
11399: $name=join('.',@file_parts);
11400: } else {
11401: $name=join('.',@file_parts);
11402: }
11403: return($name,$version,$ext);
11404: }
11405:
1.745 raeburn 11406: #----------------------------------------------Get portfolio file permissions
1.629 banghart 11407:
1.745 raeburn 11408: sub get_portfile_permissions {
11409: my ($domain,$user) = @_;
1.613 albertel 11410: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11411: my ($tmp)=keys(%current_permissions);
11412: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11413: return \%current_permissions;
11414: }
11415:
11416: #---------------------------------------------Get portfolio file access controls
11417:
1.749 raeburn 11418: sub get_access_controls {
1.745 raeburn 11419: my ($current_permissions,$group,$file) = @_;
1.769 albertel 11420: my %access;
11421: my $real_file = $file;
11422: $file =~ s/\.meta$//;
1.745 raeburn 11423: if (defined($file)) {
1.749 raeburn 11424: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11425: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 11426: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 11427: }
11428: }
1.745 raeburn 11429: } else {
1.749 raeburn 11430: foreach my $key (keys(%{$current_permissions})) {
11431: if ($key =~ /\0accesscontrol$/) {
11432: if (defined($group)) {
11433: if ($key !~ m-^\Q$group\E/-) {
11434: next;
11435: }
11436: }
11437: my ($fullpath) = split(/\0/,$key);
11438: if (ref($$current_permissions{$key}) eq 'HASH') {
11439: foreach my $control (keys(%{$$current_permissions{$key}})) {
11440: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11441: }
11442: }
11443: }
11444: }
11445: }
11446: return %access;
11447: }
11448:
11449: sub modify_access_controls {
11450: my ($file_name,$changes,$domain,$user)=@_;
11451: my ($outcome,$deloutcome);
11452: my %store_permissions;
11453: my %new_values;
11454: my %new_control;
11455: my %translation;
11456: my @deletions = ();
11457: my $now = time;
11458: if (exists($$changes{'activate'})) {
11459: if (ref($$changes{'activate'}) eq 'HASH') {
11460: my @newitems = sort(keys(%{$$changes{'activate'}}));
11461: my $numnew = scalar(@newitems);
11462: for (my $i=0; $i<$numnew; $i++) {
11463: my $newkey = $newitems[$i];
11464: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 11465: if ($newkey =~ /^\d+:/) {
11466: $newkey =~ s/^(\d+)/$newid/;
11467: $translation{$1} = $newid;
11468: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11469: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11470: $translation{$1} = $newid;
11471: }
1.749 raeburn 11472: $new_values{$file_name."\0".$newkey} =
11473: $$changes{'activate'}{$newitems[$i]};
11474: $new_control{$newkey} = $now;
11475: }
11476: }
11477: }
11478: my %todelete;
11479: my %changed_items;
11480: foreach my $action ('delete','update') {
11481: if (exists($$changes{$action})) {
11482: if (ref($$changes{$action}) eq 'HASH') {
11483: foreach my $key (keys(%{$$changes{$action}})) {
11484: my ($itemnum) = ($key =~ /^([^:]+):/);
11485: if ($action eq 'delete') {
11486: $todelete{$itemnum} = 1;
11487: } else {
11488: $changed_items{$itemnum} = $key;
11489: }
11490: }
1.745 raeburn 11491: }
11492: }
1.749 raeburn 11493: }
11494: # get lock on access controls for file.
11495: my $lockhash = {
11496: $file_name."\0".'locked_access_records' => $env{'user.name'}.
11497: ':'.$env{'user.domain'},
11498: };
11499: my $tries = 0;
11500: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11501:
1.1288 damieng 11502: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 11503: $tries ++;
1.1289 damieng 11504: sleep(0.1);
1.749 raeburn 11505: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11506: }
11507: if ($gotlock eq 'ok') {
11508: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11509: my ($tmp)=keys(%curr_permissions);
11510: if ($tmp=~/^error:/) { undef(%curr_permissions); }
11511: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11512: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11513: if (ref($curr_controls) eq 'HASH') {
11514: foreach my $control_item (keys(%{$curr_controls})) {
11515: my ($itemnum) = ($control_item =~ /^([^:]+):/);
11516: if (defined($todelete{$itemnum})) {
11517: push(@deletions,$file_name."\0".$control_item);
11518: } else {
11519: if (defined($changed_items{$itemnum})) {
11520: $new_control{$changed_items{$itemnum}} = $now;
11521: push(@deletions,$file_name."\0".$control_item);
11522: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11523: } else {
11524: $new_control{$control_item} = $$curr_controls{$control_item};
11525: }
11526: }
1.745 raeburn 11527: }
11528: }
11529: }
1.970 raeburn 11530: my ($group);
11531: if (&is_course($domain,$user)) {
11532: ($group,my $file) = split(/\//,$file_name,2);
11533: }
1.749 raeburn 11534: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11535: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11536: $outcome = &put('file_permissions',\%new_values,$domain,$user);
11537: # remove lock
11538: my @del_lock = ($file_name."\0".'locked_access_records');
11539: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 11540: my $sqlresult =
1.970 raeburn 11541: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 11542: $group);
1.749 raeburn 11543: } else {
11544: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 11545: }
1.749 raeburn 11546: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 11547: }
11548:
1.827 raeburn 11549: sub make_public_indefinitely {
1.1271 raeburn 11550: my (@requrl) = @_;
11551: return &automated_portfile_access('public',\@requrl);
11552: }
11553:
11554: sub automated_portfile_access {
11555: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 11556: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11557: return 'invalid';
11558: }
1.1271 raeburn 11559: my %urls;
11560: if (ref($addsref) eq 'ARRAY') {
11561: foreach my $requrl (@{$addsref}) {
11562: if (&is_portfolio_url($requrl)) {
11563: unless (exists($urls{$requrl})) {
11564: $urls{$requrl} = 'add';
11565: }
11566: }
11567: }
11568: }
11569: if (ref($delsref) eq 'ARRAY') {
11570: foreach my $requrl (@{$delsref}) {
11571: if (&is_portfolio_url($requrl)) {
11572: unless (exists($urls{$requrl})) {
11573: $urls{$requrl} = 'delete';
11574: }
11575: }
11576: }
11577: }
11578: unless (keys(%urls)) {
11579: return 'invalid';
11580: }
11581: my $ip;
11582: if ($accesstype eq 'ip') {
11583: if (ref($info) eq 'HASH') {
11584: if ($info->{'ip'} ne '') {
11585: $ip = $info->{'ip'};
11586: }
11587: }
11588: if ($ip eq '') {
11589: return 'invalid';
11590: }
11591: }
11592: my $errors;
1.827 raeburn 11593: my $now = time;
1.1271 raeburn 11594: my %current_perms;
11595: foreach my $requrl (sort(keys(%urls))) {
11596: my $action;
11597: if ($urls{$requrl} eq 'add') {
11598: $action = 'activate';
11599: } else {
11600: $action = 'none';
11601: }
11602: my $aclnum = 0;
1.827 raeburn 11603: my (undef,$udom,$unum,$file_name,$group) =
11604: &parse_portfolio_url($requrl);
1.1271 raeburn 11605: unless (exists($current_perms{$unum.':'.$udom})) {
11606: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11607: }
11608: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 11609: $group,$file_name);
11610: foreach my $key (keys(%{$access_controls{$file_name}})) {
11611: my ($num,$scope,$end,$start) =
11612: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 11613: if ($scope eq $accesstype) {
11614: if (($start <= $now) && ($end == 0)) {
11615: if ($accesstype eq 'ip') {
11616: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11617: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11618: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11619: if ($urls{$requrl} eq 'add') {
11620: $action = 'none';
11621: last;
11622: } else {
11623: $action = 'delete';
11624: $aclnum = $num;
11625: last;
11626: }
11627: }
11628: }
11629: }
11630: } elsif ($accesstype eq 'public') {
11631: if ($urls{$requrl} eq 'add') {
11632: $action = 'none';
11633: last;
11634: } else {
11635: $action = 'delete';
11636: $aclnum = $num;
11637: last;
11638: }
11639: }
11640: } elsif ($accesstype eq 'public') {
1.827 raeburn 11641: $action = 'update';
11642: $aclnum = $num;
1.1271 raeburn 11643: last;
1.827 raeburn 11644: }
11645: }
11646: }
11647: if ($action eq 'none') {
1.1271 raeburn 11648: next;
1.827 raeburn 11649: } else {
11650: my %changes;
11651: my $newend = 0;
11652: my $newstart = $now;
1.1271 raeburn 11653: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 11654: $changes{$action}{$newkey} = {
1.1271 raeburn 11655: type => $accesstype,
1.827 raeburn 11656: time => {
11657: start => $newstart,
11658: end => $newend,
11659: },
11660: };
1.1271 raeburn 11661: if ($accesstype eq 'ip') {
11662: $changes{$action}{$newkey}{'ip'} = [$ip];
11663: }
1.827 raeburn 11664: my ($outcome,$deloutcome,$new_values,$translation) =
11665: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 11666: unless ($outcome eq 'ok') {
11667: $errors .= $outcome.' ';
11668: }
1.827 raeburn 11669: }
1.1271 raeburn 11670: }
11671: if ($errors) {
11672: $errors =~ s/\s$//;
11673: return $errors;
1.827 raeburn 11674: } else {
1.1271 raeburn 11675: return 'ok';
1.827 raeburn 11676: }
11677: }
11678:
1.745 raeburn 11679: #------------------------------------------------------Get Marked as Read Only
11680:
11681: sub get_marked_as_readonly {
11682: my ($domain,$user,$what,$group) = @_;
11683: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 11684: my @readonly_files;
1.629 banghart 11685: my $cmp1=$what;
11686: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 11687: while (my ($file_name,$value) = each(%{$current_permissions})) {
11688: if (defined($group)) {
11689: if ($file_name !~ m-^\Q$group\E/-) {
11690: next;
11691: }
11692: }
1.561 banghart 11693: if (ref($value) eq "ARRAY"){
11694: foreach my $stored_what (@{$value}) {
1.629 banghart 11695: my $cmp2=$stored_what;
1.759 albertel 11696: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 11697: $cmp2=join('',@{$stored_what});
1.745 raeburn 11698: }
1.629 banghart 11699: if ($cmp1 eq $cmp2) {
1.561 banghart 11700: push(@readonly_files, $file_name);
1.745 raeburn 11701: last;
1.563 banghart 11702: } elsif (!defined($what)) {
11703: push(@readonly_files, $file_name);
1.745 raeburn 11704: last;
1.561 banghart 11705: }
11706: }
1.745 raeburn 11707: }
1.561 banghart 11708: }
11709: return @readonly_files;
11710: }
1.577 banghart 11711: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 11712:
1.577 banghart 11713: sub get_marked_as_readonly_hash {
1.745 raeburn 11714: my ($current_permissions,$group,$what) = @_;
1.577 banghart 11715: my %readonly_files;
1.745 raeburn 11716: while (my ($file_name,$value) = each(%{$current_permissions})) {
11717: if (defined($group)) {
11718: if ($file_name !~ m-^\Q$group\E/-) {
11719: next;
11720: }
11721: }
1.577 banghart 11722: if (ref($value) eq "ARRAY"){
11723: foreach my $stored_what (@{$value}) {
1.745 raeburn 11724: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 11725: foreach my $lock_descriptor(@{$stored_what}) {
11726: if ($lock_descriptor eq 'graded') {
11727: $readonly_files{$file_name} = 'graded';
11728: } elsif ($lock_descriptor eq 'handback') {
11729: $readonly_files{$file_name} = 'handback';
11730: } else {
11731: if (!exists($readonly_files{$file_name})) {
11732: $readonly_files{$file_name} = 'locked';
11733: }
11734: }
1.745 raeburn 11735: }
1.750 banghart 11736: }
1.577 banghart 11737: }
11738: }
11739: }
11740: return %readonly_files;
11741: }
1.559 banghart 11742: # ------------------------------------------------------------ Unmark as Read Only
11743:
11744: sub unmark_as_readonly {
1.629 banghart 11745: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11746: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 11747: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 11748: $file_name = &declutter_portfile($file_name);
1.634 albertel 11749: my $symb_crs = $what;
11750: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 11751: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 11752: my ($tmp)=keys(%current_permissions);
11753: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11754: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 11755: foreach my $file (@readonly_files) {
1.759 albertel 11756: my $clean_file = &declutter_portfile($file);
11757: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 11758: my $current_locks = $current_permissions{$file};
1.563 banghart 11759: my @new_locks;
11760: my @del_keys;
11761: if (ref($current_locks) eq "ARRAY"){
11762: foreach my $locker (@{$current_locks}) {
1.632 albertel 11763: my $compare=$locker;
1.749 raeburn 11764: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 11765: $compare=join('',@{$locker});
1.746 raeburn 11766: if ($compare ne $symb_crs) {
11767: push(@new_locks, $locker);
11768: }
1.563 banghart 11769: }
11770: }
1.650 albertel 11771: if (scalar(@new_locks) > 0) {
1.563 banghart 11772: $current_permissions{$file} = \@new_locks;
11773: } else {
11774: push(@del_keys, $file);
1.613 albertel 11775: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 11776: delete($current_permissions{$file});
1.563 banghart 11777: }
11778: }
1.561 banghart 11779: }
1.613 albertel 11780: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11781: return;
11782: }
1.512 banghart 11783:
1.17 www 11784: # ------------------------------------------------------------ Directory lister
11785:
11786: sub dirlist {
1.955 raeburn 11787: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 11788: $uri=~s/^\///;
11789: $uri=~s/\/$//;
1.253 stredwic 11790: my ($udom, $uname);
1.955 raeburn 11791: if ($getuserdir) {
1.253 stredwic 11792: $udom = $userdomain;
11793: $uname = $username;
1.955 raeburn 11794: } else {
11795: (undef,$udom,$uname)=split(/\//,$uri);
11796: if(defined($userdomain)) {
11797: $udom = $userdomain;
11798: }
11799: if(defined($username)) {
11800: $uname = $username;
11801: }
1.253 stredwic 11802: }
1.955 raeburn 11803: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 11804:
1.955 raeburn 11805: $dirRoot = $perlvar{'lonDocRoot'};
11806: if (defined($getpropath)) {
11807: $dirRoot = &propath($udom,$uname);
1.253 stredwic 11808: $dirRoot =~ s/\/$//;
1.955 raeburn 11809: } elsif (defined($getuserdir)) {
11810: my $subdir=$uname.'__';
11811: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11812: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11813: ."/$udom/$subdir/$uname";
11814: } elsif (defined($alternateRoot)) {
11815: $dirRoot = $alternateRoot;
1.751 banghart 11816: }
1.253 stredwic 11817:
11818: if($udom) {
11819: if($uname) {
1.1135 raeburn 11820: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 11821: if ($uhome eq 'no_host') {
11822: return ([],'no_host');
11823: }
1.955 raeburn 11824: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 11825: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 11826: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 11827: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11828: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 11829: } else {
11830: @listing_results = map { &unescape($_); } split(/:/,$listing);
11831: }
1.605 matthew 11832: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11833: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 11834: @listing_results = split(/:/,$listing);
11835: } else {
11836: @listing_results = map { &unescape($_); } split(/:/,$listing);
11837: }
1.1135 raeburn 11838: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 11839: ($listing eq 'rejected') || ($listing eq 'refused') ||
11840: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11841: return ([],$listing);
11842: } else {
11843: return (\@listing_results);
1.1135 raeburn 11844: }
1.955 raeburn 11845: } elsif(!$alternateRoot) {
1.1136 raeburn 11846: my (%allusers,%listerror);
1.841 albertel 11847: my %servers = &get_servers($udom,'library');
1.955 raeburn 11848: foreach my $tryserver (keys(%servers)) {
11849: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11850: &escape($udom),$tryserver);
11851: if ($listing eq 'unknown_cmd') {
11852: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11853: $udom, $tryserver);
11854: } else {
11855: @listing_results = map { &unescape($_); } split(/:/,$listing);
11856: }
1.841 albertel 11857: if ($listing eq 'unknown_cmd') {
11858: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11859: $udom, $tryserver);
11860: @listing_results = split(/:/,$listing);
11861: } else {
11862: @listing_results =
11863: map { &unescape($_); } split(/:/,$listing);
11864: }
1.1136 raeburn 11865: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11866: ($listing eq 'rejected') || ($listing eq 'refused') ||
11867: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11868: $listerror{$tryserver} = $listing;
11869: } else {
1.841 albertel 11870: foreach my $line (@listing_results) {
11871: my ($entry) = split(/&/,$line,2);
11872: $allusers{$entry} = 1;
11873: }
11874: }
1.253 stredwic 11875: }
1.1136 raeburn 11876: my @alluserslist=();
1.800 albertel 11877: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 11878: push(@alluserslist,$user.'&user');
1.253 stredwic 11879: }
1.1318 droeschl 11880:
11881: if (!%listerror) {
11882: # no errors
11883: return (\@alluserslist);
11884: } elsif (scalar(keys(%servers)) == 1) {
11885: # one library server, one error
11886: my ($key) = keys(%listerror);
11887: return (\@alluserslist, $listerror{$key});
11888: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11889: # con_lost indicates that we might miss data from at least one
11890: # library server
11891: return (\@alluserslist, 'con_lost');
11892: } else {
11893: # multiple library servers and no con_lost -> data should be
11894: # complete.
11895: return (\@alluserslist);
11896: }
11897:
1.253 stredwic 11898: } else {
1.1136 raeburn 11899: return ([],'missing username');
1.253 stredwic 11900: }
1.955 raeburn 11901: } elsif(!defined($getpropath)) {
1.1136 raeburn 11902: my $path = $perlvar{'lonDocRoot'}.'/res/';
11903: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11904: return (\@all_domains);
1.955 raeburn 11905: } else {
1.1136 raeburn 11906: return ([],'missing domain');
1.275 stredwic 11907: }
11908: }
11909:
11910: # --------------------------------------------- GetFileTimestamp
11911: # This function utilizes dirlist and returns the date stamp for
11912: # when it was last modified. It will also return an error of -1
11913: # if an error occurs
11914:
11915: sub GetFileTimestamp {
1.955 raeburn 11916: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 11917: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11918: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 11919: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11920: undef,$getuserdir);
11921: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11922: return -1;
11923: }
11924: if (ref($fileref) eq 'ARRAY') {
11925: my @stats = split('&',$fileref->[0]);
1.375 matthew 11926: # @stats contains first the filename, then the stat output
11927: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 11928: } else {
11929: return -1;
1.253 stredwic 11930: }
1.26 www 11931: }
11932:
1.712 albertel 11933: sub stat_file {
11934: my ($uri) = @_;
1.787 albertel 11935: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11936:
1.955 raeburn 11937: my ($udom,$uname,$file);
1.712 albertel 11938: if ($uri =~ m-^/(uploaded|editupload)/-) {
11939: ($udom,$uname,$file) =
1.811 albertel 11940: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11941: $file = 'userfiles/'.$file;
11942: }
11943: if ($uri =~ m-^/res/-) {
11944: ($udom,$uname) =
1.807 albertel 11945: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 11946: $file = $uri;
11947: }
11948:
11949: if (!$udom || !$uname || !$file) {
11950: # unable to handle the uri
11951: return ();
11952: }
1.956 raeburn 11953: my $getpropath;
11954: if ($file =~ /^userfiles\//) {
11955: $getpropath = 1;
11956: }
1.1136 raeburn 11957: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11958: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11959: return ();
11960: } else {
11961: if (ref($listref) eq 'ARRAY') {
11962: my @stats = split('&',$listref->[0]);
11963: shift(@stats); #filename is first
11964: return @stats;
11965: }
1.712 albertel 11966: }
11967: return ();
11968: }
11969:
1.1313 raeburn 11970: # --------------------------------------------------------- recursedirs
11971: # Recursive function to traverse either a specific user's Authoring Space
11972: # or corresponding Published Resource Space, and populate the hash ref:
11973: # $dirhashref with URLs of all directories, and if $filehashref hash
11974: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11975: # or .rights files in resource space, and .meta, .save, .log, and .bak
11976: # files in Authoring Space.
11977: #
11978: # Inputs:
11979: #
11980: # $is_home - true if current server is home server for user's space
11981: # $context - either: priv, or res respectively for Authoring or Resource Space.
11982: # $docroot - Document root (i.e., /home/httpd/html
11983: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11984: # $relpath - Current path (relative to top level).
11985: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11986: # $filehashref - reference to hash to populate with URLs of files (Optional)
11987: #
11988: # Returns: nothing
11989: #
11990: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11991: #
11992: # Currently used by interface/londocs.pm to create linked select boxes for
11993: # directory and filename to import a Course "Author" resource into a course, and
11994: # also to create linked select boxes for Authoring Space and Directory to choose
11995: # save location for creation of a new "standard" problem from the Course Editor.
11996: #
11997:
11998: sub recursedirs {
11999: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
12000: return unless (ref($dirhashref) eq 'HASH');
12001: my $currpath = $docroot.$toppath;
12002: if ($relpath) {
12003: $currpath .= "/$relpath";
12004: }
12005: my $savefile;
12006: if (ref($filehashref)) {
12007: $savefile = 1;
12008: }
12009: if ($is_home) {
12010: if (opendir(my $dirh,$currpath)) {
12011: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12012: next if ($item eq '');
12013: if (-d "$currpath/$item") {
12014: my $newpath;
12015: if ($relpath) {
12016: $newpath = "$relpath/$item";
12017: } else {
12018: $newpath = $item;
12019: }
12020: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12021: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
12022: } elsif ($savefile) {
12023: if ($context eq 'priv') {
12024: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
12025: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12026: }
12027: } else {
12028: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
12029: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12030: }
12031: }
12032: }
12033: }
12034: closedir($dirh);
12035: }
12036: } else {
12037: my ($dirlistref,$listerror) =
12038: &dirlist($toppath.$relpath);
12039: my @dir_lines;
12040: my $dirptr=16384;
12041: if (ref($dirlistref) eq 'ARRAY') {
12042: foreach my $dir_line (sort
12043: {
12044: my ($afile)=split('&',$a,2);
12045: my ($bfile)=split('&',$b,2);
12046: return (lc($afile) cmp lc($bfile));
12047: } (@{$dirlistref})) {
12048: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12049: split(/\&/,$dir_line,16);
12050: $item =~ s/\s+$//;
12051: next if (($item =~ /^\.\.?$/) || ($obs));
12052: if ($dirptr&$testdir) {
12053: my $newpath;
12054: if ($relpath) {
12055: $newpath = "$relpath/$item";
12056: } else {
12057: $relpath = '/';
12058: $newpath = $item;
12059: }
12060: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12061: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
12062: } elsif ($savefile) {
12063: if ($context eq 'priv') {
12064: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
12065: $filehashref->{$relpath}{$item} = 1;
12066: }
12067: } else {
12068: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
12069: $filehashref->{$relpath}{$item} = 1;
12070: }
12071: }
12072: }
12073: }
12074: }
12075: }
12076: return;
12077: }
12078:
1.26 www 12079: # -------------------------------------------------------- Value of a Condition
12080:
1.713 albertel 12081: # gets the value of a specific preevaluated condition
12082: # stored in the string $env{user.state.<cid>}
12083: # or looks up a condition reference in the bighash and if if hasn't
12084: # already been evaluated recurses into docondval to get the value of
12085: # the condition, then memoizing it to
12086: # $env{user.state.<cid>.<condition>}
1.40 www 12087: sub directcondval {
12088: my $number=shift;
1.620 albertel 12089: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 12090: &Apache::lonuserstate::evalstate();
12091: }
1.713 albertel 12092: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12093: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12094: } elsif ($number =~ /^_/) {
12095: my $sub_condition;
12096: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12097: &GDBM_READER(),0640)) {
12098: $sub_condition=$bighash{'conditions'.$number};
12099: untie(%bighash);
12100: }
12101: my $value = &docondval($sub_condition);
1.949 raeburn 12102: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 12103: return $value;
12104: }
1.620 albertel 12105: if ($env{'user.state.'.$env{'request.course.id'}}) {
12106: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 12107: } else {
12108: return 2;
12109: }
12110: }
12111:
1.713 albertel 12112: # get the collection of conditions for this resource
1.26 www 12113: sub condval {
12114: my $condidx=shift;
1.54 www 12115: my $allpathcond='';
1.713 albertel 12116: foreach my $cond (split(/\|/,$condidx)) {
12117: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12118: $allpathcond.=
12119: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12120: }
1.191 harris41 12121: }
1.54 www 12122: $allpathcond=~s/\|$//;
1.713 albertel 12123: return &docondval($allpathcond);
12124: }
12125:
12126: #evaluates an expression of conditions
12127: sub docondval {
12128: my ($allpathcond) = @_;
12129: my $result=0;
12130: if ($env{'request.course.id'}
12131: && defined($allpathcond)) {
12132: my $operand='|';
12133: my @stack;
12134: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12135: if ($chunk eq '(') {
12136: push @stack,($operand,$result);
12137: } elsif ($chunk eq ')') {
12138: my $before=pop @stack;
12139: if (pop @stack eq '&') {
12140: $result=$result>$before?$before:$result;
12141: } else {
12142: $result=$result>$before?$result:$before;
12143: }
12144: } elsif (($chunk eq '&') || ($chunk eq '|')) {
12145: $operand=$chunk;
12146: } else {
12147: my $new=directcondval($chunk);
12148: if ($operand eq '&') {
12149: $result=$result>$new?$new:$result;
12150: } else {
12151: $result=$result>$new?$result:$new;
12152: }
12153: }
12154: }
1.26 www 12155: }
12156: return $result;
1.421 albertel 12157: }
12158:
12159: # ---------------------------------------------------- Devalidate courseresdata
12160:
12161: sub devalidatecourseresdata {
12162: my ($coursenum,$coursedomain)=@_;
12163: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 12164: &devalidate_cache_new('courseres',$hashid);
1.28 www 12165: }
12166:
1.763 www 12167:
1.200 www 12168: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 12169: #
12170: # Parameters:
12171: # $coursenum - Number of the course.
12172: # $coursedomain - Domain at which the course was created.
12173: # Returns:
12174: # A hash of the course parameters along (I think) with timestamps
12175: # and version info.
1.877 foxr 12176:
1.624 albertel 12177: sub get_courseresdata {
12178: my ($coursenum,$coursedomain)=@_;
1.200 www 12179: my $coursehom=&homeserver($coursenum,$coursedomain);
12180: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 12181: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 12182: my %dumpreply;
1.417 albertel 12183: unless (defined($cached)) {
1.624 albertel 12184: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 12185: $result=\%dumpreply;
1.251 albertel 12186: my ($tmp) = keys(%dumpreply);
12187: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 12188: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 12189: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12190: return $tmp;
1.416 albertel 12191: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 12192: $result=undef;
1.599 albertel 12193: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 12194: }
12195: }
1.624 albertel 12196: return $result;
12197: }
12198:
1.633 albertel 12199: sub devalidateuserresdata {
12200: my ($uname,$udom)=@_;
12201: my $hashid="$udom:$uname";
12202: &devalidate_cache_new('userres',$hashid);
12203: }
12204:
1.624 albertel 12205: sub get_userresdata {
12206: my ($uname,$udom)=@_;
12207: #most student don\'t have any data set, check if there is some data
12208: if (&EXT_cache_status($udom,$uname)) { return undef; }
12209:
12210: my $hashid="$udom:$uname";
12211: my ($result,$cached)=&is_cached_new('userres',$hashid);
12212: if (!defined($cached)) {
12213: my %resourcedata=&dump('resourcedata',$udom,$uname);
12214: $result=\%resourcedata;
12215: &do_cache_new('userres',$hashid,$result,600);
12216: }
12217: my ($tmp)=keys(%$result);
12218: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12219: return $result;
12220: }
12221: #error 2 occurs when the .db doesn't exist
12222: if ($tmp!~/error: 2 /) {
1.1294 raeburn 12223: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12224: &logthis("<font color=\"blue\">WARNING:".
12225: " Trying to get resource data for ".
12226: $uname." at ".$udom.": ".
12227: $tmp."</font>");
12228: }
1.624 albertel 12229: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 12230: #&EXT_cache_set($udom,$uname);
12231: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 12232: undef($tmp); # not really an error so don't send it back
1.624 albertel 12233: }
12234: return $tmp;
12235: }
1.879 foxr 12236: #----------------------------------------------- resdata - return resource data
12237: # Purpose:
12238: # Return resource data for either users or for a course.
12239: # Parameters:
12240: # $name - Course/user name.
12241: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 12242: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 12243: # $mapp - decluttered URL of enclosing map
12244: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
12245: # $recurseup - Ref to array of map URLs, starting with map containing
12246: # $mapp up through hierarchy of nested maps to top level map.
12247: # $courseid - CourseID (first part of param identifier).
12248: # $modifier - Middle part of param identifier.
12249: # $what - Last part of param identifier.
1.879 foxr 12250: # @which - Array of names of resources desired.
12251: # Returns:
12252: # The value of the first reasource in @which that is found in the
12253: # resource hash.
12254: # Exceptional Conditions:
12255: # If the $type passed in is not valid (not the string 'course' or
12256: # 'user', an undefined reference is returned.
12257: # If none of the resources are found, an undef is returned
1.624 albertel 12258: sub resdata {
1.1301 raeburn 12259: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12260: $modifier,$what,@which)=@_;
1.624 albertel 12261: my $result;
12262: if ($type eq 'course') {
12263: $result=&get_courseresdata($name,$domain);
12264: } elsif ($type eq 'user') {
12265: $result=&get_userresdata($name,$domain);
12266: }
12267: if (!ref($result)) { return $result; }
1.251 albertel 12268: foreach my $item (@which) {
1.1301 raeburn 12269: if ($item->[1] eq 'course') {
12270: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12271: unless ($$recursed) {
1.1302 raeburn 12272: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 12273: $$recursed = 1;
12274: }
12275: foreach my $item (@${recurseup}) {
12276: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12277: last if (defined($result->{$norecursechk}));
12278: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12279: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12280: }
12281: }
12282: }
12283: if (defined($result->{$item->[0]})) {
1.927 albertel 12284: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 12285: }
1.250 albertel 12286: }
1.291 albertel 12287: return undef;
1.200 www 12288: }
12289:
1.1360 raeburn 12290: sub get_domain_lti {
12291: my ($cdom,$context) = @_;
1.1483 raeburn 12292: my ($name,$cachename,%lti);
1.1360 raeburn 12293: if ($context eq 'consumer') {
12294: $name = 'ltitools';
12295: } elsif ($context eq 'provider') {
12296: $name = 'lti';
1.1483 raeburn 12297: } elsif ($context eq 'linkprot') {
12298: $name = 'ltisec';
1.1360 raeburn 12299: } else {
12300: return %lti;
12301: }
1.1483 raeburn 12302:
12303: if ($context eq 'linkprot') {
12304: $cachename = $context;
12305: } else {
12306: $cachename = $name;
12307: }
12308:
12309: my ($result,$cached)=&is_cached_new($cachename,$cdom);
1.1298 raeburn 12310: if (defined($cached)) {
12311: if (ref($result) eq 'HASH') {
1.1360 raeburn 12312: %lti = %{$result};
1.1298 raeburn 12313: }
12314: } else {
1.1360 raeburn 12315: my %domconfig = &get_dom('configuration',[$name],$cdom);
12316: if (ref($domconfig{$name}) eq 'HASH') {
1.1483 raeburn 12317: if ($context eq 'linkprot') {
12318: if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12319: %lti = %{$domconfig{$name}{'linkprot'}};
12320: }
12321: } else {
12322: %lti = %{$domconfig{$name}};
12323: }
12324: if (($context eq 'consumer') && (keys(%lti))) {
12325: my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
12326: if (ref($encdomconfig{$name}) eq 'HASH') {
12327: foreach my $id (keys(%lti)) {
12328: if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
12329: foreach my $item ('key','secret') {
12330: $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
12331: }
1.1344 raeburn 12332: }
12333: }
12334: }
12335: }
1.1298 raeburn 12336: }
12337: my $cachetime = 24*60*60;
1.1483 raeburn 12338: &do_cache_new($cachename,$cdom,\%lti,$cachetime);
1.1298 raeburn 12339: }
1.1360 raeburn 12340: return %lti;
1.1298 raeburn 12341: }
12342:
1.1463 raeburn 12343: sub get_course_lti {
12344: my ($cnum,$cdom) = @_;
12345: my $hashid=$cdom.'_'.$cnum;
12346: my %courselti;
12347: my ($result,$cached)=&is_cached_new('courselti',$hashid);
12348: if (defined($cached)) {
12349: if (ref($result) eq 'HASH') {
12350: %courselti = %{$result};
12351: }
12352: } else {
12353: %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
12354: my $cachetime = 24*60*60;
12355: &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
12356: }
12357: return %courselti;
12358: }
12359:
1.1479 raeburn 12360: sub courselti_itemid {
12361: my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12362: my ($chome,$itemid);
12363: $chome = &homeserver($cnum,$cdom);
12364: return if ($chome eq 'no_host');
12365: if (ref($params) eq 'HASH') {
12366: my $items = &freeze_escape($params);
12367: my $rep;
12368: if (grep { $_ eq $chome } current_machine_ids()) {
12369: $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12370: } else {
12371: my $escurl = &escape($url);
12372: my $escmethod = &escape($method);
12373: my $items = &freeze_escape($params);
12374: $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12375: }
12376: unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12377: ($rep eq 'unknown_cmd')) {
12378: $itemid = $rep;
12379: }
12380: }
12381: return $itemid;
12382: }
12383:
12384: sub domainlti_itemid {
12385: my ($cdom,$url,$method,$params,$context) = @_;
12386: my ($primary_id,$itemid);
12387: $primary_id = &domain($cdom,'primary');
12388: return if ($primary_id eq '');
12389: if (ref($params) eq 'HASH') {
12390: my $items = &freeze_escape($params);
12391: my $rep;
12392: if (grep { $_ eq $primary_id } current_machine_ids()) {
12393: $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12394: } else {
12395: my $cnum = '';
12396: my $escurl = &escape($url);
12397: my $escmethod = &escape($method);
12398: my $items = &freeze_escape($params);
12399: $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12400: }
12401: unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12402: ($rep eq 'unknown_cmd')) {
12403: $itemid = $rep;
12404: }
12405: }
12406: return $itemid;
12407: }
12408:
1.1236 raeburn 12409: sub get_numsuppfiles {
12410: my ($cnum,$cdom,$ignorecache)=@_;
12411: my $hashid=$cnum.':'.$cdom;
12412: my ($suppcount,$cached);
12413: unless ($ignorecache) {
12414: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
12415: }
12416: unless (defined($cached)) {
12417: my $chome=&homeserver($cnum,$cdom);
12418: unless ($chome eq 'no_host') {
1.1366 raeburn 12419: ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236 raeburn 12420: my $suppmap = 'supplemental.sequence';
1.1366 raeburn 12421: ($suppcount,$supptools,$errors) =
12422: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
12423: $supptools,$errors);
1.1236 raeburn 12424: }
12425: &do_cache_new('suppcount',$hashid,$suppcount,600);
12426: }
12427: return $suppcount;
12428: }
12429:
1.379 matthew 12430: #
12431: # EXT resource caching routines
12432: #
12433:
1.1302 raeburn 12434: {
12435: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12436: #
12437: # The course for which we cache
12438: my $cachedmapkey='';
12439: # The cached recursive maps for this course
12440: my %cachedmaps=();
12441: # When this was last done
12442: my $cachedmaptime='';
12443:
1.379 matthew 12444: sub clear_EXT_cache_status {
1.383 albertel 12445: &delenv('cache.EXT.');
1.379 matthew 12446: }
12447:
12448: sub EXT_cache_status {
12449: my ($target_domain,$target_user) = @_;
1.383 albertel 12450: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 12451: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 12452: # We know already the user has no data
12453: return 1;
12454: } else {
12455: return 0;
12456: }
12457: }
12458:
12459: sub EXT_cache_set {
12460: my ($target_domain,$target_user) = @_;
1.383 albertel 12461: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 12462: #&appenv({$cachename => time});
1.379 matthew 12463: }
12464:
1.28 www 12465: # --------------------------------------------------------- Value of a Variable
1.58 www 12466: sub EXT {
1.715 albertel 12467:
1.1461 raeburn 12468: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
1.68 www 12469: unless ($varname) { return ''; }
1.218 albertel 12470: #get real user name/domain, courseid and symb
12471: my $courseid;
1.359 albertel 12472: my $publicuser;
1.427 www 12473: if ($symbparm) {
12474: $symbparm=&get_symb_from_alias($symbparm);
12475: }
1.218 albertel 12476: if (!($uname && $udom)) {
1.790 albertel 12477: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 12478: if (!$symbparm) { $symbparm=$cursymb; }
12479: } else {
1.620 albertel 12480: $courseid=$env{'request.course.id'};
1.218 albertel 12481: }
1.48 www 12482: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12483: my $rest;
1.320 albertel 12484: if (defined($therest[0])) {
1.48 www 12485: $rest=join('.',@therest);
12486: } else {
12487: $rest='';
12488: }
1.320 albertel 12489:
1.57 www 12490: my $qualifierrest=$qualifier;
12491: if ($rest) { $qualifierrest.='.'.$rest; }
12492: my $spacequalifierrest=$space;
12493: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 12494: if ($realm eq 'user') {
1.48 www 12495: # --------------------------------------------------------------- user.resource
12496: if ($space eq 'resource') {
1.651 albertel 12497: if ( (defined($Apache::lonhomework::parsing_a_problem)
12498: || defined($Apache::lonhomework::parsing_a_task))
12499: &&
1.1469 raeburn 12500: ($symbparm eq &symbread()) ) {
1.744 albertel 12501: # if we are in the middle of processing the resource the
12502: # get the value we are planning on committing
12503: if (defined($Apache::lonhomework::results{$qualifierrest})) {
12504: return $Apache::lonhomework::results{$qualifierrest};
12505: } else {
12506: return $Apache::lonhomework::history{$qualifierrest};
12507: }
1.335 albertel 12508: } else {
1.359 albertel 12509: my %restored;
1.620 albertel 12510: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 12511: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12512: } else {
12513: %restored=&restore($symbparm,$courseid,$udom,$uname);
12514: }
1.335 albertel 12515: return $restored{$qualifierrest};
12516: }
1.48 www 12517: # ----------------------------------------------------------------- user.access
12518: } elsif ($space eq 'access') {
1.218 albertel 12519: # FIXME - not supporting calls for a specific user
1.48 www 12520: return &allowed($qualifier,$rest);
12521: # ------------------------------------------ user.preferences, user.environment
12522: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 12523: if (($uname eq $env{'user.name'}) &&
12524: ($udom eq $env{'user.domain'})) {
12525: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 12526: } else {
1.359 albertel 12527: my %returnhash;
12528: if (!$publicuser) {
12529: %returnhash=&userenvironment($udom,$uname,
12530: $qualifierrest);
12531: }
1.218 albertel 12532: return $returnhash{$qualifierrest};
12533: }
1.48 www 12534: # ----------------------------------------------------------------- user.course
12535: } elsif ($space eq 'course') {
1.218 albertel 12536: # FIXME - not supporting calls for a specific user
1.620 albertel 12537: return $env{join('.',('request.course',$qualifier))};
1.48 www 12538: # ------------------------------------------------------------------- user.role
12539: } elsif ($space eq 'role') {
1.218 albertel 12540: # FIXME - not supporting calls for a specific user
1.620 albertel 12541: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 12542: if ($qualifier eq 'value') {
12543: return $role;
12544: } elsif ($qualifier eq 'extent') {
12545: return $where;
12546: }
12547: # ----------------------------------------------------------------- user.domain
12548: } elsif ($space eq 'domain') {
1.218 albertel 12549: return $udom;
1.48 www 12550: # ------------------------------------------------------------------- user.name
12551: } elsif ($space eq 'name') {
1.218 albertel 12552: return $uname;
1.48 www 12553: # ---------------------------------------------------- Any other user namespace
1.29 www 12554: } else {
1.359 albertel 12555: my %reply;
12556: if (!$publicuser) {
12557: %reply=&get($space,[$qualifierrest],$udom,$uname);
12558: }
12559: return $reply{$qualifierrest};
1.48 www 12560: }
1.236 www 12561: } elsif ($realm eq 'query') {
12562: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 12563: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12564: [$spacequalifierrest]);
1.620 albertel 12565: return $env{'form.'.$spacequalifierrest};
1.236 www 12566: } elsif ($realm eq 'request') {
1.48 www 12567: # ------------------------------------------------------------- request.browser
12568: if ($space eq 'browser') {
1.1145 bisitz 12569: return $env{'browser.'.$qualifier};
1.57 www 12570: # ------------------------------------------------------------ request.filename
12571: } else {
1.620 albertel 12572: return $env{'request.'.$spacequalifierrest};
1.29 www 12573: }
1.28 www 12574: } elsif ($realm eq 'course') {
1.48 www 12575: # ---------------------------------------------------------- course.description
1.620 albertel 12576: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 12577: } elsif ($realm eq 'resource') {
1.165 www 12578:
1.620 albertel 12579: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 12580: if (!$symbparm) { $symbparm=&symbread(); }
12581: }
1.693 albertel 12582:
1.1232 raeburn 12583: if ($qualifier eq '') {
12584: if ($space eq 'title') {
12585: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12586: return &gettitle($symbparm);
12587: }
1.693 albertel 12588:
1.1232 raeburn 12589: if ($space eq 'map') {
12590: my ($map) = &decode_symb($symbparm);
12591: return &symbread($map);
12592: }
12593: if ($space eq 'maptitle') {
12594: my ($map) = &decode_symb($symbparm);
12595: return &gettitle($map);
12596: }
12597: if ($space eq 'filename') {
12598: if ($symbparm) {
12599: return &clutter((&decode_symb($symbparm))[2]);
12600: }
12601: return &hreflocation('',$env{'request.filename'});
1.905 albertel 12602: }
1.1232 raeburn 12603:
1.1233 raeburn 12604: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12605: if ($space eq 'visibleparts') {
12606: my $navmap = Apache::lonnavmaps::navmap->new();
12607: my $item;
12608: if (ref($navmap)) {
12609: my $res = $navmap->getBySymb($symbparm);
12610: my $parts = $res->parts();
12611: if (ref($parts) eq 'ARRAY') {
12612: $item = join(',',@{$parts});
12613: }
12614: undef($navmap);
1.1232 raeburn 12615: }
1.1233 raeburn 12616: return $item;
1.1232 raeburn 12617: }
12618: }
12619: }
1.693 albertel 12620:
1.1301 raeburn 12621: my ($section, $group, @groups, @recurseup, $recursed);
1.1461 raeburn 12622: if (ref($recurseupref) eq 'ARRAY') {
12623: @recurseup = @{$recurseupref};
12624: $recursed = 1;
12625: }
1.1301 raeburn 12626: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 12627: if (($courseid eq '') && ($cid)) {
12628: $courseid = $cid;
12629: }
12630: if (($symbparm && $courseid) &&
12631: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 12632:
1.218 albertel 12633: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 12634:
1.60 www 12635: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 12636: my $symbp=$symbparm;
1.1301 raeburn 12637: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 12638: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 12639: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 12640: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 12641: if (($env{'user.name'} eq $uname) &&
12642: ($env{'user.domain'} eq $udom)) {
12643: $section=$env{'request.course.sec'};
1.733 raeburn 12644: @groups = split(/:/,$env{'request.course.groups'});
12645: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 12646: } else {
1.539 albertel 12647: if (! defined($usection)) {
1.551 albertel 12648: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 12649: } else {
12650: $section = $usection;
12651: }
1.733 raeburn 12652: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 12653: }
12654:
12655: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12656: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 12657: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 12658: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12659:
1.593 albertel 12660: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 12661: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 12662: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 12663: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 12664:
1.60 www 12665: # ----------------------------------------------------------- first, check user
1.624 albertel 12666:
1.1301 raeburn 12667: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12668: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 12669: ([$courselevelr,'resource'],
12670: [$courselevelm,'map' ],
1.1301 raeburn 12671: [$courseleveli,'map' ],
1.927 albertel 12672: [$courselevel, 'course' ]));
1.931 albertel 12673: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 12674:
1.594 albertel 12675: # ------------------------------------------------ second, check some of course
1.684 raeburn 12676: my $coursereply;
1.691 raeburn 12677: if (@groups > 0) {
12678: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 12679: $recurseparm,$mapparm,$spacequalifierrest,
12680: $mapp,\$recursed,\@recurseup);
12681: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 12682: }
1.96 www 12683:
1.684 raeburn 12684: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 12685: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12686: 'course',$mapp,\$recursed,\@recurseup,
12687: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 12688: ([$seclevelr, 'resource'],
12689: [$seclevelm, 'map' ],
1.1301 raeburn 12690: [$secleveli, 'map' ],
1.927 albertel 12691: [$seclevel, 'course' ],
12692: [$courselevelr,'resource']));
12693: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 12694:
1.60 www 12695: # ------------------------------------------------------ third, check map parms
1.218 albertel 12696: my %parmhash=();
12697: my $thisparm='';
12698: if (tie(%parmhash,'GDBM_File',
1.620 albertel 12699: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 12700: &GDBM_READER(),0640)) {
1.218 albertel 12701: $thisparm=$parmhash{$symbparm};
12702: untie(%parmhash);
12703: }
1.927 albertel 12704: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 12705: }
1.594 albertel 12706: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 12707:
12708: my $what = $spacequalifierrest;
12709: $what=~s/\./\_/;
1.282 albertel 12710: my $filename;
12711: if (!$symbparm) { $symbparm=&symbread(); }
12712: if ($symbparm) {
1.409 www 12713: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 12714: } else {
1.620 albertel 12715: $filename=$env{'request.filename'};
1.282 albertel 12716: }
1.1362 raeburn 12717: my $toolsymb;
12718: if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12719: $toolsymb = $symbparm;
12720: }
12721: my $metadata=&metadata($filename,$what,$toolsymb);
1.927 albertel 12722: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362 raeburn 12723: $metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927 albertel 12724: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 12725:
1.1301 raeburn 12726: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 12727: if ($symbparm && defined($courseid) &&
1.620 albertel 12728: $courseid eq $env{'request.course.id'}) {
1.624 albertel 12729: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12730: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12731: 'course',$mapp,\$recursed,\@recurseup,
12732: $courseid,'.',$spacequalifierrest,
1.927 albertel 12733: ([$courselevelm,'map' ],
1.1301 raeburn 12734: [$courseleveli,'map' ],
1.927 albertel 12735: [$courselevel, 'course']));
12736: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 12737: }
1.145 www 12738: # ------------------------------------------------------------------ Cascade up
1.218 albertel 12739: unless ($space eq '0') {
1.336 albertel 12740: my @parts=split(/_/,$space);
12741: my $id=pop(@parts);
12742: my $part=join('_',@parts);
12743: if ($part eq '') { $part='0'; }
1.927 albertel 12744: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 12745: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 12746: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 12747: }
1.395 albertel 12748: if ($recurse) { return undef; }
1.1362 raeburn 12749: my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927 albertel 12750: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 12751: # ---------------------------------------------------- Any other user namespace
12752: } elsif ($realm eq 'environment') {
12753: # ----------------------------------------------------------------- environment
1.620 albertel 12754: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12755: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 12756: } else {
1.770 albertel 12757: if ($uname eq 'anonymous' && $udom eq '') {
12758: return '';
12759: }
1.219 albertel 12760: my %returnhash=&userenvironment($udom,$uname,
12761: $spacequalifierrest);
12762: return $returnhash{$spacequalifierrest};
12763: }
1.28 www 12764: } elsif ($realm eq 'system') {
1.48 www 12765: # ----------------------------------------------------------------- system.time
12766: if ($space eq 'time') {
12767: return time;
12768: }
1.696 albertel 12769: } elsif ($realm eq 'server') {
12770: # ----------------------------------------------------------------- system.time
12771: if ($space eq 'name') {
12772: return $ENV{'SERVER_NAME'};
12773: }
1.1415 raeburn 12774: } elsif ($realm eq 'client') {
12775: if ($space eq 'remote_addr') {
1.1441 raeburn 12776: return &get_requestor_ip();
1.1415 raeburn 12777: }
1.28 www 12778: }
1.48 www 12779: return '';
1.61 www 12780: }
12781:
1.927 albertel 12782: sub get_reply {
12783: my ($reply_value) = @_;
1.940 raeburn 12784: if (ref($reply_value) eq 'ARRAY') {
12785: if (wantarray) {
12786: return @$reply_value;
12787: }
12788: return $reply_value->[0];
12789: } else {
12790: return $reply_value;
1.927 albertel 12791: }
12792: }
12793:
1.691 raeburn 12794: sub check_group_parms {
1.1301 raeburn 12795: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12796: $recursed,$recurseupref) = @_;
12797: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12798: [$what,'course']);
12799: my $coursereply;
1.691 raeburn 12800: foreach my $group (@{$groups}) {
1.1301 raeburn 12801: my @groupitems = ();
1.691 raeburn 12802: foreach my $level (@levels) {
1.927 albertel 12803: my $item = $courseid.'.['.$group.'].'.$level->[0];
12804: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 12805: }
1.1301 raeburn 12806: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12807: $env{'course.'.$courseid.'.domain'},
12808: 'course',$mapp,$recursed,$recurseupref,
12809: $courseid,'.['.$group.'].',$what,
12810: @groupitems);
12811: last if (defined($coursereply));
1.691 raeburn 12812: }
12813: return $coursereply;
12814: }
12815:
1.1301 raeburn 12816: sub get_map_hierarchy {
1.1302 raeburn 12817: my ($mapname,$courseid) = @_;
12818: my @recurseup = ();
1.1301 raeburn 12819: if ($mapname) {
1.1302 raeburn 12820: if (($cachedmapkey eq $courseid) &&
12821: (abs($cachedmaptime-time)<5)) {
12822: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12823: return @{$cachedmaps{$mapname}};
12824: }
12825: }
1.1301 raeburn 12826: my $navmap = Apache::lonnavmaps::navmap->new();
12827: if (ref($navmap)) {
12828: @recurseup = $navmap->recurseup_maps($mapname);
12829: undef($navmap);
1.1302 raeburn 12830: $cachedmaps{$mapname} = \@recurseup;
12831: $cachedmaptime=time;
12832: $cachedmapkey=$courseid;
1.1301 raeburn 12833: }
12834: }
12835: return @recurseup;
12836: }
12837:
1.1302 raeburn 12838: }
12839:
1.691 raeburn 12840: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 12841: my ($courseid,@groups) = @_;
12842: @groups = sort(@groups);
1.691 raeburn 12843: return @groups;
12844: }
12845:
1.395 albertel 12846: sub packages_tab_default {
1.1362 raeburn 12847: my ($uri,$varname,$toolsymb)=@_;
1.395 albertel 12848: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 12849:
12850: my (@extension,@specifics,$do_default);
1.1362 raeburn 12851: foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395 albertel 12852: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 12853: if ($pack_type eq 'default') {
12854: $do_default=1;
12855: } elsif ($pack_type eq 'extension') {
12856: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 12857: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 12858: # only look at packages defaults for packages that this id is
1.738 albertel 12859: push(@specifics,[$package,$pack_type,$pack_part]);
12860: }
12861: }
12862: # first look for a package that matches the requested part id
12863: foreach my $package (@specifics) {
12864: my (undef,$pack_type,$pack_part)=@{$package};
12865: next if ($pack_part ne $part);
12866: if (defined($packagetab{"$pack_type&$name&default"})) {
12867: return $packagetab{"$pack_type&$name&default"};
12868: }
12869: }
12870: # look for any possible matching non extension_ package
12871: foreach my $package (@specifics) {
12872: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 12873: if (defined($packagetab{"$pack_type&$name&default"})) {
12874: return $packagetab{"$pack_type&$name&default"};
12875: }
1.585 albertel 12876: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 12877: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12878: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 12879: }
12880: }
1.738 albertel 12881: # look for any posible extension_ match
12882: foreach my $package (@extension) {
12883: my ($package,$pack_type)=@{$package};
12884: if (defined($packagetab{"$pack_type&$name&default"})) {
12885: return $packagetab{"$pack_type&$name&default"};
12886: }
12887: if (defined($packagetab{$package."&$name&default"})) {
12888: return $packagetab{$package."&$name&default"};
12889: }
12890: }
12891: # look for a global default setting
12892: if ($do_default && defined($packagetab{"default&$name&default"})) {
12893: return $packagetab{"default&$name&default"};
12894: }
1.395 albertel 12895: return undef;
12896: }
12897:
1.334 albertel 12898: sub add_prefix_and_part {
12899: my ($prefix,$part)=@_;
12900: my $keyroot;
12901: if (defined($prefix) && $prefix !~ /^__/) {
12902: # prefix that has a part already
12903: $keyroot=$prefix;
12904: } elsif (defined($prefix)) {
12905: # prefix that is missing a part
12906: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12907: } else {
12908: # no prefix at all
12909: if (defined($part)) { $keyroot='_'.$part; }
12910: }
12911: return $keyroot;
12912: }
12913:
1.71 www 12914: # ---------------------------------------------------------------- Get metadata
12915:
1.599 albertel 12916: my %metaentry;
1.1070 www 12917: my %importedpartids;
1.1369 raeburn 12918: my %importedrespids;
1.71 www 12919: sub metadata {
1.1362 raeburn 12920: my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71 www 12921: $uri=&declutter($uri);
1.288 albertel 12922: # if it is a non metadata possible uri return quickly
1.529 albertel 12923: if (($uri eq '') ||
12924: (($uri =~ m|^/*adm/|) &&
1.1343 raeburn 12925: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 12926: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 12927: return undef;
12928: }
1.1261 raeburn 12929: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 12930: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 12931: return undef;
1.288 albertel 12932: }
1.73 www 12933: my $filename=$uri;
12934: $uri=~s/\.meta$//;
1.172 www 12935: #
12936: # Is the metadata already cached?
1.177 www 12937: # Look at timestamp of caching
1.172 www 12938: # Everything is cached by the main uri, libraries are never directly cached
12939: #
1.428 albertel 12940: if (!defined($liburi)) {
1.599 albertel 12941: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 12942: if (defined($cached)) { return $result->{':'.$what}; }
12943: }
1.1362 raeburn 12944:
12945: #
12946: # If the uri is for an external tool the file from
12947: # which metadata should be retrieved depends on whether
12948: # the tool had been configured to be gradable (set in the Course
12949: # Editor or Resource Editor).
12950: #
12951: # If a valid symb has been included as the third arg in the call
12952: # to &metadata() that can be used to retrieve the value of
12953: # parameter_0_gradable set for the resource, and included in the
12954: # uploaded map containing the tool. The value is retrieved via
12955: # &EXT(), if a valid symb is available. Otherwise the value of
12956: # gradable in the exttool_$marker.db file for the tool instance
1.1364 raeburn 12957: # is retrieved via &get().
12958: #
12959: # When lonuserstate::traceroute() calls lonnet::EXT() for
12960: # hiddenresource and encrypturl (during course initialization)
12961: # the map-level parameter for resource.0.gradable included in the
12962: # uploaded map containing the tool will not yet have been stored
12963: # in the user_course_parms.db file for the user's session, so in
12964: # this case fall back to retrieving gradable status from the
12965: # exttool_$marker.db file.
1.1362 raeburn 12966: #
12967: # In order to avoid an infinite loop, &metadata() will return
12968: # before a call to &EXT(), if the uri is for an external tool
12969: # and the $what for which metadata is being requested is
12970: # parameter_0_gradable or 0_gradable.
12971: #
12972:
12973: if ($uri =~ /ext\.tool$/) {
12974: if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12975: return;
12976: } else {
12977: my ($checked,$use_passback);
12978: if ($toolsymb ne '') {
12979: (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364 raeburn 12980: if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362 raeburn 12981: $checked = 1;
12982: if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12983: $use_passback = 1;
12984: }
12985: }
12986: }
12987: unless ($checked) {
12988: my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12989: $marker=~s/\D//g;
1.1363 raeburn 12990: if ($marker) {
1.1362 raeburn 12991: my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12992: $use_passback = $toolsettings{'gradable'};
12993: }
12994: }
12995: if ($use_passback) {
12996: $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12997: } else {
12998: $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12999: }
13000: }
13001: }
13002:
1.428 albertel 13003: {
1.1069 www 13004: # Imported parts would go here
1.1369 raeburn 13005: my @origfiletagids=();
1.1069 www 13006: my $importedparts=0;
1.1369 raeburn 13007:
13008: # Imported responseids would go here
13009: my $importedresponses=0;
1.172 www 13010: #
13011: # Is this a recursive call for a library?
13012: #
1.599 albertel 13013: # if (! exists($metacache{$uri})) {
13014: # $metacache{$uri}={};
13015: # }
1.924 albertel 13016: my $cachetime = 60*60;
1.171 www 13017: if ($liburi) {
13018: $liburi=&declutter($liburi);
13019: $filename=$liburi;
1.401 bowersj2 13020: } else {
1.599 albertel 13021: &devalidate_cache_new('meta',$uri);
13022: undef(%metaentry);
1.401 bowersj2 13023: }
1.140 www 13024: my %metathesekeys=();
1.73 www 13025: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 13026: my $metastring;
1.1140 www 13027: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 13028: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 13029: $metastring =
1.929 albertel 13030: &Apache::lonnet::ssi_body($which,
1.924 albertel 13031: ('grade_target' => 'meta'));
13032: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 13033: } elsif (($uri !~ m -^(editupload)/-) &&
13034: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 13035: my $file=&filelocation('',&clutter($filename));
1.599 albertel 13036: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 13037: $metastring=&getfile($file);
1.489 albertel 13038: }
1.208 albertel 13039: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 13040: my $token;
1.140 www 13041: undef %metathesekeys;
1.71 www 13042: while ($token=$parser->get_token) {
1.339 albertel 13043: if ($token->[0] eq 'S') {
13044: if (defined($token->[2]->{'package'})) {
1.172 www 13045: #
13046: # This is a package - get package info
13047: #
1.339 albertel 13048: my $package=$token->[2]->{'package'};
13049: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13050: if (defined($token->[2]->{'id'})) {
13051: $keyroot.='_'.$token->[2]->{'id'};
13052: }
1.599 albertel 13053: if ($metaentry{':packages'}) {
13054: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 13055: } else {
1.599 albertel 13056: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 13057: }
1.736 albertel 13058: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 13059: my $part=$keyroot;
13060: $part=~s/^\_//;
1.736 albertel 13061: if ($pack_entry=~/^\Q$package\E\&/ ||
13062: $pack_entry=~/^\Q$package\E_0\&/) {
13063: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 13064: # ignore package.tab specified default values
13065: # here &package_tab_default() will fetch those
13066: if ($subp eq 'default') { next; }
1.736 albertel 13067: my $value=$packagetab{$pack_entry};
1.432 albertel 13068: my $unikey;
13069: if ($pack =~ /_0$/) {
13070: $unikey='parameter_0_'.$name;
13071: $part=0;
13072: } else {
13073: $unikey='parameter'.$keyroot.'_'.$name;
13074: }
1.339 albertel 13075: if ($subp eq 'display') {
13076: $value.=' [Part: '.$part.']';
13077: }
1.599 albertel 13078: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 13079: $metathesekeys{$unikey}=1;
1.599 albertel 13080: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13081: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 13082: }
1.599 albertel 13083: if (defined($metaentry{':'.$unikey.'.default'})) {
13084: $metaentry{':'.$unikey}=
13085: $metaentry{':'.$unikey.'.default'};
1.356 albertel 13086: }
1.339 albertel 13087: }
13088: }
13089: } else {
1.172 www 13090: #
13091: # This is not a package - some other kind of start tag
1.339 albertel 13092: #
13093: my $entry=$token->[1];
1.1068 www 13094: my $unikey='';
1.175 www 13095:
1.339 albertel 13096: if ($entry eq 'import') {
1.175 www 13097: #
13098: # Importing a library here
1.339 albertel 13099: #
1.1067 www 13100: my $location=$parser->get_text('/import');
13101: my $dir=$filename;
13102: $dir=~s|[^/]*$||;
13103: $location=&filelocation($dir,$location);
1.1369 raeburn 13104:
13105: my $importid=$token->[2]->{'id'};
1.1068 www 13106: my $importmode=$token->[2]->{'importmode'};
1.1369 raeburn 13107: #
13108: # Check metadata for imported file to
13109: # see if it contained response items
13110: #
1.1372 raeburn 13111: my ($origfile,@libfilekeys);
1.1370 raeburn 13112: my %currmetaentry = %metaentry;
1.1372 raeburn 13113: @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13114: $depthcount+1));
13115: if (grep(/^responseorder$/,@libfilekeys)) {
13116: my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13117: undef,$depthcount+1);
13118: if ($libresponseorder ne '') {
13119: if ($#origfiletagids<0) {
13120: undef(%importedrespids);
13121: undef(%importedpartids);
13122: }
1.1373 raeburn 13123: my @respids = split(/\s*,\s*/,$libresponseorder);
13124: if (@respids) {
13125: $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13126: }
13127: if ($importedrespids{$importid} ne '') {
1.1372 raeburn 13128: $importedresponses = 1;
1.1369 raeburn 13129: # We need to get the original file and the imported file to get the response order correct
13130: # Load and inspect original file
1.1372 raeburn 13131: if ($#origfiletagids<0) {
13132: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13133: $origfile=&getfile($origfilelocation);
13134: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13135: }
1.1369 raeburn 13136: }
13137: }
13138: }
1.1370 raeburn 13139: # Do not overwrite contents of %metaentry hash for resource itself with
13140: # hash populated for imported library file
13141: %metaentry = %currmetaentry;
13142: undef(%currmetaentry);
1.1374 raeburn 13143: if ($importmode eq 'part') {
1.1068 www 13144: # Import as part(s)
1.1069 www 13145: $importedparts=1;
13146: # We need to get the original file and the imported file to get the part order correct
13147: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369 raeburn 13148: # Load and inspect original file if we didn't do that already
13149: if ($#origfiletagids<0) {
13150: undef(%importedrespids);
13151: undef(%importedpartids);
13152: if ($origfile eq '') {
13153: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13154: $origfile=&getfile($origfilelocation);
13155: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13156: }
1.1070 www 13157: }
1.1372 raeburn 13158: my @impfilepartids;
13159: # If <partorder> tag is included in metadata for the imported file
13160: # get the parts in the imported file from that.
13161: if (grep(/^partorder$/,@libfilekeys)) {
13162: %currmetaentry = %metaentry;
13163: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13164: $depthcount+1);
13165: %metaentry = %currmetaentry;
13166: undef(%currmetaentry);
13167: if ($libpartorder ne '') {
13168: @impfilepartids=split(/\s*,\s*/,$libpartorder);
13169: }
13170: } else {
13171: # If no <partorder> tag available, load and inspect imported file
13172: my $impfile=&getfile($location);
13173: @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13174: }
1.1069 www 13175: if ($#impfilepartids>=0) {
13176: # This problem had parts
1.1070 www 13177: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 13178: } else {
13179: # Importing by turning a single problem into a problem part
13180: # It gets the import-tags ID as part-ID
13181: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 13182: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 13183: }
1.1068 www 13184: } else {
1.1374 raeburn 13185: # Import as problem or as normal import
13186: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13187: unless ($importmode eq 'problem') {
1.1068 www 13188: # Normal import
1.1374 raeburn 13189: if (defined($token->[2]->{'id'})) {
13190: $unikey.='_'.$token->[2]->{'id'};
13191: }
13192: }
13193: # Check metadata for imported file to
13194: # see if it contained parts
13195: if (grep(/^partorder$/,@libfilekeys)) {
13196: %currmetaentry = %metaentry;
13197: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13198: $depthcount+1);
13199: %metaentry = %currmetaentry;
13200: undef(%currmetaentry);
13201: if ($libpartorder ne '') {
13202: $importedparts = 1;
13203: $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13204: }
13205: }
1.1067 www 13206: }
1.339 albertel 13207: if ($depthcount<20) {
1.736 albertel 13208: my $metadata =
1.1362 raeburn 13209: &metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736 albertel 13210: $depthcount+1);
13211: foreach my $meta (split(',',$metadata)) {
13212: $metaentry{':'.$meta}=$metaentry{':'.$meta};
13213: $metathesekeys{$meta}=1;
1.339 albertel 13214: }
1.1068 www 13215: }
1.1067 www 13216: } else {
13217: #
13218: # Not importing, some other kind of non-package, non-library start tag
13219: #
13220: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13221: if (defined($token->[2]->{'id'})) {
13222: $unikey.='_'.$token->[2]->{'id'};
13223: }
1.339 albertel 13224: if (defined($token->[2]->{'name'})) {
13225: $unikey.='_'.$token->[2]->{'name'};
13226: }
13227: $metathesekeys{$unikey}=1;
1.736 albertel 13228: foreach my $param (@{$token->[3]}) {
13229: $metaentry{':'.$unikey.'.'.$param} =
13230: $token->[2]->{$param};
1.339 albertel 13231: }
13232: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 13233: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 13234: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13235: # only ws inside the tag, and not in default, so use default
13236: # as value
1.599 albertel 13237: $metaentry{':'.$unikey}=$default;
1.908 albertel 13238: } elsif ( $internaltext =~ /\S/ ) {
13239: # something interesting inside the tag
13240: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 13241: } else {
1.908 albertel 13242: # no interesting values, don't set a default
1.339 albertel 13243: }
1.172 www 13244: # end of not-a-package not-a-library import
1.339 albertel 13245: }
1.172 www 13246: # end of not-a-package start tag
1.339 albertel 13247: }
1.172 www 13248: # the next is the end of "start tag"
1.339 albertel 13249: }
13250: }
1.483 albertel 13251: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 13252: $extension = lc($extension);
13253: if ($extension eq 'htm') { $extension='html'; }
13254:
1.737 albertel 13255: foreach my $key (keys(%packagetab)) {
1.483 albertel 13256: #no specific packages #how's our extension
13257: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 13258: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 13259: \%metathesekeys);
13260: }
1.883 albertel 13261:
13262: if (!exists($metaentry{':packages'})
13263: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 13264: foreach my $key (keys(%packagetab)) {
1.483 albertel 13265: #no specific packages well let's get default then
13266: if ($key!~/^default&/) { next; }
1.488 albertel 13267: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 13268: \%metathesekeys);
13269: }
13270: }
1.338 www 13271: # are there custom rights to evaluate
1.599 albertel 13272: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 13273:
1.338 www 13274: #
13275: # Importing a rights file here
1.339 albertel 13276: #
13277: unless ($depthcount) {
1.599 albertel 13278: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 13279: my $dir=$filename;
13280: $dir=~s|[^/]*$||;
13281: $location=&filelocation($dir,$location);
1.736 albertel 13282: my $rights_metadata =
1.1362 raeburn 13283: &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736 albertel 13284: $depthcount+1);
13285: foreach my $rights (split(',',$rights_metadata)) {
13286: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13287: $metathesekeys{$rights}=1;
1.339 albertel 13288: }
13289: }
13290: }
1.737 albertel 13291: # uniqifiy package listing
13292: my %seen;
13293: my @uniq_packages =
13294: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13295: $metaentry{':packages'} = join(',',@uniq_packages);
13296:
1.1369 raeburn 13297: if (($importedresponses) || ($importedparts)) {
13298: if ($importedparts) {
1.1070 www 13299: # We had imported parts and need to rebuild partorder
1.1369 raeburn 13300: $metaentry{':partorder'}='';
13301: $metathesekeys{'partorder'}=1;
13302: }
13303: if ($importedresponses) {
13304: # We had imported responses and need to rebuil responseorder
13305: $metaentry{':responseorder'}='';
13306: $metathesekeys{'responseorder'}=1;
13307: }
13308: for (my $index=0;$index<$#origfiletagids;$index+=2) {
13309: my $origid = $origfiletagids[$index+1];
13310: if ($origfiletagids[$index] eq 'part') {
13311: # Original part, part of the problem
13312: if ($importedparts) {
13313: $metaentry{':partorder'}.=','.$origid;
13314: }
13315: } elsif ($origfiletagids[$index] eq 'import') {
13316: if ($importedparts) {
13317: # We have imported parts at this position
1.1373 raeburn 13318: if ($importedpartids{$origid} ne '') {
13319: $metaentry{':partorder'}.=','.$importedpartids{$origid};
13320: }
1.1369 raeburn 13321: }
13322: if ($importedresponses) {
13323: # We have imported responses at this position
1.1373 raeburn 13324: if ($importedrespids{$origid} ne '') {
13325: $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369 raeburn 13326: }
13327: }
13328: } else {
13329: # Original response item, part of the problem
13330: if ($importedresponses) {
13331: $metaentry{':responseorder'}.=','.$origid;
13332: }
13333: }
13334: }
13335: if ($importedparts) {
13336: $metaentry{':partorder'}=~s/^\,//;
13337: }
13338: if ($importedresponses) {
13339: $metaentry{':responseorder'}=~s/^\,//;
13340: }
1.1070 www 13341: }
1.737 albertel 13342: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 13343: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 13344: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371 raeburn 13345: unless ($liburi) {
13346: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13347: }
1.177 www 13348: # this is the end of "was not already recently cached
1.71 www 13349: }
1.599 albertel 13350: return $metaentry{':'.$what};
1.261 albertel 13351: }
13352:
1.488 albertel 13353: sub metadata_create_package_def {
1.483 albertel 13354: my ($uri,$key,$package,$metathesekeys)=@_;
13355: my ($pack,$name,$subp)=split(/\&/,$key);
13356: if ($subp eq 'default') { next; }
13357:
1.599 albertel 13358: if (defined($metaentry{':packages'})) {
13359: $metaentry{':packages'}.=','.$package;
1.483 albertel 13360: } else {
1.599 albertel 13361: $metaentry{':packages'}=$package;
1.483 albertel 13362: }
13363: my $value=$packagetab{$key};
13364: my $unikey;
13365: $unikey='parameter_0_'.$name;
1.599 albertel 13366: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 13367: $$metathesekeys{$unikey}=1;
1.599 albertel 13368: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13369: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 13370: }
1.599 albertel 13371: if (defined($metaentry{':'.$unikey.'.default'})) {
13372: $metaentry{':'.$unikey}=
13373: $metaentry{':'.$unikey.'.default'};
1.483 albertel 13374: }
13375: }
13376:
1.261 albertel 13377: sub metadata_generate_part0 {
13378: my ($metadata,$metacache,$uri) = @_;
13379: my %allnames;
1.737 albertel 13380: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 13381: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 13382: my $part=$$metacache{':'.$metakey.'.part'};
13383: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 13384: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 13385: $allnames{$name}=$part;
13386: }
13387: }
13388: }
13389: foreach my $name (keys(%allnames)) {
13390: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 13391: my $key=":parameter_0_$name";
1.261 albertel 13392: $$metacache{"$key.part"}='0';
13393: $$metacache{"$key.name"}=$name;
1.428 albertel 13394: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 13395: $allnames{$name}.'_'.$name.
13396: '.type'};
1.428 albertel 13397: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 13398: '.display'};
1.644 www 13399: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 13400: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 13401: $$metacache{"$key.display"}=$olddis;
13402: }
1.71 www 13403: }
13404:
1.764 albertel 13405: # ------------------------------------------------------ Devalidate title cache
13406:
13407: sub devalidate_title_cache {
13408: my ($url)=@_;
13409: if (!$env{'request.course.id'}) { return; }
13410: my $symb=&symbread($url);
13411: if (!$symb) { return; }
13412: my $key=$env{'request.course.id'}."\0".$symb;
13413: &devalidate_cache_new('title',$key);
13414: }
13415:
1.1014 droeschl 13416: # ------------------------------------------------- Get the title of a course
13417:
13418: sub current_course_title {
13419: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13420: }
1.301 www 13421: # ------------------------------------------------- Get the title of a resource
13422:
13423: sub gettitle {
13424: my $urlsymb=shift;
13425: my $symb=&symbread($urlsymb);
1.534 albertel 13426: if ($symb) {
1.620 albertel 13427: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 13428: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 13429: if (defined($cached)) {
13430: return $result;
13431: }
1.534 albertel 13432: my ($map,$resid,$url)=&decode_symb($symb);
13433: my $title='';
1.907 albertel 13434: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13435: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13436: } else {
13437: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13438: &GDBM_READER(),0640)) {
13439: my $mapid=$bighash{'map_pc_'.&clutter($map)};
13440: $title=$bighash{'title_'.$mapid.'.'.$resid};
13441: untie(%bighash);
13442: }
1.534 albertel 13443: }
13444: $title=~s/\&colon\;/\:/gs;
13445: if ($title) {
1.1159 www 13446: # Remember both $symb and $title for dynamic metadata
13447: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 13448: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 13449: # Cache this title and then return it
1.599 albertel 13450: return &do_cache_new('title',$key,$title,600);
1.534 albertel 13451: }
13452: $urlsymb=$url;
13453: }
13454: my $title=&metadata($urlsymb,'title');
13455: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
13456: return $title;
1.301 www 13457: }
1.613 albertel 13458:
1.614 albertel 13459: sub get_slot {
13460: my ($which,$cnum,$cdom)=@_;
13461: if (!$cnum || !$cdom) {
1.790 albertel 13462: (undef,my $courseid)=&whichuser();
1.620 albertel 13463: $cdom=$env{'course.'.$courseid.'.domain'};
13464: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 13465: }
1.703 albertel 13466: my $key=join("\0",'slots',$cdom,$cnum,$which);
13467: my %slotinfo;
13468: if (exists($remembered{$key})) {
13469: $slotinfo{$which} = $remembered{$key};
13470: } else {
13471: %slotinfo=&get('slots',[$which],$cdom,$cnum);
13472: &Apache::lonhomework::showhash(%slotinfo);
13473: my ($tmp)=keys(%slotinfo);
13474: if ($tmp=~/^error:/) { return (); }
13475: $remembered{$key} = $slotinfo{$which};
13476: }
1.616 albertel 13477: if (ref($slotinfo{$which}) eq 'HASH') {
13478: return %{$slotinfo{$which}};
13479: }
13480: return $slotinfo{$which};
1.614 albertel 13481: }
1.1150 raeburn 13482:
13483: sub get_reservable_slots {
13484: my ($cnum,$cdom,$uname,$udom) = @_;
13485: my $now = time;
13486: my $reservable_info;
13487: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13488: if (exists($remembered{$key})) {
13489: $reservable_info = $remembered{$key};
13490: } else {
13491: my %resv;
13492: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13493: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13494: $reservable_info = \%resv;
13495: $remembered{$key} = $reservable_info;
13496: }
13497: return $reservable_info;
13498: }
13499:
13500: sub get_course_slots {
13501: my ($cnum,$cdom) = @_;
13502: my $hashid=$cnum.':'.$cdom;
13503: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13504: if (defined($cached)) {
13505: if (ref($result) eq 'HASH') {
13506: return %{$result};
13507: }
13508: } else {
13509: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13510: my ($tmp) = keys(%slots);
13511: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 13512: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 13513: return %slots;
13514: }
13515: }
13516: return;
13517: }
13518:
13519: sub devalidate_slots_cache {
13520: my ($cnum,$cdom)=@_;
13521: my $hashid=$cnum.':'.$cdom;
13522: &devalidate_cache_new('allslots',$hashid);
13523: }
13524:
1.1181 raeburn 13525: sub get_coursechange {
13526: my ($cdom,$cnum) = @_;
13527: if ($cdom eq '' || $cnum eq '') {
13528: return unless ($env{'request.course.id'});
13529: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13530: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13531: }
13532: my $hashid=$cdom.'_'.$cnum;
13533: my ($change,$cached)=&is_cached_new('crschange',$hashid);
13534: if ((defined($cached)) && ($change ne '')) {
13535: return $change;
13536: } else {
13537: my %crshash;
13538: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13539: if ($crshash{'internal.contentchange'} eq '') {
13540: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13541: if ($change eq '') {
13542: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13543: $change = $crshash{'internal.created'};
13544: }
13545: } else {
13546: $change = $crshash{'internal.contentchange'};
13547: }
13548: my $cachetime = 600;
13549: &do_cache_new('crschange',$hashid,$change,$cachetime);
13550: }
13551: return $change;
13552: }
13553:
13554: sub devalidate_coursechange_cache {
13555: my ($cnum,$cdom)=@_;
13556: my $hashid=$cnum.':'.$cdom;
13557: &devalidate_cache_new('crschange',$hashid);
13558: }
13559:
1.31 www 13560: # ------------------------------------------------- Update symbolic store links
13561:
13562: sub symblist {
13563: my ($mapname,%newhash)=@_;
1.438 www 13564: $mapname=&deversion(&declutter($mapname));
1.31 www 13565: my %hash;
1.620 albertel 13566: if (($env{'request.course.fn'}) && (%newhash)) {
13567: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 13568: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 13569: foreach my $url (keys(%newhash)) {
1.711 albertel 13570: next if ($url eq 'last_known'
13571: && $env{'form.no_update_last_known'});
13572: $hash{declutter($url)}=&encode_symb($mapname,
13573: $newhash{$url}->[1],
13574: $newhash{$url}->[0]);
1.191 harris41 13575: }
1.31 www 13576: if (untie(%hash)) {
13577: return 'ok';
13578: }
13579: }
13580: }
13581: return 'error';
1.212 www 13582: }
13583:
13584: # --------------------------------------------------------------- Verify a symb
13585:
13586: sub symbverify {
1.1190 raeburn 13587: my ($symb,$thisurl,$encstate)=@_;
1.510 www 13588: my $thisfn=$thisurl;
1.439 www 13589: $thisfn=&declutter($thisfn);
1.215 www 13590: # direct jump to resource in page or to a sequence - will construct own symbs
13591: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13592: # check URL part
1.409 www 13593: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 13594:
1.431 www 13595: unless ($url eq $thisfn) { return 0; }
1.213 www 13596:
1.216 www 13597: $symb=&symbclean($symb);
1.510 www 13598: $thisurl=&deversion($thisurl);
1.439 www 13599: $thisfn=&deversion($thisfn);
1.213 www 13600:
13601: my %bighash;
13602: my $okay=0;
1.431 www 13603:
1.620 albertel 13604: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13605: &GDBM_READER(),0640)) {
1.1032 raeburn 13606: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13607: $thisurl =~ s/\?.+$//;
1.1204 raeburn 13608: if ($map =~ m{^uploaded/.+\.page$}) {
13609: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13610: $thisurl =~ s{^\Qhttp://https://\E}{https://};
13611: }
13612: }
13613: my $ids;
1.1419 raeburn 13614: if ($map =~ m{^uploaded/.+\.page$}) {
13615: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204 raeburn 13616: } else {
13617: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 13618: }
1.1102 raeburn 13619: unless ($ids) {
13620: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
13621: $ids=$bighash{$idkey};
1.216 www 13622: }
13623: if ($ids) {
13624: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 13625: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 13626: $symb =~ s/\?.+$//;
1.1202 raeburn 13627: }
1.800 albertel 13628: foreach my $id (split(/\,/,$ids)) {
13629: my ($mapid,$resid)=split(/\./,$id);
1.216 www 13630: if (
13631: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 13632: eq $symb) {
13633: if (ref($encstate)) {
13634: $$encstate = $bighash{'encrypted_'.$id};
13635: }
1.620 albertel 13636: if (($env{'request.role.adv'}) ||
1.1101 raeburn 13637: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13638: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 13639: $okay=1;
1.1202 raeburn 13640: last;
1.582 albertel 13641: }
13642: }
1.216 www 13643: }
13644: }
1.213 www 13645: untie(%bighash);
13646: }
13647: return $okay;
1.31 www 13648: }
13649:
1.210 www 13650: # --------------------------------------------------------------- Clean-up symb
13651:
13652: sub symbclean {
13653: my $symb=shift;
1.568 albertel 13654: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 13655: # remove version from map
13656: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 13657:
1.210 www 13658: # remove version from URL
13659: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 13660:
1.507 www 13661: # remove wrapper
13662:
1.510 www 13663: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 13664: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 13665: return $symb;
1.409 www 13666: }
13667:
13668: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 13669:
13670: sub encode_symb {
13671: my ($map,$resid,$url)=@_;
13672: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13673: }
1.409 www 13674:
13675: sub decode_symb {
1.568 albertel 13676: my $symb=shift;
13677: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13678: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 13679: return (&fixversion($map),$resid,&fixversion($url));
13680: }
13681:
13682: sub fixversion {
13683: my $fn=shift;
1.609 banghart 13684: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 13685: my %bighash;
13686: my $uri=&clutter($fn);
1.620 albertel 13687: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 13688: # is this cached?
1.599 albertel 13689: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 13690: if (defined($cached)) { return $result; }
13691: # unfortunately not cached, or expired
1.620 albertel 13692: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 13693: &GDBM_READER(),0640)) {
13694: if ($bighash{'version_'.$uri}) {
13695: my $version=$bighash{'version_'.$uri};
1.444 www 13696: unless (($version eq 'mostrecent') ||
13697: ($version==&getversion($uri))) {
1.440 www 13698: $uri=~s/\.(\w+)$/\.$version\.$1/;
13699: }
13700: }
13701: untie %bighash;
1.413 www 13702: }
1.599 albertel 13703: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 13704: }
13705:
13706: sub deversion {
13707: my $url=shift;
13708: $url=~s/\.\d+\.(\w+)$/\.$1/;
13709: return $url;
1.210 www 13710: }
13711:
1.31 www 13712: # ------------------------------------------------------ Return symb list entry
13713:
13714: sub symbread {
1.1424 raeburn 13715: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1427 raeburn 13716: $ignoresymbdb,$noenccheck)=@_;
1.1265 raeburn 13717: my $cache_str='request.symbread.cached.'.$thisfn;
1.1427 raeburn 13718: if (defined($env{$cache_str})) {
1.1424 raeburn 13719: unless (ref($possibles) eq 'HASH') {
13720: if ($ignorecachednull) {
13721: return $env{$cache_str} unless ($env{$cache_str} eq '');
13722: } else {
13723: return $env{$cache_str};
13724: }
1.1282 raeburn 13725: }
13726: }
1.242 www 13727: # no filename provided? try from environment
1.1265 raeburn 13728: unless ($thisfn) {
1.620 albertel 13729: if ($env{'request.symb'}) {
1.1427 raeburn 13730: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 13731: }
1.620 albertel 13732: $thisfn=$env{'request.filename'};
1.44 www 13733: }
1.569 albertel 13734: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 13735: # is that filename actually a symb? Verify, clean, and return
13736: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 13737: if (&symbverify($thisfn,$1)) {
1.1427 raeburn 13738: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 13739: }
1.242 www 13740: }
1.44 www 13741: $thisfn=declutter($thisfn);
1.31 www 13742: my %hash;
1.37 www 13743: my %bighash;
13744: my $syval='';
1.620 albertel 13745: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 13746: my $targetfn = $thisfn;
1.609 banghart 13747: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 13748: $targetfn = 'adm/wrapper/'.$thisfn;
13749: }
1.687 albertel 13750: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13751: $targetfn=$1;
13752: }
1.1427 raeburn 13753: unless ($ignoresymbdb) {
1.1424 raeburn 13754: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13755: &GDBM_READER(),0640)) {
13756: $syval=$hash{$targetfn};
13757: untie(%hash);
13758: }
1.1427 raeburn 13759: if ($syval && $checkforblock) {
13760: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1424 raeburn 13761: if (@blockers) {
13762: $syval='';
13763: }
13764: }
1.37 www 13765: }
13766: # ---------------------------------------------------------- There was an entry
13767: if ($syval) {
1.601 albertel 13768: #unless ($syval=~/\_\d+$/) {
1.620 albertel 13769: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 13770: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 13771: #return $env{$cache_str}='';
1.601 albertel 13772: #}
13773: #$syval.=$1;
13774: #}
1.37 www 13775: } else {
13776: # ------------------------------------------------------- Was not in symb table
1.620 albertel 13777: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13778: &GDBM_READER(),0640)) {
1.37 www 13779: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 13780: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 13781: unless ($ids) {
13782: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 13783: }
13784: unless ($ids) {
13785: # alias?
13786: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 13787: }
1.37 www 13788: if ($ids) {
13789: # ------------------------------------------------------------------- Has ID(s)
13790: my @possibilities=split(/\,/,$ids);
1.39 www 13791: if ($#possibilities==0) {
13792: # ----------------------------------------------- There is only one possibility
1.37 www 13793: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 13794: $syval=&encode_symb($bighash{'map_id_'.$mapid},
13795: $resid,$thisfn);
1.1282 raeburn 13796: if (ref($possibles) eq 'HASH') {
1.1424 raeburn 13797: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13798: $possibles->{$syval} = 1;
13799: }
1.1282 raeburn 13800: }
13801: if ($checkforblock) {
1.1424 raeburn 13802: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1426 raeburn 13803: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1424 raeburn 13804: if (@blockers) {
13805: $syval = '';
1.1425 raeburn 13806: untie(%bighash);
13807: return $env{$cache_str}='';
1.1424 raeburn 13808: }
1.1282 raeburn 13809: }
13810: }
13811: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 13812: # ------------------------------------------ There is more than one possibility
13813: my $realpossible=0;
1.800 albertel 13814: foreach my $id (@possibilities) {
13815: my $file=$bighash{'src_'.$id};
1.1282 raeburn 13816: my $canaccess;
13817: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13818: $canaccess = 1;
13819: } else {
13820: $canaccess = &allowed('bre',$file);
13821: }
13822: if ($canaccess) {
13823: my ($mapid,$resid)=split(/\./,$id);
13824: if ($bighash{'map_type_'.$mapid} ne 'page') {
13825: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13826: $resid,$thisfn);
1.1424 raeburn 13827: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1426 raeburn 13828: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1282 raeburn 13829: if ($checkforblock) {
1.1426 raeburn 13830: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1424 raeburn 13831: if (@blockers > 0) {
13832: $syval = '';
13833: } else {
1.1282 raeburn 13834: $syval = $poss_syval;
13835: $realpossible++;
13836: }
13837: } else {
13838: $syval = $poss_syval;
13839: $realpossible++;
13840: }
1.1424 raeburn 13841: if ($syval) {
13842: if (ref($possibles) eq 'HASH') {
13843: $possibles->{$syval} = 1;
13844: }
13845: }
1.1282 raeburn 13846: }
1.39 www 13847: }
1.191 harris41 13848: }
1.39 www 13849: if ($realpossible!=1) { $syval=''; }
1.249 www 13850: } else {
13851: $syval='';
1.37 www 13852: }
13853: }
1.1282 raeburn 13854: untie(%bighash);
1.481 raeburn 13855: }
1.31 www 13856: }
1.62 www 13857: if ($syval) {
1.1427 raeburn 13858: return $env{$cache_str}=$syval;
1.62 www 13859: }
1.31 www 13860: }
1.949 raeburn 13861: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 13862: return $env{$cache_str}='';
1.31 www 13863: }
13864:
13865: # ---------------------------------------------------------- Return random seed
13866:
1.32 www 13867: sub numval {
13868: my $txt=shift;
13869: $txt=~tr/A-J/0-9/;
13870: $txt=~tr/a-j/0-9/;
13871: $txt=~tr/K-T/0-9/;
13872: $txt=~tr/k-t/0-9/;
13873: $txt=~tr/U-Z/0-5/;
13874: $txt=~tr/u-z/0-5/;
13875: $txt=~s/\D//g;
1.564 albertel 13876: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 13877: return int($txt);
1.368 albertel 13878: }
13879:
1.484 albertel 13880: sub numval2 {
13881: my $txt=shift;
13882: $txt=~tr/A-J/0-9/;
13883: $txt=~tr/a-j/0-9/;
13884: $txt=~tr/K-T/0-9/;
13885: $txt=~tr/k-t/0-9/;
13886: $txt=~tr/U-Z/0-5/;
13887: $txt=~tr/u-z/0-5/;
13888: $txt=~s/\D//g;
13889: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13890: my $total;
13891: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 13892: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 13893: return int($total);
13894: }
13895:
1.575 albertel 13896: sub numval3 {
13897: use integer;
13898: my $txt=shift;
13899: $txt=~tr/A-J/0-9/;
13900: $txt=~tr/a-j/0-9/;
13901: $txt=~tr/K-T/0-9/;
13902: $txt=~tr/k-t/0-9/;
13903: $txt=~tr/U-Z/0-5/;
13904: $txt=~tr/u-z/0-5/;
13905: $txt=~s/\D//g;
13906: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13907: my $total;
13908: foreach my $val (@txts) { $total+=$val; }
13909: if ($_64bit) { $total=(($total<<32)>>32); }
13910: return $total;
13911: }
13912:
1.675 albertel 13913: sub digest {
13914: my ($data)=@_;
13915: my $digest=&Digest::MD5::md5($data);
13916: my ($a,$b,$c,$d)=unpack("iiii",$digest);
13917: my ($e,$f);
13918: {
13919: use integer;
13920: $e=($a+$b);
13921: $f=($c+$d);
13922: if ($_64bit) {
13923: $e=(($e<<32)>>32);
13924: $f=(($f<<32)>>32);
13925: }
13926: }
13927: if (wantarray) {
13928: return ($e,$f);
13929: } else {
13930: my $g;
13931: {
13932: use integer;
13933: $g=($e+$f);
13934: if ($_64bit) {
13935: $g=(($g<<32)>>32);
13936: }
13937: }
13938: return $g;
13939: }
13940: }
13941:
1.368 albertel 13942: sub latest_rnd_algorithm_id {
1.675 albertel 13943: return '64bit5';
1.366 albertel 13944: }
1.32 www 13945:
1.503 albertel 13946: sub get_rand_alg {
13947: my ($courseid)=@_;
1.790 albertel 13948: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 13949: if ($courseid) {
1.620 albertel 13950: return $env{"course.$courseid.rndseed"};
1.503 albertel 13951: }
13952: return &latest_rnd_algorithm_id();
13953: }
13954:
1.562 albertel 13955: sub validCODE {
13956: my ($CODE)=@_;
13957: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13958: return 0;
13959: }
13960:
1.491 albertel 13961: sub getCODE {
1.620 albertel 13962: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 13963: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13964: defined($Apache::lonhomework::parsing_a_task) ) &&
13965: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 13966: return $Apache::lonhomework::history{'resource.CODE'};
13967: }
13968: return undef;
13969: }
1.1133 foxr 13970: #
13971: # Determines the random seed for a specific context:
13972: #
13973: # parameters:
13974: # symb - in course context the symb for the seed.
13975: # course_id - The course id of the form domain_coursenum.
13976: # domain - Domain for the user.
13977: # course - Course for the user.
13978: # cenv - environment of the course.
13979: #
13980: # NOTE:
13981: # All parameters are picked out of the environment if missing
13982: # or not defined.
13983: # If a symb cannot be determined the current time is used instead.
13984: #
13985: # For a given well defined symb, courside, domain, username,
13986: # and course environment, the seed is reproducible.
13987: #
1.31 www 13988: sub rndseed {
1.1133 foxr 13989: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 13990: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 13991: if (!defined($symb)) {
1.366 albertel 13992: unless ($symb=$wsymb) { return time; }
13993: }
1.1146 foxr 13994: if (!defined $courseid) {
13995: $courseid=$wcourseid;
13996: }
13997: if (!defined $domain) { $domain=$wdomain; }
13998: if (!defined $username) { $username=$wusername }
1.1133 foxr 13999:
14000: my $which;
14001: if (defined($cenv->{'rndseed'})) {
14002: $which = $cenv->{'rndseed'};
14003: } else {
14004: $which =&get_rand_alg($courseid);
14005: }
1.491 albertel 14006: if (defined(&getCODE())) {
1.1133 foxr 14007:
1.675 albertel 14008: if ($which eq '64bit5') {
14009: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14010: } elsif ($which eq '64bit4') {
1.575 albertel 14011: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14012: } else {
14013: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14014: }
1.675 albertel 14015: } elsif ($which eq '64bit5') {
14016: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 14017: } elsif ($which eq '64bit4') {
14018: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 14019: } elsif ($which eq '64bit3') {
14020: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 14021: } elsif ($which eq '64bit2') {
14022: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 14023: } elsif ($which eq '64bit') {
14024: return &rndseed_64bit($symb,$courseid,$domain,$username);
14025: }
14026: return &rndseed_32bit($symb,$courseid,$domain,$username);
14027: }
14028:
14029: sub rndseed_32bit {
14030: my ($symb,$courseid,$domain,$username)=@_;
14031: {
14032: use integer;
14033: my $symbchck=unpack("%32C*",$symb) << 27;
14034: my $symbseed=numval($symb) << 22;
14035: my $namechck=unpack("%32C*",$username) << 17;
14036: my $nameseed=numval($username) << 12;
14037: my $domainseed=unpack("%32C*",$domain) << 7;
14038: my $courseseed=unpack("%32C*",$courseid);
14039: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 14040: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14041: #&logthis("rndseed :$num:$symb");
1.564 albertel 14042: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 14043: return $num;
14044: }
14045: }
14046:
14047: sub rndseed_64bit {
14048: my ($symb,$courseid,$domain,$username)=@_;
14049: {
14050: use integer;
14051: my $symbchck=unpack("%32S*",$symb) << 21;
14052: my $symbseed=numval($symb) << 10;
14053: my $namechck=unpack("%32S*",$username);
14054:
14055: my $nameseed=numval($username) << 21;
14056: my $domainseed=unpack("%32S*",$domain) << 10;
14057: my $courseseed=unpack("%32S*",$courseid);
14058:
14059: my $num1=$symbchck+$symbseed+$namechck;
14060: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14061: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14062: #&logthis("rndseed :$num:$symb");
1.564 albertel 14063: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 14064: return "$num1,$num2";
1.155 albertel 14065: }
1.366 albertel 14066: }
14067:
1.443 albertel 14068: sub rndseed_64bit2 {
14069: my ($symb,$courseid,$domain,$username)=@_;
14070: {
14071: use integer;
14072: # strings need to be an even # of cahracters long, it it is odd the
14073: # last characters gets thrown away
14074: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14075: my $symbseed=numval($symb) << 10;
14076: my $namechck=unpack("%32S*",$username.' ');
14077:
14078: my $nameseed=numval($username) << 21;
1.501 albertel 14079: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14080: my $courseseed=unpack("%32S*",$courseid.' ');
14081:
14082: my $num1=$symbchck+$symbseed+$namechck;
14083: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14084: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14085: #&logthis("rndseed :$num:$symb");
1.803 albertel 14086: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 14087: return "$num1,$num2";
14088: }
14089: }
14090:
14091: sub rndseed_64bit3 {
14092: my ($symb,$courseid,$domain,$username)=@_;
14093: {
14094: use integer;
14095: # strings need to be an even # of cahracters long, it it is odd the
14096: # last characters gets thrown away
14097: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14098: my $symbseed=numval2($symb) << 10;
14099: my $namechck=unpack("%32S*",$username.' ');
14100:
14101: my $nameseed=numval2($username) << 21;
1.443 albertel 14102: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14103: my $courseseed=unpack("%32S*",$courseid.' ');
14104:
14105: my $num1=$symbchck+$symbseed+$namechck;
14106: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14107: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14108: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 14109: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 14110:
1.503 albertel 14111: return "$num1:$num2";
1.443 albertel 14112: }
14113: }
14114:
1.575 albertel 14115: sub rndseed_64bit4 {
14116: my ($symb,$courseid,$domain,$username)=@_;
14117: {
14118: use integer;
14119: # strings need to be an even # of cahracters long, it it is odd the
14120: # last characters gets thrown away
14121: my $symbchck=unpack("%32S*",$symb.' ') << 21;
14122: my $symbseed=numval3($symb) << 10;
14123: my $namechck=unpack("%32S*",$username.' ');
14124:
14125: my $nameseed=numval3($username) << 21;
14126: my $domainseed=unpack("%32S*",$domain.' ') << 10;
14127: my $courseseed=unpack("%32S*",$courseid.' ');
14128:
14129: my $num1=$symbchck+$symbseed+$namechck;
14130: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 14131: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14132: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 14133: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 14134:
1.575 albertel 14135: return "$num1:$num2";
14136: }
14137: }
14138:
1.675 albertel 14139: sub rndseed_64bit5 {
14140: my ($symb,$courseid,$domain,$username)=@_;
14141: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14142: return "$num1:$num2";
14143: }
14144:
1.366 albertel 14145: sub rndseed_CODE_64bit {
14146: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 14147: {
1.366 albertel 14148: use integer;
1.443 albertel 14149: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 14150: my $symbseed=numval2($symb);
1.491 albertel 14151: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14152: my $CODEseed=numval(&getCODE());
1.443 albertel 14153: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 14154: my $num1=$symbseed+$CODEchck;
14155: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 14156: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14157: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 14158: if ($_64bit) { $num1=(($num1<<32)>>32); }
14159: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 14160: return "$num1:$num2";
1.366 albertel 14161: }
14162: }
14163:
1.575 albertel 14164: sub rndseed_CODE_64bit4 {
14165: my ($symb,$courseid,$domain,$username)=@_;
14166: {
14167: use integer;
14168: my $symbchck=unpack("%32S*",$symb.' ') << 16;
14169: my $symbseed=numval3($symb);
14170: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14171: my $CODEseed=numval3(&getCODE());
14172: my $courseseed=unpack("%32S*",$courseid.' ');
14173: my $num1=$symbseed+$CODEchck;
14174: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 14175: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14176: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 14177: if ($_64bit) { $num1=(($num1<<32)>>32); }
14178: if ($_64bit) { $num2=(($num2<<32)>>32); }
14179: return "$num1:$num2";
14180: }
14181: }
14182:
1.675 albertel 14183: sub rndseed_CODE_64bit5 {
14184: my ($symb,$courseid,$domain,$username)=@_;
14185: my $code = &getCODE();
14186: my ($num1,$num2)=&digest("$symb,$courseid,$code");
14187: return "$num1:$num2";
14188: }
14189:
1.366 albertel 14190: sub setup_random_from_rndseed {
14191: my ($rndseed)=@_;
1.503 albertel 14192: if ($rndseed =~/([,:])/) {
1.1262 raeburn 14193: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14194: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14195: &Math::Random::random_set_seed_from_phrase($rndseed);
14196: } else {
14197: &Math::Random::random_set_seed($num1,$num2);
14198: }
1.366 albertel 14199: } else {
14200: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 14201: }
1.36 albertel 14202: }
14203:
1.474 albertel 14204: sub latest_receipt_algorithm_id {
1.835 albertel 14205: return 'receipt3';
1.474 albertel 14206: }
14207:
1.480 www 14208: sub recunique {
14209: my $fucourseid=shift;
14210: my $unique;
1.835 albertel 14211: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14212: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 14213: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 14214: } else {
14215: $unique=$perlvar{'lonReceipt'};
14216: }
14217: return unpack("%32C*",$unique);
14218: }
14219:
14220: sub recprefix {
14221: my $fucourseid=shift;
14222: my $prefix;
1.835 albertel 14223: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14224: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 14225: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 14226: } else {
14227: $prefix=$perlvar{'lonHostID'};
14228: }
14229: return unpack("%32C*",$prefix);
14230: }
14231:
1.76 www 14232: sub ireceipt {
1.474 albertel 14233: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 14234:
14235: my $return =&recprefix($fucourseid).'-';
14236:
14237: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14238: $env{'request.state'} eq 'construct') {
14239: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14240: return $return;
14241: }
14242:
1.76 www 14243: my $cuname=unpack("%32C*",$funame);
14244: my $cudom=unpack("%32C*",$fudom);
14245: my $cucourseid=unpack("%32C*",$fucourseid);
14246: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 14247: my $cunique=&recunique($fucourseid);
1.474 albertel 14248: my $cpart=unpack("%32S*",$part);
1.835 albertel 14249: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14250:
1.790 albertel 14251: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 14252:
14253: $return.= ($cunique%$cuname+
14254: $cunique%$cudom+
14255: $cusymb%$cuname+
14256: $cusymb%$cudom+
14257: $cucourseid%$cuname+
14258: $cucourseid%$cudom+
14259: $cpart%$cuname+
14260: $cpart%$cudom);
14261: } else {
14262: $return.= ($cunique%$cuname+
14263: $cunique%$cudom+
14264: $cusymb%$cuname+
14265: $cusymb%$cudom+
14266: $cucourseid%$cuname+
14267: $cucourseid%$cudom);
14268: }
14269: return $return;
1.76 www 14270: }
14271:
14272: sub receipt {
1.474 albertel 14273: my ($part)=@_;
1.790 albertel 14274: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 14275: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 14276: }
1.260 ng 14277:
1.790 albertel 14278: sub whichuser {
14279: my ($passedsymb)=@_;
14280: my ($symb,$courseid,$domain,$name,$publicuser);
14281: if (defined($env{'form.grade_symb'})) {
14282: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14283: my $allowed=&allowed('vgr',$tmp_courseid);
14284: if (!$allowed &&
14285: exists($env{'request.course.sec'}) &&
14286: $env{'request.course.sec'} !~ /^\s*$/) {
14287: $allowed=&allowed('vgr',$tmp_courseid.
14288: '/'.$env{'request.course.sec'});
14289: }
14290: if ($allowed) {
14291: ($symb)=&get_env_multiple('form.grade_symb');
14292: $courseid=$tmp_courseid;
14293: ($domain)=&get_env_multiple('form.grade_domain');
14294: ($name)=&get_env_multiple('form.grade_username');
14295: return ($symb,$courseid,$domain,$name,$publicuser);
14296: }
14297: }
14298: if (!$passedsymb) {
14299: $symb=&symbread();
14300: } else {
14301: $symb=$passedsymb;
14302: }
14303: $courseid=$env{'request.course.id'};
14304: $domain=$env{'user.domain'};
14305: $name=$env{'user.name'};
14306: if ($name eq 'public' && $domain eq 'public') {
14307: if (!defined($env{'form.username'})) {
14308: $env{'form.username'}.=time.rand(10000000);
14309: }
14310: $name.=$env{'form.username'};
14311: }
14312: return ($symb,$courseid,$domain,$name,$publicuser);
14313:
14314: }
14315:
1.36 albertel 14316: # ------------------------------------------------------------ Serves up a file
1.472 albertel 14317: # returns either the contents of the file or
14318: # -1 if the file doesn't exist
1.481 raeburn 14319: #
14320: # if the target is a file that was uploaded via DOCS,
14321: # a check will be made to see if a current copy exists on the local server,
14322: # if it does this will be served, otherwise a copy will be retrieved from
14323: # the home server for the course and stored in /home/httpd/html/userfiles on
14324: # the local server.
1.472 albertel 14325:
1.36 albertel 14326: sub getfile {
1.538 albertel 14327: my ($file) = @_;
1.609 banghart 14328: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 14329: &repcopy($file);
14330: return &readfile($file);
14331: }
14332:
14333: sub repcopy_userfile {
14334: my ($file)=@_;
1.1142 raeburn 14335: my $londocroot = $perlvar{'lonDocRoot'};
14336: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 14337: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 14338: my ($cdom,$cnum,$filename) =
1.811 albertel 14339: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 14340: my $uri="/uploaded/$cdom/$cnum/$filename";
14341: if (-e "$file") {
1.828 www 14342: # we already have a local copy, check it out
1.538 albertel 14343: my @fileinfo = stat($file);
1.828 www 14344: my $rtncode;
14345: my $info;
1.538 albertel 14346: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 14347: if ($lwpresp ne 'ok') {
1.828 www 14348: # there is no such file anymore, even though we had a local copy
1.482 albertel 14349: if ($rtncode eq '404') {
1.538 albertel 14350: unlink($file);
1.482 albertel 14351: }
14352: return -1;
14353: }
14354: if ($info < $fileinfo[9]) {
1.828 www 14355: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 14356: return 'ok';
1.828 www 14357: } else {
14358: # the file is outdated, get rid of it
14359: unlink($file);
1.482 albertel 14360: }
1.828 www 14361: }
14362: # one way or the other, at this point, we don't have the file
14363: # construct the correct path for the file
14364: my @parts = ($cdom,$cnum);
14365: if ($filename =~ m|^(.+)/[^/]+$|) {
14366: push @parts, split(/\//,$1);
14367: }
14368: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14369: foreach my $part (@parts) {
14370: $path .= '/'.$part;
14371: if (!-e $path) {
14372: mkdir($path,0770);
1.482 albertel 14373: }
14374: }
1.828 www 14375: # now the path exists for sure
14376: # get a user agent
14377: my $transferfile=$file.'.in.transfer';
14378: # FIXME: this should flock
14379: if (-e $transferfile) { return 'ok'; }
14380: my $request;
14381: $uri=~s/^\///;
1.980 raeburn 14382: my $homeserver = &homeserver($cnum,$cdom);
1.1398 raeburn 14383: my $hostname = &hostname($homeserver);
1.980 raeburn 14384: my $protocol = $protocol{$homeserver};
14385: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14386: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345 raeburn 14387: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828 www 14388: # did it work?
14389: if ($response->is_error()) {
14390: unlink($transferfile);
14391: &logthis("Userfile repcopy failed for $uri");
14392: return -1;
14393: }
14394: # worked, rename the transfer file
14395: rename($transferfile,$file);
1.607 raeburn 14396: return 'ok';
1.481 raeburn 14397: }
14398:
1.517 albertel 14399: sub tokenwrapper {
14400: my $uri=shift;
1.980 raeburn 14401: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 14402: $uri=~s|^/||;
1.620 albertel 14403: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 14404: my $token=$1;
1.552 albertel 14405: my (undef,$udom,$uname,$file)=split('/',$uri,4);
14406: if ($udom && $uname && $file) {
14407: $file=~s|(\?\.*)*$||;
1.949 raeburn 14408: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 14409: my $homeserver = &homeserver($uname,$udom);
1.1397 raeburn 14410: my $hostname = &hostname($homeserver);
1.980 raeburn 14411: my $protocol = $protocol{$homeserver};
14412: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14413: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 14414: (($uri=~/\?/)?'&':'?').'token='.$token.
14415: '&tokenissued='.$perlvar{'lonHostID'};
14416: } else {
14417: return '/adm/notfound.html';
14418: }
14419: }
14420:
1.828 www 14421: # call with reqtype HEAD: get last modification time
14422: # call with reqtype GET: get the file contents
14423: # Do not call this with reqtype GET for large files! It loads everything into memory
14424: #
1.481 raeburn 14425: sub getuploaded {
14426: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14427: $uri=~s/^\///;
1.980 raeburn 14428: my $homeserver = &homeserver($cnum,$cdom);
1.1397 raeburn 14429: my $hostname = &hostname($homeserver);
1.980 raeburn 14430: my $protocol = $protocol{$homeserver};
14431: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14432: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 14433: my $request=new HTTP::Request($reqtype,$uri);
1.1345 raeburn 14434: my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481 raeburn 14435: $$rtncode = $response->code;
1.482 albertel 14436: if (! $response->is_success()) {
14437: return 'failed';
14438: }
14439: if ($reqtype eq 'HEAD') {
1.486 www 14440: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 14441: } elsif ($reqtype eq 'GET') {
14442: $$info = $response->content;
1.472 albertel 14443: }
1.482 albertel 14444: return 'ok';
1.36 albertel 14445: }
14446:
1.481 raeburn 14447: sub readfile {
14448: my $file = shift;
14449: if ( (! -e $file ) || ($file eq '') ) { return -1; };
14450: my $fh;
1.1359 raeburn 14451: open($fh,"<",$file);
1.481 raeburn 14452: my $a='';
1.800 albertel 14453: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 14454: return $a;
14455: }
14456:
1.36 albertel 14457: sub filelocation {
1.590 banghart 14458: my ($dir,$file) = @_;
14459: my $location;
14460: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 14461:
14462: if ($file =~ m-^/adm/-) {
14463: $file=~s-^/adm/wrapper/-/-;
14464: $file=~s-^/adm/coursedocs/showdoc/-/-;
14465: }
1.882 albertel 14466:
1.1139 www 14467: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 14468: $location = $file;
1.609 banghart 14469: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 14470: my ($udom,$uname,$filename)=
1.811 albertel 14471: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 14472: my $home=&homeserver($uname,$udom);
14473: my $is_me=0;
14474: my @ids=¤t_machine_ids();
14475: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14476: if ($is_me) {
1.1117 foxr 14477: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 14478: } else {
14479: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14480: $udom.'/'.$uname.'/'.$filename;
14481: }
1.882 albertel 14482: } elsif ($file =~ m-^/adm/-) {
14483: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 14484: } else {
14485: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 14486: $file=~s:^/(res|priv)/:/:;
14487: my $space=$1;
1.590 banghart 14488: if ( !( $file =~ m:^/:) ) {
14489: $location = $dir. '/'.$file;
14490: } else {
1.1142 raeburn 14491: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 14492: }
1.59 albertel 14493: }
1.590 banghart 14494: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 14495: while ($location=~m{/\.\./}) {
14496: if ($location =~ m{/[^/]+/\.\./}) {
14497: $location=~ s{/[^/]+/\.\./}{/}g;
14498: } else {
14499: $location=~ s{/\.\./}{/}g;
14500: }
14501: } #remove dir/..
1.590 banghart 14502: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14503: return $location;
1.46 www 14504: }
1.36 albertel 14505:
1.46 www 14506: sub hreflocation {
14507: my ($dir,$file)=@_;
1.980 raeburn 14508: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 14509: $file=filelocation($dir,$file);
1.700 albertel 14510: } elsif ($file=~m-^/adm/-) {
14511: $file=~s-^/adm/wrapper/-/-;
14512: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 14513: }
14514: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14515: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14516: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 14517: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14518: {/uploaded/$1/$2/}x;
1.46 www 14519: }
1.913 albertel 14520: if ($file=~ m{^/userfiles/}) {
14521: $file =~ s{^/userfiles/}{/uploaded/};
14522: }
1.462 albertel 14523: return $file;
1.465 albertel 14524: }
14525:
1.1139 www 14526:
14527:
14528:
14529:
1.465 albertel 14530: sub current_machine_domains {
1.853 albertel 14531: return &machine_domains(&hostname($perlvar{'lonHostID'}));
14532: }
14533:
14534: sub machine_domains {
14535: my ($hostname) = @_;
1.465 albertel 14536: my @domains;
1.838 albertel 14537: my %hostname = &all_hostnames();
1.465 albertel 14538: while( my($id, $name) = each(%hostname)) {
1.467 matthew 14539: # &logthis("-$id-$name-$hostname-");
1.465 albertel 14540: if ($hostname eq $name) {
1.844 albertel 14541: push(@domains,&host_domain($id));
1.465 albertel 14542: }
14543: }
14544: return @domains;
14545: }
14546:
14547: sub current_machine_ids {
1.853 albertel 14548: return &machine_ids(&hostname($perlvar{'lonHostID'}));
14549: }
14550:
14551: sub machine_ids {
14552: my ($hostname) = @_;
14553: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 14554: my @ids;
1.888 albertel 14555: my %name_to_host = &all_names();
1.889 albertel 14556: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14557: return @{ $name_to_host{$hostname} };
14558: }
14559: return;
1.31 www 14560: }
14561:
1.824 raeburn 14562: sub additional_machine_domains {
14563: my @domains;
1.1466 raeburn 14564: if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
14565: if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
14566: while (my $line = <$fh>) {
14567: chomp($line);
14568: $line =~ s/\s//g;
14569: push(@domains,$line);
14570: }
14571: close($fh);
14572: }
1.824 raeburn 14573: }
14574: return @domains;
14575: }
14576:
14577: sub default_login_domain {
14578: my $domain = $perlvar{'lonDefDomain'};
14579: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14580: foreach my $posdom (¤t_machine_domains(),
14581: &additional_machine_domains()) {
14582: if (lc($posdom) eq lc($testdomain)) {
14583: $domain=$posdom;
14584: last;
14585: }
14586: }
14587: return $domain;
14588: }
14589:
1.1414 raeburn 14590: sub shared_institution {
1.1439 raeburn 14591: my ($dom,$lonhost) = @_;
14592: if ($lonhost eq '') {
14593: $lonhost = $perlvar{'lonHostID'};
14594: }
1.1414 raeburn 14595: my $same_intdom;
1.1439 raeburn 14596: my $hostintdom = &internet_dom($lonhost);
1.1414 raeburn 14597: if ($hostintdom ne '') {
14598: my %iphost = &get_iphost();
14599: my $primary_id = &domain($dom,'primary');
14600: my $primary_ip = &get_host_ip($primary_id);
14601: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14602: foreach my $id (@{$iphost{$primary_ip}}) {
14603: my $intdom = &internet_dom($id);
14604: if ($intdom eq $hostintdom) {
14605: $same_intdom = 1;
14606: last;
14607: }
14608: }
14609: }
14610: }
14611: return $same_intdom;
14612: }
14613:
1.1398 raeburn 14614: sub uses_sts {
14615: my ($ignore_cache) = @_;
14616: my $lonhost = $perlvar{'lonHostID'};
14617: my $hostname = &hostname($lonhost);
14618: my $sts_on;
14619: if ($protocol{$lonhost} eq 'https') {
14620: my $cachetime = 12*3600;
14621: if (!$ignore_cache) {
14622: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14623: if (defined($cached)) {
14624: return $sts_on;
14625: }
14626: }
14627: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14628: my $request=new HTTP::Request('HEAD',$url);
14629: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14630: if ($response->is_success) {
14631: my $has_sts = $response->header('Strict-Transport-Security');
14632: if ($has_sts eq '') {
14633: $sts_on = 0;
14634: } else {
14635: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14636: my $maxage = $1;
14637: if ($maxage) {
14638: $sts_on = 1;
14639: } else {
14640: $sts_on = 0;
14641: }
14642: } else {
14643: $sts_on = 0;
14644: }
14645: }
14646: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14647: }
14648: }
14649: return;
14650: }
14651:
1.1449 raeburn 14652: sub waf_allssl {
14653: my ($host_name) = @_;
14654: my $alias = &get_proxy_alias();
14655: if ($host_name eq '') {
14656: $host_name = $ENV{'SERVER_NAME'};
14657: }
14658: if (($host_name ne '') && ($alias eq $host_name)) {
14659: my $serverhomedom = &host_domain($perlvar{'lonHostID'});
14660: my %defdomdefaults = &get_domain_defaults($serverhomedom);
14661: if ($defdomdefaults{'waf_sslopt'}) {
14662: return $defdomdefaults{'waf_sslopt'};
14663: }
14664: }
14665: return;
14666: }
14667:
1.1434 raeburn 14668: sub get_requestor_ip {
14669: my ($r,$nolookup,$noproxy) = @_;
14670: my $from_ip;
14671: if (ref($r)) {
1.1447 raeburn 14672: if ($r->can('useragent_ip')) {
14673: if ($noproxy && $r->can('client_ip')) {
14674: $from_ip = $r->client_ip();
14675: } else {
14676: $from_ip = $r->useragent_ip();
14677: }
14678: } elsif ($r->connection->can('remote_ip')) {
14679: $from_ip = $r->connection->remote_ip();
14680: } else {
14681: $from_ip = $r->get_remote_host($nolookup);
14682: }
1.1434 raeburn 14683: } else {
14684: $from_ip = $ENV{'REMOTE_ADDR'};
14685: }
14686: return $from_ip if ($noproxy);
14687: # Who controls proxy settings for server
14688: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14689: my $proxyinfo = &get_proxy_settings($dom_in_use);
14690: if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
1.1437 raeburn 14691: if ($proxyinfo->{'vpnint'}) {
14692: if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
1.1434 raeburn 14693: return $from_ip;
14694: }
14695: }
14696: if ($proxyinfo->{'trusted'}) {
14697: if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14698: my $ipheader = $proxyinfo->{'ipheader'};
14699: my ($ip,$xfor);
14700: if (ref($r)) {
14701: if ($ipheader) {
14702: $ip = $r->headers_in->{$ipheader};
14703: }
14704: $xfor = $r->headers_in->{'X-Forwarded-For'};
14705: } else {
14706: if ($ipheader) {
14707: $ip = $ENV{'HTTP_'.uc($ipheader)};
14708: }
14709: $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14710: }
14711: if (($ip eq '') && ($xfor ne '')) {
14712: foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14713: unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14714: $ip = $poss_ip;
1.1435 raeburn 14715: last;
1.1434 raeburn 14716: }
14717: }
14718: }
14719: if ($ip ne '') {
14720: return $ip;
14721: }
14722: }
14723: }
14724: }
14725: return $from_ip;
14726: }
14727:
14728: sub get_proxy_settings {
14729: my ($dom_in_use) = @_;
14730: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
14731: my $proxyinfo = {
14732: ipheader => $domdefaults{'waf_ipheader'},
14733: trusted => $domdefaults{'waf_trusted'},
1.1437 raeburn 14734: vpnint => $domdefaults{'waf_vpnint'},
1.1438 raeburn 14735: vpnext => $domdefaults{'waf_vpnext'},
1.1449 raeburn 14736: sslopt => $domdefaults{'waf_sslopt'},
1.1434 raeburn 14737: };
14738: return $proxyinfo;
14739: }
14740:
14741: sub ip_match {
14742: my ($ip,$pattern_str) = @_;
14743: $ip=Net::CIDR::cidrvalidate($ip);
14744: if ($ip) {
14745: return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
14746: }
14747: return;
14748: }
14749:
14750: sub get_proxy_alias {
1.1450 raeburn 14751: my ($lonid) = @_;
14752: if ($lonid eq '') {
14753: $lonid = $perlvar{'lonHostID'};
14754: }
14755: if (!defined(&hostname($lonid))) {
14756: return;
14757: }
14758: if ($lonid ne '') {
14759: my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
1.1434 raeburn 14760: if ($cached) {
14761: return $alias;
14762: }
1.1450 raeburn 14763: my $dom = &Apache::lonnet::host_domain($lonid);
1.1434 raeburn 14764: if ($dom ne '') {
14765: my $cachetime = 60*60*24;
14766: my %domconfig =
1.1437 raeburn 14767: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14768: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14769: if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
1.1450 raeburn 14770: $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
14771: }
14772: }
14773: return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
14774: }
14775: }
14776: return;
14777: }
14778:
14779: sub use_proxy_alias {
14780: my ($r,$lonid) = @_;
14781: my $alias = &get_proxy_alias($lonid);
14782: if ($alias) {
14783: my $dom = &host_domain($lonid);
14784: if ($dom ne '') {
1.1467 raeburn 14785: my $proxyinfo = &get_proxy_settings($dom);
1.1450 raeburn 14786: my ($vpnint,$remote_ip);
14787: if (ref($proxyinfo) eq 'HASH') {
14788: $vpnint = $proxyinfo->{'vpnint'};
14789: if ($vpnint) {
14790: $remote_ip = &get_requestor_ip($r,1,1);
1.1434 raeburn 14791: }
14792: }
1.1450 raeburn 14793: unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
14794: return $alias;
14795: }
1.1434 raeburn 14796: }
14797: }
14798: return;
14799: }
14800:
1.1474 raeburn 14801: sub alias_sso {
1.1467 raeburn 14802: my ($lonid) = @_;
14803: if ($lonid eq '') {
14804: $lonid = $perlvar{'lonHostID'};
14805: }
14806: if (!defined(&hostname($lonid))) {
14807: return;
14808: }
14809: if ($lonid ne '') {
14810: my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
14811: if ($cached) {
14812: return $use_alias;
14813: }
14814: my $dom = &Apache::lonnet::host_domain($lonid);
14815: if ($dom ne '') {
14816: my $cachetime = 60*60*24;
14817: my %domconfig =
14818: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
14819: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14820: if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
14821: $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
14822: }
14823: }
14824: return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
14825: }
14826: }
14827: return;
14828: }
14829:
1.1465 raeburn 14830: sub get_saml_landing {
14831: my ($lonid) = @_;
14832: if ($lonid eq '') {
14833: my $defdom = &default_login_domain();
14834: my @hosts = ¤t_machine_ids();
14835: if (@hosts > 1) {
14836: foreach my $hostid (@hosts) {
14837: if (&host_domain($hostid) eq $defdom) {
14838: $lonid = $hostid;
14839: last;
14840: }
14841: }
14842: } else {
14843: $lonid = $perlvar{'lonHostID'};
14844: }
14845: if ($lonid) {
14846: unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
14847: return;
14848: }
14849: } else {
14850: return;
14851: }
14852: } elsif (!defined(&hostname($lonid))) {
14853: return;
14854: }
14855: my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
14856: if ($cached) {
14857: return $landing;
14858: }
14859: my $dom = &Apache::lonnet::host_domain($lonid);
14860: if ($dom ne '') {
14861: my $cachetime = 60*60*24;
14862: my %domconfig =
14863: &Apache::lonnet::get_dom('configuration',['login'],$dom);
14864: if (ref($domconfig{'login'}) eq 'HASH') {
14865: if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
14866: if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
14867: $landing = 1;
14868: }
14869: }
14870: }
14871: return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
14872: }
14873: return;
14874: }
14875:
1.31 www 14876: # ------------------------------------------------------------- Declutters URLs
14877:
14878: sub declutter {
14879: my $thisfn=shift;
1.569 albertel 14880: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 14881: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14882: $thisfn=~s{^/home/httpd/html}{};
14883: }
1.31 www 14884: $thisfn=~s/^\///;
1.697 albertel 14885: $thisfn=~s|^adm/wrapper/||;
14886: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 14887: $thisfn=~s/^res\///;
1.1172 bisitz 14888: $thisfn=~s/^priv\///;
1.1032 raeburn 14889: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14890: $thisfn=~s/\?.+$//;
14891: }
1.268 www 14892: return $thisfn;
14893: }
14894:
14895: # ------------------------------------------------------------- Clutter up URLs
14896:
14897: sub clutter {
14898: my $thisfn='/'.&declutter(shift);
1.887 albertel 14899: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 14900: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 14901: $thisfn='/res'.$thisfn;
14902: }
1.1031 raeburn 14903: if ($thisfn !~m|^/adm|) {
14904: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 14905: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 14906: } else {
14907: my ($ext) = ($thisfn =~ /\.(\w+)$/);
14908: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 14909: if ($embstyle eq 'ssi'
14910: || ($embstyle eq 'hdn')
14911: || ($embstyle eq 'rat')
14912: || ($embstyle eq 'prv')
14913: || ($embstyle eq 'ign')) {
14914: #do nothing with these
14915: } elsif (($embstyle eq 'img')
1.695 albertel 14916: || ($embstyle eq 'emb')
14917: || ($embstyle eq 'wrp')) {
14918: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 14919: } elsif ($embstyle eq 'unk'
14920: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 14921: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 14922: } else {
1.718 www 14923: # &logthis("Got a blank emb style");
1.695 albertel 14924: }
1.694 albertel 14925: }
1.1343 raeburn 14926: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298 raeburn 14927: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 14928: }
1.31 www 14929: return $thisfn;
1.12 www 14930: }
14931:
1.787 albertel 14932: sub clutter_with_no_wrapper {
14933: my $uri = &clutter(shift);
14934: if ($uri =~ m-^/adm/-) {
14935: $uri =~ s-^/adm/wrapper/-/-;
14936: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
14937: }
14938: return $uri;
14939: }
14940:
1.557 albertel 14941: sub freeze_escape {
14942: my ($value)=@_;
14943: if (ref($value)) {
14944: $value=&nfreeze($value);
14945: return '__FROZEN__'.&escape($value);
14946: }
14947: return &escape($value);
14948: }
14949:
1.11 www 14950:
1.557 albertel 14951: sub thaw_unescape {
14952: my ($value)=@_;
14953: if ($value =~ /^__FROZEN__/) {
14954: substr($value,0,10,undef);
14955: $value=&unescape($value);
14956: return &thaw($value);
14957: }
14958: return &unescape($value);
14959: }
14960:
1.436 albertel 14961: sub correct_line_ends {
14962: my ($result)=@_;
14963: $$result =~s/\r\n/\n/mg;
14964: $$result =~s/\r/\n/mg;
1.415 albertel 14965: }
1.1 albertel 14966: # ================================================================ Main Program
14967:
1.184 www 14968: sub goodbye {
1.204 albertel 14969: &logthis("Starting Shut down");
1.443 albertel 14970: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 14971: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 14972: #converted
1.599 albertel 14973: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 14974: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14975: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14976: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 14977: #1.1 only
1.870 albertel 14978: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14979: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14980: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14981: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14982: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 14983: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14984: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 14985: &flushcourselogs();
14986: &logthis("Shutting down");
14987: }
14988:
1.852 albertel 14989: sub get_dns {
1.1210 raeburn 14990: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 14991: if (!$ignore_cache) {
14992: my ($content,$cached)=
14993: &Apache::lonnet::is_cached_new('dns',$url);
14994: if ($cached) {
1.1210 raeburn 14995: &$func($content,$hashref);
1.869 albertel 14996: return;
14997: }
14998: }
14999:
15000: my %alldns;
1.1379 raeburn 15001: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
15002: foreach my $dns (<$config>) {
15003: next if ($dns !~ /^\^(\S*)/x);
15004: my $line = $1;
15005: my ($host,$protocol) = split(/:/,$line);
15006: if ($protocol ne 'https') {
15007: $protocol = 'http';
15008: }
15009: $alldns{$host} = $protocol;
1.979 raeburn 15010: }
1.1379 raeburn 15011: close($config);
1.869 albertel 15012: }
15013: while (%alldns) {
1.1263 raeburn 15014: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1456 raeburn 15015: my ($contents,@content);
15016: if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15017: my $command = (split('/',$url))[3];
15018: my ($dir,$file) = &parse_getdns_url($command,$url);
15019: delete($alldns{$dns});
15020: next if (($dir eq '') || ($file eq ''));
15021: if (open(my $config,'<',"$dir/$file")) {
1.1457 raeburn 15022: @content = <$config>;
1.1456 raeburn 15023: close($config);
15024: }
15025: if ($url eq '/adm/dns/loncapaCRL') {
15026: $contents = join('',@content);
15027: }
15028: } else {
15029: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15030: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15031: delete($alldns{$dns});
15032: next if ($response->is_error());
15033: if ($url eq '/adm/dns/loncapaCRL') {
15034: $contents = $response->content;
15035: } else {
15036: @content = split("\n",$response->content);
15037: }
15038: }
1.1379 raeburn 15039: if ($url eq '/adm/dns/loncapaCRL') {
1.1456 raeburn 15040: return &$func($contents);
1.1379 raeburn 15041: } else {
15042: unless ($nocache) {
15043: &do_cache_new('dns',$url,\@content,30*24*60*60);
15044: }
15045: &$func(\@content,$hashref);
15046: return;
15047: }
15048: }
15049: my $which = (split('/',$url,4))[3];
15050: if ($which eq 'loncapaCRL') {
15051: my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15052: if (-e $diskfile) {
15053: &logthis("unable to contact DNS, on disk file $diskfile not updated");
15054: } else {
15055: &logthis("unable to contact DNS, no on disk file $diskfile available");
15056: }
15057: } else {
15058: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15059: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15060: my @content = <$config>;
15061: close($config);
15062: &$func(\@content,$hashref);
15063: }
1.852 albertel 15064: }
1.1210 raeburn 15065: return;
15066: }
15067:
15068: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 15069: sub parse_dns_checksums_tab {
1.1210 raeburn 15070: my ($lines,$hashref) = @_;
1.1264 raeburn 15071: my $lonhost = $perlvar{'lonHostID'};
15072: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 15073: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 15074: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15075: my $webconfdir = '/etc/httpd/conf';
15076: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15077: $webconfdir = '/etc/apache2';
15078: } elsif ($distro =~ /^sles(\d+)$/) {
15079: if ($1 >= 10) {
15080: $webconfdir = '/etc/apache2';
15081: }
15082: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15083: if ($1 >= 10.0) {
15084: $webconfdir = '/etc/apache2';
15085: }
15086: }
1.1210 raeburn 15087: my ($release,$timestamp) = split(/\-/,$loncaparev);
15088: my (%chksum,%revnum);
15089: if (ref($lines) eq 'ARRAY') {
15090: chomp(@{$lines});
1.1238 raeburn 15091: my $version = shift(@{$lines});
15092: if ($version eq $release) {
1.1210 raeburn 15093: foreach my $line (@{$lines}) {
1.1238 raeburn 15094: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 15095: if ($file =~ m{^/etc/httpd/conf}) {
15096: if ($webconfdir eq '/etc/apache2') {
15097: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15098: }
15099: }
1.1238 raeburn 15100: $chksum{$file} = $shasum;
15101: $revnum{$file} = $version;
1.1210 raeburn 15102: }
15103: if (ref($hashref) eq 'HASH') {
15104: %{$hashref} = (
15105: sums => \%chksum,
15106: versions => \%revnum,
15107: );
15108: }
15109: }
15110: }
1.869 albertel 15111: return;
1.852 albertel 15112: }
1.1210 raeburn 15113:
15114: sub fetch_dns_checksums {
1.1238 raeburn 15115: my %checksums;
15116: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 15117: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 15118: my ($release,$timestamp) = split(/\-/,$loncaparev);
15119: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 15120: \%checksums);
1.1210 raeburn 15121: return \%checksums;
15122: }
15123:
1.1379 raeburn 15124: sub fetch_crl_pemfile {
15125: return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15126: }
15127:
15128: sub save_crl_pem {
1.1456 raeburn 15129: my ($content) = @_;
1.1380 raeburn 15130: my ($msg,$hadchanges);
1.1456 raeburn 15131: if ($content ne '') {
1.1379 raeburn 15132: my $now = time;
15133: my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15134: my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15135: if (open(my $fh,'>',"$tmpcrl")) {
1.1456 raeburn 15136: print $fh $content;
1.1379 raeburn 15137: close($fh);
15138: if (-e $lonca) {
15139: if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15140: my $check = <PIPE>;
15141: close(PIPE);
15142: chomp($check);
15143: if ($check eq 'verify OK') {
15144: my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380 raeburn 15145: my $backup;
1.1379 raeburn 15146: if (-e $dest) {
1.1380 raeburn 15147: if (&File::Copy::move($dest,"$dest.bak")) {
15148: $backup = 'ok';
15149: }
1.1379 raeburn 15150: }
15151: if (&File::Copy::move($tmpcrl,$dest)) {
15152: $msg = 'ok';
1.1380 raeburn 15153: if ($backup) {
15154: my (%oldnums,%newnums);
15155: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15156: while (<PIPE>) {
15157: $oldnums{(split(/:/))[1]} = 1;
15158: }
15159: close(PIPE);
15160: }
15161: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15162: while(<PIPE>) {
15163: $newnums{(split(/:/))[1]} = 1;
15164: }
15165: close(PIPE);
15166: }
15167: foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15168: unless (exists($oldnums{$key})) {
15169: $hadchanges = 1;
15170: last;
15171: }
15172: }
15173: unless ($hadchanges) {
15174: foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15175: unless (exists($newnums{$key})) {
15176: $hadchanges = 1;
15177: last;
15178: }
15179: }
15180: }
15181: }
1.1379 raeburn 15182: }
15183: } else {
15184: unlink($tmpcrl);
15185: }
15186: } else {
15187: unlink($tmpcrl);
15188: }
15189: } else {
15190: unlink($tmpcrl);
15191: }
15192: }
15193: }
1.1380 raeburn 15194: return ($msg,$hadchanges);
1.1379 raeburn 15195: }
15196:
1.1456 raeburn 15197: sub parse_getdns_url {
15198: my ($command,$url) = @_;
15199: my $dir = $perlvar{'lonTabDir'};
15200: my $file;
15201: if ($command eq 'hosts') {
15202: $file = 'dns_hosts.tab';
15203: } elsif ($command eq 'domain') {
15204: $file = 'dns_domain.tab';
15205: } elsif ($command eq 'checksums') {
15206: my $version = (split('/',$url))[4];
15207: $file = "dns_checksums/$version.tab",
15208: } elsif ($command eq 'loncapaCRL') {
15209: $dir = $perlvar{'lonCertificateDirectory'};
15210: $file = $perlvar{'lonnetCertRevocationList'};
15211: }
15212: return ($dir,$file);
15213: }
15214:
1.327 albertel 15215: # ------------------------------------------------------------ Read domain file
15216: {
1.852 albertel 15217: my $loaded;
1.846 albertel 15218: my %domain;
15219:
1.852 albertel 15220: sub parse_domain_tab {
15221: my ($lines) = @_;
15222: foreach my $line (@$lines) {
15223: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 15224:
1.846 albertel 15225: chomp($line);
1.852 albertel 15226: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 15227: my %this_domain;
15228: foreach my $field ('description', 'auth_def', 'auth_arg_def',
15229: 'lang_def', 'city', 'longi', 'lati',
15230: 'primary') {
15231: $this_domain{$field} = shift(@elements);
15232: }
15233: $domain{$name} = \%this_domain;
1.852 albertel 15234: }
15235: }
1.864 albertel 15236:
15237: sub reset_domain_info {
15238: undef($loaded);
15239: undef(%domain);
15240: }
15241:
1.852 albertel 15242: sub load_domain_tab {
1.1293 raeburn 15243: my ($ignore_cache,$nocache) = @_;
15244: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 15245: my $fh;
1.1359 raeburn 15246: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 15247: my @lines = <$fh>;
15248: &parse_domain_tab(\@lines);
1.448 albertel 15249: }
1.852 albertel 15250: close($fh);
15251: $loaded = 1;
1.327 albertel 15252: }
1.846 albertel 15253:
15254: sub domain {
1.852 albertel 15255: &load_domain_tab() if (!$loaded);
15256:
1.846 albertel 15257: my ($name,$what) = @_;
15258: return if ( !exists($domain{$name}) );
15259:
15260: if (!$what) {
15261: return $domain{$name}{'description'};
15262: }
15263: return $domain{$name}{$what};
15264: }
1.974 raeburn 15265:
15266: sub domain_info {
15267: &load_domain_tab() if (!$loaded);
15268: return %domain;
15269: }
15270:
1.327 albertel 15271: }
15272:
15273:
1.1 albertel 15274: # ------------------------------------------------------------- Read hosts file
15275: {
1.838 albertel 15276: my %hostname;
1.844 albertel 15277: my %hostdom;
1.845 albertel 15278: my %libserv;
1.852 albertel 15279: my $loaded;
1.888 albertel 15280: my %name_to_host;
1.1074 raeburn 15281: my %internetdom;
1.1107 raeburn 15282: my %LC_dns_serv;
1.852 albertel 15283:
15284: sub parse_hosts_tab {
15285: my ($file) = @_;
15286: foreach my $configline (@$file) {
15287: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 15288: chomp($configline);
15289: if ($configline =~ /^\^/) {
15290: if ($configline =~ /^\^([\w.\-]+)/) {
15291: $LC_dns_serv{$1} = 1;
15292: }
15293: next;
15294: }
1.1074 raeburn 15295: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 15296: $name=~s/\s//g;
15297: if ($id && $domain && $role && $name) {
1.1351 raeburn 15298: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15299: my $curr = $hostname{$id};
15300: my $skip;
15301: if (ref($name_to_host{$curr}) eq 'ARRAY') {
15302: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15303: $skip = 1;
15304: } else {
15305: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15306: }
15307: }
15308: unless ($skip) {
15309: push(@{$name_to_host{$name}},$id);
15310: }
15311: } else {
15312: push(@{$name_to_host{$name}},$id);
15313: }
1.852 albertel 15314: $hostname{$id}=$name;
15315: $hostdom{$id}=$domain;
15316: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 15317: if (defined($protocol)) {
15318: if ($protocol eq 'https') {
15319: $protocol{$id} = $protocol;
15320: } else {
15321: $protocol{$id} = 'http';
15322: }
1.968 raeburn 15323: } else {
1.969 raeburn 15324: $protocol{$id} = 'http';
1.968 raeburn 15325: }
1.1074 raeburn 15326: if (defined($intdom)) {
15327: $internetdom{$id} = $intdom;
15328: }
1.852 albertel 15329: }
15330: }
15331: }
1.864 albertel 15332:
15333: sub reset_hosts_info {
1.897 albertel 15334: &purge_remembered();
1.864 albertel 15335: &reset_domain_info();
15336: &reset_hosts_ip_info();
1.1339 raeburn 15337: undef(%internetdom);
1.892 albertel 15338: undef(%name_to_host);
1.864 albertel 15339: undef(%hostname);
15340: undef(%hostdom);
15341: undef(%libserv);
15342: undef($loaded);
15343: }
1.1 albertel 15344:
1.852 albertel 15345: sub load_hosts_tab {
1.1293 raeburn 15346: my ($ignore_cache,$nocache) = @_;
15347: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359 raeburn 15348: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 15349: my @config = <$config>;
15350: &parse_hosts_tab(\@config);
15351: close($config);
15352: $loaded=1;
1.1 albertel 15353: }
1.852 albertel 15354:
1.838 albertel 15355: sub hostname {
1.852 albertel 15356: &load_hosts_tab() if (!$loaded);
15357:
1.838 albertel 15358: my ($lonid) = @_;
15359: return $hostname{$lonid};
15360: }
1.845 albertel 15361:
1.838 albertel 15362: sub all_hostnames {
1.852 albertel 15363: &load_hosts_tab() if (!$loaded);
15364:
1.838 albertel 15365: return %hostname;
15366: }
1.845 albertel 15367:
1.888 albertel 15368: sub all_names {
1.1293 raeburn 15369: my ($ignore_cache,$nocache) = @_;
15370: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 15371:
15372: return %name_to_host;
15373: }
15374:
1.974 raeburn 15375: sub all_host_domain {
15376: &load_hosts_tab() if (!$loaded);
15377: return %hostdom;
15378: }
15379:
1.1339 raeburn 15380: sub all_host_intdom {
15381: &load_hosts_tab() if (!$loaded);
15382: return %internetdom;
15383: }
15384:
1.845 albertel 15385: sub is_library {
1.852 albertel 15386: &load_hosts_tab() if (!$loaded);
15387:
1.845 albertel 15388: return exists($libserv{$_[0]});
15389: }
15390:
15391: sub all_library {
1.852 albertel 15392: &load_hosts_tab() if (!$loaded);
15393:
1.845 albertel 15394: return %libserv;
15395: }
15396:
1.1062 droeschl 15397: sub unique_library {
15398: #2x reverse removes all hostnames that appear more than once
15399: my %unique = reverse &all_library();
15400: return reverse %unique;
15401: }
15402:
1.841 albertel 15403: sub get_servers {
1.852 albertel 15404: &load_hosts_tab() if (!$loaded);
15405:
1.841 albertel 15406: my ($domain,$type) = @_;
15407: my %possible_hosts = ($type eq 'library') ? %libserv
15408: : %hostname;
15409: my %result;
1.842 albertel 15410: if (ref($domain) eq 'ARRAY') {
15411: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 15412: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 15413: $result{$host} = $hostname;
15414: }
15415: }
15416: } else {
15417: while ( my ($host,$hostname) = each(%possible_hosts)) {
15418: if ($hostdom{$host} eq $domain) {
15419: $result{$host} = $hostname;
15420: }
1.841 albertel 15421: }
15422: }
15423: return %result;
15424: }
1.845 albertel 15425:
1.1062 droeschl 15426: sub get_unique_servers {
15427: my %unique = reverse &get_servers(@_);
15428: return reverse %unique;
15429: }
15430:
1.844 albertel 15431: sub host_domain {
1.852 albertel 15432: &load_hosts_tab() if (!$loaded);
15433:
1.844 albertel 15434: my ($lonid) = @_;
15435: return $hostdom{$lonid};
15436: }
15437:
1.841 albertel 15438: sub all_domains {
1.852 albertel 15439: &load_hosts_tab() if (!$loaded);
15440:
1.841 albertel 15441: my %seen;
15442: my @uniq = grep(!$seen{$_}++, values(%hostdom));
15443: return @uniq;
15444: }
1.1074 raeburn 15445:
15446: sub internet_dom {
15447: &load_hosts_tab() if (!$loaded);
15448:
15449: my ($lonid) = @_;
15450: return $internetdom{$lonid};
15451: }
1.1107 raeburn 15452:
15453: sub is_LC_dns {
15454: &load_hosts_tab() if (!$loaded);
15455:
15456: my ($hostname) = @_;
15457: return exists($LC_dns_serv{$hostname});
15458: }
15459:
1.1 albertel 15460: }
15461:
1.847 albertel 15462: {
15463: my %iphost;
1.856 albertel 15464: my %name_to_ip;
15465: my %lonid_to_ip;
1.869 albertel 15466:
1.847 albertel 15467: sub get_hosts_from_ip {
15468: my ($ip) = @_;
15469: my %iphosts = &get_iphost();
15470: if (ref($iphosts{$ip})) {
15471: return @{$iphosts{$ip}};
15472: }
15473: return;
1.839 albertel 15474: }
1.864 albertel 15475:
15476: sub reset_hosts_ip_info {
15477: undef(%iphost);
15478: undef(%name_to_ip);
15479: undef(%lonid_to_ip);
15480: }
1.856 albertel 15481:
15482: sub get_host_ip {
15483: my ($lonid) = @_;
15484: if (exists($lonid_to_ip{$lonid})) {
15485: return $lonid_to_ip{$lonid};
15486: }
15487: my $name=&hostname($lonid);
15488: my $ip = gethostbyname($name);
15489: return if (!$ip || length($ip) ne 4);
15490: $ip=inet_ntoa($ip);
15491: $name_to_ip{$name} = $ip;
15492: $lonid_to_ip{$lonid} = $ip;
15493: return $ip;
15494: }
1.847 albertel 15495:
15496: sub get_iphost {
1.1293 raeburn 15497: my ($ignore_cache,$nocache) = @_;
1.894 albertel 15498:
1.869 albertel 15499: if (!$ignore_cache) {
15500: if (%iphost) {
15501: return %iphost;
15502: }
15503: my ($ip_info,$cached)=
15504: &Apache::lonnet::is_cached_new('iphost','iphost');
15505: if ($cached) {
15506: %iphost = %{$ip_info->[0]};
15507: %name_to_ip = %{$ip_info->[1]};
15508: %lonid_to_ip = %{$ip_info->[2]};
15509: return %iphost;
15510: }
15511: }
1.894 albertel 15512:
15513: # get yesterday's info for fallback
15514: my %old_name_to_ip;
15515: my ($ip_info,$cached)=
15516: &Apache::lonnet::is_cached_new('iphost','iphost');
15517: if ($cached) {
15518: %old_name_to_ip = %{$ip_info->[1]};
15519: }
15520:
1.1293 raeburn 15521: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 15522: foreach my $name (keys(%name_to_host)) {
1.847 albertel 15523: my $ip;
15524: if (!exists($name_to_ip{$name})) {
15525: $ip = gethostbyname($name);
15526: if (!$ip || length($ip) ne 4) {
1.894 albertel 15527: if (defined($old_name_to_ip{$name})) {
15528: $ip = $old_name_to_ip{$name};
15529: &logthis("Can't find $name defaulting to old $ip");
15530: } else {
15531: &logthis("Name $name no IP found");
15532: next;
15533: }
15534: } else {
15535: $ip=inet_ntoa($ip);
1.847 albertel 15536: }
15537: $name_to_ip{$name} = $ip;
15538: } else {
15539: $ip = $name_to_ip{$name};
1.653 albertel 15540: }
1.888 albertel 15541: foreach my $id (@{ $name_to_host{$name} }) {
15542: $lonid_to_ip{$id} = $ip;
15543: }
15544: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 15545: }
1.1293 raeburn 15546: unless ($nocache) {
15547: &do_cache_new('iphost','iphost',
15548: [\%iphost,\%name_to_ip,\%lonid_to_ip],
15549: 48*60*60);
15550: }
1.869 albertel 15551:
1.847 albertel 15552: return %iphost;
1.598 albertel 15553: }
15554:
1.992 raeburn 15555: #
15556: # Given a DNS returns the loncapa host name for that DNS
15557: #
15558: sub host_from_dns {
15559: my ($dns) = @_;
15560: my @hosts;
15561: my $ip;
15562:
1.993 raeburn 15563: if (exists($name_to_ip{$dns})) {
1.992 raeburn 15564: $ip = $name_to_ip{$dns};
15565: }
15566: if (!$ip) {
15567: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15568: if (length($ip) == 4) {
15569: $ip = &IO::Socket::inet_ntoa($ip);
15570: }
15571: }
15572: if ($ip) {
15573: @hosts = get_hosts_from_ip($ip);
15574: return $hosts[0];
15575: }
15576: return undef;
1.986 foxr 15577: }
1.992 raeburn 15578:
1.1074 raeburn 15579: sub get_internet_names {
15580: my ($lonid) = @_;
15581: return if ($lonid eq '');
15582: my ($idnref,$cached)=
15583: &Apache::lonnet::is_cached_new('internetnames',$lonid);
15584: if ($cached) {
15585: return $idnref;
15586: }
15587: my $ip = &get_host_ip($lonid);
15588: my @hosts = &get_hosts_from_ip($ip);
15589: my %iphost = &get_iphost();
15590: my (@idns,%seen);
15591: foreach my $id (@hosts) {
15592: my $dom = &host_domain($id);
15593: my $prim_id = &domain($dom,'primary');
15594: my $prim_ip = &get_host_ip($prim_id);
15595: next if ($seen{$prim_ip});
15596: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15597: foreach my $id (@{$iphost{$prim_ip}}) {
15598: my $intdom = &internet_dom($id);
15599: unless (grep(/^\Q$intdom\E$/,@idns)) {
15600: push(@idns,$intdom);
15601: }
15602: }
15603: }
15604: $seen{$prim_ip} = 1;
15605: }
1.1219 raeburn 15606: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 15607: }
15608:
1.986 foxr 15609: }
15610:
1.1079 raeburn 15611: sub all_loncaparevs {
1.1249 raeburn 15612: 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 15613: }
15614:
1.1227 raeburn 15615: # ---------------------------------------------------------- Read loncaparev table
15616: {
15617: sub load_loncaparevs {
15618: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359 raeburn 15619: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227 raeburn 15620: while (my $configline=<$config>) {
15621: chomp($configline);
15622: my ($hostid,$loncaparev)=split(/:/,$configline);
15623: $loncaparevs{$hostid}=$loncaparev;
15624: }
15625: close($config);
15626: }
15627: }
15628: }
15629: }
15630:
15631: # ---------------------------------------------------------- Read serverhostID table
15632: {
15633: sub load_serverhomeIDs {
15634: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359 raeburn 15635: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227 raeburn 15636: while (my $configline=<$config>) {
15637: chomp($configline);
15638: my ($name,$id)=split(/:/,$configline);
15639: $serverhomeIDs{$name}=$id;
15640: }
15641: close($config);
15642: }
15643: }
15644: }
15645: }
15646:
15647:
1.862 albertel 15648: BEGIN {
15649:
15650: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15651: unless ($readit) {
15652: {
15653: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15654: %perlvar = (%perlvar,%{$configvars});
15655: }
15656:
15657:
1.1 albertel 15658: # ------------------------------------------------------ Read spare server file
15659: {
1.1359 raeburn 15660: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 15661:
15662: while (my $configline=<$config>) {
15663: chomp($configline);
1.284 matthew 15664: if ($configline) {
1.784 albertel 15665: my ($host,$type) = split(':',$configline,2);
1.785 albertel 15666: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 15667: push(@{ $spareid{$type} }, $host);
1.1 albertel 15668: }
15669: }
1.448 albertel 15670: close($config);
1.1 albertel 15671: }
1.11 www 15672: # ------------------------------------------------------------ Read permissions
15673: {
1.1359 raeburn 15674: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 15675:
15676: while (my $configline=<$config>) {
1.448 albertel 15677: chomp($configline);
15678: if ($configline) {
15679: my ($role,$perm)=split(/ /,$configline);
15680: if ($perm ne '') { $pr{$role}=$perm; }
15681: }
1.11 www 15682: }
1.448 albertel 15683: close($config);
1.11 www 15684: }
15685:
15686: # -------------------------------------------- Read plain texts for permissions
15687: {
1.1359 raeburn 15688: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 15689:
15690: while (my $configline=<$config>) {
1.448 albertel 15691: chomp($configline);
15692: if ($configline) {
1.742 raeburn 15693: my ($short,@plain)=split(/:/,$configline);
15694: %{$prp{$short}} = ();
15695: if (@plain > 0) {
15696: $prp{$short}{'std'} = $plain[0];
15697: for (my $i=1; $i<@plain; $i++) {
15698: $prp{$short}{'alt'.$i} = $plain[$i];
15699: }
15700: }
1.448 albertel 15701: }
1.135 www 15702: }
1.448 albertel 15703: close($config);
1.135 www 15704: }
15705:
15706: # ---------------------------------------------------------- Read package table
15707: {
1.1359 raeburn 15708: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 15709:
15710: while (my $configline=<$config>) {
1.483 albertel 15711: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 15712: chomp($configline);
15713: my ($short,$plain)=split(/:/,$configline);
15714: my ($pack,$name)=split(/\&/,$short);
15715: if ($plain ne '') {
15716: $packagetab{$pack.'&'.$name.'&name'}=$name;
15717: $packagetab{$short}=$plain;
15718: }
1.11 www 15719: }
1.448 albertel 15720: close($config);
1.329 matthew 15721: }
15722:
1.1073 raeburn 15723: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 15724:
15725: &load_loncaparevs();
1.1073 raeburn 15726:
1.1074 raeburn 15727: # ---------------------------------------------------------- Read serverhostID table
15728:
1.1227 raeburn 15729: &load_serverhomeIDs();
15730:
15731: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 15732: {
15733: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15734: if (-e $file) {
15735: my $parser = HTML::LCParser->new($file);
15736: while (my $token = $parser->get_token()) {
15737: if ($token->[0] eq 'S') {
15738: my $item = $token->[1];
15739: my $name = $token->[2]{'name'};
15740: my $value = $token->[2]{'value'};
1.1285 raeburn 15741: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 15742: my $namematch = $token->[2]{'namematch'};
15743: if ($item eq 'parameter') {
15744: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15745: my $release = $parser->get_text();
15746: $release =~ s/(^\s*|\s*$ )//gx;
15747: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15748: }
15749: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 15750: my $release = $parser->get_text();
15751: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 15752: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 15753: }
15754: }
15755: }
15756: }
1.1073 raeburn 15757: }
15758:
1.1138 raeburn 15759: # ---------------------------------------------------------- Read managers table
15760: {
15761: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359 raeburn 15762: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 15763: while (my $configline=<$config>) {
15764: chomp($configline);
15765: next if ($configline =~ /^\#/);
15766: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15767: $managerstab{$configline} = 1;
15768: }
15769: }
15770: close($config);
15771: }
15772: }
15773: }
15774:
1.329 matthew 15775: # ------------- set up temporary directory
15776: {
1.1117 foxr 15777: $tmpdir = LONCAPA::tempdir();
1.329 matthew 15778:
1.11 www 15779: }
15780:
1.1405 raeburn 15781: # ------------- set default texengine (domain default overrides this)
15782: {
15783: $deftex = LONCAPA::texengine();
15784: }
15785:
1.1416 raeburn 15786: # ------------- set default minimum length for passwords for internal auth users
15787: {
15788: $passwdmin = LONCAPA::passwd_min();
15789: }
15790:
1.794 albertel 15791: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
15792: 'compress_threshold'=> 20_000,
15793: });
1.185 www 15794:
1.281 www 15795: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 15796: $dumpcount=0;
1.958 www 15797: $locknum=0;
1.22 www 15798:
1.163 harris41 15799: &logtouch();
1.672 albertel 15800: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 15801: $readit=1;
1.564 albertel 15802: {
15803: use integer;
15804: my $test=(2**32)+1;
1.568 albertel 15805: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 15806: &logthis(" Detected 64bit platform ($_64bit)");
15807: }
1.195 www 15808: }
1.1 albertel 15809: }
1.179 www 15810:
1.1 albertel 15811: 1;
1.191 harris41 15812: __END__
15813:
1.243 albertel 15814: =pod
15815:
1.191 harris41 15816: =head1 NAME
15817:
1.243 albertel 15818: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 15819:
15820: =head1 SYNOPSIS
15821:
1.243 albertel 15822: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 15823:
15824: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15825:
1.243 albertel 15826: Common parameters:
15827:
15828: =over 4
15829:
15830: =item *
15831:
15832: $uname : an internal username (if $cname expecting a course Id specifically)
15833:
15834: =item *
15835:
15836: $udom : a domain (if $cdom expecting a course's domain specifically)
15837:
15838: =item *
15839:
15840: $symb : a resource instance identifier
15841:
15842: =item *
15843:
15844: $namespace : the name of a .db file that contains the data needed or
15845: being set.
15846:
15847: =back
15848:
1.394 bowersj2 15849: =head1 OVERVIEW
1.191 harris41 15850:
1.394 bowersj2 15851: lonnet provides subroutines which interact with the
15852: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15853: about classes, users, and resources.
1.243 albertel 15854:
15855: For many of these objects you can also use this to store data about
15856: them or modify them in various ways.
1.191 harris41 15857:
1.394 bowersj2 15858: =head2 Symbs
1.191 harris41 15859:
1.394 bowersj2 15860: To identify a specific instance of a resource, LON-CAPA uses symbols
15861: or "symbs"X<symb>. These identifiers are built from the URL of the
15862: map, the resource number of the resource in the map, and the URL of
15863: the resource itself. The latter is somewhat redundant, but might help
15864: if maps change.
15865:
15866: An example is
15867:
15868: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15869:
15870: The respective map entry is
15871:
15872: <resource id="19" src="/res/msu/korte/tests/part12.problem"
15873: title="Problem 2">
15874: </resource>
15875:
15876: Symbs are used by the random number generator, as well as to store and
15877: restore data specific to a certain instance of for example a problem.
15878:
15879: =head2 Storing And Retrieving Data
15880:
15881: X<store()>X<cstore()>X<restore()>Three of the most important functions
15882: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15883: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15884: is is the non-critical message twin of cstore. These functions are for
15885: handlers to store a perl hash to a user's permanent data space in an
15886: easy manner, and to retrieve it again on another call. It is expected
15887: that a handler would use this once at the beginning to retrieve data,
15888: and then again once at the end to send only the new data back.
15889:
15890: The data is stored in the user's data directory on the user's
15891: homeserver under the ID of the course.
15892:
15893: The hash that is returned by restore will have all of the previous
15894: value for all of the elements of the hash.
15895:
15896: Example:
15897:
15898: #creating a hash
15899: my %hash;
15900: $hash{'foo'}='bar';
15901:
15902: #storing it
15903: &Apache::lonnet::cstore(\%hash);
15904:
15905: #changing a value
15906: $hash{'foo'}='notbar';
15907:
15908: #adding a new value
15909: $hash{'bar'}='foo';
15910: &Apache::lonnet::cstore(\%hash);
15911:
15912: #retrieving the hash
15913: my %history=&Apache::lonnet::restore();
15914:
15915: #print the hash
15916: foreach my $key (sort(keys(%history))) {
15917: print("\%history{$key} = $history{$key}");
15918: }
15919:
15920: Will print out:
1.191 harris41 15921:
1.394 bowersj2 15922: %history{1:foo} = bar
15923: %history{1:keys} = foo:timestamp
15924: %history{1:timestamp} = 990455579
15925: %history{2:bar} = foo
15926: %history{2:foo} = notbar
15927: %history{2:keys} = foo:bar:timestamp
15928: %history{2:timestamp} = 990455580
15929: %history{bar} = foo
15930: %history{foo} = notbar
15931: %history{timestamp} = 990455580
15932: %history{version} = 2
15933:
15934: Note that the special hash entries C<keys>, C<version> and
15935: C<timestamp> were added to the hash. C<version> will be equal to the
15936: total number of versions of the data that have been stored. The
15937: C<timestamp> attribute will be the UNIX time the hash was
15938: stored. C<keys> is available in every historical section to list which
15939: keys were added or changed at a specific historical revision of a
15940: hash.
15941:
15942: B<Warning>: do not store the hash that restore returns directly. This
15943: will cause a mess since it will restore the historical keys as if the
15944: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 15945:
1.394 bowersj2 15946: Calling convention:
1.191 harris41 15947:
1.1225 raeburn 15948: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 15949: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 15950:
1.394 bowersj2 15951: For more detailed information, see lonnet specific documentation.
1.191 harris41 15952:
1.394 bowersj2 15953: =head1 RETURN MESSAGES
1.191 harris41 15954:
1.394 bowersj2 15955: =over 4
1.191 harris41 15956:
1.394 bowersj2 15957: =item * B<con_lost>: unable to contact remote host
1.191 harris41 15958:
1.394 bowersj2 15959: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15960: when the connection is brought back up
1.191 harris41 15961:
1.394 bowersj2 15962: =item * B<con_failed>: unable to contact remote host and unable to save message
15963: for later delivery
1.191 harris41 15964:
1.967 bisitz 15965: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 15966:
1.394 bowersj2 15967: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 15968: that was requested
1.191 harris41 15969:
1.243 albertel 15970: =back
1.191 harris41 15971:
1.243 albertel 15972: =head1 PUBLIC SUBROUTINES
1.191 harris41 15973:
1.243 albertel 15974: =head2 Session Environment Functions
1.191 harris41 15975:
1.243 albertel 15976: =over 4
1.191 harris41 15977:
1.394 bowersj2 15978: =item *
15979: X<appenv()>
1.949 raeburn 15980: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 15981: the user envirnoment file, and will be restored for each access this
1.620 albertel 15982: user makes during this session, also modifies the %env for the current
1.949 raeburn 15983: process. Optional rolesarrayref - if defined contains a reference to an array
15984: of roles which are exempt from the restriction on modifying user.role entries
15985: in the user's environment.db and in %env.
1.191 harris41 15986:
15987: =item *
1.394 bowersj2 15988: X<delenv()>
1.987 raeburn 15989: B<delenv($delthis,$regexp)>: removes all items from the session
15990: environment file that begin with $delthis. If the
15991: optional second arg - $regexp - is true, $delthis is treated as a
15992: regular expression, otherwise \Q$delthis\E is used.
15993: The values are also deleted from the current processes %env.
1.191 harris41 15994:
1.795 albertel 15995: =item * get_env_multiple($name)
15996:
15997: gets $name from the %env hash, it seemlessly handles the cases where multiple
15998: values may be defined and end up as an array ref.
15999:
16000: returns an array of values
16001:
1.243 albertel 16002: =back
16003:
16004: =head2 User Information
1.191 harris41 16005:
1.243 albertel 16006: =over 4
1.191 harris41 16007:
16008: =item *
1.394 bowersj2 16009: X<queryauthenticate()>
16010: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 16011: authentication scheme
16012:
16013: =item *
1.394 bowersj2 16014: X<authenticate()>
1.1073 raeburn 16015: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 16016: authenticate user from domain's lib servers (first use the current
16017: one). C<$upass> should be the users password.
1.1073 raeburn 16018: $checkdefauth is optional (value is 1 if a check should be made to
16019: authenticate user using default authentication method, and allow
16020: account creation if username does not have account in the domain).
16021: $clientcancheckhost is optional (value is 1 if checking whether the
16022: server can host will occur on the client side in lonauth.pm).
1.191 harris41 16023:
16024: =item *
1.394 bowersj2 16025: X<homeserver()>
16026: B<homeserver($uname,$udom)>: find the server which has
16027: the user's directory and files (there must be only one), this caches
16028: the answer, and also caches if there is a borken connection.
1.191 harris41 16029:
16030: =item *
1.394 bowersj2 16031: X<idget()>
1.1300 raeburn 16032: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
16033: a list of student/employee IDs or clicker IDs
16034: (student/employee IDs are a unique resource in a domain, there must be
16035: only 1 ID per username, and only 1 username per ID in a specific domain).
16036: clickerIDs are not necessarily unique, as students might share clickers.
16037: (returns hash: id=>name,id=>name)
1.191 harris41 16038:
16039: =item *
1.394 bowersj2 16040: X<idrget()>
16041: B<idrget($udom,@unames)>: find the IDs behind a list of
16042: usernames (returns hash: name=>id,name=>id)
1.191 harris41 16043:
16044: =item *
1.394 bowersj2 16045: X<idput()>
1.1300 raeburn 16046: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
16047: names and associated student/employee IDs or clicker IDs.
16048:
16049: =item *
16050: X<iddel()>
16051: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
16052: student/employee ID or clicker ID username look-ups from domain.
16053: The homeserver ($uhome) and namespace ($namespace) are optional.
16054: If no $uhome is provided, it will be determined usig &homeserver()
16055: for each user. If no $namespace is provided, the default is ids.
16056:
16057: =item *
16058: X<updateclickers()>
16059: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
16060: clicker ID-to-username look-ups in clickers.db on library server.
16061: Permitted actions are add or del (i.e., add or delete). The
16062: clickers.db contains clickerID as keys (escaped), and each corresponding
16063: value is an escaped comma-separated list of usernames (for whom the
16064: library server is the homeserver), who registered that particular ID.
16065: If $critical is true, the update will be sent via &critical, otherwise
16066: &reply() will be used.
1.191 harris41 16067:
16068: =item *
1.394 bowersj2 16069: X<rolesinit()>
1.1169 droeschl 16070: B<rolesinit($udom,$username)>: get user privileges.
16071: returns user role, first access and timer interval hashes
1.243 albertel 16072:
16073: =item *
1.1171 droeschl 16074: X<privileged()>
16075: B<privileged($username,$domain)>: returns a true if user has a
16076: privileged and active role (i.e. su or dc), false otherwise.
16077:
16078: =item *
1.551 albertel 16079: X<getsection()>
16080: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 16081: course $cname, return section name/number or '' for "not in course"
16082: and '-1' for "no section"
16083:
16084: =item *
1.394 bowersj2 16085: X<userenvironment()>
16086: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 16087: passed in @what from the requested user's environment, returns a hash
16088:
1.858 raeburn 16089: =item *
16090: X<userlog_query()>
1.859 albertel 16091: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16092: activity.log file. %filters defines filters applied when parsing the
16093: log file. These can be start or end timestamps, or the type of action
16094: - log to look for Login or Logout events, check for Checkin or
16095: Checkout, role for role selection. The response is in the form
16096: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
16097: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 16098:
1.243 albertel 16099: =back
16100:
16101: =head2 User Roles
16102:
16103: =over 4
16104:
16105: =item *
16106:
1.1284 raeburn 16107: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
16108: returns codes for allowed actions.
16109:
16110: The first argument is required, all others are optional.
16111:
16112: $priv is the privilege being checked.
16113: $uri contains additional information about what is being checked for access (e.g.,
16114: URL, course ID etc.).
16115: $symb is the unique resource instance identifier in a course; if needed,
16116: but not provided, it will be retrieved via a call to &symbread().
16117: $role is the role for which a priv is being checked (only used if priv is evb).
16118: $clientip is the user's IP address (only used when checking for access to portfolio
16119: files).
16120: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
16121: prevents recursive calls to &allowed.
16122:
1.243 albertel 16123: F: full access
16124: U,I,K: authentication modes (cxx only)
16125: '': forbidden
16126: 1: user needs to choose course
16127: 2: browse allowed
1.766 albertel 16128: A: passphrase authentication needed
1.1284 raeburn 16129: B: access temporarily blocked because of a blocking event in a course.
1.1402 raeburn 16130: D: access blocked because access is required via session initiated via deep-link
1.243 albertel 16131:
16132: =item *
16133:
1.1192 raeburn 16134: constructaccess($url,$setpriv) : check for access to construction space URL
16135:
16136: See if the owner domain and name in the URL match those in the
16137: expected environment. If so, return three element list
16138: ($ownername,$ownerdomain,$ownerhome).
16139:
16140: Otherwise return the null string.
16141:
16142: If second argument 'setpriv' is true, it assigns the privileges,
16143: and returns the same three element list, unless the owner has
16144: blocked "ad hoc" Domain Coordinator access to the Author Space,
16145: in which case the null string is returned.
16146:
16147: =item *
16148:
1.1326 raeburn 16149: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16150: define a custom role rolename set privileges in format of lonTabs/roles.tab
16151: for system, domain, and course level. $uname and $udom are optional (current
16152: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 16153:
16154: =item *
16155:
1.988 raeburn 16156: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
16157: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 16158: $type is Course (default) or Community.
1.988 raeburn 16159: If $forcedefault evaluates to true, text returned will be default
16160: text for $type. Otherwise, if this is a course, the text returned
16161: will be a custom name for the role (if defined in the course's
16162: environment). If no custom name is defined the default is returned.
16163:
1.832 raeburn 16164: =item *
16165:
1.1219 raeburn 16166: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 16167: All arguments are optional. Returns a hash of a roles, either for
16168: co-author/assistant author roles for a user's Construction Space
1.906 albertel 16169: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 16170: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16171: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16172: For each key, value is set to colon-separated start and end times for
16173: the role. If no username and domain are specified, will default to
1.934 raeburn 16174: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 16175: of role statuses (active, future or previous), roles
16176: (e.g., cc,in, st etc.) and domains of the roles which can be used
16177: to restrict the list of roles reported. If no array ref is
16178: provided for types, will default to return only active roles.
1.834 albertel 16179:
1.1195 raeburn 16180: =item *
16181:
16182: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 16183: user: $uname:$udom has a role in the course: $cdom_$cnum.
16184:
16185: Additional optional arguments are: $type (if role checking is to be restricted
16186: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 16187: available roles) or future (roles available in the future), and
16188: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 16189: have active Domain Coordinator role in course's domain or in additional
16190: domains (specified in 'Domains to check for privileged users' in course
16191: environment -- set via: Course Settings -> Classlists and staff listing).
16192:
16193: =item *
16194:
16195: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16196: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16197: $possdomains and $possroles are optional array refs -- to domains to check and
16198: roles to check. If $possdomains is not specified, a dump will be done of the
16199: users' roles.db to check for a dc or su role in any domain. This can be
16200: time consuming if &privileged is called repeatedly (e.g., when displaying a
16201: classlist), so in such cases, supplying a $possdomains array is preferred, as
16202: this then allows &privileged_by_domain() to be used, which caches the identity
16203: of privileged users, eliminating the need for repeated calls to &dump().
16204:
16205: =item *
16206:
16207: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16208: where the outer hash keys are domains specified in the $possdomains array ref,
16209: next inner hash keys are privileged roles specified in the $roles array ref,
16210: and the innermost hash contains key = value pairs for username:domain = end:start
16211: for active or future "privileged" users with that role in that domain. To avoid
16212: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16213: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 16214:
1.243 albertel 16215: =back
16216:
16217: =head2 User Modification
16218:
16219: =over 4
16220:
16221: =item *
16222:
1.957 raeburn 16223: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 16224: user for the level given by URL. Optional start and end dates (leave empty
16225: string or zero for "no date")
1.191 harris41 16226:
16227: =item *
16228:
1.243 albertel 16229: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16230: change a users, password, possible return values are: ok,
16231: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16232: refused
1.191 harris41 16233:
16234: =item *
16235:
1.243 albertel 16236: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 16237:
16238: =item *
16239:
1.1058 raeburn 16240: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16241: $forceid,$desiredhome,$email,$inststatus,$candelete) :
16242:
16243: will update user information (firstname,middlename,lastname,generation,
16244: permanentemail), and if forceid is true, student/employee ID also.
16245: A user's institutional affiliation(s) can also be updated.
16246: User information fields will not be overwritten with empty entries
16247: unless the field is included in the $candelete array reference.
16248: This array is included when a single user is modified via "Manage Users",
16249: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 16250:
16251: =item *
16252:
1.286 matthew 16253: modifystudent
16254:
1.957 raeburn 16255: modify a student's enrollment and identification information.
1.1235 raeburn 16256: The course id is resolved based on the current user's environment.
16257: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 16258: associated with a course.
16259:
1.297 matthew 16260: This call is essentially a wrapper for lonnet::modifyuser and
16261: lonnet::modify_student_enrollment
1.286 matthew 16262:
16263: Inputs:
16264:
16265: =over 4
16266:
1.957 raeburn 16267: =item B<$udom> Student's loncapa domain
1.286 matthew 16268:
1.957 raeburn 16269: =item B<$uname> Student's loncapa login name
1.286 matthew 16270:
1.964 bisitz 16271: =item B<$uid> Student/Employee ID
1.286 matthew 16272:
1.957 raeburn 16273: =item B<$umode> Student's authentication mode
1.286 matthew 16274:
1.957 raeburn 16275: =item B<$upass> Student's password
1.286 matthew 16276:
1.957 raeburn 16277: =item B<$first> Student's first name
1.286 matthew 16278:
1.957 raeburn 16279: =item B<$middle> Student's middle name
1.286 matthew 16280:
1.957 raeburn 16281: =item B<$last> Student's last name
1.286 matthew 16282:
1.957 raeburn 16283: =item B<$gene> Student's generation
1.286 matthew 16284:
1.957 raeburn 16285: =item B<$usec> Student's section in course
1.286 matthew 16286:
16287: =item B<$end> Unix time of the roles expiration
16288:
16289: =item B<$start> Unix time of the roles start date
16290:
16291: =item B<$forceid> If defined, allow $uid to be changed
16292:
16293: =item B<$desiredhome> server to use as home server for student
16294:
1.957 raeburn 16295: =item B<$email> Student's permanent e-mail address
16296:
16297: =item B<$type> Type of enrollment (auto or manual)
16298:
1.963 raeburn 16299: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
16300:
16301: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 16302:
1.963 raeburn 16303: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 16304:
1.963 raeburn 16305: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 16306:
1.1216 raeburn 16307: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16308:
16309: =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 16310:
1.286 matthew 16311: =back
1.297 matthew 16312:
16313: =item *
16314:
16315: modify_student_enrollment
16316:
1.1235 raeburn 16317: Change a student's enrollment status in a class. The environment variable
1.297 matthew 16318: 'role.request.course' must be defined for this function to proceed.
16319:
16320: Inputs:
16321:
16322: =over 4
16323:
1.1235 raeburn 16324: =item $udom, student's domain
1.297 matthew 16325:
1.1235 raeburn 16326: =item $uname, student's name
1.297 matthew 16327:
1.1235 raeburn 16328: =item $uid, student's user id
1.297 matthew 16329:
1.1235 raeburn 16330: =item $first, student's first name
1.297 matthew 16331:
16332: =item $middle
16333:
16334: =item $last
16335:
16336: =item $gene
16337:
16338: =item $usec
16339:
16340: =item $end
16341:
16342: =item $start
16343:
1.957 raeburn 16344: =item $type
16345:
16346: =item $locktype
16347:
16348: =item $cid
16349:
16350: =item $selfenroll
16351:
16352: =item $context
16353:
1.1216 raeburn 16354: =item $credits, number of credits student will earn from this class
16355:
1.1314 raeburn 16356: =item $instsec, institutional course section code for student
16357:
1.297 matthew 16358: =back
16359:
1.191 harris41 16360:
16361: =item *
16362:
1.243 albertel 16363: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
16364: custom role; give a custom role to a user for the level given by URL. Specify
16365: name and domain of role author, and role name
1.191 harris41 16366:
16367: =item *
16368:
1.243 albertel 16369: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 16370:
16371: =item *
16372:
1.243 albertel 16373: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
16374:
16375: =back
16376:
16377: =head2 Course Infomation
16378:
16379: =over 4
1.191 harris41 16380:
16381: =item *
16382:
1.1118 foxr 16383: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 16384: specified course id, including all environment settings for the
16385: course, the description of the course will be in the hash under the
16386: key 'description'
1.191 harris41 16387:
1.1118 foxr 16388: $options is an optional parameter that if supplied is a hash reference that controls
16389: what how this function works. It has the following key/values:
16390:
16391: =over 4
16392:
16393: =item freshen_cache
16394:
16395: If defined, and the environment cache for the course is valid, it is
16396: returned in the returned hash.
16397:
16398: =item one_time
16399:
16400: If defined, the last cache time is set to _now_
16401:
16402: =item user
16403:
16404: If defined, the supplied username is used instead of the current user.
16405:
16406:
16407: =back
16408:
1.191 harris41 16409: =item *
16410:
1.624 albertel 16411: resdata($name,$domain,$type,@which) : request for current parameter
16412: setting for a specific $type, where $type is either 'course' or 'user',
16413: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 16414: answers for 10 minutes.
1.243 albertel 16415:
1.877 foxr 16416: =item *
16417:
16418: get_courseresdata($courseid, $domain) : dump the entire course resource
16419: data base, returning a hash that is keyed by the resource name and has
16420: values that are the resource value. I believe that the timestamps and
16421: versions are also returned.
16422:
1.1236 raeburn 16423: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
16424: supplemental content area. This routine caches the number of files for
16425: 10 minutes.
16426:
1.243 albertel 16427: =back
16428:
16429: =head2 Course Modification
16430:
16431: =over 4
1.191 harris41 16432:
16433: =item *
16434:
1.243 albertel 16435: writecoursepref($courseid,%prefs) : write preferences (environment
16436: database) for a course
1.191 harris41 16437:
16438: =item *
16439:
1.1011 raeburn 16440: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
16441:
16442: =item *
16443:
1.1038 raeburn 16444: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 16445:
1.1167 droeschl 16446: =item *
16447:
16448: is_course($courseid), is_course($cdom, $cnum)
16449:
16450: Accepts either a combined $courseid (in the form of domain_courseid) or the
16451: two component version $cdom, $cnum. It checks if the specified course exists.
16452:
16453: Returns:
16454: undef if the course doesn't exist, otherwise
16455: in scalar context the combined courseid.
16456: in list context the two components of the course identifier, domain and
16457: courseid.
16458:
1.243 albertel 16459: =back
16460:
1.1401 raeburn 16461: =head2 Bubblesheet Configuration
16462:
16463: =over 4
16464:
16465: =item *
16466:
16467: get_scantron_config($which)
16468:
16469: $which - the name of the configuration to parse from the file.
16470:
16471: Parses and returns the bubblesheet configuration line selected as a
16472: hash of configuration file fields.
16473:
16474:
16475: Returns:
16476: If the named configuration is not in the file, an empty
16477: hash is returned.
16478:
16479: a hash with the fields
16480: name - internal name for the this configuration setup
16481: description - text to display to operator that describes this config
16482: CODElocation - if 0 or the string 'none'
16483: - no CODE exists for this config
16484: if -1 || the string 'letter'
16485: - a CODE exists for this config and is
16486: a string of letters
16487: Unsupported value (but planned for future support)
16488: if a positive integer
16489: - The CODE exists as the first n items from
16490: the question section of the form
16491: if the string 'number'
16492: - The CODE exists for this config and is
16493: a string of numbers
16494: CODEstart - (only matter if a CODE exists) column in the line where
16495: the CODE starts
16496: CODElength - length of the CODE
16497: IDstart - column where the student/employee ID starts
16498: IDlength - length of the student/employee ID info
16499: Qstart - column where the information from the bubbled
16500: 'questions' start
16501: Qlength - number of columns comprising a single bubble line from
16502: the sheet. (usually either 1 or 10)
16503: Qon - either a single character representing the character used
16504: to signal a bubble was chosen in the positional setup, or
16505: the string 'letter' if the letter of the chosen bubble is
16506: in the final, or 'number' if a number representing the
16507: chosen bubble is in the file (1->A 0->J)
16508: Qoff - the character used to represent that a bubble was
16509: left blank
16510: PaperID - if the scanning process generates a unique number for each
16511: sheet scanned the column that this ID number starts in
16512: PaperIDlength - number of columns that comprise the unique ID number
16513: for the sheet of paper
16514: FirstName - column that the first name starts in
16515: FirstNameLength - number of columns that the first name spans
16516: LastName - column that the last name starts in
16517: LastNameLength - number of columns that the last name spans
16518: BubblesPerRow - number of bubbles available in each row used to
16519: bubble an answer. (If not specified, 10 assumed).
16520:
16521:
16522: =item *
16523:
16524: get_scantronformat_file($cdom)
16525:
16526: $cdom - the course's domain (optional); if not supplied, uses
16527: domain for current $env{'request.course.id'}.
16528:
16529: Returns an array containing lines from the scantron format file for
16530: the domain of the course.
16531:
16532: If a url for a custom.tab file is listed in domain's configuration.db,
16533: lines are from this file.
16534:
16535: Otherwise, if a default.tab has been published in RES space by the
16536: domainconfig user, lines are from this file.
16537:
16538: Otherwise, fall back to getting lines from the legacy file on the
16539: local server: /home/httpd/lonTabs/default_scantronformat.tab
16540:
16541: =back
16542:
1.243 albertel 16543: =head2 Resource Subroutines
16544:
16545: =over 4
1.191 harris41 16546:
16547: =item *
16548:
1.243 albertel 16549: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 16550:
16551: =item *
16552:
1.243 albertel 16553: repcopy($filename) : subscribes to the requested file, and attempts to
16554: replicate from the owning library server, Might return
1.607 raeburn 16555: 'unavailable', 'not_found', 'forbidden', 'ok', or
16556: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 16557: resource. Expects the local filesystem pathname
16558: (/home/httpd/html/res/....)
16559:
16560: =back
16561:
16562: =head2 Resource Information
16563:
16564: =over 4
1.191 harris41 16565:
16566: =item *
16567:
1.1228 raeburn 16568: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
16569: and returns the value of a variety of different possible values,
16570: $varname should be a request string, and the other parameters can be
16571: used to specify who and what one is asking about. Ordinarily, $cid
16572: does not need to be specified, as it is retrived from
16573: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16574: within lonuserstate::loadmap() when initializing a course, before
16575: $env{'request.course.id'} has been set, so it needs to be provided
16576: in that one case.
1.243 albertel 16577:
16578: Possible values for $varname are environment.lastname (or other item
16579: from the envirnment hash), user.name (or someother aspect about the
16580: user), resource.0.maxtries (or some other part and parameter of a
16581: resource)
1.204 albertel 16582:
16583: =item *
16584:
1.243 albertel 16585: directcondval($number) : get current value of a condition; reads from a state
16586: string
1.204 albertel 16587:
16588: =item *
16589:
1.243 albertel 16590: condval($condidx) : value of condition index based on state
1.204 albertel 16591:
16592: =item *
16593:
1.1362 raeburn 16594: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243 albertel 16595: resource's metadata, $what should be either a specific key, or either
16596: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362 raeburn 16597: packages that this resource currently uses, the last 3 arguments are
16598: only used internally for recursive metadata.
16599:
16600: the toolsymb is only used where the uri is for an external tool (for which
16601: the uri as well as the symb are guaranteed to be unique).
1.243 albertel 16602:
1.1371 raeburn 16603: this function automatically caches all requests except any made recursively
16604: to retrieve a list of metadata keys for an imported library file ($liburi is
16605: defined).
1.191 harris41 16606:
16607: =item *
16608:
1.243 albertel 16609: metadata_query($query,$custom,$customshow) : make a metadata query against the
16610: network of library servers; returns file handle of where SQL and regex results
16611: will be stored for query
1.191 harris41 16612:
16613: =item *
16614:
1.1282 raeburn 16615: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
16616: return symbolic list entry (all arguments optional).
16617:
16618: Args: filename is the filename (including path) for the file for which a symb
16619: is required; donotrecurse, if true will prevent calls to allowed() being made
16620: to check access status if more than one resource was found in the bighash
16621: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
16622: a randompick); ignorecachednull, if true will prevent a symb of '' being
16623: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16624: cause possible symbs to be checked to determine if they are subject to content
16625: blocking, if so they will not be included as possible symbs; possibles is a
16626: ref to a hash, which, as a side effect, will be populated with all possible
16627: symbs (content blocking not tested).
16628:
1.243 albertel 16629: returns the data handle
1.191 harris41 16630:
16631: =item *
16632:
1.1190 raeburn 16633: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
16634: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 16635: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 16636: on failure, user must be in a course, as it assumes the existence of
16637: the course initial hash, and uses $env('request.course.id'}. The third
16638: arg is an optional reference to a scalar. If this arg is passed in the
16639: call to symbverify, it will be set to 1 if the symb has been set to be
16640: encrypted; otherwise it will be null.
1.191 harris41 16641:
16642: =item *
16643:
1.243 albertel 16644: symbclean($symb) : removes versions numbers from a symb, returns the
16645: cleaned symb
1.191 harris41 16646:
16647: =item *
16648:
1.243 albertel 16649: is_on_map($uri) : checks if the $uri is somewhere on the current
16650: course map, user must be in a course for it to work.
1.191 harris41 16651:
16652: =item *
16653:
1.243 albertel 16654: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 16655:
16656: =item *
16657:
1.243 albertel 16658: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16659: a random seed, all arguments are optional, if they aren't sent it uses the
16660: environment to derive them. Note: if symb isn't sent and it can't get one
16661: from &symbread it will use the current time as its return value
1.191 harris41 16662:
16663: =item *
16664:
1.243 albertel 16665: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16666: unfakeable, receipt
1.191 harris41 16667:
16668: =item *
16669:
1.620 albertel 16670: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 16671:
16672: =item *
16673:
1.243 albertel 16674: countacc($url) : count the number of accesses to a given URL
1.191 harris41 16675:
16676: =item *
16677:
1.243 albertel 16678: 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 16679:
16680: =item *
16681:
1.243 albertel 16682: 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 16683:
16684: =item *
16685:
1.243 albertel 16686: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 16687:
16688: =item *
16689:
1.243 albertel 16690: devalidate($symb) : devalidate temporary spreadsheet calculations,
16691: forcing spreadsheet to reevaluate the resource scores next time.
16692:
1.1195 raeburn 16693: =item *
16694:
1.1196 raeburn 16695: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16696: when viewing in course context.
1.1195 raeburn 16697:
1.1196 raeburn 16698: input: six args -- filename (decluttered), course number, course domain,
16699: url, symb (if registered) and group (if this is a
16700: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 16701:
1.1196 raeburn 16702: output: array of five scalars --
1.1195 raeburn 16703: $cfile -- url for file editing if editable on current server
16704: $home -- homeserver of resource (i.e., for author if published,
16705: or course if uploaded.).
16706: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 16707: $forceedit -- 1 if icon/link should be to go to edit mode
16708: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 16709:
16710: =item *
16711:
16712: is_course_upload($file,$cnum,$cdom)
16713:
16714: Used in course context to determine if current file was uploaded to
16715: the course (i.e., would be found in /userfiles/docs on the course's
16716: homeserver.
16717:
16718: input: 3 args -- filename (decluttered), course number and course domain.
16719: output: boolean -- 1 if file was uploaded.
16720:
1.243 albertel 16721: =back
16722:
16723: =head2 Storing/Retreiving Data
16724:
16725: =over 4
1.191 harris41 16726:
16727: =item *
16728:
1.1269 raeburn 16729: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16730: permanently for this url; hashref needs to be given and should be a \%hashname;
16731: the remaining args aren't required and if they aren't passed or are '' they will
16732: be derived from the env (with the exception of $laststore, which is an
16733: optional arg used when a user's submission is stored in grading).
16734: $laststore is $version=$timestamp, where $version is the most recent version
16735: number retrieved for the corresponding $symb in the $namespace db file, and
16736: $timestamp is the timestamp for that transaction (UNIX time).
16737: $laststore is currently only passed when cstore() is called by
16738: structuretags::finalize_storage().
1.191 harris41 16739:
16740: =item *
16741:
1.1269 raeburn 16742: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16743: but uses critical subroutine
1.191 harris41 16744:
16745: =item *
16746:
1.243 albertel 16747: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16748: all args are optional
1.191 harris41 16749:
16750: =item *
16751:
1.717 albertel 16752: dumpstore($namespace,$udom,$uname,$regexp,$range) :
16753: dumps the complete (or key matching regexp) namespace into a hash
16754: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16755: normally &store()ed into
16756:
16757: $range should be either an integer '100' (give me the first 100
16758: matching records)
16759: or be two integers sperated by a - with no spaces
16760: '30-50' (give me the 30th through the 50th matching
16761: records)
16762:
16763:
16764: =item *
16765:
1.1269 raeburn 16766: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 16767: replaces a &store() version of data with a replacement set of data
16768: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 16769: reference. If $tolog is true, the transaction is logged in the courselog
16770: with an action=PUTSTORE.
1.717 albertel 16771:
16772: =item *
16773:
1.243 albertel 16774: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16775: works very similar to store/cstore, but all data is stored in a
16776: temporary location and can be reset using tmpreset, $storehash should
16777: be a hash reference, returns nothing on success
1.191 harris41 16778:
16779: =item *
16780:
1.243 albertel 16781: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16782: similar to restore, but all data is stored in a temporary location and
16783: can be reset using tmpreset. Returns a hash of values on success,
16784: error string otherwise.
1.191 harris41 16785:
16786: =item *
16787:
1.243 albertel 16788: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16789: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 16790:
16791: =item *
16792:
1.243 albertel 16793: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16794: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 16795:
16796: =item *
16797:
1.243 albertel 16798: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16799: namesp ($udom and $uname are optional)
1.191 harris41 16800:
16801: =item *
16802:
1.702 albertel 16803: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 16804: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 16805: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 16806:
1.702 albertel 16807: $range should be either an integer '100' (give me the first 100
16808: matching records)
16809: or be two integers sperated by a - with no spaces
16810: '30-50' (give me the 30th through the 50th matching
16811: records)
1.449 matthew 16812: =item *
16813:
16814: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16815: $store can be a scalar, an array reference, or if the amount to be
16816: incremented is > 1, a hash reference.
16817:
16818: ($udom and $uname are optional)
1.191 harris41 16819:
16820: =item *
16821:
1.243 albertel 16822: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16823: ($udom and $uname are optional)
1.191 harris41 16824:
16825: =item *
16826:
1.243 albertel 16827: cput($namespace,$storehash,$udom,$uname) : critical put
16828: ($udom and $uname are optional)
1.191 harris41 16829:
16830: =item *
16831:
1.748 albertel 16832: newput($namespace,$storehash,$udom,$uname) :
16833:
16834: Attempts to store the items in the $storehash, but only if they don't
16835: currently exist, if this succeeds you can be certain that you have
16836: successfully created a new key value pair in the $namespace db.
16837:
16838:
16839: Args:
16840: $namespace: name of database to store values to
16841: $storehash: hashref to store to the db
16842: $udom: (optional) domain of user containing the db
16843: $uname: (optional) name of user caontaining the db
16844:
16845: Returns:
16846: 'ok' -> succeeded in storing all keys of $storehash
16847: 'key_exists: <key>' -> failed to anything out of $storehash, as at
16848: least <key> already existed in the db (other
16849: requested keys may also already exist)
1.967 bisitz 16850: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 16851: 'con_lost' -> unable to contact request server
16852: 'refused' -> action was not allowed by remote machine
16853:
16854:
16855: =item *
16856:
1.243 albertel 16857: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16858: reference filled in from namesp (encrypts the return communication)
16859: ($udom and $uname are optional)
1.191 harris41 16860:
16861: =item *
16862:
1.243 albertel 16863: log($udom,$name,$home,$message) : write to permanent log for user; use
16864: critical subroutine
16865:
1.806 raeburn 16866: =item *
16867:
1.860 raeburn 16868: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16869: array reference filled in from namespace found in domain level on either
16870: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 16871:
16872: =item *
16873:
1.860 raeburn 16874: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
16875: domain level either on specified domain server ($uhome) or primary domain
16876: server ($udom and $uhome are optional)
1.806 raeburn 16877:
1.943 raeburn 16878: =item *
16879:
1.1240 raeburn 16880: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
16881: for: authentication, language, quotas, timezone, date locale, and portal URL in
16882: the target domain.
16883:
16884: May also include additional key => value pairs for the following groups:
16885:
16886: =over
16887:
16888: =item
16889: disk quotas (MB allocated by default to portfolios and authoring spaces).
16890:
16891: =over
16892:
16893: =item defaultquota, authorquota
16894:
16895: =back
16896:
16897: =item
16898: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16899: portfolio for users).
16900:
16901: =over
16902:
16903: =item
16904: aboutme, blog, webdav, portfolio
16905:
16906: =back
16907:
16908: =item
16909: requestcourses: ability to request courses, and how requests are processed.
16910:
16911: =over
16912:
16913: =item
1.1305 raeburn 16914: official, unofficial, community, textbook, placement
1.1240 raeburn 16915:
16916: =back
16917:
16918: =item
16919: inststatus: types of institutional affiliation, and order in which they are displayed.
16920:
16921: =over
16922:
16923: =item
1.1256 raeburn 16924: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 16925:
16926: =back
16927:
16928: =item
16929: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16930: for course's uploaded content.
16931:
16932: =over
16933:
16934: =item
1.1246 raeburn 16935: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 16936: communityquota, textbookquota, placementquota
1.1240 raeburn 16937:
16938: =back
16939:
16940: =item
16941: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16942: on your servers.
16943:
16944: =over
16945:
16946: =item
16947: remotesessions, hostedsessions
16948:
16949: =back
16950:
16951: =back
16952:
16953: In cases where a domain coordinator has never used the "Set Domain Configuration"
16954: utility to create a configuration.db file on a domain's primary library server
16955: only the following domain defaults: auth_def, auth_arg_def, lang_def
16956: -- corresponding values are authentication type (internal, krb4, krb5,
16957: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
16958: will be available. Values are retrieved from cache (if current), unless the
16959: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16960: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16961:
16962: Typical usage:
1.943 raeburn 16963:
1.1240 raeburn 16964: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 16965:
1.243 albertel 16966: =back
16967:
16968: =head2 Network Status Functions
16969:
16970: =over 4
1.191 harris41 16971:
16972: =item *
16973:
1.1137 raeburn 16974: dirlist() : return directory list based on URI (first arg).
16975:
16976: Inputs: 1 required, 5 optional.
16977:
16978: =over
16979:
16980: =item
16981: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16982:
16983: =item
16984: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
16985:
16986: =item
16987: $username - username of user/course to be listed. Extracted from $uri if absent.
16988:
16989: =item
16990: $getpropath - boolean: 1 if prepend path using &propath().
16991:
16992: =item
16993: $getuserdir - boolean: 1 if prepend path for "userfiles".
16994:
16995: =item
16996: $alternateRoot - path to prepend in place of path from $uri.
16997:
16998: =back
16999:
17000: Returns: Array of up to two items.
17001:
17002: =over
17003:
17004: a reference to an array of files/subdirectories
17005:
17006: =over
17007:
17008: Each element in the array of files/subdirectories is a & separated list of
17009: item name and the result of running stat on the item. If dirlist was requested
17010: for a file instead of a directory, the item name will be ''. For a directory
17011: listing, if the item is a metadata file, the element will end &N&M
17012: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17013: default copyright set (1).
17014:
17015: =back
17016:
17017: a scalar containing error condition (if encountered).
17018:
17019: =over
17020:
17021: =item
17022: no_host (no homeserver identified for $username:$domain).
17023:
17024: =item
17025: no_such_host (server contacted for listing not identified as valid host).
17026:
17027: =item
17028: con_lost (connection to remote server failed).
17029:
17030: =item
17031: refused (invalid $username:$domain received on lond side).
17032:
17033: =item
17034: no_such_dir (directory at specified path on lond side does not exist).
17035:
17036: =item
17037: empty (directory at specified path on lond side is empty).
17038:
17039: =over
17040:
17041: This is currently not encountered because the &ls3, &ls2,
17042: &ls (_handler) routines on the lond side do not filter out
17043: . and .. from a directory listing.
17044:
17045: =back
17046:
17047: =back
17048:
17049: =back
1.191 harris41 17050:
17051: =item *
17052:
1.243 albertel 17053: spareserver() : find server with least workload from spare.tab
17054:
1.986 foxr 17055:
17056: =item *
17057:
17058: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17059: if there is no corresponding loncapa host.
17060:
1.243 albertel 17061: =back
17062:
1.986 foxr 17063:
1.243 albertel 17064: =head2 Apache Request
17065:
17066: =over 4
1.191 harris41 17067:
17068: =item *
17069:
1.243 albertel 17070: ssi($url,%hash) : server side include, does a complete request cycle on url to
17071: localhost, posts hash
17072:
17073: =back
17074:
17075: =head2 Data to String to Data
17076:
17077: =over 4
1.191 harris41 17078:
17079: =item *
17080:
1.243 albertel 17081: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17082: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 17083:
17084: =item *
17085:
1.243 albertel 17086: hashref2str($hashref) : convert a hashref into a string complete with
17087: escaping and '=' and '&' separators, supports elements that are
17088: arrayrefs and hashrefs
1.191 harris41 17089:
17090: =item *
17091:
1.243 albertel 17092: arrayref2str($arrayref) : convert an arrayref into a string complete
17093: with escaping and '&' separators, supports elements that are arrayrefs
17094: and hashrefs
1.191 harris41 17095:
17096: =item *
17097:
1.243 albertel 17098: str2hash($string) : convert string to hash using unescaping and
17099: splitting on '=' and '&', supports elements that are arrayrefs and
17100: hashrefs
1.191 harris41 17101:
17102: =item *
17103:
1.243 albertel 17104: str2array($string) : convert string to hash using unescaping and
17105: splitting on '&', supports elements that are arrayrefs and hashrefs
17106:
17107: =back
17108:
17109: =head2 Logging Routines
17110:
17111:
17112: These routines allow one to make log messages in the lonnet.log and
17113: lonnet.perm logfiles.
1.191 harris41 17114:
1.1119 foxr 17115: =over 4
17116:
1.191 harris41 17117: =item *
17118:
1.243 albertel 17119: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 17120:
17121: =item *
17122:
1.243 albertel 17123: logthis() : append message to the normal lonnet.log file, it gets
17124: preiodically rolled over and deleted.
1.191 harris41 17125:
17126: =item *
17127:
1.243 albertel 17128: logperm() : append a permanent message to lonnet.perm.log, this log
17129: file never gets deleted by any automated portion of the system, only
17130: messages of critical importance should go in here.
17131:
1.1119 foxr 17132:
1.243 albertel 17133: =back
17134:
17135: =head2 General File Helper Routines
17136:
17137: =over 4
1.191 harris41 17138:
17139: =item *
17140:
1.481 raeburn 17141: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17142: (a) files in /uploaded
17143: (i) If a local copy of the file exists -
17144: compares modification date of local copy with last-modified date for
17145: definitive version stored on home server for course. If local copy is
17146: stale, requests a new version from the home server and stores it.
17147: If the original has been removed from the home server, then local copy
17148: is unlinked.
17149: (ii) If local copy does not exist -
17150: requests the file from the home server and stores it.
17151:
17152: If $caller is 'uploadrep':
17153: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17154: for request for files originally uploaded via DOCS.
17155: - returns 'ok' if fresh local copy now available, -1 otherwise.
17156:
17157: Otherwise:
17158: This indicates a call from the content generation phase of the request.
17159: - returns the entire contents of the file or -1.
17160:
17161: (b) files in /res
17162: - returns the entire contents of a file or -1;
17163: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 17164:
1.712 albertel 17165:
17166: =item *
17167:
17168: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17169: reference
17170:
17171: returns either a stat() list of data about the file or an empty list
17172: if the file doesn't exist or couldn't find out about it (connection
17173: problems or user unknown)
17174:
1.191 harris41 17175: =item *
17176:
1.243 albertel 17177: filelocation($dir,$file) : returns file system location of a file
17178: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17179: directory that relative $file lookups are to looked in ($dir of /a/dir
17180: and a file of ../bob will become /a/bob)
1.191 harris41 17181:
17182: =item *
17183:
17184: hreflocation($dir,$file) : returns file system location or a URL; same as
17185: filelocation except for hrefs
17186:
17187: =item *
17188:
1.1261 raeburn 17189: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17190: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 17191:
1.243 albertel 17192: =back
17193:
1.608 albertel 17194: =head2 Usererfile file routines (/uploaded*)
17195:
17196: =over 4
17197:
17198: =item *
17199:
17200: userfileupload(): main rotine for putting a file in a user or course's
17201: filespace, arguments are,
17202:
1.620 albertel 17203: formname - required - this is the name of the element in $env where the
1.608 albertel 17204: filename, and the contents of the file to create/modifed exist
1.620 albertel 17205: the filename is in $env{'form.'.$formname.'.filename'} and the
17206: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 17207: context - if coursedoc, store the file in the course of the active role
17208: of the current user;
17209: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17210: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 17211: subdir - required - subdirectory to put the file in under ../userfiles/
17212: if undefined, it will be placed in "unknown"
17213:
17214: (This routine calls clean_filename() to remove any dangerous
17215: characters from the filename, and then calls finuserfileupload() to
17216: complete the transaction)
17217:
17218: returns either the url of the uploaded file (/uploaded/....) if successful
17219: and /adm/notfound.html if unsuccessful
17220:
17221: =item *
17222:
17223: clean_filename(): routine for cleaing a filename up for storage in
17224: userfile space, argument is:
17225:
17226: filename - proposed filename
17227:
17228: returns: the new clean filename
17229:
17230: =item *
17231:
1.1090 raeburn 17232: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 17233: userspace, probably shouldn't be called directly
17234:
17235: docuname: username or courseid of destination for the file
17236: docudom: domain of user/course of destination for the file
17237: formname: same as for userfileupload()
1.1090 raeburn 17238: fname: filename (including subdirectories) for the file
17239: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401 raeburn 17240: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 17241: allfiles: reference to hash used to store objects found by parser
17242: codebase: reference to hash used for codebases of java objects found by parser
17243: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17244: thumbheight: height (pixels) of thumbnail to be created for uploaded image
17245: resizewidth: width to be used to resize image using resizeImage from ImageMagick
17246: resizeheight: height to be used to resize image using resizeImage from ImageMagick
17247: context: if 'overwrite', will move the uploaded file from its temporary location to
17248: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 17249: mimetype: reference to scalar to accommodate mime type determined
17250: from File::MMagic if $parser = parse.
1.608 albertel 17251:
17252: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 17253: and /adm/notfound.html if unsuccessful (or an error message if context
17254: was 'overwrite').
17255:
1.608 albertel 17256:
17257: =item *
17258:
17259: renameuserfile(): renames an existing userfile to a new name
17260:
17261: Args:
17262: docuname: username or courseid of destination for the file
17263: docudom: domain of user/course of destination for the file
17264: old: current file name (including any subdirs under userfiles)
17265: new: desired file name (including any subdirs under userfiles)
17266:
17267: =item *
17268:
17269: mkdiruserfile(): creates a directory is a userfiles dir
17270:
17271: Args:
17272: docuname: username or courseid of destination for the file
17273: docudom: domain of user/course of destination for the file
17274: dir: dir to create (including any subdirs under userfiles)
17275:
17276: =item *
17277:
17278: removeuserfile(): removes a file that exists in userfiles
17279:
17280: Args:
17281: docuname: username or courseid of destination for the file
17282: docudom: domain of user/course of destination for the file
17283: fname: filname to delete (including any subdirs under userfiles)
17284:
17285: =item *
17286:
17287: removeuploadedurl(): convience function for removeuserfile()
17288:
17289: Args:
17290: url: a full /uploaded/... url to delete
17291:
1.747 albertel 17292: =item *
17293:
17294: get_portfile_permissions():
17295: Args:
17296: domain: domain of user or course contain the portfolio files
17297: user: name of user or num of course contain the portfolio files
17298: Returns:
17299: hashref of a dump of the proper file_permissions.db
17300:
17301:
17302: =item *
17303:
17304: get_access_controls():
17305:
17306: Args:
17307: current_permissions: the hash ref returned from get_portfile_permissions()
17308: group: (optional) the group you want the files associated with
17309: file: (optional) the file you want access info on
17310:
17311: Returns:
1.749 raeburn 17312: a hash (keys are file names) of hashes containing
17313: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17314: values are XML containing access control settings (see below)
1.747 albertel 17315:
17316: Internal notes:
17317:
1.749 raeburn 17318: access controls are stored in file_permissions.db as key=value pairs.
17319: key -> path to file/file_name\0uniqueID:scope_end_start
17320: where scope -> public,guest,course,group,domains or users.
17321: end -> UNIX time for end of access (0 -> no end date)
17322: start -> UNIX time for start of access
17323:
17324: value -> XML description of access control
17325: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
17326: <start></start>
17327: <end></end>
17328:
17329: <password></password> for scope type = guest
17330:
17331: <domain></domain> for scope type = course or group
17332: <number></number>
17333: <roles id="">
17334: <role></role>
17335: <access></access>
17336: <section></section>
17337: <group></group>
17338: </roles>
17339:
17340: <dom></dom> for scope type = domains
17341:
17342: <users> for scope type = users
17343: <user>
17344: <uname></uname>
17345: <udom></udom>
17346: </user>
17347: </users>
17348: </scope>
17349:
17350: Access data is also aggregated for each file in an additional key=value pair:
17351: key -> path to file/file_name\0accesscontrol
17352: value -> reference to hash
17353: hash contains key = value pairs
17354: where key = uniqueID:scope_end_start
17355: value = UNIX time record was last updated
17356:
17357: Used to improve speed of look-ups of access controls for each file.
17358:
17359: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
17360:
1.1198 raeburn 17361: =item *
17362:
1.749 raeburn 17363: modify_access_controls():
17364:
17365: Modifies access controls for a portfolio file
17366: Args
17367: 1. file name
17368: 2. reference to hash of required changes,
17369: 3. domain
17370: 4. username
17371: where domain,username are the domain of the portfolio owner
17372: (either a user or a course)
17373:
17374: Returns:
17375: 1. result of additions or updates ('ok' or 'error', with error message).
17376: 2. result of deletions ('ok' or 'error', with error message).
17377: 3. reference to hash of any new or updated access controls.
17378: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
17379: key = integer (inbound ID)
1.1198 raeburn 17380: value = uniqueID
17381:
17382: =item *
17383:
17384: get_timebased_id():
17385:
17386: Attempts to get a unique timestamp-based suffix for use with items added to a
17387: course via the Course Editor (e.g., folders, composite pages,
17388: group bulletin boards).
17389:
17390: Args: (first three required; six others optional)
17391:
17392: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
17393: docssequence, or name of group
17394:
17395: 2. keyid (alphanumeric): name of temporary locking key in hash,
17396: e.g., num, boardids
17397:
17398: 3. namespace: name of gdbm file used to store suffixes already assigned;
17399: file will be named nohist_namespace.db
17400:
17401: 4. cdom: domain of course; default is current course domain from %env
17402:
17403: 5. cnum: course number; default is current course number from %env
17404:
17405: 6. idtype: set to concat if an additional digit is to be appended to the
17406: unix timestamp to form the suffix, if the plain timestamp is already
17407: in use. Default is to not do this, but simply increment the unix
17408: timestamp by 1 until a unique key is obtained.
17409:
17410: 7. who: holder of locking key; defaults to user:domain for user.
17411:
17412: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
17413: retrying); default is 3.
17414:
17415: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
17416:
17417: Returns:
17418:
17419: 1. suffix obtained (numeric)
17420:
17421: 2. result of deleting locking key (ok if deleted, or lock never obtained)
17422:
17423: 3. error: contains (localized) error message if an error occurred.
17424:
1.747 albertel 17425:
1.608 albertel 17426: =back
17427:
1.243 albertel 17428: =head2 HTTP Helper Routines
17429:
17430: =over 4
17431:
1.191 harris41 17432: =item *
17433:
17434: escape() : unpack non-word characters into CGI-compatible hex codes
17435:
17436: =item *
17437:
17438: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
17439:
1.243 albertel 17440: =back
17441:
17442: =head1 PRIVATE SUBROUTINES
17443:
17444: =head2 Underlying communication routines (Shouldn't call)
17445:
17446: =over 4
17447:
17448: =item *
17449:
17450: subreply() : tries to pass a message to lonc, returns con_lost if incapable
17451:
17452: =item *
17453:
17454: reply() : uses subreply to send a message to remote machine, logs all failures
17455:
17456: =item *
17457:
17458: critical() : passes a critical message to another server; if cannot
17459: get through then place message in connection buffer directory and
17460: returns con_delayed, if incapable of saving message, returns
17461: con_failed
17462:
17463: =item *
17464:
17465: reconlonc() : tries to reconnect lonc client processes.
17466:
17467: =back
17468:
17469: =head2 Resource Access Logging
17470:
17471: =over 4
17472:
17473: =item *
17474:
17475: flushcourselogs() : flush (save) buffer logs and access logs
17476:
17477: =item *
17478:
17479: courselog($what) : save message for course in hash
17480:
17481: =item *
17482:
17483: courseacclog($what) : save message for course using &courselog(). Perform
17484: special processing for specific resource types (problems, exams, quizzes, etc).
17485:
1.191 harris41 17486: =item *
17487:
17488: goodbye() : flush course logs and log shutting down; it is called in srm.conf
17489: as a PerlChildExitHandler
1.243 albertel 17490:
17491: =back
17492:
17493: =head2 Other
17494:
17495: =over 4
17496:
17497: =item *
17498:
17499: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 17500:
17501: =back
17502:
17503: =cut
1.877 foxr 17504:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>