Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1460
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1460 ! raeburn 4: # $Id: lonnet.pm,v 1.1459 2021/06/12 21:37:36 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') ||
471: ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
472: (undef,undef,my @rest) = split(/:/,$cmd);
473: if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
474: splice(@rest,2,1,'Hidden');
475: } elsif ($subcmd eq 'passwd') {
476: splice(@rest,2,2,('Hidden','Hidden'));
477: } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
478: ($subcmd eq 'autoexportgrades')) {
479: splice(@rest,3,1,'Hidden');
480: }
481: $logged = join(':',('encrypt:'.$subcmd,@rest));
482: }
483: }
484: &logthis("<font color=\"blue\">WARNING:".
485: " $logged to $server returned $answer</font>");
1.12 www 486: }
1.1 albertel 487: return $answer;
488: }
489:
490: # ----------------------------------------------------------- Send USR1 to lonc
491:
492: sub reconlonc {
1.891 albertel 493: my ($lonid) = @_;
494: if ($lonid) {
1.1295 raeburn 495: my $hostname = &hostname($lonid);
1.891 albertel 496: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
497: if ($hostname && -e $peerfile) {
498: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
499: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
500: Type => SOCK_STREAM,
501: Timeout => 10);
502: if ($client) {
503: print $client ("reset_retries\n");
504: my $answer=<$client>;
505: #reset just this one.
506: }
507: }
508: return;
509: }
510:
1.836 www 511: &logthis("Trying to reconnect lonc");
1.1 albertel 512: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359 raeburn 513: if (open(my $fh,"<",$loncfile)) {
1.1 albertel 514: my $loncpid=<$fh>;
515: chomp($loncpid);
516: if (kill 0 => $loncpid) {
517: &logthis("lonc at pid $loncpid responding, sending USR1");
518: kill USR1 => $loncpid;
519: sleep 1;
1.1295 raeburn 520: } else {
1.12 www 521: &logthis(
1.672 albertel 522: "<font color=\"blue\">WARNING:".
1.12 www 523: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 524: }
525: } else {
1.836 www 526: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 527: }
528: }
529:
530: # ------------------------------------------------------ Critical communication
1.12 www 531:
1.1 albertel 532: sub critical {
533: my ($cmd,$server)=@_;
1.838 albertel 534: unless (&hostname($server)) {
1.672 albertel 535: &logthis("<font color=\"blue\">WARNING:".
1.89 www 536: " Critical message to unknown server ($server)</font>");
537: return 'no_such_host';
538: }
1.1 albertel 539: my $answer=reply($cmd,$server);
540: if ($answer eq 'con_lost') {
1.1295 raeburn 541: &reconlonc($server);
1.589 albertel 542: my $answer=reply($cmd,$server);
1.1 albertel 543: if ($answer eq 'con_lost') {
544: my $now=time;
545: my $middlename=$cmd;
1.5 www 546: $middlename=substr($middlename,0,16);
1.1 albertel 547: $middlename=~s/\W//g;
548: my $dfilename=
1.305 www 549: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
550: $dumpcount++;
1.1 albertel 551: {
1.448 albertel 552: my $dfh;
1.1359 raeburn 553: if (open($dfh,">",$dfilename)) {
1.448 albertel 554: print $dfh "$cmd\n";
555: close($dfh);
556: }
1.1 albertel 557: }
1.1288 damieng 558: sleep 1;
1.1 albertel 559: my $wcmd='';
560: {
1.448 albertel 561: my $dfh;
1.1359 raeburn 562: if (open($dfh,"<",$dfilename)) {
1.448 albertel 563: $wcmd=<$dfh>;
564: close($dfh);
565: }
1.1 albertel 566: }
567: chomp($wcmd);
1.7 www 568: if ($wcmd eq $cmd) {
1.672 albertel 569: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 570: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 571: &logperm("D:$server:$cmd");
572: return 'con_delayed';
573: } else {
1.672 albertel 574: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 575: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 576: &logperm("F:$server:$cmd");
577: return 'con_failed';
578: }
579: }
580: }
581: return $answer;
1.405 albertel 582: }
583:
1.755 albertel 584: # ------------------------------------------- check if return value is an error
585:
586: sub error {
587: my ($result) = @_;
1.756 albertel 588: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 589: if ($2 == 2) { return undef; }
590: return $1;
591: }
592: return undef;
593: }
594:
1.783 albertel 595: sub convert_and_load_session_env {
596: my ($lonidsdir,$handle)=@_;
597: my @profile;
598: {
1.917 albertel 599: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
600: if (!$opened) {
1.915 albertel 601: return 0;
602: }
1.783 albertel 603: flock($idf,LOCK_SH);
604: @profile=<$idf>;
605: close($idf);
606: }
607: my %temp_env;
608: foreach my $line (@profile) {
1.786 albertel 609: if ($line !~ m/=/) {
610: return 0;
611: }
1.783 albertel 612: chomp($line);
613: my ($envname,$envvalue)=split(/=/,$line,2);
614: $temp_env{&unescape($envname)} = &unescape($envvalue);
615: }
616: unlink("$lonidsdir/$handle.id");
617: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
618: 0640)) {
619: %disk_env = %temp_env;
620: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
621: untie(%disk_env);
622: }
1.786 albertel 623: return 1;
1.783 albertel 624: }
625:
1.374 www 626: # ------------------------------------------- Transfer profile into environment
1.780 albertel 627: my $env_loaded;
628: sub transfer_profile_to_env {
1.788 albertel 629: my ($lonidsdir,$handle,$force_transfer) = @_;
630: if (!$force_transfer && $env_loaded) { return; }
1.374 www 631:
1.720 albertel 632: if (!defined($lonidsdir)) {
633: $lonidsdir = $perlvar{'lonIDsDir'};
634: }
635: if (!defined($handle)) {
636: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
637: }
638:
1.786 albertel 639: my $convert;
640: {
1.917 albertel 641: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
642: if (!$opened) {
1.915 albertel 643: return;
644: }
1.786 albertel 645: flock($idf,LOCK_SH);
646: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
647: &GDBM_READER(),0640)) {
648: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
649: untie(%disk_env);
650: } else {
651: $convert = 1;
652: }
653: }
654: if ($convert) {
655: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
656: &logthis("Failed to load session, or convert session.");
657: }
1.374 www 658: }
1.783 albertel 659:
1.786 albertel 660: my %remove;
1.783 albertel 661: while ( my $envname = each(%env) ) {
1.433 matthew 662: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
663: if ($time < time-300) {
1.783 albertel 664: $remove{$key}++;
1.433 matthew 665: }
666: }
667: }
1.783 albertel 668:
1.619 albertel 669: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 670: $env_loaded=1;
1.783 albertel 671: foreach my $expired_key (keys(%remove)) {
1.433 matthew 672: &delenv($expired_key);
1.374 www 673: }
1.1 albertel 674: }
675:
1.916 albertel 676: # ---------------------------------------------------- Check for valid session
677: sub check_for_valid_session {
1.1355 raeburn 678: my ($r,$name,$userhashref,$domref) = @_;
1.916 albertel 679: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1378 raeburn 680: my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
681: if ($name eq 'lonDAV') {
682: $lonidsdir=$r->dir_config('lonDAVsessDir');
683: } else {
684: $lonidsdir=$r->dir_config('lonIDsDir');
685: if ($name eq '') {
686: $name = 'lonID';
687: }
688: }
689: if ($name eq 'lonID') {
690: $secure = 'lonSID';
1.1337 raeburn 691: $linkname = 'lonLinkID';
692: $pubname = 'lonPubID';
1.1378 raeburn 693: if (exists($cookies{$secure})) {
694: $lonid=$cookies{$secure};
695: } elsif (exists($cookies{$name})) {
696: $lonid=$cookies{$name};
1.1400 raeburn 697: } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
1.1337 raeburn 698: $lonid=$cookies{$linkname};
1.1378 raeburn 699: } elsif (exists($cookies{$pubname})) {
700: $lonid=$cookies{$pubname};
1.1337 raeburn 701: }
1.1378 raeburn 702: } else {
703: $lonid=$cookies{$name};
1.1337 raeburn 704: }
1.916 albertel 705: return undef if (!$lonid);
706:
707: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1378 raeburn 708: if (-l "$lonidsdir/$handle.id") {
709: my $link = readlink("$lonidsdir/$handle.id");
710: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
711: $handle = $1;
712: }
1.1155 raeburn 713: }
1.1355 raeburn 714: if (!-e "$lonidsdir/$handle.id") {
715: if ((ref($domref)) && ($name eq 'lonID') &&
716: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
717: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
718: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
719: $$domref = $possudom;
720: }
721: }
722: return undef;
723: }
1.916 albertel 724:
1.917 albertel 725: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
726: return undef if (!$opened);
1.916 albertel 727:
728: flock($idf,LOCK_SH);
729: my %disk_env;
730: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
731: &GDBM_READER(),0640)) {
732: return undef;
733: }
734:
735: if (!defined($disk_env{'user.name'})
736: || !defined($disk_env{'user.domain'})) {
1.1394 raeburn 737: untie(%disk_env);
1.916 albertel 738: return undef;
739: }
1.1245 raeburn 740:
741: if (ref($userhashref) eq 'HASH') {
742: $userhashref->{'name'} = $disk_env{'user.name'};
743: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1448 raeburn 744: if ($disk_env{'request.role'}) {
745: $userhashref->{'role'} = $disk_env{'request.role'};
746: }
1.1361 raeburn 747: $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375 raeburn 748: if ($userhashref->{'lti'}) {
749: $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
750: $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
751: }
1.1212 raeburn 752: }
1.1394 raeburn 753: untie(%disk_env);
1.1245 raeburn 754:
1.916 albertel 755: return $handle;
756: }
757:
1.830 albertel 758: sub timed_flock {
759: my ($file,$lock_type) = @_;
760: my $failed=0;
761: eval {
762: local $SIG{__DIE__}='DEFAULT';
763: local $SIG{ALRM}=sub {
764: $failed=1;
765: die("failed lock");
766: };
767: alarm(13);
768: flock($file,$lock_type);
769: alarm(0);
770: };
771: if ($failed) {
772: return undef;
773: } else {
774: return 1;
775: }
776: }
777:
1.1392 raeburn 778: sub get_sessionfile_vars {
779: my ($handle,$lonidsdir,$storearr) = @_;
780: my %returnhash;
781: unless (ref($storearr) eq 'ARRAY') {
782: return %returnhash;
783: }
784: if (-l "$lonidsdir/$handle.id") {
785: my $link = readlink("$lonidsdir/$handle.id");
786: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
787: $handle = $1;
788: }
789: }
790: if ((-e "$lonidsdir/$handle.id") &&
791: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
792: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
793: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
794: if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
795: flock($idf,LOCK_SH);
796: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
797: &GDBM_READER(),0640)) {
798: foreach my $item (@{$storearr}) {
799: $returnhash{$item} = $disk_env{$item};
800: }
801: untie(%disk_env);
802: }
803: }
804: }
805: }
806: return %returnhash;
807: }
808:
1.5 www 809: # ---------------------------------------------------------- Append Environment
810:
811: sub appenv {
1.949 raeburn 812: my ($newenv,$roles) = @_;
813: if (ref($newenv) eq 'HASH') {
814: foreach my $key (keys(%{$newenv})) {
815: my $refused = 0;
816: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
817: $refused = 1;
818: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 819: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 820: if (grep(/^\Q$role\E$/,@{$roles})) {
821: $refused = 0;
822: }
823: }
824: }
825: if ($refused) {
826: &logthis("<font color=\"blue\">WARNING: ".
827: "Attempt to modify environment ".$key." to ".$newenv->{$key}
828: .'</font>');
829: delete($newenv->{$key});
830: } else {
831: $env{$key}=$newenv->{$key};
832: }
833: }
1.1376 raeburn 834: my $lonids = $perlvar{'lonIDsDir'};
835: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
836: my $opened = open(my $env_file,'+<',$env{'user.environment'});
837: if ($opened
838: && &timed_flock($env_file,LOCK_EX)
839: &&
840: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
841: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
842: while (my ($key,$value) = each(%{$newenv})) {
843: $disk_env{$key} = $value;
844: }
845: untie(%disk_env);
846: }
1.35 www 847: }
1.191 harris41 848: }
1.56 www 849: return 'ok';
850: }
851: # ----------------------------------------------------- Delete from Environment
852:
853: sub delenv {
1.1104 raeburn 854: my ($delthis,$regexp,$roles) = @_;
855: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
856: my $refused = 1;
857: if (ref($roles) eq 'ARRAY') {
858: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
859: if (grep(/^\Q$role\E$/,@{$roles})) {
860: $refused = 0;
861: }
862: }
863: if ($refused) {
864: &logthis("<font color=\"blue\">WARNING: ".
865: "Attempt to delete from environment ".$delthis);
866: return 'error';
867: }
1.56 www 868: }
1.917 albertel 869: my $opened = open(my $env_file,'+<',$env{'user.environment'});
870: if ($opened
1.915 albertel 871: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 872: &&
873: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
874: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 875: foreach my $key (keys(%disk_env)) {
1.987 raeburn 876: if ($regexp) {
877: if ($key=~/^$delthis/) {
878: delete($env{$key});
879: delete($disk_env{$key});
880: }
881: } else {
882: if ($key=~/^\Q$delthis\E/) {
883: delete($env{$key});
884: delete($disk_env{$key});
885: }
886: }
1.448 albertel 887: }
1.783 albertel 888: untie(%disk_env);
1.5 www 889: }
890: return 'ok';
1.369 albertel 891: }
892:
1.790 albertel 893: sub get_env_multiple {
894: my ($name) = @_;
895: my @values;
896: if (defined($env{$name})) {
897: # exists is it an array
898: if (ref($env{$name})) {
899: @values=@{ $env{$name} };
900: } else {
901: $values[0]=$env{$name};
902: }
903: }
904: return(@values);
905: }
906:
1.958 www 907: # ------------------------------------------------------------------- Locking
908:
909: sub set_lock {
910: my ($text)=@_;
911: $locknum++;
912: my $id=$$.'-'.$locknum;
913: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
914: 'session.lock.'.$id => $text});
915: return $id;
916: }
917:
918: sub get_locks {
919: my $num=0;
920: my %texts=();
921: foreach my $lock (split(/\,/,$env{'session.locks'})) {
922: if ($lock=~/\w/) {
923: $num++;
924: $texts{$lock}=$env{'session.lock.'.$lock};
925: }
926: }
927: return ($num,%texts);
928: }
929:
930: sub remove_lock {
931: my ($id)=@_;
932: my $newlocks='';
933: foreach my $lock (split(/\,/,$env{'session.locks'})) {
934: if (($lock=~/\w/) && ($lock ne $id)) {
935: $newlocks.=','.$lock;
936: }
937: }
938: &appenv({'session.locks' => $newlocks});
939: &delenv('session.lock.'.$id);
940: }
941:
942: sub remove_all_locks {
943: my $activelocks=$env{'session.locks'};
944: foreach my $lock (split(/\,/,$env{'session.locks'})) {
945: if ($lock=~/\w/) {
946: &remove_lock($lock);
947: }
948: }
949: }
950:
951:
1.369 albertel 952: # ------------------------------------------ Find out current server userload
953: sub userload {
954: my $numusers=0;
955: {
956: opendir(LONIDS,$perlvar{'lonIDsDir'});
957: my $filename;
958: my $curtime=time;
959: while ($filename=readdir(LONIDS)) {
1.925 albertel 960: next if ($filename eq '.' || $filename eq '..');
961: next if ($filename =~ /publicuser_\d+\.id/);
1.1390 raeburn 962: next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404 albertel 963: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 964: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 965: }
966: closedir(LONIDS);
967: }
968: my $userloadpercent=0;
969: my $maxuserload=$perlvar{'lonUserLoadLim'};
970: if ($maxuserload) {
1.371 albertel 971: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 972: }
1.372 albertel 973: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 974: return $userloadpercent;
1.283 www 975: }
976:
1.1 albertel 977: # ------------------------------ Find server with least workload from spare.tab
1.11 www 978:
1.1 albertel 979: sub spareserver {
1.1451 raeburn 980: my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 981: my $spare_server;
1.370 albertel 982: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 983: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
984: : $userloadpercent;
1.1083 raeburn 985: my ($uint_dom,$remotesessions);
986: if (($udom ne '') && (&domain($udom) ne '')) {
987: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
988: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
989: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
990: $remotesessions = $udomdefaults{'remotesessions'};
991: }
1.1123 raeburn 992: my $spareshash = &this_host_spares($udom);
993: if (ref($spareshash) eq 'HASH') {
994: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
995: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279 raeburn 996: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
997: $try_server));
1.1123 raeburn 998: ($spare_server, $lowest_load) =
999: &compare_server_load($try_server, $spare_server, $lowest_load);
1000: }
1.1083 raeburn 1001: }
1.784 albertel 1002:
1.1123 raeburn 1003: my $found_server = ($spare_server ne '' && $lowest_load < 100);
1004:
1005: if (!$found_server) {
1006: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1007: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279 raeburn 1008: next unless (&spare_can_host($udom,$uint_dom,
1009: $remotesessions,$try_server));
1.1123 raeburn 1010: ($spare_server, $lowest_load) =
1011: &compare_server_load($try_server, $spare_server, $lowest_load);
1012: }
1013: }
1014: }
1.784 albertel 1015: }
1016:
1017: if (!$want_server_name) {
1.1001 raeburn 1018: if (defined($spare_server)) {
1019: my $hostname = &hostname($spare_server);
1.1083 raeburn 1020: if (defined($hostname)) {
1.1397 raeburn 1021: my $protocol = 'http';
1022: if ($protocol{$spare_server} eq 'https') {
1023: $protocol = $protocol{$spare_server};
1024: }
1.1451 raeburn 1025: my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
1026: $hostname = $alias if ($alias ne '');
1.1001 raeburn 1027: $spare_server = $protocol.'://'.$hostname;
1028: }
1029: }
1.784 albertel 1030: }
1031: return $spare_server;
1032: }
1033:
1034: sub compare_server_load {
1.1253 raeburn 1035: my ($try_server, $spare_server, $lowest_load, $required) = @_;
1036:
1037: if ($required) {
1038: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
1039: my $remoterev = &get_server_loncaparev(undef,$try_server);
1040: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
1041: if (($major eq '' && $minor eq '') ||
1042: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
1043: return ($spare_server,$lowest_load);
1044: }
1045: }
1.784 albertel 1046:
1047: my $loadans = &reply('load', $try_server);
1048: my $userloadans = &reply('userload',$try_server);
1049:
1050: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 1051: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 1052: }
1053:
1054: my $load;
1055: if ($loadans =~ /\d/) {
1056: if ($userloadans =~ /\d/) {
1057: #both are numbers, pick the bigger one
1058: $load = ($loadans > $userloadans) ? $loadans
1059: : $userloadans;
1.411 albertel 1060: } else {
1.784 albertel 1061: $load = $loadans;
1.411 albertel 1062: }
1.784 albertel 1063: } else {
1064: $load = $userloadans;
1065: }
1066:
1067: if (($load =~ /\d/) && ($load < $lowest_load)) {
1068: $spare_server = $try_server;
1069: $lowest_load = $load;
1.370 albertel 1070: }
1.784 albertel 1071: return ($spare_server,$lowest_load);
1.202 matthew 1072: }
1.914 albertel 1073:
1074: # --------------------------- ask offload servers if user already has a session
1075: sub find_existing_session {
1076: my ($udom,$uname) = @_;
1.1123 raeburn 1077: my $spareshash = &this_host_spares($udom);
1078: if (ref($spareshash) eq 'HASH') {
1079: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1080: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1081: return $try_server if (&has_user_session($try_server, $udom, $uname));
1082: }
1083: }
1084: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1085: foreach my $try_server (@{ $spareshash->{'default'} }) {
1086: return $try_server if (&has_user_session($try_server, $udom, $uname));
1087: }
1088: }
1.914 albertel 1089: }
1090: return;
1091: }
1092:
1.1411 raeburn 1093: sub delusersession {
1094: my ($lonid,$udom,$uname) = @_;
1095: my $uprimary_id = &domain($udom,'primary');
1096: my $uintdom = &internet_dom($uprimary_id);
1097: my $intdom = &internet_dom($lonid);
1098: my $serverhomedom = &host_domain($lonid);
1099: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1100: return &reply(join(':','delusersession',
1101: map {&escape($_)} ($udom,$uname)),$lonid);
1102: }
1103: return;
1104: }
1105:
1.1389 raeburn 1106: # check if user's browser sent load balancer cookie and server still has session
1107: # and is not overloaded.
1108: sub check_for_balancer_cookie {
1109: my ($r,$update_mtime) = @_;
1110: my ($otherserver,$cookie);
1111: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1112: if (exists($cookies{'balanceID'})) {
1113: my $balid = $cookies{'balanceID'};
1114: $cookie=&LONCAPA::clean_handle($balid->value);
1115: my $balancedir=$r->dir_config('lonBalanceDir');
1116: if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
1117: if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
1118: my ($possudom,$possuname) = ($1,$2);
1119: my $has_session = 0;
1120: if ((&domain($possudom) ne '') &&
1121: (&homeserver($possuname,$possudom) ne 'no_host')) {
1122: my $try_server;
1123: my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
1124: if ($opened) {
1125: flock($idf,LOCK_SH);
1126: while (my $line = <$idf>) {
1127: chomp($line);
1128: if (&hostname($line) ne '') {
1129: $try_server = $line;
1130: last;
1131: }
1132: }
1133: close($idf);
1134: if (($try_server) &&
1135: (&has_user_session($try_server,$possudom,$possuname))) {
1136: my $lowest_load = 30000;
1137: ($otherserver,$lowest_load) =
1138: &compare_server_load($try_server,undef,$lowest_load);
1139: if ($otherserver ne '' && $lowest_load < 100) {
1140: $has_session = 1;
1141: } else {
1142: undef($otherserver);
1143: }
1144: }
1145: }
1146: }
1147: if ($has_session) {
1148: if ($update_mtime) {
1149: my $atime = my $mtime = time;
1150: utime($atime,$mtime,"$balancedir/$cookie.id");
1151: }
1152: } else {
1153: unlink("$balancedir/$cookie.id");
1154: }
1155: }
1156: }
1157: }
1158: return ($otherserver,$cookie);
1159: }
1160:
1.1431 raeburn 1161: sub updatebalcookie {
1162: my ($cookie,$balancer,$lastentry)=@_;
1163: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1164: my ($udom,$uname) = ($1,$2);
1165: my $uprimary_id = &domain($udom,'primary');
1166: my $uintdom = &internet_dom($uprimary_id);
1167: my $intdom = &internet_dom($balancer);
1168: my $serverhomedom = &host_domain($balancer);
1169: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1170: return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
1171: }
1172: }
1173: return;
1174: }
1175:
1.1389 raeburn 1176: sub delbalcookie {
1177: my ($cookie,$balancer) =@_;
1178: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1179: my ($udom,$uname) = ($1,$2);
1180: my $uprimary_id = &domain($udom,'primary');
1181: my $uintdom = &internet_dom($uprimary_id);
1182: my $intdom = &internet_dom($balancer);
1183: my $serverhomedom = &host_domain($balancer);
1184: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1431 raeburn 1185: return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1389 raeburn 1186: }
1187: }
1188: }
1189:
1.914 albertel 1190: # -------------------------------- ask if server already has a session for user
1191: sub has_user_session {
1192: my ($lonid,$udom,$uname) = @_;
1193: my $result = &reply(join(':','userhassession',
1194: map {&escape($_)} ($udom,$uname)),$lonid);
1195: return 1 if ($result eq 'ok');
1196:
1197: return 0;
1198: }
1199:
1.1076 raeburn 1200: # --------- determine least loaded server in a user's domain which allows login
1201:
1202: sub choose_server {
1.1259 raeburn 1203: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1204: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1205: my %servers = &get_servers($udom);
1.1076 raeburn 1206: my $lowest_load = 30000;
1.1259 raeburn 1207: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1208: if ($skiploadbal) {
1209: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1210: unless (defined($cached)) {
1211: my $cachetime = 60*60*24;
1212: my %domconfig =
1213: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1214: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1215: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1216: $cachetime);
1217: }
1218: }
1219: }
1.1076 raeburn 1220: foreach my $lonhost (keys(%servers)) {
1.1259 raeburn 1221: if ($skiploadbal) {
1222: if (ref($balancers) eq 'HASH') {
1223: next if (exists($balancers->{$lonhost}));
1224: }
1.1389 raeburn 1225: }
1.1115 raeburn 1226: my $loginvia;
1227: if ($checkloginvia) {
1228: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1229: if ($loginvia) {
1230: my ($server,$path) = split(/:/,$loginvia);
1231: ($login_host, $lowest_load) =
1.1253 raeburn 1232: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1233: if ($login_host eq $server) {
1234: $portal_path = $path;
1.1151 raeburn 1235: $isredirect = 1;
1.1116 raeburn 1236: }
1237: } else {
1238: ($login_host, $lowest_load) =
1.1253 raeburn 1239: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1240: if ($login_host eq $lonhost) {
1241: $portal_path = '';
1.1151 raeburn 1242: $isredirect = '';
1.1116 raeburn 1243: }
1244: }
1245: } else {
1.1076 raeburn 1246: ($login_host, $lowest_load) =
1.1253 raeburn 1247: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1248: }
1249: }
1250: if ($login_host ne '') {
1.1116 raeburn 1251: $hostname = &hostname($login_host);
1.1076 raeburn 1252: }
1.1331 raeburn 1253: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1254: }
1255:
1.1420 raeburn 1256: sub get_course_sessions {
1257: my ($cnum,$cdom,$lastactivity) = @_;
1258: my %servers = &internet_dom_servers($cdom);
1259: my %returnhash;
1260: foreach my $server (sort(keys(%servers))) {
1261: my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
1262: my @pairs=split(/\&/,$rep);
1263: unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
1264: foreach my $item (@pairs) {
1265: my ($key,$value)=split(/=/,$item,2);
1266: $key = &unescape($key);
1267: next if ($key =~ /^error: 2 /);
1268: if (exists($returnhash{$key})) {
1269: next if ($value < $returnhash{$key});
1270: }
1271: $returnhash{$key}=$value;
1272: }
1273: }
1274: }
1275: return %returnhash;
1276: }
1277:
1.202 matthew 1278: # --------------------------------------------- Try to change a user's password
1279:
1280: sub changepass {
1.799 raeburn 1281: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1282: $currentpass = &escape($currentpass);
1283: $newpass = &escape($newpass);
1.1030 raeburn 1284: my $lonhost = $perlvar{'lonHostID'};
1285: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1286: $server);
1287: if (! $answer) {
1288: &logthis("No reply on password change request to $server ".
1289: "by $uname in domain $udom.");
1290: } elsif ($answer =~ "^ok") {
1291: &logthis("$uname in $udom successfully changed their password ".
1292: "on $server.");
1293: } elsif ($answer =~ "^pwchange_failure") {
1294: &logthis("$uname in $udom was unable to change their password ".
1295: "on $server. The action was blocked by either lcpasswd ".
1296: "or pwchange");
1297: } elsif ($answer =~ "^non_authorized") {
1298: &logthis("$uname in $udom did not get their password correct when ".
1299: "attempting to change it on $server.");
1300: } elsif ($answer =~ "^auth_mode_error") {
1301: &logthis("$uname in $udom attempted to change their password despite ".
1302: "not being locally or internally authenticated on $server.");
1303: } elsif ($answer =~ "^unknown_user") {
1304: &logthis("$uname in $udom attempted to change their password ".
1305: "on $server but were unable to because $server is not ".
1306: "their home server.");
1307: } elsif ($answer =~ "^refused") {
1308: &logthis("$server refused to change $uname in $udom password because ".
1309: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1310: } elsif ($answer =~ "invalid_client") {
1311: &logthis("$server refused to change $uname in $udom password because ".
1312: "it was a reset by e-mail originating from an invalid server.");
1.1408 raeburn 1313: } elsif ($answer =~ "^prioruse") {
1314: &logthis("$server refused to change $uname in $udom password because ".
1315: "the password had been used before");
1.202 matthew 1316: }
1317: return $answer;
1.1 albertel 1318: }
1319:
1.169 harris41 1320: # ----------------------- Try to determine user's current authentication scheme
1321:
1322: sub queryauthenticate {
1323: my ($uname,$udom)=@_;
1.456 albertel 1324: my $uhome=&homeserver($uname,$udom);
1325: if (!$uhome) {
1326: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1327: return 'no_host';
1328: }
1329: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1330: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1331: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1332: }
1.456 albertel 1333: return $answer;
1.169 harris41 1334: }
1335:
1.1 albertel 1336: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1337:
1.1 albertel 1338: sub authenticate {
1.1073 raeburn 1339: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1340: $upass=&escape($upass);
1341: $uname= &LONCAPA::clean_username($uname);
1.836 www 1342: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1343: my $newhome;
1.836 www 1344: if ((!$uhome) || ($uhome eq 'no_host')) {
1345: # Maybe the machine was offline and only re-appeared again recently?
1346: &reconlonc();
1347: # One more
1.952 raeburn 1348: $uhome=&homeserver($uname,$udom,1);
1349: if (($uhome eq 'no_host') && $checkdefauth) {
1350: if (defined(&domain($udom,'primary'))) {
1351: $newhome=&domain($udom,'primary');
1352: }
1353: if ($newhome ne '') {
1354: $uhome = $newhome;
1355: }
1356: }
1.836 www 1357: if ((!$uhome) || ($uhome eq 'no_host')) {
1358: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1359: return 'no_host';
1360: }
1.1 albertel 1361: }
1.1073 raeburn 1362: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1363: if ($answer eq 'authorized') {
1.952 raeburn 1364: if ($newhome) {
1365: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1366: return 'no_account_on_host';
1367: } else {
1368: &logthis("User $uname at $udom authorized by $uhome");
1369: return $uhome;
1370: }
1.471 albertel 1371: }
1372: if ($answer eq 'non_authorized') {
1373: &logthis("User $uname at $udom rejected by $uhome");
1374: return 'no_host';
1.9 www 1375: }
1.471 albertel 1376: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1377: return 'no_host';
1378: }
1379:
1.1073 raeburn 1380: sub can_host_session {
1.1074 raeburn 1381: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1382: my $canhost = 1;
1.1074 raeburn 1383: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1384: if (ref($remotesessions) eq 'HASH') {
1385: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1386: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1387: $canhost = 0;
1388: } else {
1389: $canhost = 1;
1390: }
1391: }
1392: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1393: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1394: $canhost = 1;
1395: } else {
1396: $canhost = 0;
1397: }
1398: }
1399: if ($canhost) {
1400: if ($remotesessions->{'version'} ne '') {
1401: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1402: if ($reqmajor ne '' && $reqminor ne '') {
1403: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1404: my $major = $1;
1405: my $minor = $2;
1406: if (($major < $reqmajor ) ||
1407: (($major == $reqmajor) && ($minor < $reqminor))) {
1408: $canhost = 0;
1409: }
1410: } else {
1411: $canhost = 0;
1412: }
1413: }
1414: }
1415: }
1416: }
1417: if ($canhost) {
1418: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1419: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1420: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1421: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1422: if (($uint_dom ne '') &&
1423: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1424: $canhost = 0;
1425: } else {
1426: $canhost = 1;
1427: }
1428: }
1429: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1430: if (($uint_dom ne '') &&
1431: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1432: $canhost = 1;
1433: } else {
1434: $canhost = 0;
1435: }
1436: }
1437: }
1438: }
1439: return $canhost;
1440: }
1441:
1.1083 raeburn 1442: sub spare_can_host {
1443: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1444: my $canhost=1;
1.1279 raeburn 1445: my $try_server_hostname = &hostname($try_server);
1446: my $serverhomeID = &get_server_homeID($try_server_hostname);
1447: my $serverhomedom = &host_domain($serverhomeID);
1448: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1449: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1450: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1451: $canhost = 0;
1452: }
1453: }
1.1439 raeburn 1454: if ($canhost) {
1455: if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
1456: if ($defdomdefaults{'offloadoth'}{$try_server}) {
1457: unless (&shared_institution($udom,$try_server)) {
1458: $canhost = 0;
1459: }
1460: }
1461: }
1462: }
1.1279 raeburn 1463: if (($canhost) && ($uint_dom)) {
1464: my @intdoms;
1465: my $internet_names = &get_internet_names($try_server);
1466: if (ref($internet_names) eq 'ARRAY') {
1467: @intdoms = @{$internet_names};
1468: }
1469: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1470: my $remoterev = &get_server_loncaparev(undef,$try_server);
1471: $canhost = &can_host_session($udom,$try_server,$remoterev,
1472: $remotesessions,
1473: $defdomdefaults{'hostedsessions'});
1474: }
1.1083 raeburn 1475: }
1476: return $canhost;
1477: }
1478:
1.1123 raeburn 1479: sub this_host_spares {
1480: my ($dom) = @_;
1.1126 raeburn 1481: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1482: my @hosts = ¤t_machine_ids();
1483: foreach my $lonhost (@hosts) {
1484: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1485: $dom_in_use = $dom;
1486: $lonhost_in_use = $lonhost;
1.1123 raeburn 1487: last;
1488: }
1489: }
1.1126 raeburn 1490: if ($dom_in_use ne '') {
1491: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1492: }
1493: if (ref($result) ne 'HASH') {
1494: $lonhost_in_use = $perlvar{'lonHostID'};
1495: $dom_in_use = &host_domain($lonhost_in_use);
1496: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1497: if (ref($result) ne 'HASH') {
1498: $result = \%spareid;
1499: }
1500: }
1501: return $result;
1502: }
1503:
1504: sub spares_for_offload {
1505: my ($dom_in_use,$lonhost_in_use) = @_;
1506: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1507: if (defined($cached)) {
1508: return $result;
1509: } else {
1.1126 raeburn 1510: my $cachetime = 60*60*24;
1511: my %domconfig =
1512: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1513: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1514: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1515: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1516: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1517: }
1518: }
1519: }
1520: }
1.1126 raeburn 1521: return;
1.1123 raeburn 1522: }
1523:
1.1129 raeburn 1524: sub get_lonbalancer_config {
1525: my ($servers) = @_;
1526: my ($currbalancer,$currtargets);
1527: if (ref($servers) eq 'HASH') {
1528: foreach my $server (keys(%{$servers})) {
1529: my %what = (
1530: spareid => 1,
1531: perlvar => 1,
1532: );
1533: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1534: if ($result eq 'ok') {
1535: if (ref($returnhash) eq 'HASH') {
1536: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1537: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1538: $currbalancer = $server;
1539: $currtargets = {};
1540: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1541: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1542: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1543: }
1544: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1545: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1546: }
1547: }
1548: last;
1549: }
1550: }
1551: }
1552: }
1553: }
1554: }
1555: return ($currbalancer,$currtargets);
1556: }
1557:
1558: sub check_loadbalancing {
1.1331 raeburn 1559: my ($uname,$udom,$caller) = @_;
1.1191 raeburn 1560: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391 raeburn 1561: $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129 raeburn 1562: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1563: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1564: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1565: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1566: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1567: my $serverhomedom = &host_domain($lonhost);
1.1307 raeburn 1568: my $domneedscache;
1.1129 raeburn 1569: my $cachetime = 60*60*24;
1570:
1571: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1572: $dom_in_use = $udom;
1573: $homeintdom = 1;
1574: } else {
1575: $dom_in_use = $serverhomedom;
1576: }
1577: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1578: unless (defined($cached)) {
1579: my %domconfig =
1580: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1581: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1582: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307 raeburn 1583: } else {
1584: $domneedscache = $dom_in_use;
1.1129 raeburn 1585: }
1586: }
1587: if (ref($result) eq 'HASH') {
1.1391 raeburn 1588: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191 raeburn 1589: &check_balancer_result($result,@hosts);
1.1129 raeburn 1590: if ($is_balancer) {
1591: if (ref($currrules) eq 'HASH') {
1592: if ($homeintdom) {
1593: if ($uname ne '') {
1594: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1595: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1596: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1597: $rule_in_effect = $currrules->{'_LC_author'};
1598: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1599: $rule_in_effect = $currrules->{'_LC_adv'}
1600: }
1601: }
1602: if ($rule_in_effect eq '') {
1603: my %userenv = &userenvironment($udom,$uname,'inststatus');
1604: if ($userenv{'inststatus'} ne '') {
1605: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1606: my ($othertitle,$usertypes,$types) =
1607: &Apache::loncommon::sorted_inst_types($udom);
1608: if (ref($types) eq 'ARRAY') {
1609: foreach my $type (@{$types}) {
1610: if (grep(/^\Q$type\E$/,@statuses)) {
1611: if (exists($currrules->{$type})) {
1612: $rule_in_effect = $currrules->{$type};
1613: }
1614: }
1615: }
1616: }
1617: } else {
1618: if (exists($currrules->{'default'})) {
1619: $rule_in_effect = $currrules->{'default'};
1620: }
1621: }
1622: }
1623: } else {
1624: if (exists($currrules->{'default'})) {
1625: $rule_in_effect = $currrules->{'default'};
1626: }
1627: }
1628: } else {
1629: if ($currrules->{'_LC_external'} ne '') {
1630: $rule_in_effect = $currrules->{'_LC_external'};
1631: }
1632: }
1633: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1634: $uname,$udom);
1635: }
1636: }
1637: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1638: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1639: unless (defined($cached)) {
1640: my %domconfig =
1641: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1642: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307 raeburn 1643: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1644: } else {
1645: $domneedscache = $serverhomedom;
1.1129 raeburn 1646: }
1647: }
1648: if (ref($result) eq 'HASH') {
1.1391 raeburn 1649: ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191 raeburn 1650: &check_balancer_result($result,@hosts);
1651: if ($is_balancer) {
1.1129 raeburn 1652: if (ref($currrules) eq 'HASH') {
1653: if ($currrules->{'_LC_internetdom'} ne '') {
1654: $rule_in_effect = $currrules->{'_LC_internetdom'};
1655: }
1656: }
1657: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1658: $uname,$udom);
1659: }
1660: } else {
1661: if ($perlvar{'lonBalancer'} eq 'yes') {
1662: $is_balancer = 1;
1663: $offloadto = &this_host_spares($dom_in_use);
1664: }
1.1307 raeburn 1665: unless (defined($cached)) {
1666: $domneedscache = $serverhomedom;
1667: }
1.1129 raeburn 1668: }
1669: } else {
1670: if ($perlvar{'lonBalancer'} eq 'yes') {
1671: $is_balancer = 1;
1672: $offloadto = &this_host_spares($dom_in_use);
1673: }
1.1307 raeburn 1674: unless (defined($cached)) {
1675: $domneedscache = $serverhomedom;
1676: }
1677: }
1678: if ($domneedscache) {
1679: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1680: }
1.1430 raeburn 1681: if (($is_balancer) && ($caller ne 'switchserver')) {
1.1176 raeburn 1682: my $lowest_load = 30000;
1683: if (ref($offloadto) eq 'HASH') {
1684: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1685: foreach my $try_server (@{$offloadto->{'primary'}}) {
1686: ($otherserver,$lowest_load) =
1687: &compare_server_load($try_server,$otherserver,$lowest_load);
1688: }
1.1129 raeburn 1689: }
1.1176 raeburn 1690: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1691:
1.1176 raeburn 1692: if (!$found_server) {
1693: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1694: foreach my $try_server (@{$offloadto->{'default'}}) {
1695: ($otherserver,$lowest_load) =
1696: &compare_server_load($try_server,$otherserver,$lowest_load);
1697: }
1698: }
1699: }
1700: } elsif (ref($offloadto) eq 'ARRAY') {
1701: if (@{$offloadto} == 1) {
1702: $otherserver = $offloadto->[0];
1703: } elsif (@{$offloadto} > 1) {
1704: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1705: ($otherserver,$lowest_load) =
1706: &compare_server_load($try_server,$otherserver,$lowest_load);
1707: }
1708: }
1709: }
1.1331 raeburn 1710: unless ($caller eq 'login') {
1711: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1712: $is_balancer = 0;
1713: if ($uname ne '' && $udom ne '') {
1714: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389 raeburn 1715: &appenv({'user.loadbalexempt' => $lonhost,
1.1331 raeburn 1716: 'user.loadbalcheck.time' => time});
1717: }
1.1176 raeburn 1718: }
1.1129 raeburn 1719: }
1720: }
1.1430 raeburn 1721: }
1722: if (($is_balancer) && (!$homeintdom)) {
1723: undef($setcookie);
1.1129 raeburn 1724: }
1.1391 raeburn 1725: return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129 raeburn 1726: }
1727:
1.1191 raeburn 1728: sub check_balancer_result {
1729: my ($result,@hosts) = @_;
1.1391 raeburn 1730: my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191 raeburn 1731: if (ref($result) eq 'HASH') {
1732: if ($result->{'lonhost'} ne '') {
1733: my $currbalancer = $result->{'lonhost'};
1734: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1735: $is_balancer = 1;
1736: $currtargets = $result->{'targets'};
1737: $currrules = $result->{'rules'};
1738: }
1.1391 raeburn 1739: $dom_balancers = $currbalancer;
1.1191 raeburn 1740: } else {
1.1391 raeburn 1741: if (keys(%{$result})) {
1742: foreach my $key (keys(%{$result})) {
1743: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1744: (ref($result->{$key}) eq 'HASH')) {
1745: $is_balancer = 1;
1746: $currrules = $result->{$key}{'rules'};
1747: $currtargets = $result->{$key}{'targets'};
1748: $setcookie = $result->{$key}{'cookie'};
1749: last;
1750: }
1.1191 raeburn 1751: }
1.1391 raeburn 1752: $dom_balancers = join(',',sort(keys(%{$result})));
1.1191 raeburn 1753: }
1754: }
1755: }
1.1391 raeburn 1756: return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191 raeburn 1757: }
1758:
1.1129 raeburn 1759: sub get_loadbalancer_targets {
1760: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1761: my $offloadto;
1.1175 raeburn 1762: if ($rule_in_effect eq 'none') {
1763: return [$perlvar{'lonHostID'}];
1764: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1765: $offloadto = $currtargets;
1766: } else {
1767: if ($rule_in_effect eq 'homeserver') {
1768: my $homeserver = &homeserver($uname,$udom);
1769: if ($homeserver ne 'no_host') {
1770: $offloadto = [$homeserver];
1771: }
1772: } elsif ($rule_in_effect eq 'externalbalancer') {
1773: my %domconfig =
1774: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1775: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1776: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1777: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1778: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1779: }
1780: }
1781: } else {
1.1178 raeburn 1782: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1783: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1784: if (&hostname($remotebalancer) ne '') {
1785: $offloadto = [$remotebalancer];
1786: }
1787: }
1788: } elsif (&hostname($rule_in_effect) ne '') {
1789: $offloadto = [$rule_in_effect];
1790: }
1791: }
1792: return $offloadto;
1793: }
1794:
1.1127 raeburn 1795: sub internet_dom_servers {
1796: my ($dom) = @_;
1797: my (%uniqservers,%servers);
1798: my $primaryserver = &hostname(&domain($dom,'primary'));
1799: my @machinedoms = &machine_domains($primaryserver);
1800: foreach my $mdom (@machinedoms) {
1801: my %currservers = %servers;
1802: my %server = &get_servers($mdom);
1803: %servers = (%currservers,%server);
1804: }
1805: my %by_hostname;
1806: foreach my $id (keys(%servers)) {
1807: push(@{$by_hostname{$servers{$id}}},$id);
1808: }
1809: foreach my $hostname (sort(keys(%by_hostname))) {
1810: if (@{$by_hostname{$hostname}} > 1) {
1811: my $match = 0;
1812: foreach my $id (@{$by_hostname{$hostname}}) {
1813: if (&host_domain($id) eq $dom) {
1814: $uniqservers{$id} = $hostname;
1815: $match = 1;
1816: }
1817: }
1818: unless ($match) {
1819: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1820: }
1821: } else {
1822: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1823: }
1824: }
1825: return %uniqservers;
1826: }
1827:
1.1347 raeburn 1828: sub trusted_domains {
1829: my ($cmdtype,$calldom) = @_;
1.1349 raeburn 1830: my ($trusted,$untrusted);
1.1347 raeburn 1831: if (&domain($calldom) eq '') {
1.1349 raeburn 1832: return ($trusted,$untrusted);
1.1347 raeburn 1833: }
1.1395 raeburn 1834: unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349 raeburn 1835: return ($trusted,$untrusted);
1.1347 raeburn 1836: }
1837: my $callprimary = &domain($calldom,'primary');
1838: my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
1839: if ($intcalldom eq '') {
1.1349 raeburn 1840: return ($trusted,$untrusted);
1.1347 raeburn 1841: }
1842:
1843: my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
1844: unless (defined($cached)) {
1845: my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
1846: &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
1847: $trustconfig = $domconfig{'trust'};
1848: }
1849: if (ref($trustconfig)) {
1850: my (%possexc,%possinc,@allexc,@allinc);
1851: if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
1852: if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
1853: map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}};
1854: }
1855: if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395 raeburn 1856: $possinc{$intcalldom} = 1;
1.1347 raeburn 1857: map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
1858: }
1859: }
1860: if (keys(%possexc)) {
1861: if (keys(%possinc)) {
1862: foreach my $key (sort(keys(%possexc))) {
1863: next if ($key eq $intcalldom);
1864: unless ($possinc{$key}) {
1865: push(@allexc,$key);
1866: }
1867: }
1868: } else {
1869: @allexc = sort(keys(%possexc));
1870: }
1871: }
1872: if (keys(%possinc)) {
1873: $possinc{$intcalldom} = 1;
1874: @allinc = sort(keys(%possinc));
1875: }
1876: if ((@allexc > 0) || (@allinc > 0)) {
1877: my %doms_by_intdom;
1878: my %allintdoms = &all_host_intdom();
1879: my %alldoms = &all_host_domain();
1880: foreach my $key (%allintdoms) {
1881: if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
1882: unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
1883: push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
1884: }
1885: } else {
1886: $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}];
1887: }
1888: }
1889: foreach my $exc (@allexc) {
1890: if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395 raeburn 1891: push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347 raeburn 1892: }
1893: }
1894: foreach my $inc (@allinc) {
1895: if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395 raeburn 1896: push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347 raeburn 1897: }
1898: }
1899: }
1900: }
1.1349 raeburn 1901: return ($trusted,$untrusted);
1.1347 raeburn 1902: }
1903:
1904: sub will_trust {
1905: my ($cmdtype,$domain,$possdom) = @_;
1906: return 1 if ($domain eq $possdom);
1907: my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
1908: my $willtrust;
1909: if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
1910: if (grep(/^\Q$domain\E$/,@{$trustedref})) {
1911: $willtrust = 1;
1912: }
1913: } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
1914: unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
1915: $willtrust = 1;
1916: }
1917: } else {
1918: $willtrust = 1;
1919: }
1920: return $willtrust;
1921: }
1922:
1.1 albertel 1923: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1924:
1.599 albertel 1925: my %homecache;
1.1 albertel 1926: sub homeserver {
1.230 stredwic 1927: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1928: my $index="$uname:$udom";
1.426 albertel 1929:
1.599 albertel 1930: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1931:
1932: my %servers = &get_servers($udom,'library');
1933: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1934: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1935: exists($badServerCache{$tryserver}));
1.841 albertel 1936:
1937: my $answer=reply("home:$udom:$uname",$tryserver);
1938: if ($answer eq 'found') {
1939: delete($badServerCache{$tryserver});
1940: return $homecache{$index}=$tryserver;
1941: } elsif ($answer eq 'no_host') {
1942: $badServerCache{$tryserver}=1;
1943: }
1.1 albertel 1944: }
1945: return 'no_host';
1.70 www 1946: }
1947:
1.1300 raeburn 1948: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70 www 1949:
1950: sub idget {
1.1300 raeburn 1951: my ($udom,$idsref,$namespace)=@_;
1.70 www 1952: my %returnhash=();
1.1300 raeburn 1953: my @ids=();
1954: if (ref($idsref) eq 'ARRAY') {
1955: @ids = @{$idsref};
1956: } else {
1957: return %returnhash;
1958: }
1959: if ($namespace eq '') {
1960: $namespace = 'ids';
1961: }
1.70 www 1962:
1.841 albertel 1963: my %servers = &get_servers($udom,'library');
1964: foreach my $tryserver (keys(%servers)) {
1.1299 raeburn 1965: my $idlist=join('&', map { &escape($_); } @ids);
1.1300 raeburn 1966: if ($namespace eq 'ids') {
1967: $idlist=~tr/A-Z/a-z/;
1968: }
1969: my $reply;
1970: if ($namespace eq 'ids') {
1971: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1972: } else {
1973: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1974: }
1.841 albertel 1975: my @answer=();
1976: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1977: @answer=split(/\&/,$reply);
1978: } ;
1979: my $i;
1980: for ($i=0;$i<=$#ids;$i++) {
1981: if ($answer[$i]) {
1.1299 raeburn 1982: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300 raeburn 1983: }
1.841 albertel 1984: }
1.1300 raeburn 1985: }
1.70 www 1986: return %returnhash;
1987: }
1988:
1989: # ------------------------------------- Find the IDs behind a list of usernames
1990:
1991: sub idrget {
1992: my ($udom,@unames)=@_;
1993: my %returnhash=();
1.800 albertel 1994: foreach my $uname (@unames) {
1995: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1996: }
1.70 www 1997: return %returnhash;
1998: }
1999:
1.1300 raeburn 2000: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70 www 2001:
2002: sub idput {
1.1300 raeburn 2003: my ($udom,$idsref,$uhom,$namespace)=@_;
1.70 www 2004: my %servers=();
1.1300 raeburn 2005: my %ids=();
2006: my %byid = ();
2007: if (ref($idsref) eq 'HASH') {
2008: %ids=%{$idsref};
2009: }
2010: if ($namespace eq '') {
2011: $namespace = 'ids';
2012: }
1.800 albertel 2013: foreach my $uname (keys(%ids)) {
2014: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300 raeburn 2015: if ($uhom eq '') {
2016: $uhom=&homeserver($uname,$udom);
2017: }
1.70 www 2018: if ($uhom ne 'no_host') {
1.800 albertel 2019: my $esc_unam=&escape($uname);
1.1300 raeburn 2020: if ($namespace eq 'ids') {
2021: my $id=&escape($ids{$uname});
2022: $id=~tr/A-Z/a-z/;
2023: my $esc_unam=&escape($uname);
2024: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70 www 2025: } else {
1.1300 raeburn 2026: my @currids = split(/,/,$ids{$uname});
2027: foreach my $id (@currids) {
2028: $byid{$uhom}{$id} .= $uname.',';
2029: }
2030: }
2031: }
2032: }
2033: if ($namespace eq 'clickers') {
2034: foreach my $server (keys(%byid)) {
2035: if (ref($byid{$server}) eq 'HASH') {
2036: foreach my $id (keys(%{$byid{$server}})) {
2037: $byid{$server} =~ s/,$//;
2038: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
2039: }
1.70 www 2040: }
2041: }
1.191 harris41 2042: }
1.800 albertel 2043: foreach my $server (keys(%servers)) {
1.1300 raeburn 2044: $servers{$server} =~ s/\&$//;
2045: if ($namespace eq 'ids') {
2046: &critical('idput:'.$udom.':'.$servers{$server},$server);
2047: } else {
2048: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
2049: }
1.191 harris41 2050: }
1.344 www 2051: }
2052:
1.1300 raeburn 2053: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231 raeburn 2054:
2055: sub iddel {
1.1300 raeburn 2056: my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231 raeburn 2057: my %result=();
1.1300 raeburn 2058: my %ids=();
2059: my %byid = ();
2060: if (ref($idshashref) eq 'HASH') {
2061: %ids=%{$idshashref};
2062: } else {
1.1231 raeburn 2063: return %result;
2064: }
1.1300 raeburn 2065: if ($namespace eq '') {
2066: $namespace = 'ids';
2067: }
1.1231 raeburn 2068: my %servers=();
1.1300 raeburn 2069: while (my ($id,$unamestr) = each(%ids)) {
2070: if ($namespace eq 'ids') {
2071: my $uhom = $uhome;
2072: if ($uhom eq '') {
2073: $uhom=&homeserver($unamestr,$udom);
2074: }
2075: if ($uhom ne 'no_host') {
2076: $servers{$uhom}.='&'.&escape($id);
2077: }
2078: } else {
2079: my @curritems = split(/,/,$ids{$id});
2080: foreach my $uname (@curritems) {
2081: my $uhom = $uhome;
2082: if ($uhom eq '') {
2083: $uhom=&homeserver($uname,$udom);
2084: }
2085: if ($uhom ne 'no_host') {
2086: $byid{$uhom}{$id} .= $uname.',';
2087: }
2088: }
1.1231 raeburn 2089: }
1.1300 raeburn 2090: }
2091: if ($namespace eq 'clickers') {
2092: foreach my $server (keys(%byid)) {
2093: if (ref($byid{$server}) eq 'HASH') {
2094: foreach my $id (keys(%{$byid{$server}})) {
2095: $byid{$server}{$id} =~ s/,$//;
2096: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
2097: }
1.1231 raeburn 2098: }
2099: }
2100: }
2101: foreach my $server (keys(%servers)) {
1.1300 raeburn 2102: $servers{$server} =~ s/\&$//;
2103: if ($namespace eq 'ids') {
2104: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
2105: } elsif ($namespace eq 'clickers') {
2106: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
2107: }
1.1231 raeburn 2108: }
2109: return %result;
2110: }
2111:
1.1300 raeburn 2112: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
2113:
2114: sub updateclickers {
2115: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
2116: my %clickers;
2117: if (ref($idshashref) eq 'HASH') {
2118: %clickers=%{$idshashref};
2119: } else {
2120: return;
2121: }
2122: my $items='';
2123: foreach my $item (keys(%clickers)) {
2124: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
2125: }
2126: $items=~s/\&$//;
2127: my $request = "updateclickers:$udom:$action:$items";
2128: if ($critical) {
2129: return &critical($request,$uhome);
2130: } else {
2131: return &reply($request,$uhome);
2132: }
2133: }
2134:
1.1023 raeburn 2135: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 2136: sub dump_dom {
1.1165 droeschl 2137: my ($namespace, $udom, $regexp) = @_;
2138:
2139: $udom ||= $env{'user.domain'};
2140:
2141: return () unless $udom;
2142:
2143: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 2144: }
2145:
1.1023 raeburn 2146: # ------------------------------------------ get items from domain db files
1.806 raeburn 2147:
2148: sub get_dom {
1.860 raeburn 2149: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267 raeburn 2150: return if ($udom eq 'public');
1.806 raeburn 2151: my $items='';
2152: foreach my $item (@$storearr) {
2153: $items.=&escape($item).'&';
2154: }
2155: $items=~s/\&$//;
1.860 raeburn 2156: if (!$udom) {
2157: $udom=$env{'user.domain'};
1.1267 raeburn 2158: return if ($udom eq 'public');
1.860 raeburn 2159: if (defined(&domain($udom,'primary'))) {
2160: $uhome=&domain($udom,'primary');
2161: } else {
1.874 albertel 2162: undef($uhome);
1.860 raeburn 2163: }
2164: } else {
2165: if (!$uhome) {
2166: if (defined(&domain($udom,'primary'))) {
2167: $uhome=&domain($udom,'primary');
2168: }
2169: }
2170: }
2171: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344 raeburn 2172: my $rep;
1.1442 raeburn 2173: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
2174: # domain information is hosted on this machine
2175: my $cmd = 'getdom';
2176: if ($namespace =~ /^enc/) {
2177: $cmd = 'egetdom';
2178: }
2179: $rep = &LONCAPA::Lond::get_dom("$cmd:$udom:$namespace:$items");
1.1344 raeburn 2180: } else {
1.1442 raeburn 2181: if ($namespace =~ /^enc/) {
2182: $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
2183: } else {
2184: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
2185: }
1.1344 raeburn 2186: }
1.866 raeburn 2187: my %returnhash;
1.875 albertel 2188: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 2189: return %returnhash;
2190: }
1.806 raeburn 2191: my @pairs=split(/\&/,$rep);
2192: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2193: return @pairs;
2194: }
2195: my $i=0;
2196: foreach my $item (@$storearr) {
2197: $returnhash{$item}=&thaw_unescape($pairs[$i]);
2198: $i++;
2199: }
2200: return %returnhash;
2201: } else {
1.880 banghart 2202: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 2203: }
2204: }
2205:
2206: # -------------------------------------------- put items in domain db files
2207:
2208: sub put_dom {
1.860 raeburn 2209: my ($namespace,$storehash,$udom,$uhome)=@_;
2210: if (!$udom) {
2211: $udom=$env{'user.domain'};
2212: if (defined(&domain($udom,'primary'))) {
2213: $uhome=&domain($udom,'primary');
2214: } else {
1.874 albertel 2215: undef($uhome);
1.860 raeburn 2216: }
2217: } else {
2218: if (!$uhome) {
2219: if (defined(&domain($udom,'primary'))) {
2220: $uhome=&domain($udom,'primary');
2221: }
2222: }
2223: }
2224: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 2225: my $items='';
2226: foreach my $item (keys(%$storehash)) {
2227: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
2228: }
2229: $items=~s/\&$//;
1.1344 raeburn 2230: if ($namespace =~ /^enc/) {
2231: return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
2232: } else {
2233: return &reply("putdom:$udom:$namespace:$items",$uhome);
2234: }
1.806 raeburn 2235: } else {
1.860 raeburn 2236: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 2237: }
2238: }
2239:
1.1023 raeburn 2240: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 2241: sub newput_dom {
1.1023 raeburn 2242: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 2243: my $result;
2244: if (!$udom) {
2245: $udom=$env{'user.domain'};
2246: }
1.1023 raeburn 2247: if ($udom) {
2248: my $uname = &get_domainconfiguser($udom);
2249: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 2250: }
2251: return $result;
2252: }
2253:
1.1023 raeburn 2254: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 2255: sub del_dom {
1.1023 raeburn 2256: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 2257: if (ref($storearr) eq 'ARRAY') {
2258: if (!$udom) {
2259: $udom=$env{'user.domain'};
2260: }
1.1023 raeburn 2261: if ($udom) {
2262: my $uname = &get_domainconfiguser($udom);
2263: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 2264: }
2265: }
2266: }
2267:
1.1023 raeburn 2268: # ----------------------------------construct domainconfig user for a domain
2269: sub get_domainconfiguser {
2270: my ($udom) = @_;
2271: return $udom.'-domainconfig';
2272: }
2273:
1.837 raeburn 2274: sub retrieve_inst_usertypes {
2275: my ($udom) = @_;
2276: my (%returnhash,@order);
1.989 raeburn 2277: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
2278: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2279: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 2280: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 2281: } else {
2282: if (defined(&domain($udom,'primary'))) {
2283: my $uhome=&domain($udom,'primary');
2284: my $rep=&reply("inst_usertypes:$udom",$uhome);
2285: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 2286: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 2287: return (\%returnhash,\@order);
2288: }
2289: my ($hashitems,$orderitems) = split(/:/,$rep);
2290: my @pairs=split(/\&/,$hashitems);
2291: foreach my $item (@pairs) {
2292: my ($key,$value)=split(/=/,$item,2);
2293: $key = &unescape($key);
2294: next if ($key =~ /^error: 2 /);
2295: $returnhash{$key}=&thaw_unescape($value);
2296: }
2297: my @esc_order = split(/\&/,$orderitems);
2298: foreach my $item (@esc_order) {
2299: push(@order,&unescape($item));
2300: }
2301: } else {
1.1256 raeburn 2302: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 2303: }
1.1256 raeburn 2304: return (\%returnhash,\@order);
1.837 raeburn 2305: }
2306: }
2307:
1.868 raeburn 2308: sub is_domainimage {
2309: my ($url) = @_;
1.1306 raeburn 2310: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 2311: if (&domain($1) ne '') {
2312: return '1';
2313: }
2314: }
2315: return;
2316: }
2317:
1.899 raeburn 2318: sub inst_directory_query {
2319: my ($srch) = @_;
2320: my $udom = $srch->{'srchdomain'};
2321: my %results;
2322: my $homeserver = &domain($udom,'primary');
1.909 raeburn 2323: my $outcome;
1.899 raeburn 2324: if ($homeserver ne '') {
1.1357 raeburn 2325: unless ($homeserver eq $perlvar{'lonHostID'}) {
2326: if ($srch->{'srchby'} eq 'email') {
1.1417 raeburn 2327: my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1357 raeburn 2328: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2329: if (($major eq '' && $minor eq '') || ($major < 2) ||
2330: (($major == 2) && ($minor < 12))) {
2331: return;
2332: }
2333: }
2334: }
1.904 albertel 2335: my $queryid=&reply("querysend:instdirsearch:".
2336: &escape($srch->{'srchby'}).':'.
2337: &escape($srch->{'srchterm'}).':'.
2338: &escape($srch->{'srchtype'}),$homeserver);
2339: my $host=&hostname($homeserver);
2340: if ($queryid !~/^\Q$host\E\_/) {
1.1343 raeburn 2341: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 2342: return;
2343: }
2344: my $response = &get_query_reply($queryid);
2345: my $maxtries = 5;
2346: my $tries = 1;
2347: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2348: $response = &get_query_reply($queryid);
2349: $tries ++;
2350: }
2351:
2352: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2353: if ($response eq 'unavailable') {
2354: $outcome = $response;
2355: } else {
2356: $outcome = 'ok';
2357: my @matches = split(/\n/,$response);
2358: foreach my $match (@matches) {
2359: my ($key,$value) = split(/=/,$match);
2360: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2361: }
1.899 raeburn 2362: }
2363: }
2364: }
1.909 raeburn 2365: return ($outcome,%results);
1.899 raeburn 2366: }
2367:
2368: sub usersearch {
2369: my ($srch) = @_;
2370: my $dom = $srch->{'srchdomain'};
2371: my %results;
2372: my %libserv = &all_library();
2373: my $query = 'usersearch';
2374: foreach my $tryserver (keys(%libserv)) {
2375: if (&host_domain($tryserver) eq $dom) {
1.1357 raeburn 2376: unless ($tryserver eq $perlvar{'lonHostID'}) {
2377: if ($srch->{'srchby'} eq 'email') {
1.1417 raeburn 2378: my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1357 raeburn 2379: my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
2380: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2381: (($major == 2) && ($minor < 12)));
2382: }
2383: }
1.899 raeburn 2384: my $host=&hostname($tryserver);
2385: my $queryid=
1.911 raeburn 2386: &reply("querysend:".&escape($query).':'.
2387: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2388: &escape($srch->{'srchtype'}).':'.
2389: &escape($srch->{'srchterm'}),$tryserver);
2390: if ($queryid !~/^\Q$host\E\_/) {
2391: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2392: next;
1.899 raeburn 2393: }
2394: my $reply = &get_query_reply($queryid);
2395: my $maxtries = 1;
2396: my $tries = 1;
2397: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2398: $reply = &get_query_reply($queryid);
2399: $tries ++;
2400: }
2401: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2402: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2403: } else {
1.911 raeburn 2404: my @matches;
2405: if ($reply =~ /\n/) {
2406: @matches = split(/\n/,$reply);
2407: } else {
2408: @matches = split(/\&/,$reply);
2409: }
1.899 raeburn 2410: foreach my $match (@matches) {
2411: my ($uname,$udom,%userhash);
1.911 raeburn 2412: foreach my $entry (split(/:/,$match)) {
2413: my ($key,$value) =
2414: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2415: $userhash{$key} = $value;
2416: if ($key eq 'username') {
2417: $uname = $value;
2418: } elsif ($key eq 'domain') {
2419: $udom = $value;
1.911 raeburn 2420: }
1.899 raeburn 2421: }
2422: $results{$uname.':'.$udom} = \%userhash;
2423: }
2424: }
2425: }
2426: }
2427: return %results;
2428: }
2429:
1.912 raeburn 2430: sub get_instuser {
2431: my ($udom,$uname,$id) = @_;
2432: my $homeserver = &domain($udom,'primary');
2433: my ($outcome,%results);
2434: if ($homeserver ne '') {
2435: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2436: &escape($id).':'.&escape($udom),$homeserver);
2437: my $host=&hostname($homeserver);
2438: if ($queryid !~/^\Q$host\E\_/) {
2439: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2440: return;
2441: }
2442: my $response = &get_query_reply($queryid);
2443: my $maxtries = 5;
2444: my $tries = 1;
2445: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2446: $response = &get_query_reply($queryid);
2447: $tries ++;
2448: }
2449: if (!&error($response) && $response ne 'refused') {
2450: if ($response eq 'unavailable') {
2451: $outcome = $response;
2452: } else {
2453: $outcome = 'ok';
2454: my @matches = split(/\n/,$response);
2455: foreach my $match (@matches) {
2456: my ($key,$value) = split(/=/,$match);
2457: $results{&unescape($key)} = &thaw_unescape($value);
2458: }
2459: }
2460: }
2461: }
2462: my %userinfo;
2463: if (ref($results{$uname}) eq 'HASH') {
2464: %userinfo = %{$results{$uname}};
2465: }
2466: return ($outcome,%userinfo);
2467: }
2468:
1.1290 raeburn 2469: sub get_multiple_instusers {
2470: my ($udom,$users,$caller) = @_;
2471: my ($outcome,$results);
2472: if (ref($users) eq 'HASH') {
2473: my $count = keys(%{$users});
2474: my $requested = &freeze_escape($users);
2475: my $homeserver = &domain($udom,'primary');
2476: if ($homeserver ne '') {
2477: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2478: my $host=&hostname($homeserver);
2479: if ($queryid !~/^\Q$host\E\_/) {
2480: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2481: ' for host: '.$homeserver.'in domain '.$udom);
2482: return ($outcome,$results);
2483: }
2484: my $response = &get_query_reply($queryid);
2485: my $maxtries = 5;
2486: if ($count > 100) {
2487: $maxtries = 1+int($count/20);
2488: }
2489: my $tries = 1;
2490: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2491: $response = &get_query_reply($queryid);
2492: $tries ++;
2493: }
2494: if ($response eq '') {
2495: $results = {};
2496: foreach my $key (keys(%{$users})) {
2497: my ($uname,$id);
2498: if ($caller eq 'id') {
2499: $id = $key;
2500: } else {
2501: $uname = $key;
2502: }
2503: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291 raeburn 2504: $outcome = $resp;
1.1290 raeburn 2505: if ($resp eq 'ok') {
2506: %{$results} = (%{$results}, %info);
2507: } else {
2508: last;
2509: }
2510: }
2511: } elsif(!&error($response) && ($response ne 'refused')) {
2512: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2513: $outcome = $response;
2514: } else {
1.1291 raeburn 2515: ($outcome,my $userdata) = split(/=/,$response,2);
1.1290 raeburn 2516: if ($outcome eq 'ok') {
2517: $results = &thaw_unescape($userdata);
2518: }
2519: }
2520: }
2521: }
2522: }
2523: return ($outcome,$results);
2524: }
2525:
1.912 raeburn 2526: sub inst_rulecheck {
1.923 raeburn 2527: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2528: my %returnhash;
2529: if ($udom ne '') {
2530: if (ref($rules) eq 'ARRAY') {
2531: @{$rules} = map {&escape($_);} (@{$rules});
2532: my $rulestr = join(':',@{$rules});
2533: my $homeserver=&domain($udom,'primary');
2534: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2535: my $response;
2536: if ($item eq 'username') {
2537: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2538: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2539: $homeserver));
1.923 raeburn 2540: } elsif ($item eq 'id') {
2541: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2542: ':'.&escape($id).':'.$rulestr,
2543: $homeserver));
1.945 raeburn 2544: } elsif ($item eq 'selfcreate') {
2545: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2546: &escape($udom).':'.&escape($uname).
2547: ':'.$rulestr,$homeserver));
1.923 raeburn 2548: }
1.912 raeburn 2549: if ($response ne 'refused') {
2550: my @pairs=split(/\&/,$response);
2551: foreach my $item (@pairs) {
2552: my ($key,$value)=split(/=/,$item,2);
2553: $key = &unescape($key);
2554: next if ($key =~ /^error: 2 /);
2555: $returnhash{$key}=&thaw_unescape($value);
2556: }
2557: }
2558: }
2559: }
2560: }
2561: return %returnhash;
2562: }
2563:
2564: sub inst_userrules {
1.923 raeburn 2565: my ($udom,$check) = @_;
1.912 raeburn 2566: my (%ruleshash,@ruleorder);
2567: if ($udom ne '') {
2568: my $homeserver=&domain($udom,'primary');
2569: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2570: my $response;
2571: if ($check eq 'id') {
2572: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2573: $homeserver);
1.943 raeburn 2574: } elsif ($check eq 'email') {
2575: $response=&reply('instemailrules:'.&escape($udom),
2576: $homeserver);
1.923 raeburn 2577: } else {
2578: $response=&reply('instuserrules:'.&escape($udom),
2579: $homeserver);
2580: }
1.912 raeburn 2581: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2582: ($response ne 'unknown_cmd') &&
1.912 raeburn 2583: ($response ne 'no_such_host')) {
2584: my ($hashitems,$orderitems) = split(/:/,$response);
2585: my @pairs=split(/\&/,$hashitems);
2586: foreach my $item (@pairs) {
2587: my ($key,$value)=split(/=/,$item,2);
2588: $key = &unescape($key);
2589: next if ($key =~ /^error: 2 /);
2590: $ruleshash{$key}=&thaw_unescape($value);
2591: }
2592: my @esc_order = split(/\&/,$orderitems);
2593: foreach my $item (@esc_order) {
2594: push(@ruleorder,&unescape($item));
2595: }
2596: }
2597: }
2598: }
2599: return (\%ruleshash,\@ruleorder);
2600: }
2601:
1.976 raeburn 2602: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2603:
2604: sub get_domain_defaults {
1.1240 raeburn 2605: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2606: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2607: my $cachetime = 60*60*24;
1.1240 raeburn 2608: unless ($ignore_cache) {
2609: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2610: if (defined($cached)) {
2611: if (ref($result) eq 'HASH') {
2612: return %{$result};
2613: }
1.943 raeburn 2614: }
2615: }
2616: my %domdefaults;
2617: my %domconfig =
1.989 raeburn 2618: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2619: 'requestcourses','inststatus',
1.1183 raeburn 2620: 'coursedefaults','usersessions',
1.1258 raeburn 2621: 'requestauthor','selfenrollment',
1.1320 raeburn 2622: 'coursecategories','ssl','autoenroll',
1.1434 raeburn 2623: 'trust','helpsettings','wafproxy'],$domain);
1.1305 raeburn 2624: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2625: if (ref($domconfig{'defaults'}) eq 'HASH') {
2626: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2627: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2628: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2629: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2630: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2631: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340 raeburn 2632: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2633: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2634: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943 raeburn 2635: } else {
2636: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2637: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2638: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2639: }
1.976 raeburn 2640: if (ref($domconfig{'quotas'}) eq 'HASH') {
2641: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2642: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2643: } else {
2644: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2645: }
1.1177 raeburn 2646: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2647: foreach my $item (@usertools) {
2648: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2649: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2650: }
2651: }
1.1229 raeburn 2652: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2653: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2654: }
1.976 raeburn 2655: }
1.985 raeburn 2656: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 raeburn 2657: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2658: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2659: }
2660: }
1.1183 raeburn 2661: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2662: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2663: }
1.989 raeburn 2664: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2665: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2666: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2667: }
2668: }
1.1047 raeburn 2669: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2670: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2671: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2672: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2673: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2674: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2675: }
1.1254 raeburn 2676: foreach my $type (@coursetypes) {
2677: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2678: unless ($type eq 'community') {
2679: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2680: }
2681: }
2682: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2683: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2684: }
1.1277 raeburn 2685: if ($domdefaults{'postsubmit'} eq 'on') {
2686: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2687: $domdefaults{$type.'postsubtimeout'} =
2688: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2689: }
2690: }
1.1230 raeburn 2691: }
1.1286 raeburn 2692: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2693: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2694: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2695: if (@clonecodes) {
2696: $domdefaults{'canclone'} = join('+',@clonecodes);
2697: }
2698: }
2699: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2700: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2701: }
1.1356 raeburn 2702: if ($domconfig{'coursedefaults'}{'texengine'}) {
2703: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
2704: }
1.1047 raeburn 2705: }
1.1073 raeburn 2706: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2707: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2708: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2709: }
2710: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2711: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2712: }
1.1279 raeburn 2713: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2714: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2715: }
1.1440 raeburn 2716: if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1439 raeburn 2717: $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
2718: }
1.1073 raeburn 2719: }
1.1254 raeburn 2720: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2721: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2722: my @settings = ('types','registered','enroll_dates','access_dates','section',
2723: 'approval','limit');
2724: foreach my $type (@coursetypes) {
2725: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2726: my @mgrdc = ();
2727: foreach my $item (@settings) {
2728: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2729: push(@mgrdc,$item);
2730: }
2731: }
2732: if (@mgrdc) {
2733: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2734: }
2735: }
2736: }
2737: }
2738: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2739: foreach my $type (@coursetypes) {
2740: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2741: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2742: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2743: }
2744: }
2745: }
2746: }
2747: }
1.1258 raeburn 2748: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2749: $domdefaults{'catauth'} = 'std';
2750: $domdefaults{'catunauth'} = 'std';
1.1413 raeburn 2751: if ($domconfig{'coursecategories'}{'auth'}) {
1.1258 raeburn 2752: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2753: }
2754: if ($domconfig{'coursecategories'}{'unauth'}) {
2755: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2756: }
2757: }
1.1315 raeburn 2758: if (ref($domconfig{'ssl'}) eq 'HASH') {
2759: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2760: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2761: }
1.1338 raeburn 2762: if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
2763: $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
2764: }
2765: if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
2766: $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315 raeburn 2767: }
2768: }
1.1320 raeburn 2769: if (ref($domconfig{'trust'}) eq 'HASH') {
2770: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2771: foreach my $prefix (@prefixes) {
2772: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2773: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2774: }
2775: }
2776: }
1.1314 raeburn 2777: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2778: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2779: }
1.1332 raeburn 2780: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2781: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2782: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2783: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2784: }
2785: }
1.1434 raeburn 2786: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
1.1449 raeburn 2787: foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
1.1434 raeburn 2788: if ($domconfig{'wafproxy'}{$item}) {
2789: $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
2790: }
2791: }
2792: }
1.1219 raeburn 2793: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2794: return %domdefaults;
2795: }
2796:
1.1412 raeburn 2797: sub get_dom_cats {
2798: my ($dom) = @_;
2799: return unless (&domain($dom));
2800: my ($cats,$cached)=&is_cached_new('cats',$dom);
2801: unless (defined($cached)) {
2802: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2803: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2804: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2805: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2806: } else {
2807: $cats = {};
2808: }
2809: } else {
2810: $cats = {};
2811: }
2812: &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
2813: }
1.1413 raeburn 2814: return $cats;
2815: }
2816:
2817: sub get_dom_instcats {
2818: my ($dom) = @_;
2819: return unless (&domain($dom));
2820: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2821: unless (defined($cached)) {
2822: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2823: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2824: if ($totcodes > 0) {
2825: my $caller = 'global';
2826: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2827: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2828: $instcats = {
2829: codes => \%codes,
2830: codetitles => \@codetitles,
2831: cat_titles => \%cat_titles,
2832: cat_order => \%cat_order,
2833: };
2834: &do_cache_new('instcats',$dom,$instcats,3600);
2835: }
2836: }
2837: }
2838: return $instcats;
2839: }
2840:
2841: sub retrieve_instcodes {
2842: my ($coursecodes,$dom) = @_;
2843: my $totcodes;
2844: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2845: foreach my $course (keys(%courses)) {
2846: if (ref($courses{$course}) eq 'HASH') {
2847: if ($courses{$course}{'inst_code'} ne '') {
2848: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2849: $totcodes ++;
2850: }
2851: }
2852: }
2853: return $totcodes;
1.1412 raeburn 2854: }
2855:
1.1311 raeburn 2856: sub course_portal_url {
1.1451 raeburn 2857: my ($cnum,$cdom,$r) = @_;
1.1311 raeburn 2858: my $chome = &homeserver($cnum,$cdom);
2859: my $hostname = &hostname($chome);
2860: my $protocol = $protocol{$chome};
2861: $protocol = 'http' if ($protocol ne 'https');
2862: my %domdefaults = &get_domain_defaults($cdom);
2863: my $firsturl;
2864: if ($domdefaults{'portal_def'}) {
2865: $firsturl = $domdefaults{'portal_def'};
2866: } else {
1.1451 raeburn 2867: my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
2868: $hostname = $alias if ($alias ne '');
1.1311 raeburn 2869: $firsturl = $protocol.'://'.$hostname;
2870: }
2871: return $firsturl;
2872: }
2873:
1.1407 raeburn 2874: # --------------------------------------------- Get domain config for passwords
2875:
2876: sub get_passwdconf {
2877: my ($dom) = @_;
2878: my (%passwdconf,$gotconf,$lookup);
2879: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2880: if (defined($cached)) {
2881: if (ref($result) eq 'HASH') {
2882: %passwdconf = %{$result};
2883: $gotconf = 1;
2884: }
2885: }
2886: unless ($gotconf) {
2887: my %domconfig = &get_dom('configuration',['passwords'],$dom);
2888: if (ref($domconfig{'passwords'}) eq 'HASH') {
2889: %passwdconf = %{$domconfig{'passwords'}};
2890: }
2891: my $cachetime = 24*60*60;
2892: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
2893: }
2894: return %passwdconf;
2895: }
2896:
1.344 www 2897: # --------------------------------------------------- Assign a key to a student
2898:
2899: sub assign_access_key {
1.364 www 2900: #
2901: # a valid key looks like uname:udom#comments
2902: # comments are being appended
2903: #
1.498 www 2904: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2905: $kdom=
1.620 albertel 2906: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2907: $knum=
1.620 albertel 2908: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2909: $cdom=
1.620 albertel 2910: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2911: $cnum=
1.620 albertel 2912: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2913: $udom=$env{'user.name'} unless (defined($udom));
2914: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2915: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2916: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2917: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2918: # assigned to this person
2919: # - this should not happen,
1.345 www 2920: # unless something went wrong
2921: # the first time around
2922: # ready to assign
1.364 www 2923: $logentry=$1.'; '.$logentry;
1.496 www 2924: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2925: $kdom,$knum) eq 'ok') {
1.345 www 2926: # key now belongs to user
1.346 www 2927: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2928: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2929: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2930: return 'ok';
2931: } else {
2932: return
2933: 'error: Count not permanently assign key, will need to be re-entered later.';
2934: }
2935: } else {
2936: return 'error: Could not assign key, try again later.';
2937: }
1.364 www 2938: } elsif (!$existing{$ckey}) {
1.345 www 2939: # the key does not exist
2940: return 'error: The key does not exist';
2941: } else {
2942: # the key is somebody else's
2943: return 'error: The key is already in use';
2944: }
1.344 www 2945: }
2946:
1.364 www 2947: # ------------------------------------------ put an additional comment on a key
2948:
2949: sub comment_access_key {
2950: #
2951: # a valid key looks like uname:udom#comments
2952: # comments are being appended
2953: #
2954: my ($ckey,$cdom,$cnum,$logentry)=@_;
2955: $cdom=
1.620 albertel 2956: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2957: $cnum=
1.620 albertel 2958: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2959: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2960: if ($existing{$ckey}) {
2961: $existing{$ckey}.='; '.$logentry;
2962: # ready to assign
1.367 www 2963: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2964: $cdom,$cnum) eq 'ok') {
2965: return 'ok';
2966: } else {
2967: return 'error: Count not store comment.';
2968: }
2969: } else {
2970: # the key does not exist
2971: return 'error: The key does not exist';
2972: }
2973: }
2974:
1.344 www 2975: # ------------------------------------------------------ Generate a set of keys
2976:
2977: sub generate_access_keys {
1.364 www 2978: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2979: $cdom=
1.620 albertel 2980: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2981: $cnum=
1.620 albertel 2982: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2983: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2984: unless (($cdom) && ($cnum)) { return 0; }
2985: if ($number>10000) { return 0; }
2986: sleep(2); # make sure don't get same seed twice
2987: srand(time()^($$+($$<<15))); # from "Programming Perl"
2988: my $total=0;
2989: for (my $i=1;$i<=$number;$i++) {
2990: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2991: sprintf("%lx",int(100000*rand)).'-'.
2992: sprintf("%lx",int(100000*rand));
2993: $newkey=~s/1/g/g; # folks mix up 1 and l
2994: $newkey=~s/0/h/g; # and also 0 and O
2995: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2996: if ($existing{$newkey}) {
2997: $i--;
2998: } else {
1.364 www 2999: if (&put('accesskeys',
3000: { $newkey => '# generated '.localtime().
1.620 albertel 3001: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 3002: '; '.$logentry },
3003: $cdom,$cnum) eq 'ok') {
1.344 www 3004: $total++;
3005: }
3006: }
3007: }
1.620 albertel 3008: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 3009: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
3010: return $total;
3011: }
3012:
3013: # ------------------------------------------------------- Validate an accesskey
3014:
3015: sub validate_access_key {
3016: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
3017: $cdom=
1.620 albertel 3018: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 3019: $cnum=
1.620 albertel 3020: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
3021: $udom=$env{'user.domain'} unless (defined($udom));
3022: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 3023: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 3024: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 3025: }
3026:
3027: # ------------------------------------- Find the section of student in a course
1.652 albertel 3028: sub devalidate_getsection_cache {
3029: my ($udom,$unam,$courseid)=@_;
3030: my $hashid="$udom:$unam:$courseid";
3031: &devalidate_cache_new('getsection',$hashid);
3032: }
1.298 matthew 3033:
1.815 albertel 3034: sub courseid_to_courseurl {
3035: my ($courseid) = @_;
3036: #already url style courseid
3037: return $courseid if ($courseid =~ m{^/});
3038:
3039: if (exists($env{'course.'.$courseid.'.num'})) {
3040: my $cnum = $env{'course.'.$courseid.'.num'};
3041: my $cdom = $env{'course.'.$courseid.'.domain'};
3042: return "/$cdom/$cnum";
3043: }
3044:
3045: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
3046: if (exists($courseinfo{'num'})) {
3047: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
3048: }
3049:
3050: return undef;
3051: }
3052:
1.298 matthew 3053: sub getsection {
3054: my ($udom,$unam,$courseid)=@_;
1.599 albertel 3055: my $cachetime=1800;
1.551 albertel 3056:
3057: my $hashid="$udom:$unam:$courseid";
1.599 albertel 3058: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 3059: if (defined($cached)) { return $result; }
3060:
1.298 matthew 3061: my %Pending;
3062: my %Expired;
3063: #
3064: # Each role can either have not started yet (pending), be active,
3065: # or have expired.
3066: #
3067: # If there is an active role, we are done.
3068: #
3069: # If there is more than one role which has not started yet,
3070: # choose the one which will start sooner
3071: # If there is one role which has not started yet, return it.
3072: #
3073: # If there is more than one expired role, choose the one which ended last.
3074: # If there is a role which has expired, return it.
3075: #
1.815 albertel 3076: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 3077: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 3078: foreach my $key (keys(%roleshash)) {
1.479 albertel 3079: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 3080: my $section=$1;
3081: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 3082: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 3083: my $now=time;
1.548 albertel 3084: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 3085: $Expired{$end}=$section;
3086: next;
3087: }
1.548 albertel 3088: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 3089: $Pending{$start}=$section;
3090: next;
3091: }
1.599 albertel 3092: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 3093: }
3094: #
3095: # Presumedly there will be few matching roles from the above
3096: # loop and the sorting time will be negligible.
3097: if (scalar(keys(%Pending))) {
3098: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 3099: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 3100: }
3101: if (scalar(keys(%Expired))) {
3102: my @sorted = sort {$a <=> $b} keys(%Expired);
3103: my $time = pop(@sorted);
1.599 albertel 3104: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 3105: }
1.599 albertel 3106: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 3107: }
1.70 www 3108:
1.599 albertel 3109: sub save_cache {
3110: &purge_remembered();
1.722 albertel 3111: #&Apache::loncommon::validate_page();
1.620 albertel 3112: undef(%env);
1.780 albertel 3113: undef($env_loaded);
1.599 albertel 3114: }
1.452 albertel 3115:
1.599 albertel 3116: my $to_remember=-1;
3117: my %remembered;
3118: my %accessed;
3119: my $kicks=0;
3120: my $hits=0;
1.849 albertel 3121: sub make_key {
3122: my ($name,$id) = @_;
1.872 albertel 3123: if (length($id) > 65
3124: && length(&escape($id)) > 200) {
3125: $id=length($id).':'.&Digest::MD5::md5_hex($id);
3126: }
1.849 albertel 3127: return &escape($name.':'.$id);
3128: }
3129:
1.599 albertel 3130: sub devalidate_cache_new {
3131: my ($name,$id,$debug) = @_;
3132: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319 damieng 3133: my $remembered_id=$name.':'.$id;
1.849 albertel 3134: $id=&make_key($name,$id);
1.599 albertel 3135: $memcache->delete($id);
1.1319 damieng 3136: delete($remembered{$remembered_id});
3137: delete($accessed{$remembered_id});
1.599 albertel 3138: }
3139:
3140: sub is_cached_new {
3141: my ($name,$id,$debug) = @_;
1.1319 damieng 3142: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
3143: if (exists($remembered{$remembered_id})) {
3144: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
3145: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3146: $hits++;
1.1319 damieng 3147: return ($remembered{$remembered_id},1);
1.599 albertel 3148: }
1.1319 damieng 3149: $id=&make_key($name,$id);
1.599 albertel 3150: my $value = $memcache->get($id);
3151: if (!(defined($value))) {
3152: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 3153: return (undef,undef);
1.416 albertel 3154: }
1.599 albertel 3155: if ($value eq '__undef__') {
3156: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
3157: $value=undef;
3158: }
1.1319 damieng 3159: &make_room($remembered_id,$value,$debug);
1.599 albertel 3160: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
3161: return ($value,1);
3162: }
3163:
3164: sub do_cache_new {
3165: my ($name,$id,$value,$time,$debug) = @_;
1.1319 damieng 3166: my $remembered_id=$name.':'.$id;
1.849 albertel 3167: $id=&make_key($name,$id);
1.599 albertel 3168: my $setvalue=$value;
3169: if (!defined($setvalue)) {
3170: $setvalue='__undef__';
3171: }
1.623 albertel 3172: if (!defined($time) ) {
3173: $time=600;
3174: }
1.599 albertel 3175: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 3176: my $result = $memcache->set($id,$setvalue,$time);
3177: if (! $result) {
1.872 albertel 3178: &logthis("caching of id -> $id failed");
1.910 albertel 3179: $memcache->disconnect_all();
1.872 albertel 3180: }
1.600 albertel 3181: # need to make a copy of $value
1.1319 damieng 3182: &make_room($remembered_id,$value,$debug);
1.599 albertel 3183: return $value;
3184: }
3185:
3186: sub make_room {
1.1319 damieng 3187: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 3188:
1.1319 damieng 3189: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 3190: : $value;
1.599 albertel 3191: if ($to_remember<0) { return; }
1.1319 damieng 3192: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 3193: if (scalar(keys(%remembered)) <= $to_remember) { return; }
3194: my $to_kick;
3195: my $max_time=0;
3196: foreach my $other (keys(%accessed)) {
3197: if (&tv_interval($accessed{$other}) > $max_time) {
3198: $to_kick=$other;
3199: $max_time=&tv_interval($accessed{$other});
3200: }
3201: }
3202: delete($remembered{$to_kick});
3203: delete($accessed{$to_kick});
3204: $kicks++;
3205: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 3206: return;
3207: }
3208:
1.599 albertel 3209: sub purge_remembered {
1.604 albertel 3210: #&logthis("Tossing ".scalar(keys(%remembered)));
3211: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 3212: undef(%remembered);
3213: undef(%accessed);
1.428 albertel 3214: }
1.70 www 3215: # ------------------------------------- Read an entry from a user's environment
3216:
3217: sub userenvironment {
3218: my ($udom,$unam,@what)=@_;
1.976 raeburn 3219: my $items;
3220: foreach my $item (@what) {
3221: $items.=&escape($item).'&';
3222: }
3223: $items=~s/\&$//;
1.70 www 3224: my %returnhash=();
1.1009 raeburn 3225: my $uhome = &homeserver($unam,$udom);
3226: unless ($uhome eq 'no_host') {
3227: my @answer=split(/\&/,
3228: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 3229: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
3230: return %returnhash;
3231: }
1.1009 raeburn 3232: my $i;
3233: for ($i=0;$i<=$#what;$i++) {
3234: $returnhash{$what[$i]}=&unescape($answer[$i]);
3235: }
1.70 www 3236: }
3237: return %returnhash;
1.1 albertel 3238: }
3239:
1.617 albertel 3240: # ---------------------------------------------------------- Get a studentphoto
3241: sub studentphoto {
3242: my ($udom,$unam,$ext) = @_;
3243: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 3244: if (defined($env{'request.course.id'})) {
1.708 raeburn 3245: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 3246: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
3247: return(&retrievestudentphoto($udom,$unam,$ext));
3248: } else {
3249: my ($result,$perm_reqd)=
1.707 albertel 3250: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 3251: if ($result eq 'ok') {
3252: if (!($perm_reqd eq 'yes')) {
3253: return(&retrievestudentphoto($udom,$unam,$ext));
3254: }
3255: }
3256: }
3257: }
3258: } else {
3259: my ($result,$perm_reqd) =
1.707 albertel 3260: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 3261: if ($result eq 'ok') {
3262: if (!($perm_reqd eq 'yes')) {
3263: return(&retrievestudentphoto($udom,$unam,$ext));
3264: }
3265: }
3266: }
3267: return '/adm/lonKaputt/lonlogo_broken.gif';
3268: }
3269:
3270: sub retrievestudentphoto {
3271: my ($udom,$unam,$ext,$type) = @_;
3272: my $home=&Apache::lonnet::homeserver($unam,$udom);
3273: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
3274: if ($ret eq 'ok') {
3275: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
3276: if ($type eq 'thumbnail') {
3277: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
3278: }
3279: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
3280: return $tokenurl;
3281: } else {
3282: if ($type eq 'thumbnail') {
3283: return '/adm/lonKaputt/genericstudent_tn.gif';
3284: } else {
3285: return '/adm/lonKaputt/lonlogo_broken.gif';
3286: }
1.617 albertel 3287: }
3288: }
3289:
1.263 www 3290: # -------------------------------------------------------------------- New chat
3291:
3292: sub chatsend {
1.724 raeburn 3293: my ($newentry,$anon,$group)=@_;
1.620 albertel 3294: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
3295: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3296: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 3297: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 3298: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 3299: &escape($newentry)).':'.$group,$chome);
1.292 www 3300: }
3301:
3302: # ------------------------------------------ Find current version of a resource
3303:
3304: sub getversion {
3305: my $fname=&clutter(shift);
1.1189 raeburn 3306: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 3307: return ¤tversion(&filelocation('',$fname));
3308: }
3309:
3310: sub currentversion {
3311: my $fname=shift;
3312: my $author=$fname;
3313: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3314: my ($udom,$uname)=split(/\//,$author);
1.1112 www 3315: my $home=&homeserver($uname,$udom);
1.292 www 3316: if ($home eq 'no_host') {
3317: return -1;
3318: }
1.1112 www 3319: my $answer=&reply("currentversion:$fname",$home);
1.292 www 3320: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3321: return -1;
3322: }
1.1112 www 3323: return $answer;
1.263 www 3324: }
3325:
1.1111 www 3326: #
3327: # Return special version number of resource if set by override, empty otherwise
3328: #
3329: sub usedversion {
3330: my $fname=shift;
3331: unless ($fname) { $fname=$env{'request.uri'}; }
3332: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3333: if ($urlversion) { return $urlversion; }
3334: return '';
3335: }
3336:
1.1 albertel 3337: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 3338:
1.1 albertel 3339: sub subscribe {
3340: my $fname=shift;
1.761 raeburn 3341: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 3342: $fname=~s/[\n\r]//g;
1.1 albertel 3343: my $author=$fname;
3344: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3345: my ($udom,$uname)=split(/\//,$author);
3346: my $home=homeserver($uname,$udom);
1.335 albertel 3347: if ($home eq 'no_host') {
3348: return 'not_found';
1.1 albertel 3349: }
3350: my $answer=reply("sub:$fname",$home);
1.64 www 3351: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3352: $answer.=' by '.$home;
3353: }
1.1 albertel 3354: return $answer;
3355: }
3356:
1.8 www 3357: # -------------------------------------------------------------- Replicate file
3358:
3359: sub repcopy {
3360: my $filename=shift;
1.23 www 3361: $filename=~s/\/+/\//g;
1.1142 raeburn 3362: my $londocroot = $perlvar{'lonDocRoot'};
3363: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3364: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3365: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3366: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3367: return &repcopy_userfile($filename);
3368: }
1.532 albertel 3369: $filename=~s/[\n\r]//g;
1.8 www 3370: my $transname="$filename.in.transfer";
1.828 www 3371: # FIXME: this should flock
1.607 raeburn 3372: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3373: my $remoteurl=subscribe($filename);
1.64 www 3374: if ($remoteurl =~ /^con_lost by/) {
3375: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3376: return 'unavailable';
1.8 www 3377: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3378: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3379: return 'not_found';
1.64 www 3380: } elsif ($remoteurl =~ /^rejected by/) {
3381: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3382: return 'forbidden';
1.20 www 3383: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3384: return 'ok';
1.8 www 3385: } else {
1.290 www 3386: my $author=$filename;
3387: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3388: my ($udom,$uname)=split(/\//,$author);
3389: my $home=homeserver($uname,$udom);
3390: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3391: my @parts=split(/\//,$filename);
3392: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3393: if ($path ne "$londocroot/res") {
1.8 www 3394: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3395: return 'bad_request';
1.8 www 3396: }
3397: my $count;
3398: for ($count=5;$count<$#parts;$count++) {
3399: $path.="/$parts[$count]";
3400: if ((-e $path)!=1) {
3401: mkdir($path,0777);
3402: }
3403: }
3404: my $request=new HTTP::Request('GET',"$remoteurl");
1.1345 raeburn 3405: my $response;
3406: if ($remoteurl =~ m{/raw/}) {
3407: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
3408: } else {
3409: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
3410: }
1.8 www 3411: if ($response->is_error()) {
3412: unlink($transname);
3413: my $message=$response->status_line;
1.672 albertel 3414: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3415: ." LWP get: $message: $filename</font>");
1.607 raeburn 3416: return 'unavailable';
1.8 www 3417: } else {
1.16 www 3418: if ($remoteurl!~/\.meta$/) {
3419: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345 raeburn 3420: my $mresponse;
3421: if ($remoteurl =~ m{/raw/}) {
3422: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
3423: } else {
3424: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
3425: }
1.16 www 3426: if ($mresponse->is_error()) {
3427: unlink($filename.'.meta');
3428: &logthis(
1.672 albertel 3429: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3430: }
3431: }
1.8 www 3432: rename($transname,$filename);
1.607 raeburn 3433: return 'ok';
1.8 www 3434: }
1.290 www 3435: }
1.8 www 3436: }
1.330 www 3437: }
3438:
1.1422 raeburn 3439: # ------------------------------------------------- Unsubscribe from a resource
3440:
3441: sub unsubscribe {
3442: my ($fname) = @_;
3443: my $answer;
3444: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3445: $fname=~s/[\n\r]//g;
3446: my $author=$fname;
3447: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3448: my ($udom,$uname)=split(/\//,$author);
3449: my $home=homeserver($uname,$udom);
3450: if ($home eq 'no_host') {
3451: $answer = 'no_host';
3452: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3453: $answer = 'home';
3454: } else {
3455: my $defdom = $perlvar{'lonDefDomain'};
3456: if (&will_trust('content',$defdom,$udom)) {
3457: $answer = reply("unsub:$fname",$home);
3458: } else {
3459: $answer = 'untrusted';
3460: }
3461: }
3462: return $answer;
3463: }
3464:
1.330 www 3465: # ------------------------------------------------ Get server side include body
3466: sub ssi_body {
1.381 albertel 3467: my ($filelink,%form)=@_;
1.606 matthew 3468: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3469: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3470: }
1.953 www 3471: my $output='';
3472: my $response;
1.980 raeburn 3473: if ($filelink=~/^https?\:/) {
1.954 raeburn 3474: ($output,$response)=&externalssi($filelink);
1.953 www 3475: } else {
1.1004 droeschl 3476: $filelink .= $filelink=~/\?/ ? '&' : '?';
3477: $filelink .= 'inhibitmenu=yes';
1.953 www 3478: ($output,$response)=&ssi($filelink,%form);
3479: }
1.778 albertel 3480: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3481: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3482: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3483: if (wantarray) {
3484: return ($output, $response);
3485: } else {
3486: return $output;
3487: }
1.8 www 3488: }
3489:
1.15 www 3490: # --------------------------------------------------------- Server Side Include
3491:
1.782 albertel 3492: sub absolute_url {
1.1447 raeburn 3493: my ($host_name,$unalias,$keep_proto) = @_;
1.782 albertel 3494: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3495: if ($host_name eq '') {
3496: $host_name = $ENV{'SERVER_NAME'};
3497: }
1.1447 raeburn 3498: if ($unalias) {
3499: my $alias = &get_proxy_alias();
3500: if ($alias eq $host_name) {
3501: my $lonhost = $perlvar{'lonHostID'};
3502: my $hostname = &hostname($lonhost);
3503: my $lcproto;
3504: if (($keep_proto) || ($hostname eq '')) {
3505: $lcproto = $protocol;
3506: } else {
3507: $lcproto = $protocol{$lonhost};
3508: $lcproto = 'http' if ($lcproto ne 'https');
3509: $lcproto .= '://';
3510: }
3511: unless ($hostname eq '') {
3512: return $lcproto.$hostname;
3513: }
3514: }
3515: }
1.782 albertel 3516: return $protocol.$host_name;
3517: }
3518:
1.942 foxr 3519: #
3520: # Server side include.
3521: # Parameters:
3522: # fn Possibly encrypted resource name/id.
3523: # form Hash that describes how the rendering should be done
3524: # and other things.
1.944 foxr 3525: # Returns:
1.950 raeburn 3526: # Scalar context: The content of the response.
3527: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3528: #
1.15 www 3529: sub ssi {
3530:
1.944 foxr 3531: my ($fn,%form)=@_;
1.1447 raeburn 3532: my ($host,$request,$response);
3533: $host = &absolute_url('',1);
1.711 albertel 3534:
3535: $form{'no_update_last_known'}=1;
1.895 albertel 3536: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3537: if (%form) {
1.1447 raeburn 3538: $request=new HTTP::Request('POST',$host.$fn);
1.1272 droeschl 3539: $request->content(join('&',map {
3540: my $name = escape($_);
3541: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3542: ? join("&$name=", map {escape($_) } @{$form{$_}})
3543: : &escape($form{$_}) );
3544: } keys(%form)));
1.23 www 3545: } else {
1.1447 raeburn 3546: $request=new HTTP::Request('GET',$host.$fn);
1.23 www 3547: }
3548:
1.15 www 3549: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345 raeburn 3550: my $lonhost = $perlvar{'lonHostID'};
1.1385 raeburn 3551: my $islocal;
3552: if (($env{'request.course.id'}) &&
3553: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3554: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3555: ($form{'grade_symb'} ne '') &&
3556: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3557: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
3558: $islocal = 1;
3559: }
1.1447 raeburn 3560: $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
3561: '','','',$islocal);
1.1182 foxr 3562:
1.944 foxr 3563: if (wantarray) {
1.1345 raeburn 3564: return ($response->content, $response);
1.944 foxr 3565: } else {
1.1345 raeburn 3566: return $response->content;
1.942 foxr 3567: }
1.324 www 3568: }
3569:
3570: sub externalssi {
3571: my ($url)=@_;
3572: my $request=new HTTP::Request('GET',$url);
1.1345 raeburn 3573: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954 raeburn 3574: if (wantarray) {
3575: return ($response->content, $response);
3576: } else {
3577: return $response->content;
3578: }
1.15 www 3579: }
1.254 www 3580:
1.1354 raeburn 3581:
3582: # If the local copy of a replicated resource is outdated, trigger a
3583: # connection from the homeserver to flush the delayed queue. If no update
3584: # happens, remove local copies of outdated resource (and corresponding
3585: # metadata file).
3586:
1.1352 raeburn 3587: sub remove_stale_resfile {
3588: my ($url) = @_;
1.1354 raeburn 3589: my $removed;
1.1352 raeburn 3590: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3591: my $audom = $1;
3592: my $auname = $2;
1.1353 raeburn 3593: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352 raeburn 3594: my $homeserver = &homeserver($auname,$audom);
3595: unless (($homeserver eq 'no_host') ||
3596: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3597: my $fname = &filelocation('',$url);
3598: if (-e $fname) {
3599: my $hostname = &hostname($homeserver);
3600: if ($hostname) {
1.1397 raeburn 3601: my $protocol = $protocol{$homeserver};
3602: $protocol = 'http' if ($protocol ne 'https');
1.1352 raeburn 3603: my $uri = &declutter($url);
3604: my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
3605: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
3606: if ($response->is_success()) {
3607: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3608: my $locmodtime = (stat($fname))[9];
3609: if ($locmodtime < $remmodtime) {
1.1354 raeburn 3610: my $stale;
3611: my $answer = &reply('pong',$homeserver);
3612: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3613: sleep(0.2);
3614: $locmodtime = (stat($fname))[9];
3615: if ($locmodtime < $remmodtime) {
3616: my $posstransfer = $fname.'.in.transfer';
3617: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3618: $removed = 1;
3619: } else {
3620: $stale = 1;
3621: }
3622: } else {
3623: $removed = 1;
3624: }
3625: } else {
3626: $stale = 1;
3627: }
3628: if ($stale) {
1.1421 raeburn 3629: if (unlink($fname)) {
3630: if ($uri!~/\.meta$/) {
3631: if (-e $fname.'.meta') {
3632: unlink($fname.'.meta');
3633: }
3634: }
1.1422 raeburn 3635: my $unsubresult = &unsubscribe($fname);
3636: unless ($unsubresult eq 'ok') {
3637: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3638: }
1.1421 raeburn 3639: $removed = 1;
1.1354 raeburn 3640: }
1.1352 raeburn 3641: }
3642: }
3643: }
3644: }
3645: }
3646: }
3647: }
3648: }
1.1354 raeburn 3649: return $removed;
1.1352 raeburn 3650: }
3651:
1.492 albertel 3652: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3653:
3654: sub allowuploaded {
3655: my ($srcurl,$url)=@_;
3656: $url=&clutter(&declutter($url));
3657: my $dir=$url;
3658: $dir=~s/\/[^\/]+$//;
3659: my %httpref=();
3660: my $httpurl=&hreflocation('',$url);
3661: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3662: &Apache::lonnet::appenv(\%httpref);
1.254 www 3663: }
1.477 raeburn 3664:
1.1193 raeburn 3665: #
3666: # Determine if the current user should be able to edit a particular resource,
3667: # when viewing in course context.
3668: # (a) When viewing resource used to determine if "Edit" item is included in
3669: # Functions.
3670: # (b) When displaying folder contents in course editor, used to determine if
3671: # "Edit" link will be displayed alongside resource.
3672: #
1.1196 raeburn 3673: # input: six args -- filename (decluttered), course number, course domain,
3674: # url, symb (if registered) and group (if this is a group
3675: # item -- e.g., bulletin board, group page etc.).
3676: # output: array of five scalars --
1.1193 raeburn 3677: # $cfile -- url for file editing if editable on current server
3678: # $home -- homeserver of resource (i.e., for author if published,
3679: # or course if uploaded.).
3680: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 3681: # $forceedit -- 1 if icon/link should be to go to edit mode
3682: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 3683: #
3684:
3685: sub can_edit_resource {
1.1194 raeburn 3686: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3687: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3688: #
3689: # For aboutme pages user can only edit his/her own.
3690: #
1.1199 raeburn 3691: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 3692: my ($sdom,$sname) = ($1,$2);
3693: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3694: $home = $env{'user.home'};
3695: $cfile = $resurl;
3696: if ($env{'form.forceedit'}) {
3697: $forceview = 1;
3698: } else {
3699: $forceedit = 1;
3700: }
3701: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3702: } else {
3703: return;
3704: }
3705: }
3706:
3707: if ($env{'request.course.id'}) {
3708: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3709: if ($group ne '') {
3710: # if this is a group homepage or group bulletin board, check group privs
3711: my $allowed = 0;
1.1197 raeburn 3712: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3713: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3714: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3715: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3716: $allowed = 1;
3717: }
1.1197 raeburn 3718: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3719: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3720: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3721: $allowed = 1;
3722: }
3723: }
3724: if ($allowed) {
3725: $home=&homeserver($cnum,$cdom);
3726: if ($env{'form.forceedit'}) {
3727: $forceview = 1;
3728: } else {
3729: $forceedit = 1;
3730: }
3731: $cfile = $resurl;
3732: } else {
3733: return;
3734: }
3735: } else {
1.1208 raeburn 3736: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3737: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3738: return;
3739: }
3740: } elsif (!$crsedit) {
1.1194 raeburn 3741: #
3742: # No edit allowed where CC has switched to student role.
3743: #
3744: return;
3745: }
3746: }
3747: }
3748:
1.1193 raeburn 3749: if ($file ne '') {
3750: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3751: if (&is_course_upload($file,$cnum,$cdom)) {
3752: $uploaded = 1;
3753: $incourse = 1;
1.1193 raeburn 3754: if ($file =~/\.(htm|html|css|js|txt)$/) {
3755: $cfile = &hreflocation('',$file);
1.1201 raeburn 3756: if ($env{'form.forceedit'}) {
3757: $forceview = 1;
3758: } else {
3759: $forceedit = 1;
3760: }
1.1194 raeburn 3761: }
3762: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3763: $incourse = 1;
3764: if ($env{'form.forceedit'}) {
3765: $forceview = 1;
3766: } else {
3767: $forceedit = 1;
3768: }
3769: $cfile = $resurl;
3770: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3771: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3772: $incourse = 1;
3773: if ($env{'form.forceedit'}) {
3774: $forceview = 1;
3775: } else {
3776: $forceedit = 1;
3777: }
3778: $cfile = $resurl;
1.1199 raeburn 3779: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3780: $incourse = 1;
3781: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3782: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3783: $incourse = 1;
1.1199 raeburn 3784: if ($env{'form.forceedit'}) {
3785: $forceview = 1;
3786: } else {
3787: $forceedit = 1;
3788: }
3789: $cfile = $resurl;
1.1419 raeburn 3790: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3791: my ($map,$id,$res) = &decode_symb($symb);
3792: if ($map =~ /\.page$/) {
3793: $incourse = 1;
3794: if ($env{'form.forceedit'}) {
3795: $forceview = 1;
3796: $cfile = $map;
3797: } else {
3798: $forceedit = 1;
3799: $cfile = '/adm/wrapper'.$resurl;
3800: }
3801: }
1.1343 raeburn 3802: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3803: $incourse = 1;
3804: if ($env{'form.forceedit'}) {
3805: $forceview = 1;
3806: } else {
3807: $forceedit = 1;
3808: }
3809: $cfile = $resurl;
1.1208 raeburn 3810: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3811: $incourse = 1;
3812: if ($env{'form.forceedit'}) {
3813: $forceview = 1;
3814: } else {
3815: $forceedit = 1;
3816: }
3817: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3818: }
3819: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3820: my $template = '/res/lib/templates/simpleproblem.problem';
3821: if (&is_on_map($template)) {
3822: $incourse = 1;
3823: $forceview = 1;
3824: $cfile = $template;
1.1193 raeburn 3825: }
1.1199 raeburn 3826: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1418 raeburn 3827: $incourse = 1;
3828: if ($env{'form.forceedit'}) {
3829: $forceview = 1;
3830: } else {
3831: $forceedit = 1;
3832: }
3833: $cfile = $resurl;
1.1343 raeburn 3834: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298 raeburn 3835: $incourse = 1;
3836: if ($env{'form.forceedit'}) {
3837: $forceview = 1;
3838: } else {
3839: $forceedit = 1;
3840: }
3841: $cfile = $resurl;
1.1199 raeburn 3842: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3843: $incourse = 1;
3844: $forceview = 1;
3845: if ($symb) {
3846: my ($map,$id,$res)=&decode_symb($symb);
3847: $env{'request.symb'} = $symb;
3848: $cfile = &clutter($res);
3849: } else {
3850: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3851: my $escfile = &unescape($cfile);
1.1343 raeburn 3852: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3853: $cfile = '/adm/wrapper'.$escfile;
3854: } else {
3855: $escfile =~ s{^http://}{};
3856: $cfile = &escape("/adm/wrapper/ext/$escfile");
3857: }
1.1199 raeburn 3858: }
1.1234 raeburn 3859: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3860: if ($env{'form.forceedit'}) {
3861: $forceview = 1;
3862: } else {
3863: $forceedit = 1;
3864: }
3865: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 3866: }
3867: }
1.1194 raeburn 3868: if ($uploaded || $incourse) {
3869: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 3870: } elsif ($file !~ m{/$}) {
1.1193 raeburn 3871: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3872: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3873: # Check that the user has permission to edit this resource
3874: my $setpriv = 1;
3875: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3876: if (defined($cfudom)) {
3877: $home=&homeserver($cfuname,$cfudom);
3878: $cfile=$file;
3879: }
3880: }
1.1194 raeburn 3881: if (($cfile ne '') && (!$incourse || $uploaded) &&
3882: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 3883: my @ids=¤t_machine_ids();
3884: unless (grep(/^\Q$home\E$/,@ids)) {
3885: $switchserver=1;
3886: }
3887: }
3888: }
1.1194 raeburn 3889: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 3890: }
3891:
3892: sub is_course_upload {
3893: my ($file,$cnum,$cdom) = @_;
3894: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3895: $uploadpath =~ s{^\/}{};
1.1201 raeburn 3896: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3897: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 3898: return 1;
3899: }
3900: return;
3901: }
3902:
1.1194 raeburn 3903: sub in_course {
1.1195 raeburn 3904: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3905: if ($hideprivileged) {
3906: my $skipuser;
1.1219 raeburn 3907: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3908: my @possdoms = ($cdom);
3909: if ($coursehash{'checkforpriv'}) {
3910: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3911: }
3912: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3913: $skipuser = 1;
3914: if ($coursehash{'nothideprivileged'}) {
3915: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3916: my $user;
3917: if ($item =~ /:/) {
3918: $user = $item;
3919: } else {
3920: $user = join(':',split(/[\@]/,$item));
3921: }
3922: if ($user eq $uname.':'.$udom) {
3923: undef($skipuser);
3924: last;
3925: }
3926: }
3927: }
3928: if ($skipuser) {
3929: return 0;
3930: }
3931: }
3932: }
1.1194 raeburn 3933: $type ||= 'any';
3934: if (!defined($cdom) || !defined($cnum)) {
3935: my $cid = $env{'request.course.id'};
3936: $cdom = $env{'course.'.$cid.'.domain'};
3937: $cnum = $env{'course.'.$cid.'.num'};
3938: }
3939: my $typesref;
1.1195 raeburn 3940: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3941: $typesref = ['active','previous','future'];
3942: } elsif ($type eq 'previous' || $type eq 'future') {
3943: $typesref = [$type];
3944: }
3945: my %roles = &get_my_roles($uname,$udom,'userroles',
3946: $typesref,undef,[$cdom]);
3947: my ($tmp) = keys(%roles);
3948: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3949: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3950: if (@course_roles > 0) {
3951: return 1;
3952: }
3953: return 0;
3954: }
3955:
1.478 albertel 3956: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3957: # input: action, courseID, current domain, intended
1.637 raeburn 3958: # path to file, source of file, instruction to parse file for objects,
3959: # ref to hash for embedded objects,
3960: # ref to hash for codebase of java objects.
1.1095 raeburn 3961: # reference to scalar to accommodate mime type determined
3962: # from File::MMagic if $parser = parse.
1.637 raeburn 3963: #
1.485 raeburn 3964: # output: url to file (if action was uploaddoc),
3965: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3966: #
1.478 albertel 3967: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3968: # course.
1.477 raeburn 3969: #
1.478 albertel 3970: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3971: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3972: # course's home server.
1.477 raeburn 3973: #
1.478 albertel 3974: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3975: # be copied from $source (current location) to
3976: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3977: # and will then be copied to
3978: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3979: # course's home server.
1.485 raeburn 3980: #
1.481 raeburn 3981: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3982: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3983: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3984: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3985: # in course's home server.
1.637 raeburn 3986: #
1.477 raeburn 3987:
3988: sub process_coursefile {
1.1095 raeburn 3989: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3990: $mimetype)=@_;
1.477 raeburn 3991: my $fetchresult;
1.638 albertel 3992: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3993: if ($action eq 'propagate') {
1.638 albertel 3994: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3995: $home);
1.481 raeburn 3996: } else {
1.477 raeburn 3997: my $fpath = '';
3998: my $fname = $file;
1.478 albertel 3999: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 4000: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 4001: my $filepath = &build_filepath($fpath);
1.481 raeburn 4002: if ($action eq 'copy') {
4003: if ($source eq '') {
4004: $fetchresult = 'no source file';
4005: return $fetchresult;
4006: } else {
4007: my $destination = $filepath.'/'.$fname;
4008: rename($source,$destination);
4009: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4010: $home);
1.481 raeburn 4011: }
4012: } elsif ($action eq 'uploaddoc') {
1.1359 raeburn 4013: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 4014: print $fh $env{'form.'.$source};
1.481 raeburn 4015: close($fh);
1.637 raeburn 4016: if ($parser eq 'parse') {
1.1024 raeburn 4017: my $mm = new File::MMagic;
1.1095 raeburn 4018: my $type = $mm->checktype_filename($filepath.'/'.$fname);
4019: if ($type eq 'text/html') {
1.1024 raeburn 4020: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
4021: unless ($parse_result eq 'ok') {
4022: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
4023: }
1.637 raeburn 4024: }
1.1095 raeburn 4025: if (ref($mimetype)) {
4026: $$mimetype = $type;
4027: }
1.637 raeburn 4028: }
1.477 raeburn 4029: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4030: $home);
1.481 raeburn 4031: if ($fetchresult eq 'ok') {
4032: return '/uploaded/'.$fpath.'/'.$fname;
4033: } else {
4034: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 4035: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 4036: return '/adm/notfound.html';
4037: }
1.477 raeburn 4038: }
4039: }
1.485 raeburn 4040: unless ( $fetchresult eq 'ok') {
1.477 raeburn 4041: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 4042: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 4043: }
4044: return $fetchresult;
4045: }
4046:
1.637 raeburn 4047: sub build_filepath {
4048: my ($fpath) = @_;
4049: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
4050: unless ($fpath eq '') {
4051: my @parts=split('/',$fpath);
4052: foreach my $part (@parts) {
4053: $filepath.= '/'.$part;
4054: if ((-e $filepath)!=1) {
4055: mkdir($filepath,0777);
4056: }
4057: }
4058: }
4059: return $filepath;
4060: }
4061:
4062: sub store_edited_file {
1.638 albertel 4063: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 4064: my $file = $primary_url;
4065: $file =~ s#^/uploaded/$docudom/$docuname/##;
4066: my $fpath = '';
4067: my $fname = $file;
4068: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
4069: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
4070: my $filepath = &build_filepath($fpath);
1.1359 raeburn 4071: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 4072: print $fh $content;
4073: close($fh);
1.638 albertel 4074: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 4075: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 4076: $home);
1.637 raeburn 4077: if ($$fetchresult eq 'ok') {
4078: return '/uploaded/'.$fpath.'/'.$fname;
4079: } else {
1.638 albertel 4080: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
4081: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 4082: return '/adm/notfound.html';
4083: }
4084: }
4085:
1.531 albertel 4086: sub clean_filename {
1.831 albertel 4087: my ($fname,$args)=@_;
1.315 www 4088: # Replace Windows backslashes by forward slashes
1.257 www 4089: $fname=~s/\\/\//g;
1.831 albertel 4090: if (!$args->{'keep_path'}) {
4091: # Get rid of everything but the actual filename
4092: $fname=~s/^.*\/([^\/]+)$/$1/;
4093: }
1.315 www 4094: # Replace spaces by underscores
4095: $fname=~s/\s+/\_/g;
1.1406 raeburn 4096: # Transliterate non-ascii text to ascii
4097: my $lang = &Apache::lonlocal::current_language();
4098: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 4099: # Replace all other weird characters by nothing
1.831 albertel 4100: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 4101: # Replace all .\d. sequences with _\d. so they no longer look like version
4102: # numbers
4103: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1443 raeburn 4104: # Replace three or more adjacent underscores with one for consistency
4105: # with loncfile::filename_check() so complete url can be extracted by
4106: # lonnet::decode_symb()
4107: $fname=~s/_{3,}/_/g;
1.531 albertel 4108: return $fname;
4109: }
1.1406 raeburn 4110:
1.1051 raeburn 4111: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
4112: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
4113: # image with the same aspect ratio as the original, but with dimensions which do
4114: # not exceed $resizewidth and $resizeheight.
4115:
1.984 neumanie 4116: sub resizeImage {
1.1051 raeburn 4117: my ($img_path,$resizewidth,$resizeheight) = @_;
4118: my $ima = Image::Magick->new;
4119: my $resized;
4120: if (-e $img_path) {
4121: $ima->Read($img_path);
4122: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
4123: my $width = $ima->Get('width');
4124: my $height = $ima->Get('height');
4125: if ($width > $resizewidth) {
4126: my $factor = $width/$resizewidth;
4127: my $newheight = $height/$factor;
4128: $ima->Scale(width=>$resizewidth,height=>$newheight);
4129: $resized = 1;
4130: }
4131: }
4132: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
4133: my $width = $ima->Get('width');
4134: my $height = $ima->Get('height');
4135: if ($height > $resizeheight) {
4136: my $factor = $height/$resizeheight;
4137: my $newwidth = $width/$factor;
4138: $ima->Scale(width=>$newwidth,height=>$resizeheight);
4139: $resized = 1;
4140: }
4141: }
4142: if ($resized) {
4143: $ima->Write($img_path);
4144: }
4145: }
4146: return;
1.977 amueller 4147: }
4148:
1.608 albertel 4149: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 4150: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 4151: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 4152: # $context - possible values: coursedoc, existingfile, overwrite,
1.1401 raeburn 4153: # canceloverwrite, scantron or ''.
1.1090 raeburn 4154: # if 'coursedoc': upload to the current course
4155: # if 'existingfile': write file to tmp/overwrites directory
4156: # if 'canceloverwrite': delete file written to tmp/overwrites directory
4157: # $context is passed as argument to &finishuserfileupload
1.686 albertel 4158: # $subdir - directory in userfile to store the file into
1.1401 raeburn 4159: # $parser - instruction to parse file for objects ($parser = parse) or
4160: # if context is 'scantron', $parser is hashref of csv column mapping
4161: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
4162: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 4163: # $allfiles - reference to hash for embedded objects
4164: # $codebase - reference to hash for codebase of java objects
4165: # $desuname - username for permanent storage of uploaded file
4166: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 4167: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
4168: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 4169: # $resizewidth - width (pixels) to which to resize uploaded image
4170: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 4171: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 4172: # from File::MMagic.
1.858 raeburn 4173: #
1.686 albertel 4174: # output: url of file in userspace, or error: <message>
4175: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 4176:
1.531 albertel 4177: sub userfileupload {
1.1090 raeburn 4178: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 4179: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 4180: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 4181: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 4182: $fname=&clean_filename($fname);
1.1090 raeburn 4183: # See if there is anything left
1.257 www 4184: unless ($fname) { return 'error: no uploaded file'; }
1.1406 raeburn 4185: # If filename now begins with a . prepend unix timestamp _ milliseconds
4186: if ($fname =~ /^\./) {
4187: my ($s,$usec) = &gettimeofday();
4188: while (length($usec) < 6) {
4189: $usec = '0'.$usec;
4190: }
4191: $fname = $s.'_'.substr($usec,0,3).$fname;
4192: }
1.1090 raeburn 4193: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
4194: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
4195: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
4196: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 4197: my $now = time;
1.1090 raeburn 4198: my $filepath;
1.1095 raeburn 4199: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 4200: $filepath = 'tmp/helprequests/'.$now;
4201: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
4202: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
4203: '_'.$env{'user.domain'}.'/pending';
4204: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
4205: my ($docuname,$docudom);
1.1350 raeburn 4206: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 4207: $docudom = $destudom;
4208: } else {
4209: $docudom = $env{'user.domain'};
4210: }
1.1350 raeburn 4211: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 4212: $docuname = $destuname;
4213: } else {
4214: $docuname = $env{'user.name'};
4215: }
4216: if (exists($env{'form.group'})) {
4217: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4218: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4219: }
4220: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
4221: if ($context eq 'canceloverwrite') {
4222: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
4223: if (-e $tempfile) {
4224: my @info = stat($tempfile);
4225: if ($info[9] eq $env{'form.timestamp'}) {
4226: unlink($tempfile);
4227: }
4228: }
4229: return;
1.523 raeburn 4230: }
4231: }
1.1090 raeburn 4232: # Create the directory if not present
1.741 raeburn 4233: my @parts=split(/\//,$filepath);
4234: my $fullpath = $perlvar{'lonDaemons'};
4235: for (my $i=0;$i<@parts;$i++) {
4236: $fullpath .= '/'.$parts[$i];
4237: if ((-e $fullpath)!=1) {
4238: mkdir($fullpath,0777);
4239: }
4240: }
1.1359 raeburn 4241: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 4242: print $fh $env{'form.'.$formname};
4243: close($fh);
1.1090 raeburn 4244: if ($context eq 'existingfile') {
4245: my @info = stat($fullpath.'/'.$fname);
4246: return ($fullpath.'/'.$fname,$info[9]);
4247: } else {
4248: return $fullpath.'/'.$fname;
4249: }
1.523 raeburn 4250: }
1.995 raeburn 4251: if ($subdir eq 'scantron') {
4252: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 4253: } else {
1.995 raeburn 4254: $fname="$subdir/$fname";
4255: }
1.1090 raeburn 4256: if ($context eq 'coursedoc') {
1.638 albertel 4257: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4258: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 4259: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 4260: return &finishuserfileupload($docuname,$docudom,
4261: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 4262: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 4263: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 4264: } else {
1.1218 raeburn 4265: if ($env{'form.folder'}) {
4266: $fname=$env{'form.folder'}.'/'.$fname;
4267: }
1.638 albertel 4268: return &process_coursefile('uploaddoc',$docuname,$docudom,
4269: $fname,$formname,$parser,
1.1095 raeburn 4270: $allfiles,$codebase,$mimetype);
1.481 raeburn 4271: }
1.719 banghart 4272: } elsif (defined($destuname)) {
4273: my $docuname=$destuname;
4274: my $docudom=$destudom;
1.860 raeburn 4275: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4276: $parser,$allfiles,$codebase,
1.1051 raeburn 4277: $thumbwidth,$thumbheight,
1.1095 raeburn 4278: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4279: } else {
1.638 albertel 4280: my $docuname=$env{'user.name'};
4281: my $docudom=$env{'user.domain'};
1.1220 raeburn 4282: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 4283: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
4284: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4285: }
1.860 raeburn 4286: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
4287: $parser,$allfiles,$codebase,
1.1051 raeburn 4288: $thumbwidth,$thumbheight,
1.1095 raeburn 4289: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 4290: }
1.271 www 4291: }
4292:
4293: sub finishuserfileupload {
1.860 raeburn 4294: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 4295: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 4296: my $path=$docudom.'/'.$docuname.'/';
1.258 www 4297: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 4298:
1.860 raeburn 4299: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 4300: $file=$fname;
4301: if ($fname=~m|/|) {
4302: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
4303: $path.=$fnamepath.'/';
4304: }
1.259 www 4305: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 4306: my $count;
4307: for ($count=4;$count<=$#parts;$count++) {
4308: $filepath.="/$parts[$count]";
4309: if ((-e $filepath)!=1) {
4310: mkdir($filepath,0777);
4311: }
4312: }
1.984 neumanie 4313:
1.258 www 4314: # Save the file
4315: {
1.1359 raeburn 4316: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 4317: &logthis('Failed to create '.$filepath.'/'.$file);
4318: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
4319: return '/adm/notfound.html';
4320: }
1.1090 raeburn 4321: if ($context eq 'overwrite') {
1.1117 foxr 4322: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 4323: my $target = $filepath.'/'.$file;
4324: if (-e $source) {
4325: my @info = stat($source);
4326: if ($info[9] eq $env{'form.timestamp'}) {
4327: unless (&File::Copy::move($source,$target)) {
4328: &logthis('Failed to overwrite '.$filepath.'/'.$file);
4329: return "Moving from $source failed";
4330: }
4331: } else {
4332: return "Temporary file: $source had unexpected date/time for last modification";
4333: }
4334: } else {
4335: return "Temporary file: $source missing";
4336: }
4337: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 4338: &logthis('Failed to write to '.$filepath.'/'.$file);
4339: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
4340: return '/adm/notfound.html';
4341: }
1.570 albertel 4342: close(FH);
1.1051 raeburn 4343: if ($resizewidth && $resizeheight) {
4344: my $mm = new File::MMagic;
4345: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
4346: if ($mime_type =~ m{^image/}) {
4347: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
4348: }
1.977 amueller 4349: }
1.258 www 4350: }
1.1152 raeburn 4351: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
4352: if (ref($mimetype)) {
4353: if ($$mimetype eq '') {
4354: my $mm = new File::MMagic;
4355: my $type = $mm->checktype_filename($filepath.'/'.$file);
4356: $$mimetype = $type;
4357: }
4358: }
4359: }
1.1401 raeburn 4360: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 4361: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 4362: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
4363: $allfiles,$codebase);
4364: unless ($parse_result eq 'ok') {
4365: &logthis('Failed to parse '.$filepath.$file.
4366: ' for embedded media: '.$parse_result);
4367: }
1.637 raeburn 4368: }
1.1401 raeburn 4369: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4370: my $format = $env{'form.scantron_format'};
4371: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 4372: }
1.860 raeburn 4373: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4374: my $input = $filepath.'/'.$file;
4375: my $output = $filepath.'/'.'tn-'.$file;
4376: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359 raeburn 4377: my @args = ('convert','-sample',$thumbsize,$input,$output);
4378: system({$args[0]} @args);
1.860 raeburn 4379: if (-e $filepath.'/'.'tn-'.$file) {
4380: $fetchthumb = 1;
4381: }
4382: }
1.858 raeburn 4383:
1.259 www 4384: # Notify homeserver to grep it
4385: #
1.984 neumanie 4386: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 4387: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 4388: if ($fetchresult eq 'ok') {
1.860 raeburn 4389: if ($fetchthumb) {
4390: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4391: if ($thumbresult ne 'ok') {
4392: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4393: $docuhome.': '.$thumbresult);
4394: }
4395: }
1.259 www 4396: #
1.258 www 4397: # Return the URL to it
1.494 albertel 4398: return '/uploaded/'.$path.$file;
1.263 www 4399: } else {
1.494 albertel 4400: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4401: ': '.$fetchresult);
1.263 www 4402: return '/adm/notfound.html';
1.858 raeburn 4403: }
1.493 albertel 4404: }
4405:
1.637 raeburn 4406: sub extract_embedded_items {
1.961 raeburn 4407: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4408: my @state = ();
1.1164 raeburn 4409: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4410: my %javafiles = (
4411: codebase => '',
4412: code => '',
4413: archive => ''
4414: );
4415: my %mediafiles = (
4416: src => '',
4417: movie => '',
4418: );
1.648 raeburn 4419: my $p;
4420: if ($content) {
4421: $p = HTML::LCParser->new($content);
4422: } else {
1.961 raeburn 4423: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4424: }
1.641 albertel 4425: while (my $t=$p->get_token()) {
1.640 albertel 4426: if ($t->[0] eq 'S') {
4427: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4428: push(@state, $tagname);
1.648 raeburn 4429: if (lc($tagname) eq 'allow') {
4430: &add_filetype($allfiles,$attr->{'src'},'src');
4431: }
1.640 albertel 4432: if (lc($tagname) eq 'img') {
4433: &add_filetype($allfiles,$attr->{'src'},'src');
4434: }
1.886 albertel 4435: if (lc($tagname) eq 'a') {
1.1222 raeburn 4436: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 4437: &add_filetype($allfiles,$attr->{'href'},'href');
4438: }
1.886 albertel 4439: }
1.645 raeburn 4440: if (lc($tagname) eq 'script') {
1.1164 raeburn 4441: my $src;
1.645 raeburn 4442: if ($attr->{'archive'} =~ /\.jar$/i) {
4443: &add_filetype($allfiles,$attr->{'archive'},'archive');
4444: } else {
1.1164 raeburn 4445: if ($attr->{'src'} ne '') {
4446: $src = $attr->{'src'};
4447: &add_filetype($allfiles,$src,'src');
4448: }
4449: }
4450: my $text = $p->get_trimmed_text();
4451: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4452: my @swfargs = split(/,/,$1);
4453: foreach my $item (@swfargs) {
4454: $item =~ s/["']//g;
4455: $item =~ s/^\s+//;
4456: $item =~ s/\s+$//;
4457: }
4458: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4459: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4460: push(@{$related{$swfargs[0]}},$swfargs[2]);
4461: } else {
4462: $related{$swfargs[0]} = [$swfargs[2]];
4463: }
4464: }
1.645 raeburn 4465: }
4466: }
4467: if (lc($tagname) eq 'link') {
4468: if (lc($attr->{'rel'}) eq 'stylesheet') {
4469: &add_filetype($allfiles,$attr->{'href'},'href');
4470: }
4471: }
1.640 albertel 4472: if (lc($tagname) eq 'object' ||
4473: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4474: foreach my $item (keys(%javafiles)) {
4475: $javafiles{$item} = '';
4476: }
1.1164 raeburn 4477: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4478: $lastids{lc($tagname)} = $attr->{'id'};
4479: }
1.640 albertel 4480: }
4481: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4482: my $name = lc($attr->{'name'});
4483: foreach my $item (keys(%javafiles)) {
4484: if ($name eq $item) {
4485: $javafiles{$item} = $attr->{'value'};
4486: last;
4487: }
4488: }
1.1164 raeburn 4489: my $pathfrom;
1.640 albertel 4490: foreach my $item (keys(%mediafiles)) {
4491: if ($name eq $item) {
1.1164 raeburn 4492: $pathfrom = $attr->{'value'};
4493: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4494: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4495: last;
4496: }
4497: }
1.1164 raeburn 4498: if ($name eq 'flashvars') {
4499: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4500: }
4501: if ($pathfrom ne '') {
4502: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4503: $pathfrom);
4504: }
1.640 albertel 4505: }
4506: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4507: foreach my $item (keys(%javafiles)) {
4508: if ($attr->{$item}) {
4509: $javafiles{$item} = $attr->{$item};
4510: last;
4511: }
4512: }
4513: foreach my $item (keys(%mediafiles)) {
4514: if ($attr->{$item}) {
4515: &add_filetype($allfiles,$attr->{$item},$item);
4516: last;
4517: }
4518: }
1.1164 raeburn 4519: if (lc($tagname) eq 'embed') {
4520: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4521: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4522: $attr->{'src'});
4523: }
4524: }
1.640 albertel 4525: }
1.1243 raeburn 4526: if (lc($tagname) eq 'iframe') {
4527: my $src = $attr->{'src'} ;
4528: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4529: &add_filetype($allfiles,$src,'src');
4530: } elsif ($src =~ m{^/}) {
4531: if ($env{'request.course.id'}) {
4532: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4533: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4534: my $url = &hreflocation('',$fullpath);
4535: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4536: my $relpath = $1;
4537: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4538: &add_filetype($allfiles,$1,'src');
4539: }
4540: }
4541: }
4542: }
4543: }
1.1164 raeburn 4544: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 4545: pop(@state);
1.1164 raeburn 4546: }
1.640 albertel 4547: } elsif ($t->[0] eq 'E') {
4548: my ($tagname) = ($t->[1]);
4549: if ($javafiles{'codebase'} ne '') {
4550: $javafiles{'codebase'} .= '/';
4551: }
4552: if (lc($tagname) eq 'applet' ||
4553: lc($tagname) eq 'object' ||
4554: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4555: ) {
4556: foreach my $item (keys(%javafiles)) {
4557: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4558: my $file=$javafiles{'codebase'}.$javafiles{$item};
4559: &add_filetype($allfiles,$file,$item);
4560: }
4561: }
4562: }
4563: pop @state;
4564: }
4565: }
1.1164 raeburn 4566: foreach my $id (sort(keys(%flashvars))) {
4567: if ($shockwave{$id} ne '') {
4568: my @pairs = split(/\&/,$flashvars{$id});
4569: foreach my $pair (@pairs) {
4570: my ($key,$value) = split(/\=/,$pair);
4571: if ($key eq 'thumb') {
4572: &add_filetype($allfiles,$value,$key);
4573: } elsif ($key eq 'content') {
4574: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4575: my ($ext) = ($value =~ /\.([^.]+)$/);
4576: if ($ext ne '') {
4577: &add_filetype($allfiles,$path.$value,$ext);
4578: }
4579: }
4580: }
4581: }
4582: }
1.637 raeburn 4583: return 'ok';
4584: }
4585:
1.639 albertel 4586: sub add_filetype {
4587: my ($allfiles,$file,$type)=@_;
4588: if (exists($allfiles->{$file})) {
4589: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4590: push(@{$allfiles->{$file}}, &escape($type));
4591: }
4592: } else {
4593: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4594: }
4595: }
4596:
1.1164 raeburn 4597: sub embedded_dependency {
4598: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4599: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4600: if (($identifier ne '') &&
4601: (ref($related->{$identifier}) eq 'ARRAY') &&
4602: ($pathfrom ne '')) {
4603: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4604: foreach my $dep (@{$related->{$identifier}}) {
4605: &add_filetype($allfiles,$path.$dep,'object');
4606: }
4607: }
4608: }
4609: return;
4610: }
4611:
1.1401 raeburn 4612: sub bubblesheet_converter {
4613: my ($cdom,$fullpath,$config,$format) = @_;
4614: if ((&domain($cdom) ne '') &&
1.1403 raeburn 4615: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401 raeburn 4616: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404 raeburn 4617: my (%csvcols,%csvoptions);
4618: if (ref($config->{'fields'}) eq 'HASH') {
4619: %csvcols = %{$config->{'fields'}};
4620: }
4621: if (ref($config->{'options'}) eq 'HASH') {
4622: %csvoptions = %{$config->{'options'}};
4623: }
1.1401 raeburn 4624: my %csvbynum = reverse(%csvcols);
4625: my %scantronconf = &get_scantron_config($format,$cdom);
4626: if (keys(%scantronconf)) {
4627: my %bynum = (
4628: $scantronconf{CODEstart} => 'CODEstart',
4629: $scantronconf{IDstart} => 'IDstart',
4630: $scantronconf{PaperID} => 'PaperID',
4631: $scantronconf{FirstName} => 'FirstName',
4632: $scantronconf{LastName} => 'LastName',
4633: $scantronconf{Qstart} => 'Qstart',
4634: );
4635: my @ordered;
4636: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403 raeburn 4637: push(@ordered,$bynum{$item});
1.1401 raeburn 4638: }
4639: my %mapstart = (
4640: CODEstart => 'CODE',
4641: IDstart => 'ID',
4642: PaperID => 'PaperID',
4643: FirstName => 'FirstName',
4644: LastName => 'LastName',
4645: Qstart => 'FirstQuestion',
4646: );
4647: my %maplength = (
4648: CODEstart => 'CODElength',
4649: IDstart => 'IDlength',
4650: PaperID => 'PaperIDlength',
4651: FirstName => 'FirstNamelength',
4652: LastName => 'LastNamelength',
4653: );
4654: if (open(my $fh,'<',$fullpath)) {
4655: my $output;
1.1403 raeburn 4656: my %lettdig = &letter_to_digits();
4657: my %diglett = reverse(%lettdig);
4658: my $numletts = scalar(keys(%lettdig));
1.1404 raeburn 4659: my $num = 0;
1.1401 raeburn 4660: while (my $line=<$fh>) {
1.1404 raeburn 4661: $num ++;
4662: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401 raeburn 4663: $line =~ s{[\r\n]+$}{};
4664: my %found;
4665: my @values = split(/,/,$line);
4666: my ($qstart,$record);
4667: for (my $i=0; $i<@values; $i++) {
1.1403 raeburn 4668: if ((($qstart ne '') && ($i > $qstart)) ||
4669: ($csvbynum{$i} eq 'FirstQuestion')) {
4670: if ($values[$i] eq '') {
4671: $values[$i] = $scantronconf{'Qoff'};
4672: } elsif ($scantronconf{'Qon'} eq 'number') {
4673: if ($values[$i] =~ /^[A-Ja-j]$/) {
4674: $values[$i] = $lettdig{uc($values[$i])};
4675: }
4676: } elsif ($scantronconf{'Qon'} eq 'letter') {
4677: if ($values[$i] =~ /^[0-9]$/) {
4678: $values[$i] = $diglett{$values[$i]};
4679: }
4680: } else {
4681: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4682: my $digit;
4683: if ($values[$i] =~ /^[A-Ja-j]$/) {
4684: $digit = $lettdig{uc($values[$i])}-1;
4685: if ($values[$i] eq 'J') {
4686: $digit += $numletts;
4687: }
4688: } elsif ($values[$i] =~ /^[0-9]$/) {
4689: $digit = $values[$i]-1;
4690: if ($values[$i] eq '0') {
4691: $digit += $numletts;
4692: }
4693: }
4694: my $qval='';
4695: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4696: if ($j == $digit) {
4697: $qval .= $scantronconf{'Qon'};
4698: } else {
4699: $qval .= $scantronconf{'Qoff'};
4700: }
4701: }
4702: $values[$i] = $qval;
4703: }
4704: }
4705: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4706: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4707: }
4708: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4709: if ($numblank > 0) {
4710: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4711: }
1.1401 raeburn 4712: if ($csvbynum{$i} eq 'FirstQuestion') {
4713: $qstart = $i;
1.1403 raeburn 4714: $found{$csvbynum{$i}} = $values[$i];
1.1401 raeburn 4715: } else {
1.1403 raeburn 4716: $found{'FirstQuestion'} .= $values[$i];
4717: }
4718: } elsif (exists($csvbynum{$i})) {
1.1404 raeburn 4719: if ($csvoptions{'rem'}) {
4720: $values[$i] =~ s/^\s+//;
4721: }
4722: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403 raeburn 4723: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4724: $values[$i] = '0'.$values[$i];
1.1401 raeburn 4725: }
4726: }
4727: $found{$csvbynum{$i}} = $values[$i];
4728: }
4729: }
4730: foreach my $item (@ordered) {
4731: my $currlength = 1+length($record);
4732: my $numspaces = $scantronconf{$item} - $currlength;
4733: if ($numspaces > 0) {
4734: $record .= (' ' x $numspaces);
4735: }
4736: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4737: unless ($item eq 'Qstart') {
4738: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4739: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4740: }
4741: }
4742: $record .= $found{$mapstart{$item}};
4743: }
4744: }
4745: $output .= "$record\n";
4746: }
4747: close($fh);
4748: if ($output) {
4749: if (open(my $fh,'>',$fullpath)) {
4750: print $fh $output;
4751: close($fh);
4752: }
4753: }
4754: }
4755: }
4756: return;
4757: }
4758: }
4759:
1.1403 raeburn 4760: sub letter_to_digits {
4761: my %lettdig = (
4762: A => 1,
4763: B => 2,
4764: C => 3,
4765: D => 4,
4766: E => 5,
4767: F => 6,
4768: G => 7,
4769: H => 8,
4770: I => 9,
4771: J => 0,
4772: );
4773: return %lettdig;
4774: }
4775:
1.1401 raeburn 4776: sub get_scantron_config {
4777: my ($which,$cdom) = @_;
4778: my @lines = &get_scantronformat_file($cdom);
4779: my %config;
4780: #FIXME probably should move to XML it has already gotten a bit much now
4781: foreach my $line (@lines) {
4782: my ($name,$descrip)=split(/:/,$line);
4783: if ($name ne $which ) { next; }
4784: chomp($line);
4785: my @config=split(/:/,$line);
4786: $config{'name'}=$config[0];
4787: $config{'description'}=$config[1];
4788: $config{'CODElocation'}=$config[2];
4789: $config{'CODEstart'}=$config[3];
4790: $config{'CODElength'}=$config[4];
4791: $config{'IDstart'}=$config[5];
4792: $config{'IDlength'}=$config[6];
4793: $config{'Qstart'}=$config[7];
4794: $config{'Qlength'}=$config[8];
4795: $config{'Qoff'}=$config[9];
4796: $config{'Qon'}=$config[10];
4797: $config{'PaperID'}=$config[11];
4798: $config{'PaperIDlength'}=$config[12];
4799: $config{'FirstName'}=$config[13];
4800: $config{'FirstNamelength'}=$config[14];
4801: $config{'LastName'}=$config[15];
4802: $config{'LastNamelength'}=$config[16];
4803: $config{'BubblesPerRow'}=$config[17];
4804: last;
4805: }
4806: return %config;
4807: }
4808:
4809: sub get_scantronformat_file {
4810: my ($cdom) = @_;
4811: if ($cdom eq '') {
4812: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4813: }
4814: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4815: my $gottab = 0;
4816: my @lines;
4817: if (ref($domconfig{'scantron'}) eq 'HASH') {
4818: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4819: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4820: if ($formatfile ne '-1') {
4821: @lines = split("\n",$formatfile,-1);
4822: $gottab = 1;
4823: }
4824: }
4825: }
4826: if (!$gottab) {
4827: my $confname = $cdom.'-domainconfig';
4828: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4829: my $formatfile = &getfile($default);
4830: if ($formatfile ne '-1') {
4831: @lines = split("\n",$formatfile,-1);
4832: $gottab = 1;
4833: }
4834: }
4835: if (!$gottab) {
4836: my @domains = ¤t_machine_domains();
4837: if (grep(/^\Q$cdom\E$/,@domains)) {
4838: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4839: @lines = <$fh>;
4840: close($fh);
1.1403 raeburn 4841: }
1.1401 raeburn 4842: } else {
4843: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4844: @lines = <$fh>;
4845: close($fh);
4846: }
4847: }
4848: }
4849: return @lines;
4850: }
4851:
1.493 albertel 4852: sub removeuploadedurl {
1.984 neumanie 4853: my ($url)=@_;
4854: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4855: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4856: }
4857:
4858: sub removeuserfile {
4859: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4860: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4861: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4862: if ($result eq 'ok') {
1.798 raeburn 4863: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4864: my $metafile = $fname.'.meta';
4865: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4866: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4867: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4868: my $sqlresult =
1.823 albertel 4869: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4870: 'portfolio_metadata',$group,
4871: 'delete');
1.798 raeburn 4872: }
4873: }
4874: return $result;
1.257 www 4875: }
1.15 www 4876:
1.530 albertel 4877: sub mkdiruserfile {
4878: my ($docuname,$docudom,$dir)=@_;
4879: my $home=&homeserver($docuname,$docudom);
4880: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4881: }
4882:
1.531 albertel 4883: sub renameuserfile {
4884: my ($docuname,$docudom,$old,$new)=@_;
4885: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4886: my $result = &reply("renameuserfile:$docudom:$docuname:".
4887: &escape("$old").':'.&escape("$new"),$home);
4888: if ($result eq 'ok') {
4889: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4890: my $oldmeta = $old.'.meta';
4891: my $newmeta = $new.'.meta';
4892: my $metaresult =
4893: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4894: my $url = "/uploaded/$docudom/$docuname/$old";
4895: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4896: my $sqlresult =
1.823 albertel 4897: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4898: 'portfolio_metadata',$group,
4899: 'delete');
1.798 raeburn 4900: }
4901: }
4902: return $result;
1.531 albertel 4903: }
4904:
1.14 www 4905: # ------------------------------------------------------------------------- Log
4906:
4907: sub log {
4908: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4909: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4910: }
4911:
4912: # ------------------------------------------------------------------ Course Log
1.352 www 4913: #
4914: # This routine flushes several buffers of non-mission-critical nature
4915: #
1.157 www 4916:
4917: sub flushcourselogs {
1.352 www 4918: &logthis('Flushing log buffers');
4919: #
4920: # course logs
4921: # This is a log of all transactions in a course, which can be used
4922: # for data mining purposes
4923: #
4924: # It also collects the courseid database, which lists last transaction
4925: # times and course titles for all courseids
4926: #
4927: my %courseidbuffer=();
1.921 raeburn 4928: foreach my $crsid (keys(%courselogs)) {
1.352 www 4929: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4930: &escape($courselogs{$crsid}),
4931: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4932: delete $courselogs{$crsid};
4933: } else {
4934: &logthis('Failed to flush log buffer for '.$crsid);
4935: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4936: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4937: " exceeded maximum size, deleting.</font>");
4938: delete $courselogs{$crsid};
4939: }
1.352 www 4940: }
1.920 raeburn 4941: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4942: 'description' => $coursedescrbuf{$crsid},
4943: 'inst_code' => $courseinstcodebuf{$crsid},
4944: 'type' => $coursetypebuf{$crsid},
4945: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4946: };
1.191 harris41 4947: }
1.352 www 4948: #
4949: # Write course id database (reverse lookup) to homeserver of courses
4950: # Is used in pickcourse
4951: #
1.840 albertel 4952: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4953: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4954: $courseidbuffer{$crs_home},
4955: $crs_home,'timeonly');
1.352 www 4956: }
4957: #
4958: # File accesses
4959: # Writes to the dynamic metadata of resources to get hit counts, etc.
4960: #
1.449 matthew 4961: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4962: if ($entry =~ /___count$/) {
4963: my ($dom,$name);
1.807 albertel 4964: ($dom,$name,undef)=
1.811 albertel 4965: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4966: if (! defined($dom) || $dom eq '' ||
4967: ! defined($name) || $name eq '') {
1.620 albertel 4968: my $cid = $env{'request.course.id'};
4969: $dom = $env{'request.'.$cid.'.domain'};
4970: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4971: }
1.450 matthew 4972: my $value = $accesshash{$entry};
4973: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4974: my %temphash=($url => $value);
1.449 matthew 4975: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4976: if ($result eq 'ok') {
4977: delete $accesshash{$entry};
4978: }
4979: } else {
1.811 albertel 4980: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4981: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4982: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4983: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4984: delete $accesshash{$entry};
4985: }
1.185 www 4986: }
1.191 harris41 4987: }
1.352 www 4988: #
4989: # Roles
4990: # Reverse lookup of user roles for course faculty/staff and co-authorship
4991: #
1.800 albertel 4992: foreach my $entry (keys(%userrolehash)) {
1.351 www 4993: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4994: split(/\:/,$entry);
4995: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4996: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4997: $rudom,$runame) eq 'ok') {
4998: delete $userrolehash{$entry};
4999: }
5000: }
1.662 raeburn 5001: #
1.1334 raeburn 5002: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 5003: #
5004: my %domrolebuffer = ();
1.1000 raeburn 5005: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 5006: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 5007: if ($domrolebuffer{$rudom}) {
5008: $domrolebuffer{$rudom}.='&'.&escape($entry).
5009: '='.&escape($domainrolehash{$entry});
5010: } else {
5011: $domrolebuffer{$rudom}.=&escape($entry).
5012: '='.&escape($domainrolehash{$entry});
5013: }
5014: delete $domainrolehash{$entry};
5015: }
5016: foreach my $dom (keys(%domrolebuffer)) {
1.1324 raeburn 5017: my %servers;
5018: if (defined(&domain($dom,'primary'))) {
5019: my $primary=&domain($dom,'primary');
5020: my $hostname=&hostname($primary);
5021: $servers{$primary} = $hostname;
5022: } else {
5023: %servers = &get_servers($dom,'library');
5024: }
1.841 albertel 5025: foreach my $tryserver (keys(%servers)) {
1.1324 raeburn 5026: if (&reply('domroleput:'.$dom.':'.
5027: $domrolebuffer{$dom},$tryserver) eq 'ok') {
5028: last;
5029: } else {
1.841 albertel 5030: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
5031: }
1.662 raeburn 5032: }
5033: }
1.186 www 5034: $dumpcount++;
1.157 www 5035: }
5036:
5037: sub courselog {
5038: my $what=shift;
1.158 www 5039: $what=time.':'.$what;
1.620 albertel 5040: unless ($env{'request.course.id'}) { return ''; }
5041: $coursedombuf{$env{'request.course.id'}}=
5042: $env{'course.'.$env{'request.course.id'}.'.domain'};
5043: $coursenumbuf{$env{'request.course.id'}}=
5044: $env{'course.'.$env{'request.course.id'}.'.num'};
5045: $coursehombuf{$env{'request.course.id'}}=
5046: $env{'course.'.$env{'request.course.id'}.'.home'};
5047: $coursedescrbuf{$env{'request.course.id'}}=
5048: $env{'course.'.$env{'request.course.id'}.'.description'};
5049: $courseinstcodebuf{$env{'request.course.id'}}=
5050: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
5051: $courseownerbuf{$env{'request.course.id'}}=
5052: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 5053: $coursetypebuf{$env{'request.course.id'}}=
5054: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 5055: if (defined $courselogs{$env{'request.course.id'}}) {
5056: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 5057: } else {
1.620 albertel 5058: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 5059: }
1.620 albertel 5060: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 5061: &flushcourselogs();
5062: }
1.158 www 5063: }
5064:
5065: sub courseacclog {
5066: my $fnsymb=shift;
1.620 albertel 5067: unless ($env{'request.course.id'}) { return ''; }
5068: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 5069: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 5070: $what.=':POST';
1.583 matthew 5071: # FIXME: Probably ought to escape things....
1.800 albertel 5072: foreach my $key (keys(%env)) {
5073: if ($key=~/^form\.(.*)/) {
1.975 raeburn 5074: my $formitem = $1;
5075: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
5076: $what.=':'.$formitem.'='.$env{$key};
5077: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1432 raeburn 5078: if ($formitem eq 'proctorpassword') {
1.1433 raeburn 5079: $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1432 raeburn 5080: } else {
5081: $what.=':'.$formitem.'='.$env{$key};
5082: }
1.975 raeburn 5083: }
1.158 www 5084: }
1.191 harris41 5085: }
1.583 matthew 5086: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
5087: # FIXME: We should not be depending on a form parameter that someone
5088: # editing lonsearchcat.pm might change in the future.
1.620 albertel 5089: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 5090: $what.= ':POST';
5091: # FIXME: Probably ought to escape things....
5092: foreach my $element ('courseexp','crsfulltext','crsrelated',
5093: 'crsdiscuss') {
1.620 albertel 5094: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 5095: }
5096: }
1.158 www 5097: }
5098: &courselog($what);
1.149 www 5099: }
5100:
1.185 www 5101: sub countacc {
5102: my $url=&declutter(shift);
1.458 matthew 5103: return if (! defined($url) || $url eq '');
1.620 albertel 5104: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 5105: #
5106: # Mark that this url was used in this course
5107: #
1.620 albertel 5108: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 5109: #
5110: # Increase the access count for this resource in this child process
5111: #
1.281 www 5112: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 5113: $accesshash{$key}++;
1.185 www 5114: }
1.349 www 5115:
1.361 www 5116: sub linklog {
5117: my ($from,$to)=@_;
5118: $from=&declutter($from);
5119: $to=&declutter($to);
5120: $accesshash{$from.'___'.$to.'___comefrom'}=1;
5121: $accesshash{$to.'___'.$from.'___goto'}=1;
5122: }
1.1160 www 5123:
5124: sub statslog {
5125: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
5126: if ($users<2) { return; }
5127: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
5128: 'course' => $env{'request.course.id'},
5129: 'sections' => '"all"',
5130: 'num_students' => $users,
5131: 'part' => $part,
5132: 'symb' => $symb,
5133: 'mean_tries' => $av_attempts,
5134: 'deg_of_diff' => $degdiff});
5135: foreach my $key (keys(%dynstore)) {
5136: $accesshash{$key}=$dynstore{$key};
5137: }
5138: }
1.361 www 5139:
1.349 www 5140: sub userrolelog {
5141: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 5142: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 5143: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5144: $userrolehash
5145: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 5146: =$tend.':'.$tstart;
1.662 raeburn 5147: }
1.1169 droeschl 5148: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 5149: $userrolehash
5150: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
5151: =$tend.':'.$tstart;
5152: }
1.1334 raeburn 5153: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 5154: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
5155: $domainrolehash
5156: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
5157: = $tend.':'.$tstart;
5158: }
1.351 www 5159: }
5160:
1.957 raeburn 5161: sub courserolelog {
5162: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 5163: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
5164: my $cdom = $1;
5165: my $cnum = $2;
5166: my $sec = $3;
5167: my $namespace = 'rolelog';
5168: my %storehash = (
5169: role => $trole,
5170: start => $tstart,
5171: end => $tend,
5172: selfenroll => $selfenroll,
5173: context => $context,
5174: );
5175: if ($trole eq 'gr') {
5176: $namespace = 'groupslog';
5177: $storehash{'group'} = $sec;
5178: } else {
5179: $storehash{'section'} = $sec;
5180: }
1.1188 raeburn 5181: &write_log('course',$namespace,\%storehash,$delflag,$username,
5182: $domain,$cnum,$cdom);
1.1184 raeburn 5183: if (($trole ne 'st') || ($sec ne '')) {
5184: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 5185: }
5186: }
5187: return;
5188: }
5189:
1.1184 raeburn 5190: sub domainrolelog {
5191: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5192: if ($area =~ m{^/($match_domain)/$}) {
5193: my $cdom = $1;
5194: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
5195: my $namespace = 'rolelog';
5196: my %storehash = (
5197: role => $trole,
5198: start => $tstart,
5199: end => $tend,
5200: context => $context,
5201: );
1.1188 raeburn 5202: &write_log('domain',$namespace,\%storehash,$delflag,$username,
5203: $domain,$domconfiguser,$cdom);
1.1184 raeburn 5204: }
5205: return;
5206:
5207: }
5208:
5209: sub coauthorrolelog {
5210: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
5211: if ($area =~ m{^/($match_domain)/($match_username)$}) {
5212: my $audom = $1;
5213: my $auname = $2;
5214: my $namespace = 'rolelog';
5215: my %storehash = (
5216: role => $trole,
5217: start => $tstart,
5218: end => $tend,
5219: context => $context,
5220: );
1.1188 raeburn 5221: &write_log('author',$namespace,\%storehash,$delflag,$username,
5222: $domain,$auname,$audom);
1.1184 raeburn 5223: }
5224: return;
5225: }
5226:
1.351 www 5227: sub get_course_adv_roles {
1.948 raeburn 5228: my ($cid,$codes) = @_;
1.620 albertel 5229: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 5230: my %coursehash=&coursedescription($cid);
1.988 raeburn 5231: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 5232: my %nothide=();
1.800 albertel 5233: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 5234: if ($user !~ /:/) {
5235: $nothide{join(':',split(/[\@]/,$user))}=1;
5236: } else {
5237: $nothide{$user}=1;
5238: }
1.470 www 5239: }
1.1219 raeburn 5240: my @possdoms = ($coursehash{'domain'});
5241: if ($coursehash{'checkforpriv'}) {
5242: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
5243: }
1.351 www 5244: my %returnhash=();
5245: my %dumphash=
5246: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
5247: my $now=time;
1.997 raeburn 5248: my %privileged;
1.1000 raeburn 5249: foreach my $entry (keys(%dumphash)) {
1.800 albertel 5250: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 5251: if (($tstart) && ($tstart<0)) { next; }
5252: if (($tend) && ($tend<$now)) { next; }
5253: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 5254: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 5255: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 5256: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 5257: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 5258: if ($role eq 'cr') { next; }
1.948 raeburn 5259: if ($codes) {
5260: if ($section) { $role .= ':'.$section; }
5261: if ($returnhash{$role}) {
5262: $returnhash{$role}.=','.$username.':'.$domain;
5263: } else {
5264: $returnhash{$role}=$username.':'.$domain;
5265: }
1.351 www 5266: } else {
1.988 raeburn 5267: my $key=&plaintext($role,$crstype);
1.973 bisitz 5268: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 5269: if ($returnhash{$key}) {
5270: $returnhash{$key}.=','.$username.':'.$domain;
5271: } else {
5272: $returnhash{$key}=$username.':'.$domain;
5273: }
1.351 www 5274: }
1.948 raeburn 5275: }
1.400 www 5276: return %returnhash;
5277: }
5278:
5279: sub get_my_roles {
1.937 raeburn 5280: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 5281: unless (defined($uname)) { $uname=$env{'user.name'}; }
5282: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 5283: my (%dumphash,%nothide);
1.1086 raeburn 5284: if ($context eq 'userroles') {
1.1166 raeburn 5285: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 5286: } else {
1.1219 raeburn 5287: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 5288: if ($hidepriv) {
5289: my %coursehash=&coursedescription($udom.'_'.$uname);
5290: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
5291: if ($user !~ /:/) {
5292: $nothide{join(':',split(/[\@]/,$user))} = 1;
5293: } else {
5294: $nothide{$user} = 1;
5295: }
5296: }
5297: }
1.858 raeburn 5298: }
1.400 www 5299: my %returnhash=();
5300: my $now=time;
1.999 raeburn 5301: my %privileged;
1.800 albertel 5302: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 5303: my ($role,$tend,$tstart);
5304: if ($context eq 'userroles') {
1.1149 raeburn 5305: next if ($entry =~ /^rolesdef/);
1.867 raeburn 5306: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
5307: } else {
5308: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
5309: }
1.400 www 5310: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 5311: my $status = 'active';
1.939 raeburn 5312: if (($tend) && ($tend<=$now)) {
1.832 raeburn 5313: $status = 'previous';
5314: }
5315: if (($tstart) && ($now<$tstart)) {
5316: $status = 'future';
5317: }
5318: if (ref($types) eq 'ARRAY') {
5319: if (!grep(/^\Q$status\E$/,@{$types})) {
5320: next;
5321: }
5322: } else {
5323: if ($status ne 'active') {
5324: next;
5325: }
5326: }
1.867 raeburn 5327: my ($rolecode,$username,$domain,$section,$area);
5328: if ($context eq 'userroles') {
1.1186 raeburn 5329: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 5330: (undef,$domain,$username,$section) = split(/\//,$area);
5331: } else {
5332: ($role,$username,$domain,$section) = split(/\:/,$entry);
5333: }
1.832 raeburn 5334: if (ref($roledoms) eq 'ARRAY') {
5335: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
5336: next;
5337: }
5338: }
5339: if (ref($roles) eq 'ARRAY') {
5340: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 5341: if ($role =~ /^cr\//) {
5342: if (!grep(/^cr$/,@{$roles})) {
5343: next;
5344: }
1.1104 raeburn 5345: } elsif ($role =~ /^gr\//) {
5346: if (!grep(/^gr$/,@{$roles})) {
5347: next;
5348: }
1.922 raeburn 5349: } else {
5350: next;
5351: }
1.832 raeburn 5352: }
1.867 raeburn 5353: }
1.937 raeburn 5354: if ($hidepriv) {
1.1219 raeburn 5355: my @privroles = ('dc','su');
1.999 raeburn 5356: if ($context eq 'userroles') {
1.1219 raeburn 5357: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 5358: } else {
1.1219 raeburn 5359: my $possdoms = [$domain];
5360: if (ref($roledoms) eq 'ARRAY') {
5361: push(@{$possdoms},@{$roledoms});
1.999 raeburn 5362: }
1.1219 raeburn 5363: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 5364: if (!$nothide{$username.':'.$domain}) {
5365: next;
5366: }
5367: }
1.937 raeburn 5368: }
5369: }
1.933 raeburn 5370: if ($withsec) {
5371: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5372: $tstart.':'.$tend;
5373: } else {
5374: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5375: }
1.832 raeburn 5376: }
1.373 www 5377: return %returnhash;
1.399 www 5378: }
5379:
1.1333 raeburn 5380: sub get_all_adhocroles {
5381: my ($dom) = @_;
5382: my @roles_by_num = ();
5383: my %domdefaults = &get_domain_defaults($dom);
5384: my (%description,%access_in_dom,%access_info);
5385: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5386: my $count = 0;
5387: my %domcurrent = %{$domdefaults{'adhocroles'}};
5388: my %ordered;
5389: foreach my $role (sort(keys(%domcurrent))) {
5390: my ($order,$desc,$access_in_dom);
5391: if (ref($domcurrent{$role}) eq 'HASH') {
5392: $order = $domcurrent{$role}{'order'};
5393: $desc = $domcurrent{$role}{'desc'};
5394: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5395: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5396: }
5397: if ($order eq '') {
5398: $order = $count;
5399: }
5400: $ordered{$order} = $role;
5401: if ($desc ne '') {
5402: $description{$role} = $desc;
5403: } else {
5404: $description{$role}= $role;
5405: }
5406: $count++;
5407: }
5408: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5409: push(@roles_by_num,$ordered{$item});
5410: }
5411: }
5412: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5413: }
5414:
1.1332 raeburn 5415: sub get_my_adhocroles {
1.1333 raeburn 5416: my ($cid,$checkreg) = @_;
5417: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5418: if ($env{'request.course.id'} eq $cid) {
5419: $cdom = $env{'course.'.$cid.'.domain'};
5420: $cnum = $env{'course.'.$cid.'.num'};
5421: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5422: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5423: $cdom = $1;
5424: $cnum = $2;
5425: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5426: $cdom,$cnum);
5427: }
5428: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5429: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5430: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5431: if ($rosterhash{$user} ne '') {
5432: my $type = (split(/:/,$rosterhash{$user}))[5];
5433: return ([],{}) if ($type eq 'auto');
5434: }
5435: }
5436: if (($cdom ne '') && ($cnum ne '')) {
1.1334 raeburn 5437: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332 raeburn 5438: my $then=$env{'user.login.time'};
5439: my $update=$env{'user.update.time'};
1.1335 raeburn 5440: if (!$update) {
5441: $update = $then;
5442: }
5443: my @liveroles;
1.1334 raeburn 5444: foreach my $role ('dh','da') {
5445: if ($env{"user.role.$role./$cdom/"}) {
1.1335 raeburn 5446: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334 raeburn 5447: my $limit = $update;
5448: if ($env{'request.role'} eq "$role./$cdom/") {
5449: $limit = $then;
5450: }
1.1335 raeburn 5451: my $activerole = 1;
5452: if ($tstart && $tstart>$limit) { $activerole = 0; }
5453: if ($tend && $tend <$limit) { $activerole = 0; }
5454: if ($activerole) {
5455: push(@liveroles,$role);
5456: }
1.1334 raeburn 5457: }
1.1332 raeburn 5458: }
1.1335 raeburn 5459: if (@liveroles) {
1.1332 raeburn 5460: if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333 raeburn 5461: my ($accessref,$accessinfo,%access_in_dom);
5462: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5463: if (ref($roles_by_num) eq 'ARRAY') {
5464: if (@{$roles_by_num}) {
1.1332 raeburn 5465: my %settings;
5466: if ($env{'request.course.id'} eq $cid) {
5467: foreach my $envkey (keys(%env)) {
5468: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5469: $settings{$1} = $env{$envkey};
5470: }
5471: }
5472: } else {
5473: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5474: }
5475: my %setincrs;
5476: if ($settings{'internal.adhocaccess'}) {
5477: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5478: }
5479: my @statuses;
5480: if ($env{'environment.inststatus'}) {
5481: @statuses = split(/,/,$env{'environment.inststatus'});
5482: }
5483: my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333 raeburn 5484: if (ref($accessref) eq 'HASH') {
5485: %access_in_dom = %{$accessref};
5486: }
5487: foreach my $role (@{$roles_by_num}) {
1.1332 raeburn 5488: my ($curraccess,@okstatus,@personnel);
5489: if ($setincrs{$role}) {
5490: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5491: if ($curraccess eq 'status') {
5492: @okstatus = split(/\&/,$rest);
5493: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5494: @personnel = split(/\&/,$rest);
5495: }
5496: } else {
5497: $curraccess = $access_in_dom{$role};
1.1333 raeburn 5498: if (ref($accessinfo) eq 'HASH') {
5499: if ($curraccess eq 'status') {
5500: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5501: @okstatus = @{$accessinfo->{$role}};
5502: }
5503: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5504: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5505: @personnel = @{$accessinfo->{$role}};
5506: }
1.1332 raeburn 5507: }
5508: }
5509: }
5510: if ($curraccess eq 'none') {
5511: next;
5512: } elsif ($curraccess eq 'all') {
5513: push(@possroles,$role);
1.1336 raeburn 5514: } elsif ($curraccess eq 'dh') {
1.1335 raeburn 5515: if (grep(/^dh$/,@liveroles)) {
5516: push(@possroles,$role);
5517: } else {
5518: next;
5519: }
1.1336 raeburn 5520: } elsif ($curraccess eq 'da') {
1.1335 raeburn 5521: if (grep(/^da$/,@liveroles)) {
5522: push(@possroles,$role);
5523: } else {
5524: next;
5525: }
1.1332 raeburn 5526: } elsif ($curraccess eq 'status') {
5527: if (@okstatus) {
5528: if (!@statuses) {
5529: if (grep(/^default$/,@okstatus)) {
5530: push(@possroles,$role);
5531: }
5532: } else {
5533: foreach my $status (@okstatus) {
5534: if (grep(/^\Q$status\E$/,@statuses)) {
5535: push(@possroles,$role);
5536: last;
5537: }
5538: }
5539: }
5540: }
5541: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5542: if (grep(/^\Q$user\E$/,@personnel)) {
5543: if ($curraccess eq 'exc') {
5544: push(@possroles,$role);
5545: }
5546: } elsif ($curraccess eq 'inc') {
5547: push(@possroles,$role);
5548: }
5549: }
5550: }
5551: }
5552: }
5553: }
5554: }
5555: }
5556: }
1.1333 raeburn 5557: unless (ref($description) eq 'HASH') {
5558: if (ref($roles_by_num) eq 'ARRAY') {
5559: my %desc;
5560: map { $desc{$_} = $_; } (@{$roles_by_num});
5561: $description = \%desc;
5562: } else {
5563: $description = {};
5564: }
5565: }
5566: return (\@possroles,$description);
1.1332 raeburn 5567: }
5568:
1.399 www 5569: # ----------------------------------------------------- Frontpage Announcements
5570: #
5571: #
5572:
5573: sub postannounce {
5574: my ($server,$text)=@_;
1.844 albertel 5575: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5576: unless ($text=~/\w/) { $text=''; }
5577: return &reply('setannounce:'.&escape($text),$server);
5578: }
5579:
5580: sub getannounce {
1.448 albertel 5581:
1.1359 raeburn 5582: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5583: my $announcement='';
1.800 albertel 5584: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5585: close($fh);
1.399 www 5586: if ($announcement=~/\w/) {
5587: return
5588: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5589: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5590: } else {
5591: return '';
5592: }
5593: } else {
5594: return '';
5595: }
1.351 www 5596: }
1.353 www 5597:
5598: # ---------------------------------------------------------- Course ID routines
5599: # Deal with domain's nohist_courseid.db files
5600: #
5601:
5602: sub courseidput {
1.921 raeburn 5603: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5604: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5605: my $outcome;
5606: if ($caller eq 'timeonly') {
5607: my $cids = '';
5608: foreach my $item (keys(%$storehash)) {
5609: $cids.=&escape($item).'&';
5610: }
5611: $cids=~s/\&$//;
5612: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5613: $coursehome);
5614: } else {
5615: my $items = '';
5616: foreach my $item (keys(%$storehash)) {
5617: $items.= &escape($item).'='.
5618: &freeze_escape($$storehash{$item}).'&';
5619: }
5620: $items=~s/\&$//;
5621: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5622: $coursehome);
1.918 raeburn 5623: }
5624: if ($outcome eq 'unknown_cmd') {
5625: my $what;
5626: foreach my $cid (keys(%$storehash)) {
5627: $what .= &escape($cid).'=';
1.921 raeburn 5628: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5629: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5630: }
5631: $what =~ s/\:$/&/;
5632: }
5633: $what =~ s/\&$//;
5634: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5635: } else {
5636: return $outcome;
5637: }
1.353 www 5638: }
5639:
5640: sub courseiddump {
1.921 raeburn 5641: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5642: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5643: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 5644: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 5645: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5646: my $as_hash = 1;
5647: my %returnhash;
5648: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5649: my %libserv = &all_library();
5650: foreach my $tryserver (keys(%libserv)) {
5651: if ( ( $hostidflag == 1
5652: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5653: || (!defined($hostidflag)) ) {
5654:
1.918 raeburn 5655: if (($domfilter eq '') ||
5656: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 5657: my $rep;
5658: if (grep { $_ eq $tryserver } current_machine_ids()) {
5659: $rep = LONCAPA::Lond::dump_course_id_handler(
5660: join(":", (&host_domain($tryserver), $sincefilter,
5661: &escape($descfilter), &escape($instcodefilter),
5662: &escape($ownerfilter), &escape($coursefilter),
5663: &escape($typefilter), &escape($regexp_ok),
5664: $as_hash, &escape($selfenrollonly),
5665: &escape($catfilter), $showhidden, $caller,
5666: &escape($cloner), &escape($cc_clone), $cloneonly,
5667: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 5668: &escape($creationcontext),$domcloner,$hasuniquecode,
5669: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 5670: } else {
5671: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5672: $sincefilter.':'.&escape($descfilter).':'.
5673: &escape($instcodefilter).':'.&escape($ownerfilter).
5674: ':'.&escape($coursefilter).':'.&escape($typefilter).
5675: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5676: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5677: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5678: &escape($cc_clone).':'.$cloneonly.':'.
5679: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 5680: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5681: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 5682: }
5683:
1.918 raeburn 5684: my @pairs=split(/\&/,$rep);
5685: foreach my $item (@pairs) {
5686: my ($key,$value)=split(/\=/,$item,2);
5687: $key = &unescape($key);
5688: next if ($key =~ /^error: 2 /);
5689: my $result = &thaw_unescape($value);
5690: if (ref($result) eq 'HASH') {
5691: $returnhash{$key}=$result;
5692: } else {
1.921 raeburn 5693: my @responses = split(/:/,$value);
5694: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5695: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5696: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5697: }
1.1008 raeburn 5698: }
1.353 www 5699: }
5700: }
5701: }
5702: }
5703: return %returnhash;
5704: }
5705:
1.1055 raeburn 5706: sub courselastaccess {
5707: my ($cdom,$cnum,$hostidref) = @_;
5708: my %returnhash;
5709: if ($cdom && $cnum) {
5710: my $chome = &homeserver($cnum,$cdom);
5711: if ($chome ne 'no_host') {
5712: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5713: &extract_lastaccess(\%returnhash,$rep);
5714: }
5715: } else {
5716: if (!$cdom) { $cdom=''; }
5717: my %libserv = &all_library();
5718: foreach my $tryserver (keys(%libserv)) {
5719: if (ref($hostidref) eq 'ARRAY') {
5720: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5721: }
5722: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5723: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5724: &extract_lastaccess(\%returnhash,$rep);
5725: }
5726: }
5727: }
5728: return %returnhash;
5729: }
5730:
5731: sub extract_lastaccess {
5732: my ($returnhash,$rep) = @_;
5733: if (ref($returnhash) eq 'HASH') {
5734: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5735: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5736: $rep eq '') {
5737: my @pairs=split(/\&/,$rep);
5738: foreach my $item (@pairs) {
5739: my ($key,$value)=split(/\=/,$item,2);
5740: $key = &unescape($key);
5741: next if ($key =~ /^error: 2 /);
5742: $returnhash->{$key} = &thaw_unescape($value);
5743: }
5744: }
5745: }
5746: return;
5747: }
5748:
1.658 raeburn 5749: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5750:
5751: sub dcmailput {
1.685 raeburn 5752: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 5753: my $status = &Apache::lonnet::critical(
1.740 www 5754: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5755: &escape($message),$server);
1.662 raeburn 5756: return $status;
5757: }
5758:
1.658 raeburn 5759: sub dcmaildump {
5760: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5761: my %returnhash=();
1.846 albertel 5762:
5763: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5764: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5765: &escape($enddate).':';
5766: my @esc_senders=map { &escape($_)} @$senders;
5767: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5768: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5769: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5770: if (($key) && ($value)) {
5771: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5772: }
5773: }
5774: }
5775: return %returnhash;
5776: }
1.662 raeburn 5777: # ---------------------------------------------------------- Domain roles
5778:
5779: sub get_domain_roles {
5780: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5781: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5782: $startdate = '.';
5783: }
1.1018 raeburn 5784: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5785: $enddate = '.';
5786: }
1.922 raeburn 5787: my $rolelist;
5788: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 5789: $rolelist = join('&',@{$roles});
1.922 raeburn 5790: }
1.662 raeburn 5791: my %personnel = ();
1.841 albertel 5792:
5793: my %servers = &get_servers($dom,'library');
5794: foreach my $tryserver (keys(%servers)) {
5795: %{$personnel{$tryserver}}=();
5796: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5797: &escape($startdate).':'.
5798: &escape($enddate).':'.
5799: &escape($rolelist), $tryserver))) {
5800: my ($key,$value) = split(/\=/,$line,2);
5801: if (($key) && ($value)) {
5802: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5803: }
5804: }
1.662 raeburn 5805: }
5806: return %personnel;
5807: }
1.658 raeburn 5808:
1.1332 raeburn 5809: sub get_active_domroles {
5810: my ($dom,$roles) = @_;
5811: return () unless (ref($roles) eq 'ARRAY');
5812: my $now = time;
5813: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5814: my %domroles;
5815: foreach my $server (keys(%dompersonnel)) {
5816: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5817: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5818: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5819: }
5820: }
5821: return %domroles;
5822: }
5823:
1.1057 www 5824: # ----------------------------------------------------------- Interval timing
1.149 www 5825:
1.1153 www 5826: {
5827: # Caches needed for speedup of navmaps
5828: # We don't want to cache this for very long at all (5 seconds at most)
5829: #
5830: # The user for whom we cache
5831: my $cachedkey='';
5832: # The cached times for this user
5833: my %cachedtimes=();
5834: # When this was last done
1.1282 raeburn 5835: my $cachedtime='';
1.1153 www 5836:
5837: sub load_all_first_access {
1.1308 raeburn 5838: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 5839: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 raeburn 5840: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5841: (!$ignorecache)) {
1.1154 raeburn 5842: return;
5843: }
5844: $cachedtime=time;
5845: $cachedkey=$uname.':'.$udom;
5846: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5847: }
5848:
1.504 albertel 5849: sub get_first_access {
1.1308 raeburn 5850: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 5851: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5852: if ($argsymb) { $symb=$argsymb; }
5853: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5854: if ($argmap) { $map = $argmap; }
1.926 albertel 5855: if ($type eq 'course') {
5856: $res='course';
5857: } elsif ($type eq 'map') {
1.588 albertel 5858: $res=&symbread($map);
5859: } else {
5860: $res=$symb;
5861: }
1.1308 raeburn 5862: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 5863: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5864: }
5865:
5866: sub set_first_access {
1.1162 raeburn 5867: my ($type,$interval)=@_;
1.790 albertel 5868: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5869: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5870: if ($type eq 'course') {
5871: $res='course';
5872: } elsif ($type eq 'map') {
1.588 albertel 5873: $res=&symbread($map);
5874: } else {
5875: $res=$symb;
5876: }
1.1153 www 5877: $cachedkey='';
1.1162 raeburn 5878: my $firstaccess=&get_first_access($type,$symb,$map);
1.1386 raeburn 5879: if ($firstaccess) {
5880: &logthis("First access time already set ($firstaccess) when attempting ".
1.1393 raeburn 5881: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5882: "in $courseid");
1.1386 raeburn 5883: return 'already_set';
5884: } else {
1.1162 raeburn 5885: my $start = time;
5886: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5887: $udom,$uname);
5888: if ($putres eq 'ok') {
5889: &put('timerinterval',{"$courseid\0$res"=>$interval},
5890: $udom,$uname);
5891: &appenv(
5892: {
5893: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5894: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5895: }
5896: );
1.1365 raeburn 5897: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5898: $cachedtimes{"$courseid\0$res"} = $start;
5899: }
1.1386 raeburn 5900: } elsif ($putres ne 'refused') {
5901: &logthis("Result: $putres when attempting to set first access time ".
5902: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 5903: }
5904: return $putres;
1.505 albertel 5905: }
5906: return 'already_set';
1.504 albertel 5907: }
1.1153 www 5908: }
1.1282 raeburn 5909:
1.110 www 5910: # --------------------------------------------- Set Expire Date for Spreadsheet
5911:
5912: sub expirespread {
5913: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5914: my $cid=$env{'request.course.id'};
1.110 www 5915: if ($cid) {
5916: my $now=time;
5917: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5918: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5919: $env{'course.'.$cid.'.num'}.
1.110 www 5920: ':nohist_expirationdates:'.
5921: &escape($key).'='.$now,
1.620 albertel 5922: $env{'course.'.$cid.'.home'})
1.110 www 5923: }
5924: return 'ok';
1.14 www 5925: }
5926:
1.109 www 5927: # ----------------------------------------------------- Devalidate Spreadsheets
5928:
5929: sub devalidate {
1.325 www 5930: my ($symb,$uname,$udom)=@_;
1.620 albertel 5931: my $cid=$env{'request.course.id'};
1.109 www 5932: if ($cid) {
1.391 matthew 5933: # delete the stored spreadsheets for
5934: # - the student level sheet of this user in course's homespace
5935: # - the assessment level sheet for this resource
5936: # for this user in user's homespace
1.553 albertel 5937: # - current conditional state info
1.325 www 5938: my $key=$uname.':'.$udom.':';
1.109 www 5939: my $status=
1.299 matthew 5940: &del('nohist_calculatedsheets',
1.391 matthew 5941: [$key.'studentcalc:'],
1.620 albertel 5942: $env{'course.'.$cid.'.domain'},
5943: $env{'course.'.$cid.'.num'})
1.133 albertel 5944: .' '.
5945: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5946: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5947: unless ($status eq 'ok ok') {
5948: &logthis('Could not devalidate spreadsheet '.
1.325 www 5949: $uname.' at '.$udom.' for '.
1.109 www 5950: $symb.': '.$status);
1.133 albertel 5951: }
1.553 albertel 5952: &delenv('user.state.'.$cid);
1.109 www 5953: }
5954: }
5955:
1.265 albertel 5956: sub get_scalar {
5957: my ($string,$end) = @_;
5958: my $value;
5959: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5960: $value = $1;
5961: } elsif ($$string =~ s/^([^&]*?)&//) {
5962: $value = $1;
5963: }
5964: return &unescape($value);
5965: }
5966:
5967: sub array2str {
5968: my (@array) = @_;
5969: my $result=&arrayref2str(\@array);
5970: $result=~s/^__ARRAY_REF__//;
5971: $result=~s/__END_ARRAY_REF__$//;
5972: return $result;
5973: }
5974:
1.204 albertel 5975: sub arrayref2str {
5976: my ($arrayref) = @_;
1.265 albertel 5977: my $result='__ARRAY_REF__';
1.204 albertel 5978: foreach my $elem (@$arrayref) {
1.265 albertel 5979: if(ref($elem) eq 'ARRAY') {
5980: $result.=&arrayref2str($elem).'&';
5981: } elsif(ref($elem) eq 'HASH') {
5982: $result.=&hashref2str($elem).'&';
5983: } elsif(ref($elem)) {
5984: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5985: } else {
5986: $result.=&escape($elem).'&';
5987: }
5988: }
5989: $result=~s/\&$//;
1.265 albertel 5990: $result .= '__END_ARRAY_REF__';
1.204 albertel 5991: return $result;
5992: }
5993:
1.168 albertel 5994: sub hash2str {
1.204 albertel 5995: my (%hash) = @_;
5996: my $result=&hashref2str(\%hash);
1.265 albertel 5997: $result=~s/^__HASH_REF__//;
5998: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5999: return $result;
6000: }
6001:
6002: sub hashref2str {
6003: my ($hashref)=@_;
1.265 albertel 6004: my $result='__HASH_REF__';
1.800 albertel 6005: foreach my $key (sort(keys(%$hashref))) {
6006: if (ref($key) eq 'ARRAY') {
6007: $result.=&arrayref2str($key).'=';
6008: } elsif (ref($key) eq 'HASH') {
6009: $result.=&hashref2str($key).'=';
6010: } elsif (ref($key)) {
1.265 albertel 6011: $result.='=';
1.800 albertel 6012: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 6013: } else {
1.1132 raeburn 6014: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 6015: }
6016:
1.800 albertel 6017: if(ref($hashref->{$key}) eq 'ARRAY') {
6018: $result.=&arrayref2str($hashref->{$key}).'&';
6019: } elsif(ref($hashref->{$key}) eq 'HASH') {
6020: $result.=&hashref2str($hashref->{$key}).'&';
6021: } elsif(ref($hashref->{$key})) {
1.265 albertel 6022: $result.='&';
1.800 albertel 6023: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 6024: } else {
1.800 albertel 6025: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 6026: }
6027: }
1.168 albertel 6028: $result=~s/\&$//;
1.265 albertel 6029: $result .= '__END_HASH_REF__';
1.168 albertel 6030: return $result;
6031: }
6032:
6033: sub str2hash {
1.265 albertel 6034: my ($string)=@_;
6035: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
6036: return %$hash;
6037: }
6038:
6039: sub str2hashref {
1.168 albertel 6040: my ($string) = @_;
1.265 albertel 6041:
6042: my %hash;
6043:
6044: if($string !~ /^__HASH_REF__/) {
6045: if (! ($string eq '' || !defined($string))) {
6046: $hash{'error'}='Not hash reference';
6047: }
6048: return (\%hash, $string);
6049: }
6050:
6051: $string =~ s/^__HASH_REF__//;
6052:
6053: while($string !~ /^__END_HASH_REF__/) {
6054: #key
6055: my $key='';
6056: if($string =~ /^__HASH_REF__/) {
6057: ($key, $string)=&str2hashref($string);
6058: if(defined($key->{'error'})) {
6059: $hash{'error'}='Bad data';
6060: return (\%hash, $string);
6061: }
6062: } elsif($string =~ /^__ARRAY_REF__/) {
6063: ($key, $string)=&str2arrayref($string);
6064: if($key->[0] eq 'Array reference error') {
6065: $hash{'error'}='Bad data';
6066: return (\%hash, $string);
6067: }
6068: } else {
6069: $string =~ s/^(.*?)=//;
1.267 albertel 6070: $key=&unescape($1);
1.265 albertel 6071: }
6072: $string =~ s/^=//;
6073:
6074: #value
6075: my $value='';
6076: if($string =~ /^__HASH_REF__/) {
6077: ($value, $string)=&str2hashref($string);
6078: if(defined($value->{'error'})) {
6079: $hash{'error'}='Bad data';
6080: return (\%hash, $string);
6081: }
6082: } elsif($string =~ /^__ARRAY_REF__/) {
6083: ($value, $string)=&str2arrayref($string);
6084: if($value->[0] eq 'Array reference error') {
6085: $hash{'error'}='Bad data';
6086: return (\%hash, $string);
6087: }
6088: } else {
6089: $value=&get_scalar(\$string,'__END_HASH_REF__');
6090: }
6091: $string =~ s/^&//;
6092:
6093: $hash{$key}=$value;
1.204 albertel 6094: }
1.265 albertel 6095:
6096: $string =~ s/^__END_HASH_REF__//;
6097:
6098: return (\%hash, $string);
1.204 albertel 6099: }
6100:
6101: sub str2array {
1.265 albertel 6102: my ($string)=@_;
6103: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
6104: return @$array;
6105: }
6106:
6107: sub str2arrayref {
1.204 albertel 6108: my ($string) = @_;
1.265 albertel 6109: my @array;
6110:
6111: if($string !~ /^__ARRAY_REF__/) {
6112: if (! ($string eq '' || !defined($string))) {
6113: $array[0]='Array reference error';
6114: }
6115: return (\@array, $string);
6116: }
6117:
6118: $string =~ s/^__ARRAY_REF__//;
6119:
6120: while($string !~ /^__END_ARRAY_REF__/) {
6121: my $value='';
6122: if($string =~ /^__HASH_REF__/) {
6123: ($value, $string)=&str2hashref($string);
6124: if(defined($value->{'error'})) {
6125: $array[0] ='Array reference error';
6126: return (\@array, $string);
6127: }
6128: } elsif($string =~ /^__ARRAY_REF__/) {
6129: ($value, $string)=&str2arrayref($string);
6130: if($value->[0] eq 'Array reference error') {
6131: $array[0] ='Array reference error';
6132: return (\@array, $string);
6133: }
6134: } else {
6135: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
6136: }
6137: $string =~ s/^&//;
6138:
6139: push(@array, $value);
1.191 harris41 6140: }
1.265 albertel 6141:
6142: $string =~ s/^__END_ARRAY_REF__//;
6143:
6144: return (\@array, $string);
1.168 albertel 6145: }
6146:
1.167 albertel 6147: # -------------------------------------------------------------------Temp Store
6148:
1.168 albertel 6149: sub tmpreset {
6150: my ($symb,$namespace,$domain,$stuname) = @_;
6151: if (!$symb) {
6152: $symb=&symbread();
1.620 albertel 6153: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6154: }
6155: $symb=escape($symb);
6156:
1.620 albertel 6157: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 6158: $namespace=~s/\//\_/g;
6159: $namespace=~s/\W//g;
6160:
1.620 albertel 6161: if (!$domain) { $domain=$env{'user.domain'}; }
6162: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6163: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6164: $stuname=&get_requestor_ip();
1.591 albertel 6165: }
1.1117 foxr 6166: my $path=LONCAPA::tempdir();
1.168 albertel 6167: my %hash;
6168: if (tie(%hash,'GDBM_File',
6169: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6170: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 6171: foreach my $key (keys(%hash)) {
1.180 albertel 6172: if ($key=~ /:$symb/) {
1.168 albertel 6173: delete($hash{$key});
6174: }
6175: }
6176: }
6177: }
6178:
1.167 albertel 6179: sub tmpstore {
1.168 albertel 6180: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
6181:
6182: if (!$symb) {
6183: $symb=&symbread();
1.620 albertel 6184: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6185: }
6186: $symb=escape($symb);
6187:
6188: if (!$namespace) {
6189: # I don't think we would ever want to store this for a course.
6190: # it seems this will only be used if we don't have a course.
1.620 albertel 6191: #$namespace=$env{'request.course.id'};
1.168 albertel 6192: #if (!$namespace) {
1.620 albertel 6193: $namespace=$env{'request.state'};
1.168 albertel 6194: #}
6195: }
6196: $namespace=~s/\//\_/g;
6197: $namespace=~s/\W//g;
1.620 albertel 6198: if (!$domain) { $domain=$env{'user.domain'}; }
6199: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6200: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6201: $stuname=&get_requestor_ip();
1.591 albertel 6202: }
1.168 albertel 6203: my $now=time;
6204: my %hash;
1.1117 foxr 6205: my $path=LONCAPA::tempdir();
1.168 albertel 6206: if (tie(%hash,'GDBM_File',
6207: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6208: &GDBM_WRCREAT(),0640)) {
1.168 albertel 6209: $hash{"version:$symb"}++;
6210: my $version=$hash{"version:$symb"};
6211: my $allkeys='';
6212: foreach my $key (keys(%$storehash)) {
6213: $allkeys.=$key.':';
1.591 albertel 6214: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 6215: }
6216: $hash{"$version:$symb:timestamp"}=$now;
6217: $allkeys.='timestamp';
6218: $hash{"$version:keys:$symb"}=$allkeys;
6219: if (untie(%hash)) {
6220: return 'ok';
6221: } else {
6222: return "error:$!";
6223: }
6224: } else {
6225: return "error:$!";
6226: }
6227: }
1.167 albertel 6228:
1.168 albertel 6229: # -----------------------------------------------------------------Temp Restore
1.167 albertel 6230:
1.168 albertel 6231: sub tmprestore {
6232: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 6233:
1.168 albertel 6234: if (!$symb) {
6235: $symb=&symbread();
1.620 albertel 6236: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 6237: }
6238: $symb=escape($symb);
6239:
1.620 albertel 6240: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 6241:
1.620 albertel 6242: if (!$domain) { $domain=$env{'user.domain'}; }
6243: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 6244: if ($domain eq 'public' && $stuname eq 'public') {
1.1434 raeburn 6245: $stuname=&get_requestor_ip();
1.591 albertel 6246: }
1.168 albertel 6247: my %returnhash;
6248: $namespace=~s/\//\_/g;
6249: $namespace=~s/\W//g;
6250: my %hash;
1.1117 foxr 6251: my $path=LONCAPA::tempdir();
1.168 albertel 6252: if (tie(%hash,'GDBM_File',
6253: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 6254: &GDBM_READER(),0640)) {
1.168 albertel 6255: my $version=$hash{"version:$symb"};
6256: $returnhash{'version'}=$version;
6257: my $scope;
6258: for ($scope=1;$scope<=$version;$scope++) {
6259: my $vkeys=$hash{"$scope:keys:$symb"};
6260: my @keys=split(/:/,$vkeys);
6261: my $key;
6262: $returnhash{"$scope:keys"}=$vkeys;
6263: foreach $key (@keys) {
1.591 albertel 6264: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
6265: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 6266: }
6267: }
1.168 albertel 6268: if (!(untie(%hash))) {
6269: return "error:$!";
6270: }
6271: } else {
6272: return "error:$!";
6273: }
6274: return %returnhash;
1.167 albertel 6275: }
6276:
1.9 www 6277: # ----------------------------------------------------------------------- Store
6278:
6279: sub store {
1.1269 raeburn 6280: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6281: my $home='';
6282:
1.168 albertel 6283: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6284:
1.213 www 6285: $symb=&symbclean($symb);
1.122 albertel 6286: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6287:
1.620 albertel 6288: if (!$domain) { $domain=$env{'user.domain'}; }
6289: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6290:
6291: &devalidate($symb,$stuname,$domain);
1.109 www 6292:
6293: $symb=escape($symb);
1.187 www 6294: if (!$namespace) {
1.620 albertel 6295: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6296: return '';
6297: }
6298: }
1.620 albertel 6299: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6300:
1.1434 raeburn 6301: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6302: $$storehash{'host'}=$perlvar{'lonHostID'};
6303:
1.12 www 6304: my $namevalue='';
1.800 albertel 6305: foreach my $key (keys(%$storehash)) {
6306: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6307: }
1.12 www 6308: $namevalue=~s/\&$//;
1.187 www 6309: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 6310: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6311: }
6312:
1.47 www 6313: # -------------------------------------------------------------- Critical Store
6314:
6315: sub cstore {
1.1269 raeburn 6316: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6317: my $home='';
6318:
1.168 albertel 6319: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6320:
1.213 www 6321: $symb=&symbclean($symb);
1.122 albertel 6322: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6323:
1.620 albertel 6324: if (!$domain) { $domain=$env{'user.domain'}; }
6325: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6326:
6327: &devalidate($symb,$stuname,$domain);
1.109 www 6328:
6329: $symb=escape($symb);
1.187 www 6330: if (!$namespace) {
1.620 albertel 6331: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6332: return '';
6333: }
6334: }
1.620 albertel 6335: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6336:
1.1434 raeburn 6337: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6338: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6339:
1.47 www 6340: my $namevalue='';
1.800 albertel 6341: foreach my $key (keys(%$storehash)) {
6342: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6343: }
1.47 www 6344: $namevalue=~s/\&$//;
1.187 www 6345: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6346: return critical
1.1269 raeburn 6347: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6348: }
6349:
1.9 www 6350: # --------------------------------------------------------------------- Restore
6351:
6352: sub restore {
1.124 www 6353: my ($symb,$namespace,$domain,$stuname) = @_;
6354: my $home='';
6355:
1.168 albertel 6356: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6357:
1.122 albertel 6358: if (!$symb) {
1.1224 raeburn 6359: return if ($namespace eq 'courserequests');
6360: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6361: } else {
1.1224 raeburn 6362: unless ($namespace eq 'courserequests') {
6363: $symb=&escape(&symbclean($symb));
6364: }
1.122 albertel 6365: }
1.188 www 6366: if (!$namespace) {
1.620 albertel 6367: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6368: return '';
6369: }
6370: }
1.620 albertel 6371: if (!$domain) { $domain=$env{'user.domain'}; }
6372: if (!$stuname) { $stuname=$env{'user.name'}; }
6373: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6374: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6375:
1.12 www 6376: my %returnhash=();
1.800 albertel 6377: foreach my $line (split(/\&/,$answer)) {
6378: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6379: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6380: }
1.75 www 6381: my $version;
6382: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6383: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6384: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6385: }
1.75 www 6386: }
1.13 www 6387: return %returnhash;
1.34 www 6388: }
6389:
6390: # ---------------------------------------------------------- Course Description
1.1118 foxr 6391: #
6392: #
1.34 www 6393:
6394: sub coursedescription {
1.731 albertel 6395: my ($courseid,$args)=@_;
1.34 www 6396: $courseid=~s/^\///;
1.49 www 6397: $courseid=~s/\_/\//g;
1.34 www 6398: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6399: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6400: my $normalid=$cdomain.'_'.$cnum;
6401: # need to always cache even if we get errors otherwise we keep
6402: # trying and trying and trying to get the course description.
6403: my %envhash=();
6404: my %returnhash=();
1.731 albertel 6405:
6406: my $expiretime=600;
6407: if ($env{'request.course.id'} eq $normalid) {
6408: $expiretime=120;
6409: }
6410:
6411: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6412: if (!$args->{'freshen_cache'}
6413: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6414: foreach my $key (keys(%env)) {
6415: next if ($key !~ /^\Q$prefix\E(.*)/);
6416: my ($setting) = $1;
6417: $returnhash{$setting} = $env{$key};
6418: }
6419: return %returnhash;
6420: }
6421:
1.1118 foxr 6422: # get the data again
6423:
1.731 albertel 6424: if (!$args->{'one_time'}) {
6425: $envhash{'course.'.$normalid.'.last_cache'}=time;
6426: }
1.811 albertel 6427:
1.34 www 6428: if ($chome ne 'no_host') {
1.302 albertel 6429: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6430: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6431: my $username = $env{'user.name'}; # Defult username
6432: if(defined $args->{'user'}) {
6433: $username = $args->{'user'};
6434: }
1.129 albertel 6435: $returnhash{'home'}= $chome;
6436: $returnhash{'domain'} = $cdomain;
6437: $returnhash{'num'} = $cnum;
1.741 raeburn 6438: if (!defined($returnhash{'type'})) {
6439: $returnhash{'type'} = 'Course';
6440: }
1.130 albertel 6441: while (my ($name,$value) = each %returnhash) {
1.53 www 6442: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6443: }
1.270 www 6444: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6445: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6446: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6447: $envhash{'course.'.$normalid.'.home'}=$chome;
6448: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6449: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6450: }
6451: }
1.731 albertel 6452: if (!$args->{'one_time'}) {
1.949 raeburn 6453: &appenv(\%envhash);
1.731 albertel 6454: }
1.302 albertel 6455: return %returnhash;
1.461 www 6456: }
6457:
1.1080 raeburn 6458: sub update_released_required {
6459: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6460: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6461: $cid = $env{'request.course.id'};
6462: $cdom = $env{'course.'.$cid.'.domain'};
6463: $cnum = $env{'course.'.$cid.'.num'};
6464: $chome = $env{'course.'.$cid.'.home'};
6465: }
6466: if ($needsrelease) {
6467: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6468: my $needsupdate;
6469: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6470: $needsupdate = 1;
6471: } else {
6472: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6473: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6474: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6475: $needsupdate = 1;
6476: }
6477: }
6478: if ($needsupdate) {
6479: my %needshash = (
6480: 'internal.releaserequired' => $needsrelease,
6481: );
6482: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6483: if ($putresult eq 'ok') {
6484: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6485: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6486: if (ref($crsinfo{$cid}) eq 'HASH') {
6487: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6488: &courseidput($cdom,\%crsinfo,$chome,'notime');
6489: }
6490: }
6491: }
6492: }
6493: return;
6494: }
6495:
1.461 www 6496: # -------------------------------------------------See if a user is privileged
6497:
6498: sub privileged {
1.1219 raeburn 6499: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6500: my $now = time;
1.1219 raeburn 6501: my $roles;
6502: if (ref($possroles) eq 'ARRAY') {
6503: $roles = $possroles;
6504: } else {
6505: $roles = ['dc','su'];
6506: }
6507: if (ref($possdomains) eq 'ARRAY') {
6508: my %privileged = &privileged_by_domain($possdomains,$roles);
6509: foreach my $dom (@{$possdomains}) {
6510: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6511: (ref($privileged{$dom}) eq 'HASH')) {
6512: foreach my $role (@{$roles}) {
6513: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6514: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6515: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6516: return 1 unless (($end && $end < $now) ||
6517: ($start && $start > $now));
6518: }
6519: }
6520: }
6521: }
6522: }
6523: } else {
6524: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6525: my $now = time;
1.1170 droeschl 6526:
1.1275 musolffc 6527: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6528: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 6529: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 6530: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 6531: or ($tstart && $tstart > $now);
1.1170 droeschl 6532: }
1.1219 raeburn 6533: }
6534: }
6535: return 0;
6536: }
1.1170 droeschl 6537:
1.1219 raeburn 6538: sub privileged_by_domain {
6539: my ($domains,$roles) = @_;
6540: my %privileged = ();
6541: my $cachetime = 60*60*24;
6542: my $now = time;
6543: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6544: return %privileged;
6545: }
6546: foreach my $dom (@{$domains}) {
6547: next if (ref($privileged{$dom}) eq 'HASH');
6548: my $needroles;
6549: foreach my $role (@{$roles}) {
6550: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6551: if (defined($cached)) {
6552: if (ref($result) eq 'HASH') {
6553: $privileged{$dom}{$role} = $result;
6554: }
6555: } else {
6556: $needroles = 1;
6557: }
6558: }
6559: if ($needroles) {
6560: my %dompersonnel = &get_domain_roles($dom,$roles);
6561: $privileged{$dom} = {};
6562: foreach my $server (keys(%dompersonnel)) {
6563: if (ref($dompersonnel{$server}) eq 'HASH') {
6564: foreach my $item (keys(%{$dompersonnel{$server}})) {
6565: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6566: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6567: next if ($end && $end < $now);
6568: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6569: $dompersonnel{$server}{$item};
6570: }
6571: }
6572: }
6573: if (ref($privileged{$dom}) eq 'HASH') {
6574: foreach my $role (@{$roles}) {
6575: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6576: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6577: } else {
6578: my %hash = ();
6579: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6580: }
6581: }
6582: }
6583: }
6584: }
6585: return %privileged;
1.9 www 6586: }
1.1 albertel 6587:
1.103 harris41 6588: # -------------------------------------------------------- Get user privileges
1.11 www 6589:
6590: sub rolesinit {
1.1169 droeschl 6591: my ($domain, $username) = @_;
6592: my %userroles = ('user.login.time' => time);
6593: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6594:
6595: # firstaccess and timerinterval are related to timed maps/resources.
6596: # also, blocking can be triggered by an activating timer
6597: # it's saved in the user's %env.
6598: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6599: my %timerinterval = &dump('timerinterval', $domain, $username);
6600: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6601: %timerintchk, %timerintenv);
6602:
1.1162 raeburn 6603: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6604: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6605: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6606: }
1.1169 droeschl 6607:
1.1162 raeburn 6608: foreach my $key (keys(%timerinterval)) {
6609: my ($cid,$rest) = split(/\0/,$key);
6610: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6611: }
1.1169 droeschl 6612:
1.11 www 6613: my %allroles=();
1.1162 raeburn 6614: my %allgroups=();
1.11 www 6615:
1.1274 raeburn 6616: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6617: my $role = $rolesdump{$area};
6618: $area =~ s/\_\w\w$//;
6619:
6620: my ($trole, $tend, $tstart, $group_privs);
6621:
6622: if ($role =~ /^cr/) {
6623: # Custom role, defined by a user
6624: # e.g., user.role.cr/msu/smith/mynewrole
6625: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6626: $trole = $1;
6627: ($tend, $tstart) = split('_', $2);
6628: } else {
6629: $trole = $role;
6630: }
6631: } elsif ($role =~ m|^gr/|) {
6632: # Role of member in a group, defined within a course/community
6633: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6634: ($trole, $tend, $tstart) = split(/_/, $role);
6635: next if $tstart eq '-1';
6636: ($trole, $group_privs) = split(/\//, $trole);
6637: $group_privs = &unescape($group_privs);
6638: } else {
6639: # Just a normal role, defined in roles.tab
6640: ($trole, $tend, $tstart) = split(/_/,$role);
6641: }
6642:
6643: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6644: $username);
6645: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6646:
6647: # role expired or not available yet?
6648: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6649: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6650:
6651: next if $area eq '' or $trole eq '';
6652:
6653: my $spec = "$trole.$area";
6654: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6655:
6656: if ($trole =~ /^cr\//) {
6657: # Custom role, defined by a user
6658: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6659: } elsif ($trole eq 'gr') {
6660: # Role of a member in a group, defined within a course/community
6661: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6662: next;
6663: } else {
6664: # Normal role, defined in roles.tab
6665: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6666: }
6667:
6668: my $cid = $tdomain.'_'.$trest;
6669: unless ($firstaccchk{$cid}) {
6670: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6671: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6672: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6673: $coursetimerstarts{$cid}{$item};
6674: }
6675: }
6676: $firstaccchk{$cid} = 1;
6677: }
6678: unless ($timerintchk{$cid}) {
6679: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6680: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6681: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6682: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6683: }
1.12 www 6684: }
1.1169 droeschl 6685: $timerintchk{$cid} = 1;
1.191 harris41 6686: }
1.11 www 6687: }
1.1169 droeschl 6688:
1.1341 raeburn 6689: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6690: \%allroles, \%allgroups);
1.1169 droeschl 6691: $env{'user.adv'} = $userroles{'user.adv'};
1.1341 raeburn 6692: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6693:
1.1162 raeburn 6694: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6695: }
6696:
1.567 raeburn 6697: sub set_arearole {
1.1215 raeburn 6698: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6699: unless ($nolog) {
1.567 raeburn 6700: # log the associated role with the area
1.1215 raeburn 6701: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6702: }
1.743 albertel 6703: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6704: }
6705:
6706: sub custom_roleprivs {
6707: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6708: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 6709: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6710: if (&hostname($homsvr) ne '') {
1.567 raeburn 6711: my ($rdummy,$roledef)=
6712: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6713: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6714: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6715: if (defined($syspriv)) {
1.1043 raeburn 6716: if ($trest =~ /^$match_community$/) {
6717: $syspriv =~ s/bre\&S//;
6718: }
1.567 raeburn 6719: $$allroles{'cm./'}.=':'.$syspriv;
6720: $$allroles{$spec.'./'}.=':'.$syspriv;
6721: }
6722: if ($tdomain ne '') {
6723: if (defined($dompriv)) {
6724: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6725: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6726: }
6727: if (($trest ne '') && (defined($coursepriv))) {
1.1332 raeburn 6728: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6729: my $rolename = $1;
6730: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6731: }
1.567 raeburn 6732: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6733: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6734: }
6735: }
6736: }
6737: }
6738: }
6739:
1.1332 raeburn 6740: sub course_adhocrole_privs {
6741: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6742: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6743: if ($overrides{"internal.adhocpriv.$rolename"}) {
6744: my (%currprivs,%storeprivs);
6745: foreach my $item (split(/:/,$coursepriv)) {
6746: my ($priv,$restrict) = split(/\&/,$item);
6747: $currprivs{$priv} = $restrict;
6748: }
6749: my (%possadd,%possremove,%full);
6750: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6751: my ($priv,$restrict)=split(/\&/,$item);
6752: $full{$priv} = $restrict;
6753: }
6754: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6755: next if ($item eq '');
6756: my ($rule,$rest) = split(/=/,$item);
6757: next unless (($rule eq 'off') || ($rule eq 'on'));
6758: foreach my $priv (split(/:/,$rest)) {
6759: if ($priv ne '') {
6760: if ($rule eq 'off') {
6761: $possremove{$priv} = 1;
6762: } else {
6763: $possadd{$priv} = 1;
6764: }
6765: }
6766: }
6767: }
6768: foreach my $priv (sort(keys(%full))) {
6769: if (exists($currprivs{$priv})) {
6770: unless (exists($possremove{$priv})) {
6771: $storeprivs{$priv} = $currprivs{$priv};
6772: }
6773: } elsif (exists($possadd{$priv})) {
6774: $storeprivs{$priv} = $full{$priv};
6775: }
6776: }
6777: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6778: }
6779: return $coursepriv;
6780: }
6781:
1.678 raeburn 6782: sub group_roleprivs {
6783: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6784: my $access = 1;
6785: my $now = time;
6786: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6787: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6788: if ($access) {
1.811 albertel 6789: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6790: $$allgroups{$course}{$group} .=':'.$group_privs;
6791: }
6792: }
1.567 raeburn 6793:
6794: sub standard_roleprivs {
6795: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6796: if (defined($pr{$trole.':s'})) {
6797: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6798: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6799: }
6800: if ($tdomain ne '') {
6801: if (defined($pr{$trole.':d'})) {
6802: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6803: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6804: }
6805: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6806: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6807: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6808: }
6809: }
6810: }
6811:
6812: sub set_userprivs {
1.1064 raeburn 6813: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6814: my $author=0;
6815: my $adv=0;
1.1341 raeburn 6816: my $rar=0;
1.678 raeburn 6817: my %grouproles = ();
6818: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6819: my @groupkeys;
1.1000 raeburn 6820: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6821: push(@groupkeys,$role);
6822: }
6823: if (ref($groups_roles) eq 'HASH') {
6824: foreach my $key (keys(%{$groups_roles})) {
6825: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6826: push(@groupkeys,$key);
6827: }
6828: }
6829: }
6830: if (@groupkeys > 0) {
6831: foreach my $role (@groupkeys) {
6832: my ($trole,$area,$sec,$extendedarea);
6833: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6834: $trole = $1;
6835: $area = $2;
6836: $sec = $3;
6837: $extendedarea = $area.$sec;
6838: if (exists($$allgroups{$area})) {
6839: foreach my $group (keys(%{$$allgroups{$area}})) {
6840: my $spec = $trole.'.'.$extendedarea;
6841: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6842: $$allgroups{$area}{$group};
1.1064 raeburn 6843: }
1.678 raeburn 6844: }
6845: }
6846: }
6847: }
6848: }
1.800 albertel 6849: foreach my $group (keys(%grouproles)) {
6850: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6851: }
1.800 albertel 6852: foreach my $role (keys(%{$allroles})) {
6853: my %thesepriv;
1.941 raeburn 6854: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6855: foreach my $item (split(/:/,$$allroles{$role})) {
6856: if ($item ne '') {
6857: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 6858: if ($restrictions eq '') {
6859: $thesepriv{$privilege}='F';
6860: } elsif ($thesepriv{$privilege} ne 'F') {
6861: $thesepriv{$privilege}.=$restrictions;
6862: }
6863: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341 raeburn 6864: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 6865: }
6866: }
6867: my $thesestr='';
1.1104 raeburn 6868: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 6869: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6870: }
6871: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 6872: }
1.1341 raeburn 6873: return ($author,$adv,$rar);
1.567 raeburn 6874: }
6875:
1.994 raeburn 6876: sub role_status {
1.1104 raeburn 6877: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 6878: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 6879: my ($one,$two) = split(m{\./},$rolekey,2);
6880: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 6881: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 6882: $$where = '/'.$two;
1.994 raeburn 6883: $$trolecode=$$role.'.'.$$where;
6884: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6885: $$tstatus='is';
1.1104 raeburn 6886: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6887: $$tstatus='future';
1.1034 raeburn 6888: if ($$tstart<$now) {
6889: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6890: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6891: my (%allroles,%allgroups,$group_privs,
6892: %groups_roles,@rolecodes);
1.1002 raeburn 6893: my %userroles = (
6894: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6895: );
1.1064 raeburn 6896: @rolecodes = ('cm');
1.1002 raeburn 6897: my $spec=$$role.'.'.$$where;
6898: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6899: if ($$role =~ /^cr\//) {
6900: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6901: push(@rolecodes,'cr');
1.1002 raeburn 6902: } elsif ($$role eq 'gr') {
1.1064 raeburn 6903: push(@rolecodes,$$role);
1.1002 raeburn 6904: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6905: $env{'user.name'});
1.1064 raeburn 6906: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6907: (undef,my $group_privs) = split(/\//,$trole);
6908: $group_privs = &unescape($group_privs);
6909: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6910: 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 6911: &get_groups_roles($tdomain,$trest,
6912: \%course_roles,\@rolecodes,
6913: \%groups_roles);
1.1002 raeburn 6914: } else {
1.1064 raeburn 6915: push(@rolecodes,$$role);
1.1002 raeburn 6916: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6917: }
1.1341 raeburn 6918: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6919: \%groups_roles);
1.1064 raeburn 6920: &appenv(\%userroles,\@rolecodes);
1.1342 raeburn 6921: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 6922: }
6923: }
1.1034 raeburn 6924: $$tstatus = 'is';
1.1002 raeburn 6925: }
1.994 raeburn 6926: }
6927: if ($$tend) {
1.1104 raeburn 6928: if ($$tend<$update) {
1.994 raeburn 6929: $$tstatus='expired';
6930: } elsif ($$tend<$now) {
6931: $$tstatus='will_not';
6932: }
6933: }
6934: }
6935: }
6936: }
6937:
1.1104 raeburn 6938: sub get_groups_roles {
6939: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6940: return unless((ref($cdom_courseroles) eq 'HASH') &&
6941: (ref($rolecodes) eq 'ARRAY') &&
6942: (ref($groups_roles) eq 'HASH'));
6943: if (keys(%{$cdom_courseroles}) > 0) {
6944: my ($cnum) = ($rest =~ /^($match_courseid)/);
6945: if ($cdom ne '' && $cnum ne '') {
6946: foreach my $key (keys(%{$cdom_courseroles})) {
6947: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6948: my $crsrole = $1;
6949: my $crssec = $2;
6950: if ($crsrole =~ /^cr/) {
6951: unless (grep(/^cr$/,@{$rolecodes})) {
6952: push(@{$rolecodes},'cr');
6953: }
6954: } else {
6955: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6956: push(@{$rolecodes},$crsrole);
6957: }
6958: }
6959: my $rolekey = "$crsrole./$cdom/$cnum";
6960: if ($crssec ne '') {
6961: $rolekey .= "/$crssec";
6962: }
6963: $rolekey .= './';
6964: $groups_roles->{$rolekey} = $rolecodes;
6965: }
6966: }
6967: }
6968: }
6969: return;
6970: }
6971:
6972: sub delete_env_groupprivs {
6973: my ($where,$courseroles,$possroles) = @_;
6974: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6975: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6976: unless (ref($courseroles->{$udom}) eq 'HASH') {
6977: %{$courseroles->{$udom}} =
6978: &get_my_roles('','','userroles',['active'],
6979: $possroles,[$udom],1);
6980: }
6981: if (ref($courseroles->{$udom}) eq 'HASH') {
6982: foreach my $item (keys(%{$courseroles->{$udom}})) {
6983: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6984: my $area = '/'.$cdom.'/'.$cnum;
6985: my $privkey = "user.priv.$crsrole.$area";
6986: if ($crssec ne '') {
6987: $privkey .= '/'.$crssec;
6988: }
6989: $privkey .= ".$area/$group";
6990: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6991: }
6992: }
6993: return;
6994: }
6995:
1.994 raeburn 6996: sub check_adhoc_privs {
1.1329 raeburn 6997: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6998: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329 raeburn 6999: if ($sec) {
7000: $cckey .= '/'.$sec;
7001: }
1.1185 raeburn 7002: my $setprivs;
1.994 raeburn 7003: if ($env{$cckey}) {
7004: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 7005: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 7006: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329 raeburn 7007: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 7008: $setprivs = 1;
1.994 raeburn 7009: }
7010: } else {
1.1330 raeburn 7011: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 7012: $setprivs = 1;
1.994 raeburn 7013: }
1.1185 raeburn 7014: return $setprivs;
1.994 raeburn 7015: }
7016:
7017: sub set_adhoc_privileges {
1.1326 raeburn 7018: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329 raeburn 7019: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 7020: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329 raeburn 7021: if ($sec ne '') {
7022: $area .= '/'.$sec;
7023: }
1.994 raeburn 7024: my $spec = $role.'.'.$area;
7025: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 7026: $env{'user.name'},1);
1.1326 raeburn 7027: my %rolehash = ();
1.1332 raeburn 7028: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
7029: my $rolename = $1;
1.1326 raeburn 7030: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332 raeburn 7031: my %domdef = &get_domain_defaults($dcdom);
7032: if (ref($domdef{'adhocroles'}) eq 'HASH') {
7033: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
7034: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
7035: }
7036: }
1.1326 raeburn 7037: } else {
7038: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
7039: }
1.1341 raeburn 7040: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 7041: &appenv(\%userroles,[$role,'cm']);
1.1342 raeburn 7042: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402 raeburn 7043: unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
7044: ($caller eq 'tiny')) {
1.1088 raeburn 7045: &appenv( {'request.role' => $spec,
7046: 'request.role.domain' => $dcdom,
1.1332 raeburn 7047: 'request.course.sec' => $sec,
1.1088 raeburn 7048: }
7049: );
7050: my $tadv=0;
7051: if (&allowed('adv') eq 'F') { $tadv=1; }
7052: &appenv({'request.role.adv' => $tadv});
7053: }
1.994 raeburn 7054: }
7055:
1.12 www 7056: # --------------------------------------------------------------- get interface
7057:
7058: sub get {
1.131 albertel 7059: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7060: my $items='';
1.800 albertel 7061: foreach my $item (@$storearr) {
7062: $items.=&escape($item).'&';
1.191 harris41 7063: }
1.12 www 7064: $items=~s/\&$//;
1.620 albertel 7065: if (!$udomain) { $udomain=$env{'user.domain'}; }
7066: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 7067: my $uhome=&homeserver($uname,$udomain);
7068:
1.133 albertel 7069: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7070: my @pairs=split(/\&/,$rep);
1.273 albertel 7071: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
7072: return @pairs;
7073: }
1.15 www 7074: my %returnhash=();
1.42 www 7075: my $i=0;
1.800 albertel 7076: foreach my $item (@$storearr) {
7077: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7078: $i++;
1.191 harris41 7079: }
1.15 www 7080: return %returnhash;
1.27 www 7081: }
7082:
7083: # --------------------------------------------------------------- del interface
7084:
7085: sub del {
1.133 albertel 7086: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 7087: my $items='';
1.800 albertel 7088: foreach my $item (@$storearr) {
7089: $items.=&escape($item).'&';
1.191 harris41 7090: }
1.984 neumanie 7091:
1.27 www 7092: $items=~s/\&$//;
1.620 albertel 7093: if (!$udomain) { $udomain=$env{'user.domain'}; }
7094: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7095: my $uhome=&homeserver($uname,$udomain);
7096: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 7097: }
7098:
7099: # -------------------------------------------------------------- dump interface
7100:
1.1180 droeschl 7101: sub unserialize {
7102: my ($rep, $escapedkeys) = @_;
7103:
7104: return {} if $rep =~ /^error/;
7105:
7106: my %returnhash=();
1.1252 raeburn 7107: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 7108: my ($key, $value) = split(/=/, $item, 2);
7109: $key = unescape($key) unless $escapedkeys;
7110: next if $key =~ /^error: 2 /;
1.1252 raeburn 7111: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 7112: }
7113: #return %returnhash;
7114: return \%returnhash;
7115: }
7116:
7117: # see Lond::dump_with_regexp
7118: # if $escapedkeys hash keys won't get unescaped.
1.15 www 7119: sub dump {
1.1180 droeschl 7120: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 7121: if (!$udomain) { $udomain=$env{'user.domain'}; }
7122: if (!$uname) { $uname=$env{'user.name'}; }
7123: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 7124:
1.1266 raeburn 7125: if ($regexp) {
7126: $regexp=&escape($regexp);
7127: } else {
7128: $regexp='.';
7129: }
1.1180 droeschl 7130: if (grep { $_ eq $uhome } current_machine_ids()) {
7131: # user is hosted on this machine
1.1266 raeburn 7132: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 7133: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 7134: return %{unserialize($reply, $escapedkeys)};
7135: }
1.1166 raeburn 7136: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 7137: my @pairs=split(/\&/,$rep);
7138: my %returnhash=();
1.1098 foxr 7139: if (!($rep =~ /^error/ )) {
7140: foreach my $item (@pairs) {
7141: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 7142: $key = unescape($key) unless $escapedkeys;
7143: #$key = &unescape($key);
1.1098 foxr 7144: next if ($key =~ /^error: 2 /);
7145: $returnhash{$key}=&thaw_unescape($value);
7146: }
1.755 albertel 7147: }
7148: return %returnhash;
1.407 www 7149: }
7150:
1.1098 foxr 7151:
1.717 albertel 7152: # --------------------------------------------------------- dumpstore interface
7153:
7154: sub dumpstore {
7155: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 7156: # same as dump but keys must be escaped. They may contain colon separated
7157: # lists of values that may themself contain colons (e.g. symbs).
7158: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 7159: }
7160:
1.407 www 7161: # -------------------------------------------------------------- keys interface
7162:
7163: sub getkeys {
7164: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 7165: if (!$udomain) { $udomain=$env{'user.domain'}; }
7166: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 7167: my $uhome=&homeserver($uname,$udomain);
7168: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
7169: my @keyarray=();
1.800 albertel 7170: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 7171: next if ($key =~ /^error: 2 /);
1.800 albertel 7172: push(@keyarray,&unescape($key));
1.407 www 7173: }
7174: return @keyarray;
1.318 matthew 7175: }
7176:
1.319 matthew 7177: # --------------------------------------------------------------- currentdump
7178: sub currentdump {
1.328 matthew 7179: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 7180: $courseid = $env{'request.course.id'} if (! defined($courseid));
7181: $sdom = $env{'user.domain'} if (! defined($sdom));
7182: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 7183: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 7184: my $rep;
7185:
7186: if (grep { $_ eq $uhome } current_machine_ids()) {
7187: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
7188: $courseid)));
7189: } else {
7190: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
7191: }
7192:
1.318 matthew 7193: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 7194: #
1.318 matthew 7195: my %returnhash=();
1.319 matthew 7196: #
1.1343 raeburn 7197: if ($rep eq 'unknown_cmd') {
1.319 matthew 7198: # an old lond will not know currentdump
7199: # Do a dump and make it look like a currentdump
1.822 albertel 7200: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 7201: return if ($tmp[0] =~ /^(error:|no_such_host)/);
7202: my %hash = @tmp;
7203: @tmp=();
1.424 matthew 7204: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 7205: } else {
7206: my @pairs=split(/\&/,$rep);
1.800 albertel 7207: foreach my $pair (@pairs) {
7208: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 7209: my ($symb,$param) = split(/:/,$key);
7210: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 7211: &thaw_unescape($value);
1.319 matthew 7212: }
1.191 harris41 7213: }
1.12 www 7214: return %returnhash;
1.424 matthew 7215: }
7216:
7217: sub convert_dump_to_currentdump{
7218: my %hash = %{shift()};
7219: my %returnhash;
7220: # Code ripped from lond, essentially. The only difference
7221: # here is the unescaping done by lonnet::dump(). Conceivably
7222: # we might run in to problems with parameter names =~ /^v\./
7223: while (my ($key,$value) = each(%hash)) {
7224: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 7225: $symb = &unescape($symb);
7226: $param = &unescape($param);
1.424 matthew 7227: next if ($v eq 'version' || $symb eq 'keys');
7228: next if (exists($returnhash{$symb}) &&
7229: exists($returnhash{$symb}->{$param}) &&
7230: $returnhash{$symb}->{'v.'.$param} > $v);
7231: $returnhash{$symb}->{$param}=$value;
7232: $returnhash{$symb}->{'v.'.$param}=$v;
7233: }
7234: #
7235: # Remove all of the keys in the hashes which keep track of
7236: # the version of the parameter.
7237: while (my ($symb,$param_hash) = each(%returnhash)) {
7238: # use a foreach because we are going to delete from the hash.
7239: foreach my $key (keys(%$param_hash)) {
7240: delete($param_hash->{$key}) if ($key =~ /^v\./);
7241: }
7242: }
7243: return \%returnhash;
1.12 www 7244: }
7245:
1.627 albertel 7246: # ------------------------------------------------------ critical inc interface
7247:
7248: sub cinc {
7249: return &inc(@_,'critical');
7250: }
7251:
1.449 matthew 7252: # --------------------------------------------------------------- inc interface
7253:
7254: sub inc {
1.627 albertel 7255: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 7256: if (!$udomain) { $udomain=$env{'user.domain'}; }
7257: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 7258: my $uhome=&homeserver($uname,$udomain);
7259: my $items='';
7260: if (! ref($store)) {
7261: # got a single value, so use that instead
7262: $items = &escape($store).'=&';
7263: } elsif (ref($store) eq 'SCALAR') {
7264: $items = &escape($$store).'=&';
7265: } elsif (ref($store) eq 'ARRAY') {
7266: $items = join('=&',map {&escape($_);} @{$store});
7267: } elsif (ref($store) eq 'HASH') {
7268: while (my($key,$value) = each(%{$store})) {
7269: $items.= &escape($key).'='.&escape($value).'&';
7270: }
7271: }
7272: $items=~s/\&$//;
1.627 albertel 7273: if ($critical) {
7274: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
7275: } else {
7276: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
7277: }
1.449 matthew 7278: }
7279:
1.12 www 7280: # --------------------------------------------------------------- put interface
7281:
7282: sub put {
1.134 albertel 7283: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7284: if (!$udomain) { $udomain=$env{'user.domain'}; }
7285: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7286: my $uhome=&homeserver($uname,$udomain);
1.12 www 7287: my $items='';
1.800 albertel 7288: foreach my $item (keys(%$storehash)) {
7289: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7290: }
1.12 www 7291: $items=~s/\&$//;
1.134 albertel 7292: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 7293: }
7294:
1.631 albertel 7295: # ------------------------------------------------------------ newput interface
7296:
7297: sub newput {
7298: my ($namespace,$storehash,$udomain,$uname)=@_;
7299: if (!$udomain) { $udomain=$env{'user.domain'}; }
7300: if (!$uname) { $uname=$env{'user.name'}; }
7301: my $uhome=&homeserver($uname,$udomain);
7302: my $items='';
7303: foreach my $key (keys(%$storehash)) {
7304: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7305: }
7306: $items=~s/\&$//;
7307: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7308: }
7309:
7310: # --------------------------------------------------------- putstore interface
7311:
1.524 raeburn 7312: sub putstore {
1.1269 raeburn 7313: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7314: if (!$udomain) { $udomain=$env{'user.domain'}; }
7315: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7316: my $uhome=&homeserver($uname,$udomain);
7317: my $items='';
1.715 albertel 7318: foreach my $key (keys(%$storehash)) {
7319: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7320: }
1.715 albertel 7321: $items=~s/\&$//;
1.716 albertel 7322: my $esc_symb=&escape($symb);
7323: my $esc_v=&escape($version);
1.715 albertel 7324: my $reply =
1.716 albertel 7325: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7326: $uhome);
1.1269 raeburn 7327: if (($tolog) && ($reply eq 'ok')) {
7328: my $namevalue='';
7329: foreach my $key (keys(%{$storehash})) {
7330: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7331: }
1.1434 raeburn 7332: my $ip = &get_requestor_ip();
7333: $namevalue .= 'ip='.&escape($ip).
1.1269 raeburn 7334: '&host='.&escape($perlvar{'lonHostID'}).
7335: '&version='.$esc_v.
7336: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7337: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7338: }
1.715 albertel 7339: if ($reply eq 'unknown_cmd') {
1.716 albertel 7340: # gfall back to way things use to be done
1.715 albertel 7341: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7342: $uname);
1.524 raeburn 7343: }
1.715 albertel 7344: return $reply;
7345: }
7346:
7347: sub old_putstore {
1.716 albertel 7348: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7349: if (!$udomain) { $udomain=$env{'user.domain'}; }
7350: if (!$uname) { $uname=$env{'user.name'}; }
7351: my $uhome=&homeserver($uname,$udomain);
7352: my %newstorehash;
1.800 albertel 7353: foreach my $item (keys(%$storehash)) {
7354: my $key = $version.':'.&escape($symb).':'.$item;
7355: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7356: }
7357: my $items='';
7358: my %allitems = ();
1.800 albertel 7359: foreach my $item (keys(%newstorehash)) {
7360: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7361: my $key = $1.':keys:'.$2;
7362: $allitems{$key} .= $3.':';
7363: }
1.800 albertel 7364: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7365: }
1.800 albertel 7366: foreach my $item (keys(%allitems)) {
7367: $allitems{$item} =~ s/\:$//;
7368: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7369: }
7370: $items=~s/\&$//;
7371: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7372: }
7373:
1.47 www 7374: # ------------------------------------------------------ critical put interface
7375:
7376: sub cput {
1.134 albertel 7377: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7378: if (!$udomain) { $udomain=$env{'user.domain'}; }
7379: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7380: my $uhome=&homeserver($uname,$udomain);
1.47 www 7381: my $items='';
1.800 albertel 7382: foreach my $item (keys(%$storehash)) {
7383: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7384: }
1.47 www 7385: $items=~s/\&$//;
1.134 albertel 7386: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7387: }
7388:
7389: # -------------------------------------------------------------- eget interface
7390:
7391: sub eget {
1.133 albertel 7392: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7393: my $items='';
1.800 albertel 7394: foreach my $item (@$storearr) {
7395: $items.=&escape($item).'&';
1.191 harris41 7396: }
1.12 www 7397: $items=~s/\&$//;
1.620 albertel 7398: if (!$udomain) { $udomain=$env{'user.domain'}; }
7399: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7400: my $uhome=&homeserver($uname,$udomain);
7401: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7402: my @pairs=split(/\&/,$rep);
7403: my %returnhash=();
1.42 www 7404: my $i=0;
1.800 albertel 7405: foreach my $item (@$storearr) {
7406: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7407: $i++;
1.191 harris41 7408: }
1.12 www 7409: return %returnhash;
7410: }
7411:
1.667 albertel 7412: # ------------------------------------------------------------ tmpput interface
7413: sub tmpput {
1.802 raeburn 7414: my ($storehash,$server,$context)=@_;
1.667 albertel 7415: my $items='';
1.800 albertel 7416: foreach my $item (keys(%$storehash)) {
7417: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7418: }
7419: $items=~s/\&$//;
1.802 raeburn 7420: if (defined($context)) {
7421: $items .= ':'.&escape($context);
7422: }
1.667 albertel 7423: return &reply("tmpput:$items",$server);
7424: }
7425:
7426: # ------------------------------------------------------------ tmpget interface
7427: sub tmpget {
1.688 albertel 7428: my ($token,$server)=@_;
7429: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7430: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7431: my %returnhash;
1.1328 raeburn 7432: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7433: return %returnhash;
7434: }
1.667 albertel 7435: foreach my $item (split(/\&/,$rep)) {
7436: my ($key,$value)=split(/=/,$item);
7437: $returnhash{&unescape($key)}=&thaw_unescape($value);
7438: }
7439: return %returnhash;
7440: }
7441:
1.1113 raeburn 7442: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7443: sub tmpdel {
7444: my ($token,$server)=@_;
7445: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7446: return &reply("tmpdel:$token",$server);
7447: }
7448:
1.1198 raeburn 7449: # ------------------------------------------------------------ get_timebased_id
7450:
7451: sub get_timebased_id {
7452: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7453: $maxtries) = @_;
7454: my ($newid,$error,$dellock);
7455: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7456: return ('','ok','invalid call to get suffix');
7457: }
7458:
7459: # set defaults for any optional args for which values were not supplied
7460: if ($who eq '') {
7461: $who = $env{'user.name'}.':'.$env{'user.domain'};
7462: }
7463: if (!$locktries) {
7464: $locktries = 3;
7465: }
7466: if (!$maxtries) {
7467: $maxtries = 10;
7468: }
7469:
7470: if (($cdom eq '') || ($cnum eq '')) {
7471: if ($env{'request.course.id'}) {
7472: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7473: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7474: }
7475: if (($cdom eq '') || ($cnum eq '')) {
7476: return ('','ok','call to get suffix not in course context');
7477: }
7478: }
7479:
7480: # construct locking item
7481: my $lockhash = {
7482: $prefix."\0".'locked_'.$keyid => $who,
7483: };
7484: my $tries = 0;
7485:
7486: # attempt to get lock on nohist_$namespace file
7487: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7488: while (($gotlock ne 'ok') && $tries <$locktries) {
7489: $tries ++;
7490: sleep 1;
7491: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7492: }
7493:
7494: # attempt to get unique identifier, based on current timestamp
7495: if ($gotlock eq 'ok') {
7496: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7497: my $id = time;
7498: $newid = $id;
1.1268 raeburn 7499: if ($idtype eq 'addcode') {
7500: $newid .= &sixnum_code();
7501: }
1.1198 raeburn 7502: my $idtries = 0;
7503: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7504: if ($idtype eq 'concat') {
7505: $newid = $id.$idtries;
1.1268 raeburn 7506: } elsif ($idtype eq 'addcode') {
7507: $newid = $newid.&sixnum_code();
1.1198 raeburn 7508: } else {
7509: $newid ++;
7510: }
7511: $idtries ++;
7512: }
7513: if (!exists($inuse{$prefix."\0".$newid})) {
7514: my %new_item = (
7515: $prefix."\0".$newid => $who,
7516: );
7517: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7518: $cdom,$cnum);
7519: if ($putresult ne 'ok') {
7520: undef($newid);
7521: $error = 'error saving new item: '.$putresult;
7522: }
7523: } else {
1.1268 raeburn 7524: undef($newid);
1.1198 raeburn 7525: $error = ('error: no unique suffix available for the new item ');
7526: }
7527: # remove lock
7528: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7529: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7530: } else {
7531: $error = "error: could not obtain lockfile\n";
7532: $dellock = 'ok';
1.1276 raeburn 7533: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7534: $dellock = 'nolock';
7535: }
1.1198 raeburn 7536: }
7537: return ($newid,$dellock,$error);
7538: }
7539:
1.1268 raeburn 7540: sub sixnum_code {
7541: my $code;
7542: for (0..6) {
7543: $code .= int( rand(9) );
7544: }
7545: return $code;
7546: }
7547:
1.765 albertel 7548: # -------------------------------------------------- portfolio access checking
7549:
7550: sub portfolio_access {
1.1270 raeburn 7551: my ($requrl,$clientip) = @_;
1.765 albertel 7552: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 7553: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7554: if ($result) {
7555: my %setters;
7556: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7557: my ($startblock,$endblock) =
7558: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
7559: if ($startblock && $endblock) {
7560: return 'B';
7561: }
7562: } else {
7563: my ($startblock,$endblock) =
7564: &Apache::loncommon::blockcheck(\%setters,'port');
7565: if ($startblock && $endblock) {
7566: return 'B';
7567: }
7568: }
7569: }
1.765 albertel 7570: if ($result eq 'ok') {
1.766 albertel 7571: return 'F';
1.765 albertel 7572: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7573: return 'A';
1.765 albertel 7574: }
1.766 albertel 7575: return '';
1.765 albertel 7576: }
7577:
7578: sub get_portfolio_access {
1.1270 raeburn 7579: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7580:
7581: if (!ref($access_hash)) {
7582: my $current_perms = &get_portfile_permissions($udom,$unum);
7583: my %access_controls = &get_access_controls($current_perms,$group,
7584: $file_name);
7585: $access_hash = $access_controls{$file_name};
7586: }
7587:
1.1270 raeburn 7588: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7589: my $now = time;
7590: if (ref($access_hash) eq 'HASH') {
7591: foreach my $key (keys(%{$access_hash})) {
7592: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7593: if ($start > $now) {
7594: next;
7595: }
7596: if ($end && $end<$now) {
7597: next;
7598: }
7599: if ($scope eq 'public') {
7600: $public = $key;
7601: last;
7602: } elsif ($scope eq 'guest') {
7603: $guest = $key;
7604: } elsif ($scope eq 'domains') {
7605: push(@domains,$key);
7606: } elsif ($scope eq 'users') {
7607: push(@users,$key);
7608: } elsif ($scope eq 'course') {
7609: push(@courses,$key);
7610: } elsif ($scope eq 'group') {
7611: push(@groups,$key);
1.1270 raeburn 7612: } elsif ($scope eq 'ip') {
7613: push(@ips,$key);
1.765 albertel 7614: }
7615: }
7616: if ($public) {
7617: return 'ok';
1.1270 raeburn 7618: } elsif (@ips > 0) {
7619: my $allowed;
7620: foreach my $ipkey (@ips) {
7621: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7622: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7623: $allowed = 1;
7624: last;
7625: }
7626: }
7627: }
7628: if ($allowed) {
7629: return 'ok';
7630: }
1.765 albertel 7631: }
7632: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7633: if ($guest) {
7634: return $guest;
7635: }
7636: } else {
7637: if (@domains > 0) {
7638: foreach my $domkey (@domains) {
7639: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7640: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7641: return 'ok';
7642: }
7643: }
7644: }
7645: }
7646: if (@users > 0) {
7647: foreach my $userkey (@users) {
1.865 raeburn 7648: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7649: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7650: if (ref($item) eq 'HASH') {
7651: if (($item->{'uname'} eq $env{'user.name'}) &&
7652: ($item->{'udom'} eq $env{'user.domain'})) {
7653: return 'ok';
7654: }
7655: }
7656: }
7657: }
1.765 albertel 7658: }
7659: }
7660: my %roleshash;
7661: my @courses_and_groups = @courses;
7662: push(@courses_and_groups,@groups);
7663: if (@courses_and_groups > 0) {
7664: my (%allgroups,%allroles);
7665: my ($start,$end,$role,$sec,$group);
7666: foreach my $envkey (%env) {
1.1060 raeburn 7667: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7668: my $cid = $2.'_'.$3;
7669: if ($1 eq 'gr') {
7670: $group = $4;
7671: $allgroups{$cid}{$group} = $env{$envkey};
7672: } else {
7673: if ($4 eq '') {
7674: $sec = 'none';
7675: } else {
7676: $sec = $4;
7677: }
7678: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7679: }
1.811 albertel 7680: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7681: my $cid = $2.'_'.$3;
7682: if ($4 eq '') {
7683: $sec = 'none';
7684: } else {
7685: $sec = $4;
7686: }
7687: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7688: }
7689: }
7690: if (keys(%allroles) == 0) {
7691: return;
7692: }
7693: foreach my $key (@courses_and_groups) {
7694: my %content = %{$$access_hash{$key}};
7695: my $cnum = $content{'number'};
7696: my $cdom = $content{'domain'};
7697: my $cid = $cdom.'_'.$cnum;
7698: if (!exists($allroles{$cid})) {
7699: next;
7700: }
7701: foreach my $role_id (keys(%{$content{'roles'}})) {
7702: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7703: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7704: my @status = @{$content{'roles'}{$role_id}{'access'}};
7705: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7706: foreach my $role (keys(%{$allroles{$cid}})) {
7707: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7708: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7709: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7710: if (grep/^all$/,@sections) {
7711: return 'ok';
7712: } else {
7713: if (grep/^$sec$/,@sections) {
7714: return 'ok';
7715: }
7716: }
7717: }
7718: }
7719: if (keys(%{$allgroups{$cid}}) == 0) {
7720: if (grep/^none$/,@groups) {
7721: return 'ok';
7722: }
7723: } else {
7724: if (grep/^all$/,@groups) {
7725: return 'ok';
7726: }
7727: foreach my $group (keys(%{$allgroups{$cid}})) {
7728: if (grep/^$group$/,@groups) {
7729: return 'ok';
7730: }
7731: }
7732: }
7733: }
7734: }
7735: }
7736: }
7737: }
7738: if ($guest) {
7739: return $guest;
7740: }
7741: }
7742: }
7743: return;
7744: }
7745:
7746: sub course_group_datechecker {
7747: my ($dates,$now,$status) = @_;
7748: my ($start,$end) = split(/\./,$dates);
7749: if (!$start && !$end) {
7750: return 'ok';
7751: }
7752: if (grep/^active$/,@{$status}) {
7753: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7754: return 'ok';
7755: }
7756: }
7757: if (grep/^previous$/,@{$status}) {
7758: if ($end > $now ) {
7759: return 'ok';
7760: }
7761: }
7762: if (grep/^future$/,@{$status}) {
7763: if ($start > $now) {
7764: return 'ok';
7765: }
7766: }
7767: return;
7768: }
7769:
7770: sub parse_portfolio_url {
7771: my ($url) = @_;
7772:
7773: my ($type,$udom,$unum,$group,$file_name);
7774:
1.823 albertel 7775: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7776: $type = 1;
7777: $udom = $1;
7778: $unum = $2;
7779: $file_name = $3;
1.823 albertel 7780: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7781: $type = 2;
7782: $udom = $1;
7783: $unum = $2;
7784: $group = $3;
7785: $file_name = $3.'/'.$4;
7786: }
7787: if (wantarray) {
7788: return ($type,$udom,$unum,$file_name,$group);
7789: }
7790: return $type;
7791: }
7792:
7793: sub is_portfolio_url {
7794: my ($url) = @_;
7795: return scalar(&parse_portfolio_url($url));
7796: }
7797:
1.798 raeburn 7798: sub is_portfolio_file {
7799: my ($file) = @_;
1.820 raeburn 7800: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7801: return 1;
7802: }
7803: return;
7804: }
7805:
1.976 raeburn 7806: sub usertools_access {
1.1084 raeburn 7807: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7808: my ($access,%tools);
7809: if ($context eq '') {
7810: $context = 'tools';
7811: }
7812: if ($context eq 'requestcourses') {
7813: %tools = (
7814: official => 1,
7815: unofficial => 1,
1.1006 raeburn 7816: community => 1,
1.1246 raeburn 7817: textbook => 1,
1.1305 raeburn 7818: placement => 1,
1.1368 raeburn 7819: lti => 1,
1.985 raeburn 7820: );
1.1183 raeburn 7821: } elsif ($context eq 'requestauthor') {
7822: %tools = (
7823: requestauthor => 1,
7824: );
1.985 raeburn 7825: } else {
7826: %tools = (
7827: aboutme => 1,
7828: blog => 1,
1.1177 raeburn 7829: webdav => 1,
1.985 raeburn 7830: portfolio => 1,
7831: );
7832: }
1.976 raeburn 7833: return if (!defined($tools{$tool}));
7834:
1.1242 raeburn 7835: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7836: $udom = $env{'user.domain'};
7837: $uname = $env{'user.name'};
7838: }
7839:
1.978 raeburn 7840: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7841: if ($action ne 'reload') {
1.985 raeburn 7842: if ($context eq 'requestcourses') {
7843: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 7844: } elsif ($context eq 'requestauthor') {
7845: return $env{'environment.canrequest.author'};
1.985 raeburn 7846: } else {
7847: return $env{'environment.availabletools.'.$tool};
7848: }
7849: }
1.976 raeburn 7850: }
7851:
1.1183 raeburn 7852: my ($toolstatus,$inststatus,$envkey);
7853: if ($context eq 'requestauthor') {
7854: $envkey = $context;
7855: } else {
7856: $envkey = $context.'.'.$tool;
7857: }
1.976 raeburn 7858:
1.985 raeburn 7859: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7860: ($action ne 'reload')) {
1.1183 raeburn 7861: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 7862: $inststatus = $env{'environment.inststatus'};
7863: } else {
1.1084 raeburn 7864: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 7865: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 7866: $inststatus = $userenvref->{'inststatus'};
7867: } else {
1.1183 raeburn 7868: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7869: $toolstatus = $userenv{$envkey};
1.1084 raeburn 7870: $inststatus = $userenv{'inststatus'};
7871: }
1.976 raeburn 7872: }
7873:
7874: if ($toolstatus ne '') {
7875: if ($toolstatus) {
7876: $access = 1;
7877: } else {
7878: $access = 0;
7879: }
7880: return $access;
7881: }
7882:
1.1084 raeburn 7883: my ($is_adv,%domdef);
7884: if (ref($is_advref) eq 'HASH') {
7885: $is_adv = $is_advref->{'is_adv'};
7886: } else {
7887: $is_adv = &is_advanced_user($udom,$uname);
7888: }
7889: if (ref($domdefref) eq 'HASH') {
7890: %domdef = %{$domdefref};
7891: } else {
7892: %domdef = &get_domain_defaults($udom);
7893: }
1.976 raeburn 7894: if (ref($domdef{$tool}) eq 'HASH') {
7895: if ($is_adv) {
7896: if ($domdef{$tool}{'_LC_adv'} ne '') {
7897: if ($domdef{$tool}{'_LC_adv'}) {
7898: $access = 1;
7899: } else {
7900: $access = 0;
7901: }
7902: return $access;
7903: }
7904: }
7905: if ($inststatus ne '') {
7906: my ($hasaccess,$hasnoaccess);
7907: foreach my $affiliation (split(/:/,$inststatus)) {
7908: if ($domdef{$tool}{$affiliation} ne '') {
7909: if ($domdef{$tool}{$affiliation}) {
7910: $hasaccess = 1;
7911: } else {
7912: $hasnoaccess = 1;
7913: }
7914: }
7915: }
7916: if ($hasaccess || $hasnoaccess) {
7917: if ($hasaccess) {
7918: $access = 1;
7919: } elsif ($hasnoaccess) {
7920: $access = 0;
7921: }
7922: return $access;
7923: }
7924: } else {
7925: if ($domdef{$tool}{'default'} ne '') {
7926: if ($domdef{$tool}{'default'}) {
7927: $access = 1;
7928: } elsif ($domdef{$tool}{'default'} == 0) {
7929: $access = 0;
7930: }
7931: return $access;
7932: }
7933: }
7934: } else {
1.1177 raeburn 7935: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7936: $access = 1;
7937: } else {
7938: $access = 0;
7939: }
1.976 raeburn 7940: return $access;
7941: }
7942: }
7943:
1.1050 raeburn 7944: sub is_course_owner {
7945: my ($cdom,$cnum,$udom,$uname) = @_;
7946: if (($udom eq '') || ($uname eq '')) {
7947: $udom = $env{'user.domain'};
7948: $uname = $env{'user.name'};
7949: }
7950: unless (($udom eq '') || ($uname eq '')) {
7951: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7952: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7953: return 1;
7954: } else {
7955: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7956: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7957: return 1;
7958: }
7959: }
7960: }
7961: }
7962: return;
7963: }
7964:
1.976 raeburn 7965: sub is_advanced_user {
7966: my ($udom,$uname) = @_;
1.1085 raeburn 7967: if ($udom ne '' && $uname ne '') {
7968: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7969: if (wantarray) {
7970: return ($env{'user.adv'},$env{'user.author'});
7971: } else {
7972: return $env{'user.adv'};
7973: }
1.1085 raeburn 7974: }
7975: }
1.976 raeburn 7976: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7977: my %allroles;
1.1128 raeburn 7978: my ($is_adv,$is_author);
1.976 raeburn 7979: foreach my $role (keys(%roleshash)) {
7980: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7981: my $area = '/'.$tdomain.'/'.$trest;
7982: if ($sec ne '') {
7983: $area .= '/'.$sec;
7984: }
7985: if (($area ne '') && ($trole ne '')) {
7986: my $spec=$trole.'.'.$area;
7987: if ($trole =~ /^cr\//) {
7988: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7989: } elsif ($trole ne 'gr') {
7990: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7991: }
1.1128 raeburn 7992: if ($trole eq 'au') {
7993: $is_author = 1;
7994: }
1.976 raeburn 7995: }
7996: }
7997: foreach my $role (keys(%allroles)) {
7998: last if ($is_adv);
7999: foreach my $item (split(/:/,$allroles{$role})) {
8000: if ($item ne '') {
8001: my ($privilege,$restrictions)=split(/&/,$item);
8002: if ($privilege eq 'adv') {
8003: $is_adv = 1;
8004: last;
8005: }
8006: }
8007: }
8008: }
1.1128 raeburn 8009: if (wantarray) {
8010: return ($is_adv,$is_author);
8011: }
1.976 raeburn 8012: return $is_adv;
8013: }
1.798 raeburn 8014:
1.1035 raeburn 8015: sub check_can_request {
1.1368 raeburn 8016: my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035 raeburn 8017: my $canreq = 0;
1.1368 raeburn 8018: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8019: $uname = $env{'user.name'};
8020: $udom = $env{'user.domain'};
8021: }
1.1035 raeburn 8022: my ($types,$typename) = &Apache::loncommon::course_types();
8023: my @options = ('approval','validate','autolimit');
8024: my $optregex = join('|',@options);
8025: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
8026: foreach my $type (@{$types}) {
1.1368 raeburn 8027: if (&usertools_access($uname,$udom,$type,undef,
8028: 'requestcourses')) {
1.1035 raeburn 8029: $canreq ++;
1.1036 raeburn 8030: if (ref($request_domains) eq 'HASH') {
1.1368 raeburn 8031: push(@{$request_domains->{$type}},$udom);
1.1036 raeburn 8032: }
1.1368 raeburn 8033: if ($dom eq $udom) {
1.1035 raeburn 8034: $can_request->{$type} = 1;
8035: }
8036: }
1.1368 raeburn 8037: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
8038: ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035 raeburn 8039: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
8040: if (@curr > 0) {
1.1036 raeburn 8041: foreach my $item (@curr) {
8042: if (ref($request_domains) eq 'HASH') {
8043: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
8044: if ($otherdom ne '') {
8045: if (ref($request_domains->{$type}) eq 'ARRAY') {
8046: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
8047: push(@{$request_domains->{$type}},$otherdom);
8048: }
8049: } else {
8050: push(@{$request_domains->{$type}},$otherdom);
8051: }
8052: }
8053: }
8054: }
1.1368 raeburn 8055: unless ($dom eq $env{'user.domain'}) {
1.1036 raeburn 8056: $canreq ++;
1.1035 raeburn 8057: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
8058: $can_request->{$type} = 1;
8059: }
8060: }
8061: }
8062: }
8063: }
8064: }
8065: return $canreq;
8066: }
8067:
1.341 www 8068: # ---------------------------------------------- Custom access rule evaluation
8069:
8070: sub customaccess {
8071: my ($priv,$uri)=@_;
1.807 albertel 8072: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 8073: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 8074: $udom = &LONCAPA::clean_domain($udom);
8075: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 8076: my $access=0;
1.800 albertel 8077: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 8078: my ($effect,$realm,$role,$type)=split(/\:/,$right);
8079: if ($type eq 'user') {
8080: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 8081: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 8082: if ($tdom) {
8083: if ($tdom ne $env{'user.domain'}) { next; }
8084: }
1.896 albertel 8085: if ($tuname) {
8086: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 8087: }
8088: $access=($effect eq 'allow');
8089: last;
8090: }
8091: } else {
8092: if ($role) {
8093: if ($role ne $urole) { next; }
8094: }
8095: foreach my $scope (split(/\s*\,\s*/,$realm)) {
8096: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
8097: if ($tdom) {
8098: if ($tdom ne $udom) { next; }
8099: }
8100: if ($tcrs) {
8101: if ($tcrs ne $ucrs) { next; }
8102: }
8103: if ($tsec) {
8104: if ($tsec ne $usec) { next; }
8105: }
8106: $access=($effect eq 'allow');
8107: last;
8108: }
8109: if ($realm eq '' && $role eq '') {
8110: $access=($effect eq 'allow');
8111: }
1.402 bowersj2 8112: }
1.341 www 8113: }
8114: return $access;
8115: }
8116:
1.103 harris41 8117: # ------------------------------------------------- Check for a user privilege
1.12 www 8118:
8119: sub allowed {
1.1424 raeburn 8120: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705 albertel 8121: my $ver_orguri=$uri;
1.439 www 8122: $uri=&deversion($uri);
1.152 www 8123: my $orguri=$uri;
1.52 www 8124: $uri=&declutter($uri);
1.809 raeburn 8125:
1.810 raeburn 8126: if ($priv eq 'evb') {
8127: # Evade communication block restrictions for specified role in a course
8128: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
8129: return $1;
8130: } else {
8131: return;
8132: }
8133: }
8134:
1.620 albertel 8135: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 8136: # Free bre access to adm and meta resources
1.1436 raeburn 8137: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$}))
1.769 albertel 8138: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
8139: && ($priv eq 'bre')) {
1.14 www 8140: return 'F';
1.159 www 8141: }
8142:
1.545 banghart 8143: # Free bre access to user's own portfolio contents
1.714 raeburn 8144: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 8145: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 8146: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 8147: my %setters;
8148: my ($startblock,$endblock) =
8149: &Apache::loncommon::blockcheck(\%setters,'port');
8150: if ($startblock && $endblock) {
8151: return 'B';
8152: } else {
8153: return 'F';
8154: }
1.545 banghart 8155: }
8156:
1.762 raeburn 8157: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 8158: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
8159: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
8160: if (exists($env{'request.course.id'})) {
8161: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8162: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8163: if (($domain eq $cdom) && ($name eq $cnum)) {
8164: my $courseprivid=$env{'request.course.id'};
8165: $courseprivid=~s/\_/\//;
8166: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
8167: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
8168: return $1;
1.762 raeburn 8169: } else {
8170: if ($env{'request.course.sec'}) {
8171: $courseprivid.='/'.$env{'request.course.sec'};
8172: }
8173: if ($env{'user.priv.'.$env{'request.role'}.'./'.
8174: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
8175: return $2;
8176: }
1.714 raeburn 8177: }
8178: }
8179: }
8180: }
8181:
1.159 www 8182: # Free bre to public access
8183:
8184: if ($priv eq 'bre') {
1.1362 raeburn 8185: my $copyright;
8186: unless ($uri =~ /ext\.tool/) {
8187: $copyright=&metadata($uri,'copyright');
8188: }
1.620 albertel 8189: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 8190: return 'F';
8191: }
1.238 www 8192: if ($copyright eq 'priv') {
8193: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8194: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 8195: return '';
8196: }
8197: }
8198: if ($copyright eq 'domain') {
8199: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 8200: unless (($env{'user.domain'} eq $1) ||
8201: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 8202: return '';
8203: }
1.262 matthew 8204: }
1.620 albertel 8205: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 8206: # Library role, so allow browsing of resources in this domain.
8207: return 'F';
1.238 www 8208: }
1.341 www 8209: if ($copyright eq 'custom') {
8210: unless (&customaccess($priv,$uri)) { return ''; }
8211: }
1.14 www 8212: }
1.264 matthew 8213: # Domain coordinator is trying to create a course
1.620 albertel 8214: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 8215: # uri is the requested domain in this case.
8216: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 8217: # a role of dc for the domain in question.
1.620 albertel 8218: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 8219: }
1.29 www 8220:
1.52 www 8221: my $thisallowed='';
8222: my $statecond=0;
8223: my $courseprivid='';
8224:
1.1039 raeburn 8225: my $ownaccess;
1.1043 raeburn 8226: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 8227: if (($priv eq 'bro') && ($env{'user.author'})) {
8228: if ($uri eq '') {
8229: $ownaccess = 1;
8230: } else {
8231: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
8232: my $udom = $env{'user.domain'};
8233: my $uname = $env{'user.name'};
8234: if ($uri =~ m{^\Q$udom\E/?$}) {
8235: $ownaccess = 1;
1.1040 raeburn 8236: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 8237: unless ($uri =~ m{\.\./}) {
8238: $ownaccess = 1;
8239: }
8240: } elsif (($udom ne 'public') && ($uname ne 'public')) {
8241: my $now = time;
8242: if ($uri =~ m{^([^/]+)/?$}) {
8243: my $adom = $1;
8244: foreach my $key (keys(%env)) {
1.1042 raeburn 8245: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1452 raeburn 8246: my ($start,$end) = split(/\./,$env{$key});
8247: if (($now >= $start) && (!$end || $end > $now)) {
1.1039 raeburn 8248: $ownaccess = 1;
8249: last;
8250: }
8251: }
8252: }
8253: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
8254: my $adom = $1;
8255: my $aname = $2;
1.1042 raeburn 8256: foreach my $role ('ca','aa') {
8257: if ($env{"user.role.$role./$adom/$aname"}) {
8258: my ($start,$end) =
1.1452 raeburn 8259: split(/\./,$env{"user.role.$role./$adom/$aname"});
8260: if (($now >= $start) && (!$end || $end > $now)) {
1.1042 raeburn 8261: $ownaccess = 1;
8262: last;
8263: }
1.1039 raeburn 8264: }
8265: }
8266: }
8267: }
8268: }
8269: }
8270: }
8271:
1.52 www 8272: # Course
8273:
1.620 albertel 8274: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8275: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8276: $thisallowed.=$1;
8277: }
1.52 www 8278: }
1.29 www 8279:
1.52 www 8280: # Domain
8281:
1.620 albertel 8282: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 8283: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 8284: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 8285: $thisallowed.=$1;
8286: }
1.12 www 8287: }
1.52 www 8288:
1.1141 raeburn 8289: # User who is not author or co-author might still be able to edit
8290: # resource of an author in the domain (e.g., if Domain Coordinator).
8291: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8292: (&allowed('mdc',$env{'request.course.id'}))) {
8293: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8294: $thisallowed.=$1;
8295: }
8296: }
8297:
1.52 www 8298: # Course: uri itself is a course
1.66 www 8299: my $courseuri=$uri;
8300: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8301: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8302:
1.620 albertel 8303: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8304: =~/\Q$priv\E\&([^\:]*)/) {
1.1409 raeburn 8305: if ($priv eq 'mip') {
8306: my $rem = $1;
8307: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8308: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8309: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8310: if ($cdom ne '') {
1.1410 raeburn 8311: my %passwdconf = &get_passwdconf($cdom);
8312: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8313: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8314: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8315: my @inststatuses = split(':',$env{'environment.inststatus'});
8316: unless (@inststatuses) {
8317: @inststatuses = ('default');
8318: }
8319: foreach my $status (@inststatuses) {
8320: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8321: $thisallowed.=$rem;
8322: }
8323: }
8324: }
8325: }
1.1409 raeburn 8326: }
8327: }
8328: }
8329: } else {
8330: unless (($priv eq 'bro') && (!$ownaccess)) {
8331: $thisallowed.=$1;
8332: }
1.1039 raeburn 8333: }
1.12 www 8334: }
1.29 www 8335:
1.665 albertel 8336: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8337: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8338: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8339: $thisallowed='';
1.671 raeburn 8340: my ($match)=&is_on_map($uri);
8341: if ($match) {
8342: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8343: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 8344: my $value = $1;
1.1402 raeburn 8345: my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8346: if ($deeplinkblock) {
8347: $thisallowed='D';
8348: } elsif ($noblockcheck) {
1.1281 raeburn 8349: $thisallowed.=$value;
1.1162 raeburn 8350: } else {
1.1424 raeburn 8351: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281 raeburn 8352: if (@blockers > 0) {
8353: $thisallowed = 'B';
8354: } else {
8355: $thisallowed.=$value;
8356: }
1.1162 raeburn 8357: }
1.671 raeburn 8358: }
8359: } else {
1.705 albertel 8360: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8361: if ($refuri) {
8362: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8363: $thisallowed='F';
1.671 raeburn 8364: } else {
8365: $refuri=&declutter($refuri);
8366: my ($match) = &is_on_map($refuri);
8367: if ($match) {
1.1402 raeburn 8368: my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8369: if ($deeplinkblock) {
8370: $thisallowed='D';
8371: } elsif ($noblockcheck) {
1.1281 raeburn 8372: $thisallowed='F';
1.1162 raeburn 8373: } else {
1.1426 raeburn 8374: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281 raeburn 8375: if (@blockers > 0) {
8376: $thisallowed = 'B';
8377: } else {
8378: $thisallowed='F';
8379: }
1.1162 raeburn 8380: }
1.671 raeburn 8381: }
1.669 raeburn 8382: }
1.671 raeburn 8383: }
8384: }
1.314 www 8385: }
1.492 albertel 8386:
1.766 albertel 8387: if ($priv eq 'bre'
8388: && $thisallowed ne 'F'
8389: && $thisallowed ne '2'
8390: && &is_portfolio_url($uri)) {
1.1270 raeburn 8391: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8392: }
1.1250 raeburn 8393:
1.52 www 8394: # Full access at system, domain or course-wide level? Exit.
1.29 www 8395: if ($thisallowed=~/F/) {
8396: return 'F';
8397: }
8398:
1.52 www 8399: # If this is generating or modifying users, exit with special codes
1.29 www 8400:
1.643 www 8401: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8402: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8403: my ($audom,$auname)=split('/',$uri);
1.643 www 8404: # no author name given, so this just checks on the general right to make a co-author in this domain
8405: unless ($auname) { return $thisallowed; }
8406: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8407: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8408: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8409: ($audom ne $env{'request.role.domain'}))) { return ''; }
8410: }
1.52 www 8411: return $thisallowed;
8412: }
8413: #
1.103 harris41 8414: # Gathered so far: system, domain and course wide privileges
1.52 www 8415: #
8416: # Course: See if uri or referer is an individual resource that is part of
8417: # the course
8418:
1.620 albertel 8419: if ($env{'request.course.id'}) {
1.232 www 8420:
1.1409 raeburn 8421: # If this is modifying password (internal auth) domains must match for user and user's role.
8422:
8423: if ($priv eq 'mip') {
8424: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8425: return $thisallowed;
8426: } else {
8427: return '';
8428: }
8429: }
8430:
1.620 albertel 8431: $courseprivid=$env{'request.course.id'};
8432: if ($env{'request.course.sec'}) {
8433: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8434: }
8435: $courseprivid=~s/\_/\//;
8436: my $checkreferer=1;
1.232 www 8437: my ($match,$cond)=&is_on_map($uri);
8438: if ($match) {
8439: $statecond=$cond;
1.620 albertel 8440: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8441: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8442: my $value = $1;
8443: if ($priv eq 'bre') {
1.1458 raeburn 8444: my $deeplinkblock = &deeplink_check($priv,$symb,$uri);
8445: if ($deeplinkblock) {
8446: $thisallowed = 'D';
8447: } elsif ($noblockcheck) {
1.1281 raeburn 8448: $thisallowed.=$value;
1.1162 raeburn 8449: } else {
1.1424 raeburn 8450: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281 raeburn 8451: if (@blockers > 0) {
8452: $thisallowed = 'B';
8453: } else {
8454: $thisallowed.=$value;
8455: }
1.1162 raeburn 8456: }
8457: } else {
8458: $thisallowed.=$value;
8459: }
1.52 www 8460: $checkreferer=0;
8461: }
1.29 www 8462: }
1.1424 raeburn 8463:
1.148 www 8464: if ($checkreferer) {
1.620 albertel 8465: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8466: unless ($refuri) {
1.800 albertel 8467: foreach my $key (keys(%env)) {
8468: if ($key=~/^httpref\..*\*/) {
8469: my $pattern=$key;
1.156 www 8470: $pattern=~s/^httpref\.\/res\///;
1.148 www 8471: $pattern=~s/\*/\[\^\/\]\+/g;
8472: $pattern=~s/\//\\\//g;
1.152 www 8473: if ($orguri=~/$pattern/) {
1.800 albertel 8474: $refuri=$env{$key};
1.148 www 8475: }
8476: }
1.191 harris41 8477: }
1.148 www 8478: }
1.232 www 8479:
1.148 www 8480: if ($refuri) {
1.152 www 8481: $refuri=&declutter($refuri);
1.232 www 8482: my ($match,$cond)=&is_on_map($refuri);
8483: if ($match) {
8484: my $refstatecond=$cond;
1.620 albertel 8485: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8486: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8487: my $value = $1;
8488: if ($priv eq 'bre') {
1.1402 raeburn 8489: my $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
8490: if ($deeplinkblock) {
8491: $thisallowed = 'D';
8492: } elsif ($noblockcheck) {
1.1281 raeburn 8493: $thisallowed.=$value;
1.1162 raeburn 8494: } else {
1.1426 raeburn 8495: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281 raeburn 8496: if (@blockers > 0) {
8497: $thisallowed = 'B';
8498: } else {
8499: $thisallowed.=$value;
8500: }
1.1162 raeburn 8501: }
8502: } else {
8503: $thisallowed.=$value;
8504: }
1.53 www 8505: $uri=$refuri;
8506: $statecond=$refstatecond;
1.52 www 8507: }
8508: }
1.148 www 8509: }
1.29 www 8510: }
1.52 www 8511: }
1.29 www 8512:
1.52 www 8513: #
1.103 harris41 8514: # Gathered now: all privileges that could apply, and condition number
1.52 www 8515: #
8516: #
8517: # Full or no access?
8518: #
1.29 www 8519:
1.52 www 8520: if ($thisallowed=~/F/) {
8521: return 'F';
8522: }
1.29 www 8523:
1.52 www 8524: unless ($thisallowed) {
8525: return '';
8526: }
1.29 www 8527:
1.52 www 8528: # Restrictions exist, deal with them
8529: #
8530: # C:according to course preferences
8531: # R:according to resource settings
8532: # L:unless locked
8533: # X:according to user session state
8534: #
8535:
8536: # Possibly locked functionality, check all courses
1.1454 raeburn 8537: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54 www 8538: # Locks might take effect only after 10 minutes cache expiration for other
1.1454 raeburn 8539: # courses, and 2 minutes for current course, in which user has st or ta role
8540: # which is neither expired nor a future role (unless current course).
1.52 www 8541:
1.1454 raeburn 8542: my ($needlockcheck,$now,$crsonly);
1.52 www 8543: if ($thisallowed=~/L/) {
1.1454 raeburn 8544: $now = time;
8545: if ($priv eq 'bre') {
8546: if ($uri ne '') {
8547: if ($orguri =~ m{^/+res/}) {
8548: if ($uri =~ m{^lib/templates/}) {
8549: if ($env{'request.course.id'}) {
8550: $crsonly = 1;
8551: $needlockcheck = 1;
8552: }
8553: } else {
8554: $needlockcheck = 1;
8555: }
8556: } elsif ($env{'request.course.id'}) {
8557: my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
8558: if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
8559: ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
8560: $crsonly = 1;
8561: }
8562: $needlockcheck = 1;
8563: }
8564: }
8565: } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
8566: $needlockcheck = 1;
8567: }
8568: }
8569: if ($needlockcheck) {
1.1453 raeburn 8570: foreach my $envkey (keys(%env)) {
1.54 www 8571: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8572: my $courseid=$2;
8573: my $roleid=$1.'.'.$2;
1.92 www 8574: $courseid=~s/^\///;
1.1453 raeburn 8575: unless ($env{'request.role'} eq $roleid) {
8576: my ($start,$end) = split(/\./,$env{$envkey});
8577: next unless (($now >= $start) && (!$end || $end > $now));
8578: }
1.54 www 8579: my $expiretime=600;
1.620 albertel 8580: if ($env{'request.role'} eq $roleid) {
1.54 www 8581: $expiretime=120;
8582: }
8583: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8584: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8585: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8586: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8587: }
1.620 albertel 8588: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8589: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8590: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8591: &log($env{'user.domain'},$env{'user.name'},
8592: $env{'user.home'},
1.57 www 8593: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8594: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8595: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8596: return '';
8597: }
8598: }
1.620 albertel 8599: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8600: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1455 raeburn 8601: if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620 albertel 8602: &log($env{'user.domain'},$env{'user.name'},
8603: $env{'user.home'},
1.57 www 8604: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8605: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8606: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8607: return '';
8608: }
8609: }
8610: }
1.29 www 8611: }
1.52 www 8612: }
1.1424 raeburn 8613:
1.52 www 8614: #
8615: # Rest of the restrictions depend on selected course
8616: #
8617:
1.620 albertel 8618: unless ($env{'request.course.id'}) {
1.766 albertel 8619: if ($thisallowed eq 'A') {
8620: return 'A';
1.814 raeburn 8621: } elsif ($thisallowed eq 'B') {
8622: return 'B';
1.766 albertel 8623: } else {
8624: return '1';
8625: }
1.52 www 8626: }
1.29 www 8627:
1.52 www 8628: #
8629: # Now user is definitely in a course
8630: #
1.53 www 8631:
8632:
8633: # Course preferences
8634:
8635: if ($thisallowed=~/C/) {
1.620 albertel 8636: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8637: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8638: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8639: =~/\Q$rolecode\E/) {
1.1304 raeburn 8640: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8641: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8642: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8643: $env{'request.course.id'});
8644: }
1.237 www 8645: return '';
8646: }
8647:
1.620 albertel 8648: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8649: =~/\Q$unamedom\E/) {
1.1304 raeburn 8650: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 8651: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8652: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8653: $env{'request.course.id'});
8654: }
1.54 www 8655: return '';
8656: }
1.53 www 8657: }
8658:
8659: # Resource preferences
8660:
8661: if ($thisallowed=~/R/) {
1.620 albertel 8662: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8663: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8664: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8665: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8666: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8667: }
8668: return '';
1.54 www 8669: }
1.53 www 8670: }
1.30 www 8671:
1.246 www 8672: # Restricted by state or randomout?
1.30 www 8673:
1.52 www 8674: if ($thisallowed=~/X/) {
1.620 albertel 8675: if ($env{'acc.randomout'}) {
1.579 albertel 8676: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8677: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8678: return '';
8679: }
1.247 www 8680: }
8681: if (&condval($statecond)) {
1.52 www 8682: return '2';
8683: } else {
8684: return '';
8685: }
8686: }
1.30 www 8687:
1.766 albertel 8688: if ($thisallowed eq 'A') {
8689: return 'A';
1.814 raeburn 8690: } elsif ($thisallowed eq 'B') {
8691: return 'B';
1.1402 raeburn 8692: } elsif ($thisallowed eq 'D') {
8693: return 'D';
1.766 albertel 8694: }
1.52 www 8695: return 'F';
1.232 www 8696: }
1.1162 raeburn 8697:
1.1192 raeburn 8698: # ------------------------------------------- Check construction space access
8699:
8700: sub constructaccess {
8701: my ($url,$setpriv)=@_;
8702:
8703: # We do not allow editing of previous versions of files
8704: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8705:
8706: # Get username and domain from URL
8707: my ($ownername,$ownerdomain,$ownerhome);
8708:
8709: ($ownerdomain,$ownername) =
1.1325 raeburn 8710: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192 raeburn 8711:
8712: # The URL does not really point to any authorspace, forget it
8713: unless (($ownername) && ($ownerdomain)) { return ''; }
8714:
8715: # Now we need to see if the user has access to the authorspace of
8716: # $ownername at $ownerdomain
8717:
8718: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8719: # Real author for this?
8720: $ownerhome = $env{'user.home'};
8721: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8722: return ($ownername,$ownerdomain,$ownerhome);
8723: }
8724: } else {
8725: # Co-author for this?
8726: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8727: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8728: $ownerhome = &homeserver($ownername,$ownerdomain);
8729: return ($ownername,$ownerdomain,$ownerhome);
8730: }
1.1312 raeburn 8731: if ($env{'request.course.id'}) {
8732: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
8733: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
8734: if (&allowed('mdc',$env{'request.course.id'})) {
8735: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
8736: return ($ownername,$ownerdomain,$ownerhome);
8737: }
8738: }
8739: }
1.1192 raeburn 8740: }
8741:
8742: # We don't have any access right now. If we are not possibly going to do anything about this,
8743: # we might as well leave
8744: unless ($setpriv) { return ''; }
8745:
8746: # Backdoor access?
8747: my $allowed=&allowed('eco',$ownerdomain);
8748: # Nope
8749: unless ($allowed) { return ''; }
8750: # Looks like we may have access, but could be locked by the owner of the construction space
8751: if ($allowed eq 'U') {
8752: my %blocked=&get('environment',['domcoord.author'],
8753: $ownerdomain,$ownername);
8754: # Is blocked by owner
8755: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8756: }
8757: if (($allowed eq 'F') || ($allowed eq 'U')) {
8758: # Grant temporary access
8759: my $then=$env{'user.login.time'};
1.1209 raeburn 8760: my $update=$env{'user.update.time'};
1.1192 raeburn 8761: if (!$update) { $update = $then; }
8762: my $refresh=$env{'user.refresh.time'};
8763: if (!$refresh) { $refresh = $update; }
8764: my $now = time;
8765: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8766: $now,'ca','constructaccess');
8767: $ownerhome = &homeserver($ownername,$ownerdomain);
8768: return($ownername,$ownerdomain,$ownerhome);
8769: }
8770: # No business here
8771: return '';
8772: }
8773:
1.1282 raeburn 8774: # ----------------------------------------------------------- Content Blocking
8775:
8776: {
8777: # Caches for faster Course Contents display where content blocking
8778: # is in operation (i.e., interval param set) for timed quiz.
8779: #
8780: # User for whom data are being temporarily cached.
8781: my $cacheduser='';
1.1424 raeburn 8782: # Course for which data are being temporarily cached.
8783: my $cachedcid='';
1.1282 raeburn 8784: # Cached blockers for this user (a hash of blocking items).
8785: my %cachedblockers=();
8786: # When the data were last cached.
8787: my $cachedlast='';
8788:
8789: sub load_all_blockers {
1.1427 raeburn 8790: my ($uname,$udom)=@_;
1.1282 raeburn 8791: if (($uname ne '') && ($udom ne '')) {
8792: if (($cacheduser eq $uname.':'.$udom) &&
1.1424 raeburn 8793: ($cachedcid eq $env{'request.course.id'}) &&
1.1427 raeburn 8794: (abs($cachedlast-time)<5)) {
1.1282 raeburn 8795: return;
8796: }
8797: }
8798: $cachedlast=time;
8799: $cacheduser=$uname.':'.$udom;
1.1424 raeburn 8800: $cachedcid=$env{'request.course.id'};
1.1427 raeburn 8801: %cachedblockers = &get_commblock_resources();
1.1424 raeburn 8802: return;
1.1282 raeburn 8803: }
8804:
1.1162 raeburn 8805: sub get_comm_blocks {
8806: my ($cdom,$cnum) = @_;
8807: if ($cdom eq '' || $cnum eq '') {
8808: return unless ($env{'request.course.id'});
8809: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8810: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8811: }
8812: my %commblocks;
8813: my $hashid=$cdom.'_'.$cnum;
8814: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8815: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8816: %commblocks = %{$blocksref};
8817: } else {
8818: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8819: my $cachetime = 600;
8820: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8821: }
8822: return %commblocks;
8823: }
8824:
1.1282 raeburn 8825: sub get_commblock_resources {
8826: my ($blocks) = @_;
8827: my %blockers = ();
8828: return %blockers unless ($env{'request.course.id'});
8829: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 8830: my %commblocks;
8831: if (ref($blocks) eq 'HASH') {
8832: %commblocks = %{$blocks};
8833: } else {
8834: %commblocks = &get_comm_blocks();
8835: }
1.1282 raeburn 8836: return %blockers unless (keys(%commblocks) > 0);
8837: my $navmap = Apache::lonnavmaps::navmap->new();
8838: return %blockers unless (ref($navmap));
1.1162 raeburn 8839: my $now = time;
8840: foreach my $block (keys(%commblocks)) {
8841: if ($block =~ /^(\d+)____(\d+)$/) {
8842: my ($start,$end) = ($1,$2);
8843: if ($start <= $now && $end >= $now) {
8844: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8845: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8846: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 8847: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8848: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 8849: }
8850: }
8851: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 8852: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8853: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 8854: }
8855: }
8856: }
8857: }
8858: }
8859: } elsif ($block =~ /^firstaccess____(.+)$/) {
8860: my $item = $1;
1.1163 raeburn 8861: my @to_test;
1.1162 raeburn 8862: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8863: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282 raeburn 8864: my @interval;
8865: my $type = 'map';
8866: if ($item eq 'course') {
8867: $type = 'course';
8868: @interval=&EXT("resource.0.interval");
8869: } else {
8870: if ($item =~ /___\d+___/) {
8871: $type = 'resource';
8872: @interval=&EXT("resource.0.interval",$item);
8873: if (ref($navmap)) {
8874: my $res = $navmap->getBySymb($item);
8875: push(@to_test,$res);
8876: }
1.1162 raeburn 8877: } else {
1.1282 raeburn 8878: my $mapsymb = &symbread($item,1);
8879: if ($mapsymb) {
8880: if (ref($navmap)) {
8881: my $mapres = $navmap->getBySymb($mapsymb);
1.1428 raeburn 8882: if (ref($mapres)) {
8883: my $first = $mapres->map_start();
8884: my $finish = $mapres->map_finish();
8885: my $it = $navmap->getIterator($first,$finish,undef,0,0);
1.1429 raeburn 8886: if (ref($it)) {
8887: my $res;
8888: while ($res = $it->next(undef,1)) {
8889: next unless (ref($res));
8890: my $symb = $res->symb();
8891: next if (($symb eq $mapsymb) || ($symb eq ''));
8892: @interval=&EXT("resource.0.interval",$symb);
8893: if ($interval[1] eq 'map') {
8894: if ($res->answerable()) {
8895: push(@to_test,$res);
8896: last;
8897: }
1.1428 raeburn 8898: }
1.1162 raeburn 8899: }
8900: }
8901: }
8902: }
8903: }
8904: }
1.1282 raeburn 8905: }
1.1310 raeburn 8906: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 8907: my $timelimit = $1;
1.1282 raeburn 8908: my $first_access;
8909: if ($type eq 'resource') {
8910: $first_access=&get_first_access($interval[1],$item);
8911: } elsif ($type eq 'map') {
8912: $first_access=&get_first_access($interval[1],undef,$item);
8913: } else {
8914: $first_access=&get_first_access($interval[1]);
8915: }
8916: if ($first_access) {
1.1292 raeburn 8917: my $timesup = $first_access+$timelimit;
1.1282 raeburn 8918: if ($timesup > $now) {
8919: my $activeblock;
8920: foreach my $res (@to_test) {
1.1283 raeburn 8921: if ($res->answerable()) {
1.1282 raeburn 8922: $activeblock = 1;
8923: last;
8924: }
8925: }
8926: if ($activeblock) {
8927: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8928: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8929: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8930: }
8931: }
8932: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8933: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8934: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 8935: }
1.1162 raeburn 8936: }
8937: }
8938: }
8939: }
8940: }
8941: }
8942: }
8943: }
8944: }
1.1282 raeburn 8945: return %blockers;
1.1162 raeburn 8946: }
8947:
1.1282 raeburn 8948: sub has_comm_blocking {
1.1427 raeburn 8949: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1282 raeburn 8950: my @blockers;
8951: return unless ($env{'request.course.id'});
8952: return unless ($priv eq 'bre');
8953: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8954: return if ($env{'request.state'} eq 'construct');
1.1427 raeburn 8955: my %blockinfo;
8956: if (ref($blocks) eq 'HASH') {
8957: %blockinfo = &get_commblock_resources($blocks);
8958: } else {
8959: &load_all_blockers($env{'user.name'},$env{'user.domain'});
8960: %blockinfo = %cachedblockers;
8961: }
8962: return unless (keys(%blockinfo) > 0);
1.1282 raeburn 8963: my (%possibles,@symbs);
8964: if (!$symb) {
1.1427 raeburn 8965: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162 raeburn 8966: }
1.1282 raeburn 8967: if ($symb) {
8968: @symbs = ($symb);
8969: } elsif (keys(%possibles)) {
8970: @symbs = keys(%possibles);
8971: }
8972: my $noblock;
8973: foreach my $symb (@symbs) {
8974: last if ($noblock);
8975: my ($map,$resid,$resurl)=&decode_symb($symb);
1.1427 raeburn 8976: foreach my $block (keys(%blockinfo)) {
1.1282 raeburn 8977: if ($block =~ /^firstaccess____(.+)$/) {
8978: my $item = $1;
1.1424 raeburn 8979: unless ($blocked) {
8980: if (($item eq $map) || ($item eq $symb)) {
8981: $noblock = 1;
8982: last;
8983: }
1.1282 raeburn 8984: }
8985: }
1.1427 raeburn 8986: if (ref($blockinfo{$block}) eq 'HASH') {
8987: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
8988: if ($blockinfo{$block}{'resources'}{$symb}) {
1.1282 raeburn 8989: unless (grep(/^\Q$block\E$/,@blockers)) {
8990: push(@blockers,$block);
8991: }
8992: }
8993: }
1.1427 raeburn 8994: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
8995: if ($blockinfo{$block}{'maps'}{$map}) {
1.1424 raeburn 8996: unless (grep(/^\Q$block\E$/,@blockers)) {
8997: push(@blockers,$block);
8998: }
1.1282 raeburn 8999: }
9000: }
1.1162 raeburn 9001: }
9002: }
9003: }
1.1424 raeburn 9004: unless ($noblock) {
9005: return @blockers;
9006: }
9007: return;
1.1282 raeburn 9008: }
1.1162 raeburn 9009: }
9010:
1.1402 raeburn 9011: sub deeplink_check {
9012: my ($priv,$symb,$uri) = @_;
9013: return unless ($env{'request.course.id'});
9014: return unless ($priv eq 'bre');
9015: return if ($env{'request.state'} eq 'construct');
9016: return if ($env{'request.role.adv'});
9017: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9018: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9019: my (%possibles,@symbs);
9020: if (!$symb) {
9021: $symb = &symbread($uri,1,1,1,\%possibles);
9022: }
9023: if ($symb) {
9024: @symbs = ($symb);
9025: } elsif (keys(%possibles)) {
9026: @symbs = keys(%possibles);
9027: }
9028:
9029: my ($login,$switchrole,$allow);
9030: if ($env{'request.deeplink.login'} =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
9031: my $key = $1;
9032: my $tinyurl;
9033: my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
9034: if (defined($cached)) {
9035: $tinyurl = $result;
9036: } else {
9037: my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
9038: my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
9039: if ($currtiny{$key} ne '') {
9040: $tinyurl = $currtiny{$key};
9041: &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
9042: }
9043: }
9044: if ($tinyurl ne '') {
9045: my ($cnumreq,$posslogin) = split(/\&/,$tinyurl);
9046: if ($cnumreq eq $cnum) {
9047: $login = $posslogin;
9048: } else {
9049: $switchrole = 1;
9050: }
9051: }
9052: }
9053: foreach my $symb (@symbs) {
9054: last if ($allow);
9055: my $deeplink = &EXT("resource.0.deeplink",$symb);
9056: if ($deeplink eq '') {
9057: $allow = 1;
9058: } else {
9059: my ($listed,$scope,$access) = split(/,/,$deeplink);
9060: if ($access eq 'any') {
9061: $allow = 1;
9062: } elsif ($login) {
9063: if ($access eq 'only') {
9064: if ($scope eq 'res') {
9065: if ($symb eq $login) {
9066: $allow = 1;
9067: }
1.1459 raeburn 9068: } elsif (($scope eq 'map') || ($scope eq 'rec')) {
9069: my ($map_from_symb) = &deversion((&decode_symb($symb))[0]);
9070: my ($map_from_login) = &deversion((&decode_symb($login))[0]);
9071: if (($map_from_symb) && ($map_from_login)) {
9072: if ($map_from_symb eq $map_from_login) {
9073: $allow = 1;
9074: } elsif ($scope eq 'rec') {
9075: my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
9076: if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
9077: $allow = 1;
9078: }
9079: }
9080: }
1.1402 raeburn 9081: }
9082: } else {
9083: my ($acctype,$item) = split(/:/,$access);
9084: if (($acctype eq 'lti') && ($env{'user.linkprotector'})) {
9085: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.linkprotector'}))) {
9086: my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
9087: if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.linkproturis'}))) {
9088: $allow = 1;
9089: }
9090: }
9091: } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
9092: if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
9093: my %tinyurls = &get('tiny',[$symb],$cdom,$cnum);
9094: if (grep(/\Q$tinyurls{$symb}\E$/,split(/,/,$env{'user.keyedlinkuri'}))) {
9095: $allow = 1;
9096: }
9097: }
9098: }
9099: }
9100: }
9101: }
9102: }
9103: return if ($allow);
9104: return 1;
9105: }
9106:
1.1282 raeburn 9107: # -------------------------------- Deversion and split uri into path an filename
9108:
1.1133 foxr 9109: #
1.1282 raeburn 9110: # Removes the version from a URI and
1.1133 foxr 9111: # splits it in to its filename and path to the filename.
9112: # Seems like File::Basename could have done this more clearly.
9113: # Parameters:
9114: # $uri - input URI
9115: # Returns:
9116: # Two element list consisting of
9117: # $pathname - the URI up to and excluding the trailing /
9118: # $filename - The part of the URI following the last /
9119: # NOTE:
9120: # Another realization of this is simply:
9121: # use File::Basename;
9122: # ...
9123: # $uri = shift;
9124: # $filename = basename($uri);
9125: # $path = dirname($uri);
9126: # return ($filename, $path);
9127: #
9128: # The implementation below is probably faster however.
9129: #
1.710 albertel 9130: sub split_uri_for_cond {
9131: my $uri=&deversion(&declutter(shift));
9132: my @uriparts=split(/\//,$uri);
9133: my $filename=pop(@uriparts);
9134: my $pathname=join('/',@uriparts);
9135: return ($pathname,$filename);
9136: }
1.232 www 9137: # --------------------------------------------------- Is a resource on the map?
9138:
9139: sub is_on_map {
1.710 albertel 9140: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 9141: #Trying to find the conditional for the file
1.620 albertel 9142: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 9143: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 9144: if ($match) {
1.289 bowersj2 9145: return (1,$1);
9146: } else {
1.434 www 9147: return (0,0);
1.289 bowersj2 9148: }
1.12 www 9149: }
9150:
1.427 www 9151: # --------------------------------------------------------- Get symb from alias
9152:
9153: sub get_symb_from_alias {
9154: my $symb=shift;
9155: my ($map,$resid,$url)=&decode_symb($symb);
9156: # Already is a symb
9157: if ($url) { return $symb; }
9158: # Must be an alias
9159: my $aliassymb='';
9160: my %bighash;
1.620 albertel 9161: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 9162: &GDBM_READER(),0640)) {
9163: my $rid=$bighash{'mapalias_'.$symb};
9164: if ($rid) {
9165: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 9166: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
9167: $resid,$bighash{'src_'.$rid});
1.427 www 9168: }
9169: untie %bighash;
9170: }
9171: return $aliassymb;
9172: }
9173:
1.12 www 9174: # ----------------------------------------------------------------- Define Role
9175:
9176: sub definerole {
9177: if (allowed('mcr','/')) {
1.1326 raeburn 9178: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 9179: foreach my $role (split(':',$sysrole)) {
9180: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9181: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
9182: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
9183: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9184: return "refused:s:$crole&$cqual";
9185: }
9186: }
1.191 harris41 9187: }
1.800 albertel 9188: foreach my $role (split(':',$domrole)) {
9189: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9190: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
9191: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
9192: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 9193: return "refused:d:$crole&$cqual";
9194: }
9195: }
1.191 harris41 9196: }
1.800 albertel 9197: foreach my $role (split(':',$courole)) {
9198: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 9199: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
9200: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
9201: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 9202: return "refused:c:$crole&$cqual";
9203: }
9204: }
1.191 harris41 9205: }
1.1326 raeburn 9206: my $uhome;
9207: if (($uname ne '') && ($udom ne '')) {
9208: $uhome = &homeserver($uname,$udom);
9209: return $uhome if ($uhome eq 'no_host');
9210: } else {
9211: $uname = $env{'user.name'};
9212: $udom = $env{'user.domain'};
9213: $uhome = $env{'user.home'};
9214: }
1.620 albertel 9215: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326 raeburn 9216: "$udom:$uname:rolesdef_$rolename=".
1.21 www 9217: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326 raeburn 9218: return reply($command,$uhome);
1.12 www 9219: } else {
9220: return 'refused';
9221: }
1.105 harris41 9222: }
9223:
9224: # ---------------- Make a metadata query against the network of library servers
9225:
9226: sub metadata_query {
1.1237 raeburn 9227: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 9228: my %rhash;
1.845 albertel 9229: my %libserv = &all_library();
1.244 matthew 9230: my @server_list = (defined($server_array) ? @$server_array
9231: : keys(%libserv) );
9232: for my $server (@server_list) {
1.1237 raeburn 9233: my $domains = '';
9234: if (ref($domains_hash) eq 'HASH') {
9235: $domains = $domains_hash->{$server};
9236: }
1.118 harris41 9237: unless ($custom or $customshow) {
1.1237 raeburn 9238: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 9239: $rhash{$server}=$reply;
9240: }
9241: else {
9242: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 9243: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 9244: $server);
9245: $rhash{$server}=$reply;
9246: }
1.112 harris41 9247: }
1.118 harris41 9248: return \%rhash;
1.240 www 9249: }
9250:
9251: # ----------------------------------------- Send log queries and wait for reply
9252:
9253: sub log_query {
9254: my ($uname,$udom,$query,%filters)=@_;
9255: my $uhome=&homeserver($uname,$udom);
9256: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 9257: my $uhost=&hostname($uhome);
1.800 albertel 9258: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 9259: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
9260: $uhome);
1.479 albertel 9261: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 9262: return get_query_reply($queryid);
9263: }
9264:
1.818 raeburn 9265: # -------------------------- Update MySQL table for portfolio file
9266:
9267: sub update_portfolio_table {
1.821 raeburn 9268: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 9269: if ($group ne '') {
9270: $file_name =~s /^\Q$group\E//;
9271: }
1.818 raeburn 9272: my $homeserver = &homeserver($uname,$udom);
9273: my $queryid=
1.821 raeburn 9274: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
9275: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 9276: my $reply = &get_query_reply($queryid);
9277: return $reply;
9278: }
9279:
1.899 raeburn 9280: # -------------------------- Update MySQL allusers table
9281:
9282: sub update_allusers_table {
9283: my ($uname,$udom,$names) = @_;
9284: my $homeserver = &homeserver($uname,$udom);
9285: my $queryid=
9286: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
9287: 'lastname='.&escape($names->{'lastname'}).'%%'.
9288: 'firstname='.&escape($names->{'firstname'}).'%%'.
9289: 'middlename='.&escape($names->{'middlename'}).'%%'.
9290: 'generation='.&escape($names->{'generation'}).'%%'.
9291: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
9292: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 9293: return;
1.899 raeburn 9294: }
9295:
1.508 raeburn 9296: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 9297:
9298: sub fetch_enrollment_query {
1.511 raeburn 9299: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 raeburn 9300: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 9301: my $maxtries = 1;
1.508 raeburn 9302: if ($context eq 'automated') {
9303: $homeserver = $perlvar{'lonHostID'};
1.1317 raeburn 9304: $sleep = 2;
9305: $loopmax = 100;
1.547 raeburn 9306: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 9307: } else {
9308: $homeserver = &homeserver($cnum,$dom);
9309: }
1.838 albertel 9310: my $host=&hostname($homeserver);
1.506 raeburn 9311: my $cmd = '';
1.1000 raeburn 9312: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 9313: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 9314: }
9315: $cmd =~ s/%%$//;
9316: $cmd = &escape($cmd);
9317: my $query = 'fetchenrollment';
1.620 albertel 9318: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 9319: unless ($queryid=~/^\Q$host\E\_/) {
9320: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
9321: return 'error: '.$queryid;
9322: }
1.1317 raeburn 9323: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9324: my $tries = 1;
9325: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 raeburn 9326: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 9327: $tries ++;
9328: }
1.526 raeburn 9329: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 9330: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 9331: } else {
1.901 albertel 9332: my @responses = split(/:/,$reply);
1.1322 raeburn 9333: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 9334: foreach my $line (@responses) {
9335: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 9336: $$replyref{$key} = $value;
9337: }
9338: } else {
1.1117 foxr 9339: my $pathname = LONCAPA::tempdir();
1.800 albertel 9340: foreach my $line (@responses) {
9341: my ($key,$value) = split(/=/,$line);
1.506 raeburn 9342: $$replyref{$key} = $value;
9343: if ($value > 0) {
1.800 albertel 9344: foreach my $item (@{$$affiliatesref{$key}}) {
9345: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 9346: my $destname = $pathname.'/'.$filename;
9347: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 9348: if ($xml_classlist =~ /^error/) {
9349: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
9350: } else {
1.1359 raeburn 9351: if ( open(FILE,">",$destname) ) {
1.506 raeburn 9352: print FILE &unescape($xml_classlist);
9353: close(FILE);
1.526 raeburn 9354: } else {
9355: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 9356: }
9357: }
9358: }
9359: }
9360: }
9361: }
9362: return 'ok';
9363: }
9364: return 'error';
9365: }
9366:
1.242 www 9367: sub get_query_reply {
1.1317 raeburn 9368: my ($queryid,$sleep,$loopmax) = @_;;
9369: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
9370: $sleep = 0.2;
9371: }
9372: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
9373: $loopmax = 100;
9374: }
1.1117 foxr 9375: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 9376: my $reply='';
1.1317 raeburn 9377: for (1..$loopmax) {
9378: sleep($sleep);
1.240 www 9379: if (-e $replyfile.'.end') {
1.1359 raeburn 9380: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 9381: $reply = join('',<$fh>);
9382: close($fh);
1.240 www 9383: } else { return 'error: reply_file_error'; }
1.242 www 9384: return &unescape($reply);
9385: }
1.240 www 9386: }
1.242 www 9387: return 'timeout:'.$queryid;
1.240 www 9388: }
9389:
9390: sub courselog_query {
1.241 www 9391: #
9392: # possible filters:
9393: # url: url or symb
9394: # username
9395: # domain
9396: # action: view, submit, grade
9397: # start: timestamp
9398: # end: timestamp
9399: #
1.240 www 9400: my (%filters)=@_;
1.620 albertel 9401: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 9402: if ($filters{'url'}) {
9403: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
9404: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
9405: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
9406: }
1.620 albertel 9407: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9408: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 9409: return &log_query($cname,$cdom,'courselog',%filters);
9410: }
9411:
9412: sub userlog_query {
1.858 raeburn 9413: #
9414: # possible filters:
9415: # action: log check role
9416: # start: timestamp
9417: # end: timestamp
9418: #
1.240 www 9419: my ($uname,$udom,%filters)=@_;
9420: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 9421: }
9422:
1.506 raeburn 9423: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
9424:
9425: sub auto_run {
1.508 raeburn 9426: my ($cnum,$cdom) = @_;
1.876 raeburn 9427: my $response = 0;
9428: my $settings;
9429: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
9430: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
9431: $settings = $domconfig{'autoenroll'};
9432: if ($settings->{'run'} eq '1') {
9433: $response = 1;
9434: }
9435: } else {
1.934 raeburn 9436: my $homeserver;
9437: if (&is_course($cdom,$cnum)) {
9438: $homeserver = &homeserver($cnum,$cdom);
9439: } else {
9440: $homeserver = &domain($cdom,'primary');
9441: }
9442: if ($homeserver ne 'no_host') {
9443: $response = &reply('autorun:'.$cdom,$homeserver);
9444: }
1.876 raeburn 9445: }
1.506 raeburn 9446: return $response;
9447: }
1.776 albertel 9448:
1.506 raeburn 9449: sub auto_get_sections {
1.508 raeburn 9450: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 9451: my $homeserver;
9452: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9453: $homeserver = &homeserver($cnum,$cdom);
9454: }
9455: if (!defined($homeserver)) {
9456: if ($cdom =~ /^$match_domain$/) {
9457: $homeserver = &domain($cdom,'primary');
9458: }
9459: }
9460: my @secs;
9461: if (defined($homeserver)) {
9462: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9463: unless ($response eq 'refused') {
9464: @secs = split(/:/,$response);
9465: }
1.506 raeburn 9466: }
9467: return @secs;
9468: }
1.776 albertel 9469:
1.506 raeburn 9470: sub auto_new_course {
1.1099 raeburn 9471: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 9472: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 9473: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 9474: return $response;
9475: }
1.776 albertel 9476:
1.506 raeburn 9477: sub auto_validate_courseID {
1.508 raeburn 9478: my ($cnum,$cdom,$inst_course_id) = @_;
9479: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 9480: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 9481: return $response;
9482: }
1.776 albertel 9483:
1.1007 raeburn 9484: sub auto_validate_instcode {
1.1020 raeburn 9485: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 9486: my ($homeserver,$response);
9487: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9488: $homeserver = &homeserver($cnum,$cdom);
9489: }
9490: if (!defined($homeserver)) {
9491: if ($cdom =~ /^$match_domain$/) {
9492: $homeserver = &domain($cdom,'primary');
9493: }
9494: }
1.1065 raeburn 9495: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9496: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 9497: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9498: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9499: }
9500:
1.1444 raeburn 9501: sub auto_validate_inst_crosslist {
9502: my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
9503: my ($homeserver,$response);
9504: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9505: $homeserver = &homeserver($cnum,$cdom);
9506: }
9507: if (!defined($homeserver)) {
9508: if ($cdom =~ /^$match_domain$/) {
9509: $homeserver = &domain($cdom,'primary');
9510: }
9511: }
9512: unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
9513: $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
9514: &escape($instcode).':'.&escape($inst_xlist).':'.
1.1445 raeburn 9515: &escape($coowner),$homeserver);
1.1444 raeburn 9516: }
9517: return $response;
9518: }
9519:
1.506 raeburn 9520: sub auto_create_password {
1.873 raeburn 9521: my ($cnum,$cdom,$authparam,$udom) = @_;
9522: my ($homeserver,$response);
1.506 raeburn 9523: my $create_passwd = 0;
9524: my $authchk = '';
1.873 raeburn 9525: if ($udom =~ /^$match_domain$/) {
9526: $homeserver = &domain($udom,'primary');
9527: }
9528: if ($homeserver eq '') {
9529: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9530: $homeserver = &homeserver($cnum,$cdom);
9531: }
9532: }
9533: if ($homeserver eq '') {
9534: $authchk = 'nodomain';
1.506 raeburn 9535: } else {
1.873 raeburn 9536: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9537: if ($response eq 'refused') {
9538: $authchk = 'refused';
9539: } else {
1.901 albertel 9540: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9541: }
1.506 raeburn 9542: }
9543: return ($authparam,$create_passwd,$authchk);
9544: }
9545:
1.706 raeburn 9546: sub auto_photo_permission {
9547: my ($cnum,$cdom,$students) = @_;
9548: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9549: my ($outcome,$perm_reqd,$conditions) =
9550: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9551: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9552: return (undef,undef);
9553: }
1.706 raeburn 9554: return ($outcome,$perm_reqd,$conditions);
9555: }
9556:
9557: sub auto_checkphotos {
9558: my ($uname,$udom,$pid) = @_;
9559: my $homeserver = &homeserver($uname,$udom);
9560: my ($result,$resulttype);
9561: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9562: &escape($uname).':'.&escape($pid),
9563: $homeserver));
1.709 albertel 9564: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9565: return (undef,undef);
9566: }
1.706 raeburn 9567: if ($outcome) {
9568: ($result,$resulttype) = split(/:/,$outcome);
9569: }
9570: return ($result,$resulttype);
9571: }
9572:
9573: sub auto_photochoice {
9574: my ($cnum,$cdom) = @_;
9575: my $homeserver = &homeserver($cnum,$cdom);
9576: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9577: &escape($cdom),
9578: $homeserver)));
1.709 albertel 9579: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9580: return (undef,undef);
9581: }
1.706 raeburn 9582: return ($update,$comment);
9583: }
9584:
9585: sub auto_photoupdate {
9586: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9587: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9588: my $host=&hostname($homeserver);
1.706 raeburn 9589: my $cmd = '';
9590: my $maxtries = 1;
1.800 albertel 9591: foreach my $affiliate (keys(%{$affiliatesref})) {
9592: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9593: }
9594: $cmd =~ s/%%$//;
9595: $cmd = &escape($cmd);
9596: my $query = 'institutionalphotos';
9597: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9598: unless ($queryid=~/^\Q$host\E\_/) {
9599: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9600: return 'error: '.$queryid;
9601: }
9602: my $reply = &get_query_reply($queryid);
9603: my $tries = 1;
9604: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9605: $reply = &get_query_reply($queryid);
9606: $tries ++;
9607: }
9608: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9609: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9610: } else {
9611: my @responses = split(/:/,$reply);
9612: my $outcome = shift(@responses);
9613: foreach my $item (@responses) {
9614: my ($key,$value) = split(/=/,$item);
9615: $$photo{$key} = $value;
9616: }
9617: return $outcome;
9618: }
9619: return 'error';
9620: }
9621:
1.521 raeburn 9622: sub auto_instcode_format {
1.793 albertel 9623: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9624: $cat_order) = @_;
1.521 raeburn 9625: my $courses = '';
1.772 raeburn 9626: my @homeservers;
1.521 raeburn 9627: if ($caller eq 'global') {
1.841 albertel 9628: my %servers = &get_servers($codedom,'library');
9629: foreach my $tryserver (keys(%servers)) {
9630: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9631: push(@homeservers,$tryserver);
9632: }
1.584 raeburn 9633: }
1.1022 raeburn 9634: } elsif ($caller eq 'requests') {
9635: if ($codedom =~ /^$match_domain$/) {
9636: my $chome = &domain($codedom,'primary');
9637: unless ($chome eq 'no_host') {
9638: push(@homeservers,$chome);
9639: }
9640: }
1.521 raeburn 9641: } else {
1.772 raeburn 9642: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9643: }
1.793 albertel 9644: foreach my $code (keys(%{$instcodes})) {
9645: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9646: }
9647: chop($courses);
1.772 raeburn 9648: my $ok_response = 0;
9649: my $response;
9650: while (@homeservers > 0 && $ok_response == 0) {
9651: my $server = shift(@homeservers);
9652: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9653: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9654: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9655: split(/:/,$response);
1.772 raeburn 9656: %{$codes} = (%{$codes},&str2hash($codes_str));
9657: push(@{$codetitles},&str2array($codetitles_str));
9658: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9659: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9660: $ok_response = 1;
9661: }
9662: }
9663: if ($ok_response) {
1.521 raeburn 9664: return 'ok';
1.772 raeburn 9665: } else {
9666: return $response;
1.521 raeburn 9667: }
9668: }
9669:
1.792 raeburn 9670: sub auto_instcode_defaults {
9671: my ($domain,$returnhash,$code_order) = @_;
9672: my @homeservers;
1.841 albertel 9673:
9674: my %servers = &get_servers($domain,'library');
9675: foreach my $tryserver (keys(%servers)) {
9676: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9677: push(@homeservers,$tryserver);
9678: }
1.792 raeburn 9679: }
1.841 albertel 9680:
1.792 raeburn 9681: my $response;
1.841 albertel 9682: foreach my $server (@homeservers) {
1.792 raeburn 9683: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9684: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9685:
9686: foreach my $pair (split(/\&/,$response)) {
9687: my ($name,$value)=split(/\=/,$pair);
9688: if ($name eq 'code_order') {
9689: @{$code_order} = split(/\&/,&unescape($value));
9690: } else {
9691: $returnhash->{&unescape($name)}=&unescape($value);
9692: }
9693: }
9694: return 'ok';
1.792 raeburn 9695: }
1.841 albertel 9696:
9697: return $response;
1.1003 raeburn 9698: }
9699:
9700: sub auto_possible_instcodes {
1.1007 raeburn 9701: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9702: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9703: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9704: return;
9705: }
1.1003 raeburn 9706: my (@homeservers,$uhome);
9707: if (defined(&domain($domain,'primary'))) {
9708: $uhome=&domain($domain,'primary');
9709: push(@homeservers,&domain($domain,'primary'));
9710: } else {
9711: my %servers = &get_servers($domain,'library');
9712: foreach my $tryserver (keys(%servers)) {
9713: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9714: push(@homeservers,$tryserver);
9715: }
9716: }
9717: }
9718: my $response;
9719: foreach my $server (@homeservers) {
9720: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9721: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9722: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9723: split(':',$response);
9724: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9725: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9726: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9727: my ($name,$value)=split('=',$item);
9728: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9729: }
9730: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9731: my ($name,$value)=split('=',$item);
9732: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9733: }
9734: return 'ok';
9735: }
9736: return $response;
9737: }
1.792 raeburn 9738:
1.1010 raeburn 9739: sub auto_courserequest_checks {
9740: my ($dom) = @_;
1.1020 raeburn 9741: my ($homeserver,%validations);
9742: if ($dom =~ /^$match_domain$/) {
9743: $homeserver = &domain($dom,'primary');
9744: }
9745: unless ($homeserver eq 'no_host') {
9746: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9747: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9748: my @items = split(/&/,$response);
9749: foreach my $item (@items) {
9750: my ($key,$value) = split('=',$item);
9751: $validations{&unescape($key)} = &thaw_unescape($value);
9752: }
9753: }
9754: }
1.1010 raeburn 9755: return %validations;
9756: }
9757:
1.1020 raeburn 9758: sub auto_courserequest_validation {
1.1255 raeburn 9759: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 9760: my ($homeserver,$response);
9761: if ($dom =~ /^$match_domain$/) {
9762: $homeserver = &domain($dom,'primary');
9763: }
1.1255 raeburn 9764: unless ($homeserver eq 'no_host') {
9765: my $customdata;
9766: if (ref($custominfo) eq 'HASH') {
9767: $customdata = &freeze_escape($custominfo);
9768: }
1.1020 raeburn 9769: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 9770: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 9771: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9772: $customdata,$homeserver));
1.1020 raeburn 9773: }
9774: return $response;
9775: }
9776:
1.777 albertel 9777: sub auto_validate_class_sec {
1.918 raeburn 9778: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 9779: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 9780: my $ownerlist;
9781: if (ref($owners) eq 'ARRAY') {
9782: $ownerlist = join(',',@{$owners});
9783: } else {
9784: $ownerlist = $owners;
9785: }
1.773 raeburn 9786: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 9787: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 9788: return $response;
9789: }
9790:
1.1460 ! raeburn 9791: sub auto_instsec_reformat {
! 9792: my ($cdom,$action,$instsecref) = @_;
! 9793: return unless(($action eq 'clutter') || ($action eq 'declutter'));
! 9794: my @homeservers;
! 9795: if (defined(&domain($cdom,'primary'))) {
! 9796: push(@homeservers,&domain($cdom,'primary'));
! 9797: } else {
! 9798: my %servers = &get_servers($cdom,'library');
! 9799: foreach my $tryserver (keys(%servers)) {
! 9800: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
! 9801: push(@homeservers,$tryserver);
! 9802: }
! 9803: }
! 9804: }
! 9805: my $response;
! 9806: my %reformatted = %{$instsecref};
! 9807: foreach my $server (@homeservers) {
! 9808: if (ref($instsecref) eq 'HASH') {
! 9809: my $info = &freeze_escape($instsecref);
! 9810: my $response=&reply('autoinstsecreformat:'.$cdom.':'.
! 9811: $action.':'.$info,$server);
! 9812: next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
! 9813: my @items = split(/&/,$response);
! 9814: foreach my $item (@items) {
! 9815: my ($key,$value) = split(/=/,$item);
! 9816: $reformatted{&unescape($key)} = &thaw_unescape($value);
! 9817: }
! 9818: }
! 9819: }
! 9820: return %reformatted;
! 9821: }
! 9822:
1.1367 raeburn 9823: sub auto_validate_instclasses {
9824: my ($cdom,$cnum,$owners,$classesref) = @_;
9825: my ($homeserver,%validations);
9826: $homeserver = &homeserver($cnum,$cdom);
9827: unless ($homeserver eq 'no_host') {
9828: my $ownerlist;
9829: if (ref($owners) eq 'ARRAY') {
9830: $ownerlist = join(',',@{$owners});
9831: } else {
9832: $ownerlist = $owners;
9833: }
9834: if (ref($classesref) eq 'HASH') {
9835: my $classes = &freeze_escape($classesref);
9836: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9837: ':'.$cdom.':'.$classes,$homeserver);
9838: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9839: my @items = split(/&/,$response);
9840: foreach my $item (@items) {
9841: my ($key,$value) = split('=',$item);
9842: $validations{&unescape($key)} = &thaw_unescape($value);
9843: }
9844: }
9845: }
9846: }
9847: return %validations;
9848: }
9849:
1.1248 raeburn 9850: sub auto_crsreq_update {
9851: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 9852: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 9853: my ($homeserver,%crsreqresponse);
9854: if ($cdom =~ /^$match_domain$/) {
9855: $homeserver = &domain($cdom,'primary');
9856: }
9857: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9858: my $info;
9859: if (ref($inbound) eq 'HASH') {
9860: $info = &freeze_escape($inbound);
9861: }
9862: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9863: ':'.&escape($action).':'.&escape($ownername).':'.
9864: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 9865: &escape($title).':'.&escape($code).':'.
9866: &escape($accessstart).':'.&escape($accessend).':'.$info,
9867: $homeserver);
1.1248 raeburn 9868: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9869: my @items = split(/&/,$response);
9870: foreach my $item (@items) {
9871: my ($key,$value) = split('=',$item);
9872: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9873: }
9874: }
9875: }
9876: return \%crsreqresponse;
9877: }
9878:
1.1305 raeburn 9879: sub auto_export_grades {
1.1309 raeburn 9880: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9881: my ($homeserver,%exportresponse);
9882: if ($cdom =~ /^$match_domain$/) {
9883: $homeserver = &domain($cdom,'primary');
9884: }
9885: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9886: my $info;
9887: if (ref($inforef) eq 'HASH') {
9888: $info = &freeze_escape($inforef);
9889: }
9890: if (ref($gradesref) eq 'HASH') {
9891: my $grades = &freeze_escape($gradesref);
9892: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9893: $info.':'.$grades,$homeserver);
9894: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9895: my @items = split(/&/,$response);
9896: foreach my $item (@items) {
9897: my ($key,$value) = split('=',$item);
9898: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9899: }
9900: }
9901: }
9902: }
9903: return \%exportresponse;
1.1305 raeburn 9904: }
9905:
1.1287 raeburn 9906: sub check_instcode_cloning {
9907: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9908: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9909: return;
9910: }
9911: my $canclone;
9912: if (@{$code_order} > 0) {
9913: my $instcoderegexp ='^';
9914: my @clonecodes = split(/\&/,$cloner);
9915: foreach my $item (@{$code_order}) {
9916: if (grep(/^\Q$item\E=/,@clonecodes)) {
9917: foreach my $pair (@clonecodes) {
9918: my ($key,$val) = split(/\=/,$pair,2);
9919: $val = &unescape($val);
9920: if ($key eq $item) {
9921: $instcoderegexp .= '('.$val.')';
9922: last;
9923: }
9924: }
9925: } else {
9926: $instcoderegexp .= $codedefaults->{$item};
9927: }
9928: }
9929: $instcoderegexp .= '$';
9930: my (@from,@to);
9931: eval {
9932: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9933: (@to) = ($clonetocode =~ /$instcoderegexp/);
9934: };
9935: if ((@from > 0) && (@to > 0)) {
9936: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9937: if (!@diffs) {
9938: $canclone = 1;
9939: }
9940: }
9941: }
9942: return $canclone;
9943: }
9944:
9945: sub default_instcode_cloning {
9946: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9947: my (%codedefaults,@code_order,$canclone);
9948: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9949: %codedefaults = %{$codedefaultsref};
9950: @code_order = @{$codeorderref};
9951: } elsif ($clonedom) {
9952: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9953: }
9954: if (($domdefclone) && (@code_order)) {
9955: my @clonecodes = split(/\+/,$domdefclone);
9956: my $instcoderegexp ='^';
9957: foreach my $item (@code_order) {
9958: if (grep(/^\Q$item\E$/,@clonecodes)) {
9959: $instcoderegexp .= '('.$codedefaults{$item}.')';
9960: } else {
9961: $instcoderegexp .= $codedefaults{$item};
9962: }
9963: }
9964: $instcoderegexp .= '$';
9965: my (@from,@to);
9966: eval {
9967: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9968: (@to) = ($clonetocode =~ /$instcoderegexp/);
9969: };
9970: if ((@from > 0) && (@to > 0)) {
9971: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9972: if (!@diffs) {
9973: $canclone = 1;
9974: }
9975: }
9976: }
9977: return $canclone;
9978: }
9979:
1.679 raeburn 9980: # ------------------------------------------------------- Course Group routines
9981:
9982: sub get_coursegroups {
1.809 raeburn 9983: my ($cdom,$cnum,$group,$namespace) = @_;
9984: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 9985: }
9986:
1.679 raeburn 9987: sub modify_coursegroup {
9988: my ($cdom,$cnum,$groupsettings) = @_;
9989: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9990: }
9991:
1.809 raeburn 9992: sub toggle_coursegroup_status {
9993: my ($cdom,$cnum,$group,$action) = @_;
9994: my ($from_namespace,$to_namespace);
9995: if ($action eq 'delete') {
9996: $from_namespace = 'coursegroups';
9997: $to_namespace = 'deleted_groups';
9998: } else {
9999: $from_namespace = 'deleted_groups';
10000: $to_namespace = 'coursegroups';
10001: }
10002: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 10003: if (my $tmp = &error(%curr_group)) {
10004: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10005: return ('read error',$tmp);
10006: } else {
10007: my %savedsettings = %curr_group;
1.809 raeburn 10008: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 10009: my $deloutcome;
10010: if ($result eq 'ok') {
1.809 raeburn 10011: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 10012: } else {
10013: return ('write error',$result);
10014: }
10015: if ($deloutcome eq 'ok') {
10016: return 'ok';
10017: } else {
10018: return ('delete error',$deloutcome);
10019: }
10020: }
10021: }
10022:
1.679 raeburn 10023: sub modify_group_roles {
1.957 raeburn 10024: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 10025: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10026: my $role = 'gr/'.&escape($userprivs);
10027: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 10028: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 10029: if ($result eq 'ok') {
10030: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10031: }
1.679 raeburn 10032: return $result;
10033: }
10034:
10035: sub modify_coursegroup_membership {
10036: my ($cdom,$cnum,$membership) = @_;
10037: my $result = &put('groupmembership',$membership,$cdom,$cnum);
10038: return $result;
10039: }
10040:
1.682 raeburn 10041: sub get_active_groups {
10042: my ($udom,$uname,$cdom,$cnum) = @_;
10043: my $now = time;
10044: my %groups = ();
10045: foreach my $key (keys(%env)) {
1.811 albertel 10046: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 10047: my ($start,$end) = split(/\./,$env{$key});
10048: if (($end!=0) && ($end<$now)) { next; }
10049: if (($start!=0) && ($start>$now)) { next; }
10050: if ($1 eq $cdom && $2 eq $cnum) {
10051: $groups{$3} = $env{$key} ;
10052: }
10053: }
10054: }
10055: return %groups;
10056: }
10057:
1.683 raeburn 10058: sub get_group_membership {
10059: my ($cdom,$cnum,$group) = @_;
10060: return(&dump('groupmembership',$cdom,$cnum,$group));
10061: }
10062:
10063: sub get_users_groups {
10064: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 10065: my @usersgroups;
1.683 raeburn 10066: my $cachetime=1800;
10067:
10068: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 10069: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10070: if (defined($cached)) {
1.734 albertel 10071: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 10072: } else {
10073: $grouplist = '';
1.816 raeburn 10074: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 10075: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 10076: my $access_end = $env{'course.'.$courseid.
10077: '.default_enrollment_end_date'};
10078: my $now = time;
10079: foreach my $key (keys(%roleshash)) {
10080: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10081: my $group = $1;
10082: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10083: my $start = $2;
10084: my $end = $1;
10085: if ($start == -1) { next; } # deleted from group
10086: if (($start!=0) && ($start>$now)) { next; }
10087: if (($end!=0) && ($end<$now)) {
10088: if ($access_end && $access_end < $now) {
10089: if ($access_end - $end < 86400) {
10090: push(@usersgroups,$group);
1.733 raeburn 10091: }
10092: }
1.817 raeburn 10093: next;
1.733 raeburn 10094: }
1.817 raeburn 10095: push(@usersgroups,$group);
1.683 raeburn 10096: }
10097: }
10098: }
1.817 raeburn 10099: @usersgroups = &sort_course_groups($courseid,@usersgroups);
10100: $grouplist = join(':',@usersgroups);
10101: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 10102: }
1.733 raeburn 10103: return @usersgroups;
1.683 raeburn 10104: }
10105:
10106: sub devalidate_getgroups_cache {
10107: my ($udom,$uname,$cdom,$cnum)=@_;
10108: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 10109:
1.683 raeburn 10110: my $hashid="$udom:$uname:$courseid";
10111: &devalidate_cache_new('getgroups',$hashid);
10112: }
10113:
1.12 www 10114: # ------------------------------------------------------------------ Plain Text
10115:
10116: sub plaintext {
1.988 raeburn 10117: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 10118: if ($short =~ m{^cr/}) {
1.758 albertel 10119: return (split('/',$short))[-1];
10120: }
1.742 raeburn 10121: if (!defined($cid)) {
10122: $cid = $env{'request.course.id'};
10123: }
10124: my %rolenames = (
1.1008 raeburn 10125: Course => 'std',
10126: Community => 'alt1',
1.1305 raeburn 10127: Placement => 'std',
1.742 raeburn 10128: );
1.1037 raeburn 10129: if ($cid ne '') {
10130: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10131: unless ($forcedefault) {
10132: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
10133: &Apache::lonlocal::mt_escape(\$roletext);
10134: return &Apache::lonlocal::mt($roletext);
10135: }
10136: }
10137: }
10138: if ((defined($type)) && (defined($rolenames{$type})) &&
10139: (defined($rolenames{$type})) &&
10140: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 10141: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 10142: } elsif ($cid ne '') {
10143: my $crstype = $env{'course.'.$cid.'.type'};
10144: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10145: (defined($prp{$short}{$rolenames{$crstype}}))) {
10146: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10147: }
1.742 raeburn 10148: }
1.1037 raeburn 10149: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 10150: }
10151:
10152: # ----------------------------------------------------------------- Assign Role
10153:
10154: sub assignrole {
1.957 raeburn 10155: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10156: $context)=@_;
1.21 www 10157: my $mrole;
10158: if ($role =~ /^cr\//) {
1.393 www 10159: my $cwosec=$url;
1.811 albertel 10160: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 10161: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 10162: my $refused = 1;
10163: if ($context eq 'requestcourses') {
10164: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10165: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10166: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10167: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10168: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10169: if ($crsenv{'internal.courseowner'} eq
10170: $env{'user.name'}.':'.$env{'user.domain'}) {
10171: $refused = '';
10172: }
10173: }
10174: }
10175: }
10176: }
10177: if ($refused) {
10178: &logthis('Refused custom assignrole: '.
10179: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10180: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10181: return 'refused';
10182: }
1.104 www 10183: }
1.21 www 10184: $mrole='cr';
1.678 raeburn 10185: } elsif ($role =~ /^gr\//) {
10186: my $cwogrp=$url;
1.811 albertel 10187: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 10188: unless (&allowed('mdg',$cwogrp)) {
10189: &logthis('Refused group assignrole: '.
10190: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10191: $env{'user.name'}.' at '.$env{'user.domain'});
10192: return 'refused';
10193: }
10194: $mrole='gr';
1.21 www 10195: } else {
1.82 www 10196: my $cwosec=$url;
1.811 albertel 10197: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 10198: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10199: my $refused;
10200: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
10201: if (!(&allowed('c'.$role,$url))) {
10202: $refused = 1;
10203: }
10204: } else {
10205: $refused = 1;
10206: }
1.947 raeburn 10207: if ($refused) {
1.1045 raeburn 10208: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377 raeburn 10209: if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045 raeburn 10210: my %crsenv;
10211: if ($role eq 'cc' || $role eq 'co') {
10212: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10213: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10214: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10215: if ($crsenv{'internal.courseowner'} eq
10216: $env{'user.name'}.':'.$env{'user.domain'}) {
10217: $refused = '';
10218: }
10219: }
10220: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
10221: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10222: if ($crsenv{'internal.courseowner'} eq
10223: $env{'user.name'}.':'.$env{'user.domain'}) {
10224: $refused = '';
10225: }
10226: }
10227: }
10228: }
1.1368 raeburn 10229: } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10230: if ($role eq 'st') {
10231: $refused = '';
1.1377 raeburn 10232: } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368 raeburn 10233: $refused = '';
10234: }
1.1017 raeburn 10235: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 10236: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 10237: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 10238: my $wrongcc;
10239: if ($cnum =~ /^$match_community$/) {
10240: $wrongcc = 1 if ($role eq 'cc');
10241: } else {
10242: $wrongcc = 1 if ($role eq 'co');
10243: }
10244: unless ($wrongcc) {
10245: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10246: if ($crsenv{'internal.courseowner'} eq
10247: $env{'user.name'}.':'.$env{'user.domain'}) {
10248: $refused = '';
10249: }
1.1017 raeburn 10250: }
10251: }
1.1183 raeburn 10252: } elsif ($context eq 'requestauthor') {
10253: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
10254: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10255: if ($env{'environment.requestauthor'} eq 'automatic') {
10256: $refused = '';
10257: } else {
10258: my %domdefaults = &get_domain_defaults($udom);
10259: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10260: my $checkbystatus;
10261: if ($env{'user.adv'}) {
10262: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10263: if ($disposition eq 'automatic') {
10264: $refused = '';
10265: } elsif ($disposition eq '') {
10266: $checkbystatus = 1;
10267: }
10268: } else {
10269: $checkbystatus = 1;
10270: }
10271: if ($checkbystatus) {
10272: if ($env{'environment.inststatus'}) {
10273: my @inststatuses = split(/,/,$env{'environment.inststatus'});
10274: foreach my $type (@inststatuses) {
10275: if (($type ne '') &&
10276: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10277: $refused = '';
10278: }
10279: }
10280: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10281: $refused = '';
10282: }
10283: }
10284: }
10285: }
10286: }
1.1017 raeburn 10287: }
10288: if ($refused) {
1.947 raeburn 10289: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10290: ' '.$role.' '.$end.' '.$start.' by '.
10291: $env{'user.name'}.' at '.$env{'user.domain'});
10292: return 'refused';
10293: }
1.932 raeburn 10294: }
1.1131 raeburn 10295: } elsif ($role eq 'au') {
10296: if ($url ne '/'.$udom.'/') {
10297: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10298: ' to assign author role for '.$uname.':'.$udom.
10299: ' in domain: '.$url.' refused (wrong domain).');
10300: return 'refused';
10301: }
1.104 www 10302: }
1.21 www 10303: $mrole=$role;
10304: }
1.620 albertel 10305: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 10306: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 10307: if ($end) { $command.='_'.$end; }
1.21 www 10308: if ($start) {
10309: if ($end) {
1.81 www 10310: $command.='_'.$start;
1.21 www 10311: } else {
1.81 www 10312: $command.='_0_'.$start;
1.21 www 10313: }
10314: }
1.739 raeburn 10315: my $origstart = $start;
10316: my $origend = $end;
1.957 raeburn 10317: my $delflag;
1.357 www 10318: # actually delete
10319: if ($deleteflag) {
1.373 www 10320: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 10321: # modify command to delete the role
1.620 albertel 10322: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 10323: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 10324: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 10325: # set start and finish to negative values for userrolelog
10326: $start=-1;
10327: $end=-1;
1.957 raeburn 10328: $delflag = 1;
1.357 www 10329: }
10330: }
10331: # send command
1.349 www 10332: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 10333: # log new user role if status is ok
1.349 www 10334: if ($answer eq 'ok') {
1.663 raeburn 10335: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 10336: if (($role eq 'cc') || ($role eq 'in') ||
10337: ($role eq 'ep') || ($role eq 'ad') ||
10338: ($role eq 'ta') || ($role eq 'st') ||
10339: ($role=~/^cr/) || ($role eq 'gr') ||
10340: ($role eq 'co')) {
1.1200 raeburn 10341: # for course roles, perform group memberships changes triggered by role change.
10342: unless ($role =~ /^gr/) {
10343: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10344: $origstart,$selfenroll,$context);
10345: }
1.1184 raeburn 10346: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10347: $selfenroll,$context);
10348: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334 raeburn 10349: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10350: ($role eq 'da')) {
1.1184 raeburn 10351: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10352: $context);
10353: } elsif (($role eq 'ca') || ($role eq 'aa')) {
10354: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10355: $context);
10356: }
1.1053 raeburn 10357: if ($role eq 'cc') {
10358: &autoupdate_coowners($url,$end,$start,$uname,$udom);
10359: }
1.349 www 10360: }
10361: return $answer;
1.169 harris41 10362: }
10363:
1.1053 raeburn 10364: sub autoupdate_coowners {
10365: my ($url,$end,$start,$uname,$udom) = @_;
10366: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10367: if (($cdom ne '') && ($cnum ne '')) {
10368: my $now = time;
10369: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10370: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10371: my %coursehash = &coursedescription($cdom.'_'.$cnum);
10372: my $instcode = $coursehash{'internal.coursecode'};
1.1444 raeburn 10373: my $xlists = $coursehash{'internal.crosslistings'};
1.1053 raeburn 10374: if ($instcode ne '') {
1.1056 raeburn 10375: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10376: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 10377: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 10378: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1444 raeburn 10379: unless ($result eq 'valid') {
10380: if ($xlists ne '') {
10381: foreach my $xlist (split(',',$xlists)) {
10382: my ($inst_crosslist,$lcsec) = split(':',$xlist);
10383: $result =
1.1446 raeburn 10384: &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10385: $inst_crosslist,$uname.':'.$udom);
10386: last if ($result eq 'valid');
1.1444 raeburn 10387: }
10388: }
10389: }
1.1056 raeburn 10390: if ($result eq 'valid') {
10391: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 10392: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10393: push(@newcoowners,$coowner);
10394: }
10395: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10396: push(@newcoowners,$uname.':'.$udom);
10397: }
10398: @newcoowners = sort(@newcoowners);
10399: } else {
10400: push(@newcoowners,$uname.':'.$udom);
10401: }
1.1444 raeburn 10402: } elsif ($coursehash{'internal.co-owners'}) {
10403: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10404: unless ($coowner eq $uname.':'.$udom) {
10405: push(@newcoowners,$coowner);
1.1053 raeburn 10406: }
1.1444 raeburn 10407: }
10408: unless (@newcoowners > 0) {
10409: $delcoowners = 1;
10410: $coowners = '';
1.1053 raeburn 10411: }
10412: }
10413: if (@newcoowners || $delcoowners) {
10414: &store_coowners($cdom,$cnum,$coursehash{'home'},
10415: $delcoowners,@newcoowners);
10416: }
10417: }
10418: }
10419: }
10420: }
10421: }
10422: }
10423:
10424: sub store_coowners {
10425: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10426: my $cid = $cdom.'_'.$cnum;
10427: my ($coowners,$delresult,$putresult);
10428: if (@newcoowners) {
10429: $coowners = join(',',@newcoowners);
10430: my %coownershash = (
10431: 'internal.co-owners' => $coowners,
10432: );
10433: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10434: if ($putresult eq 'ok') {
10435: if ($env{'course.'.$cid.'.num'} eq $cnum) {
10436: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10437: }
10438: }
10439: }
10440: if ($delcoowners) {
10441: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10442: if ($delresult eq 'ok') {
10443: if ($env{'course.'.$cid.'.internal.co-owners'}) {
10444: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10445: }
10446: }
10447: }
10448: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10449: my %crsinfo =
10450: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10451: if (ref($crsinfo{$cid}) eq 'HASH') {
10452: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10453: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10454: }
10455: }
10456: }
10457:
1.169 harris41 10458: # -------------------------------------------------- Modify user authentication
1.197 www 10459: # Overrides without validation
10460:
1.169 harris41 10461: sub modifyuserauth {
10462: my ($udom,$uname,$umode,$upass)=@_;
10463: my $uhome=&homeserver($uname,$udom);
1.1409 raeburn 10464: my $allowed;
10465: if (&allowed('mau',$udom)) {
10466: $allowed = 1;
10467: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10468: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10469: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10470: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10471: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10472: if (($cdom ne '') && ($cnum ne '')) {
10473: my $is_owner = &is_course_owner($cdom,$cnum);
10474: if ($is_owner) {
10475: $allowed = 1;
10476: }
10477: }
10478: }
10479: unless ($allowed) { return 'refused'; }
1.197 www 10480: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 10481: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10482: ' in domain '.$env{'request.role.domain'});
1.169 harris41 10483: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10484: &escape($upass),$uhome);
1.1434 raeburn 10485: my $ip = &get_requestor_ip();
1.620 albertel 10486: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 10487: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1434 raeburn 10488: '(Remote '.$ip.'): '.$reply);
1.197 www 10489: &log($udom,,$uname,$uhome,
1.620 albertel 10490: 'Authentication changed by '.$env{'user.domain'}.', '.
10491: $env{'user.name'}.', '.$umode.
1.1435 raeburn 10492: '(Remote '.$ip.'): '.$reply);
1.169 harris41 10493: unless ($reply eq 'ok') {
1.197 www 10494: &logthis('Authentication mode error: '.$reply);
1.169 harris41 10495: return 'error: '.$reply;
10496: }
1.170 harris41 10497: return 'ok';
1.80 www 10498: }
10499:
1.81 www 10500: # --------------------------------------------------------------- Modify a user
1.80 www 10501:
1.81 www 10502: sub modifyuser {
1.206 matthew 10503: my ($udom, $uname, $uid,
10504: $umode, $upass, $first,
10505: $middle, $last, $gene,
1.1058 raeburn 10506: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 10507: $udom= &LONCAPA::clean_domain($udom);
10508: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 10509: my $showcandelete = 'none';
10510: if (ref($candelete) eq 'ARRAY') {
10511: if (@{$candelete} > 0) {
10512: $showcandelete = join(', ',@{$candelete});
10513: }
10514: }
1.81 www 10515: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 10516: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 10517: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 10518: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10519: ' desiredhome not specified').
1.620 albertel 10520: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10521: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 10522: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 10523: my $newuser;
10524: if ($uhome eq 'no_host') {
10525: $newuser = 1;
1.1368 raeburn 10526: unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10527: ($umode eq 'lti')) {
10528: return 'error: more information needed to create new user';
10529: }
1.1075 raeburn 10530: }
1.80 www 10531: # ----------------------------------------------------------------- Create User
1.406 albertel 10532: if (($uhome eq 'no_host') &&
1.1368 raeburn 10533: (($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80 www 10534: my $unhome='';
1.844 albertel 10535: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 10536: $unhome = $desiredhome;
1.620 albertel 10537: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10538: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 10539: } else { # load balancing routine for determining $unhome
1.81 www 10540: my $loadm=10000000;
1.841 albertel 10541: my %servers = &get_servers($udom,'library');
10542: foreach my $tryserver (keys(%servers)) {
10543: my $answer=reply('load',$tryserver);
10544: if (($answer=~/\d+/) && ($answer<$loadm)) {
10545: $loadm=$answer;
10546: $unhome=$tryserver;
10547: }
1.80 www 10548: }
10549: }
10550: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 10551: return 'error: unable to find a home server for '.$uname.
10552: ' in domain '.$udom;
1.80 www 10553: }
10554: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10555: &escape($upass),$unhome);
10556: unless ($reply eq 'ok') {
10557: return 'error: '.$reply;
10558: }
1.230 stredwic 10559: $uhome=&homeserver($uname,$udom,'true');
1.80 www 10560: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 10561: return 'error: unable verify users home machine.';
1.80 www 10562: }
1.209 matthew 10563: } # End of creation of new user
1.80 www 10564: # ---------------------------------------------------------------------- Add ID
10565: if ($uid) {
10566: $uid=~tr/A-Z/a-z/;
10567: my %uidhash=&idrget($udom,$uname);
1.196 www 10568: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10569: && (!$forceid)) {
1.80 www 10570: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10571: return 'error: user id "'.$uid.'" does not match '.
10572: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10573: }
10574: } else {
1.1300 raeburn 10575: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 10576: }
10577: }
10578: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10579: my @tmp=&get('environment',
1.899 raeburn 10580: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10581: 'permanentemail','inststatus'],
1.134 albertel 10582: $udom,$uname);
1.1075 raeburn 10583: my (%names,%oldnames);
1.313 matthew 10584: if ($tmp[0] =~ m/^error:.*/) {
10585: %names=();
10586: } else {
10587: %names = @tmp;
1.1075 raeburn 10588: %oldnames = %names;
1.313 matthew 10589: }
1.388 www 10590: #
1.1058 raeburn 10591: # If name, email and/or uid are blank (e.g., because an uploaded file
10592: # of users did not contain them), do not overwrite existing values
10593: # unless field is in $candelete array ref.
10594: #
10595:
10596: my @fields = ('firstname','middlename','lastname','generation',
10597: 'permanentemail','id');
10598: my %newvalues;
10599: if (ref($candelete) eq 'ARRAY') {
10600: foreach my $field (@fields) {
10601: if (grep(/^\Q$field\E$/,@{$candelete})) {
10602: if ($field eq 'firstname') {
10603: $names{$field} = $first;
10604: } elsif ($field eq 'middlename') {
10605: $names{$field} = $middle;
10606: } elsif ($field eq 'lastname') {
10607: $names{$field} = $last;
10608: } elsif ($field eq 'generation') {
10609: $names{$field} = $gene;
10610: } elsif ($field eq 'permanentemail') {
10611: $names{$field} = $email;
10612: } elsif ($field eq 'id') {
10613: $names{$field} = $uid;
10614: }
10615: }
10616: }
10617: }
1.388 www 10618: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10619: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10620: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10621: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10622: if ($email) {
10623: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10624: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10625: }
1.899 raeburn 10626: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10627: if (defined($inststatus)) {
10628: $names{'inststatus'} = '';
10629: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10630: if (ref($usertypes) eq 'HASH') {
10631: my @okstatuses;
10632: foreach my $item (split(/:/,$inststatus)) {
10633: if (defined($usertypes->{$item})) {
10634: push(@okstatuses,$item);
10635: }
10636: }
10637: if (@okstatuses) {
10638: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10639: }
10640: }
10641: }
1.1075 raeburn 10642: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10643: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10644: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10645: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10646: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10647: } else {
10648: $logmsg .= ' during self creation';
10649: }
1.1075 raeburn 10650: my $changed;
10651: if ($newuser) {
10652: $changed = 1;
10653: } else {
10654: foreach my $field (@fields) {
10655: if ($names{$field} ne $oldnames{$field}) {
10656: $changed = 1;
10657: last;
10658: }
10659: }
10660: }
10661: unless ($changed) {
10662: $logmsg = 'No changes in user information needed for: '.$logmsg;
10663: &logthis($logmsg);
10664: return 'ok';
10665: }
10666: my $reply = &put('environment', \%names, $udom,$uname);
10667: if ($reply ne 'ok') {
10668: return 'error: '.$reply;
10669: }
1.1087 raeburn 10670: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10671: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10672: }
1.1075 raeburn 10673: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10674: &devalidate_cache_new('namescache',$uname.':'.$udom);
10675: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10676: &logthis($logmsg);
1.134 albertel 10677: return 'ok';
1.80 www 10678: }
10679:
1.81 www 10680: # -------------------------------------------------------------- Modify student
1.80 www 10681:
1.81 www 10682: sub modifystudent {
10683: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10684: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 10685: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10686: if (!$cid) {
1.620 albertel 10687: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10688: return 'not_in_class';
10689: }
1.80 www 10690: }
10691: # --------------------------------------------------------------- Make the user
1.81 www 10692: my $reply=&modifyuser
1.209 matthew 10693: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10694: $desiredhome,$email,$inststatus);
1.80 www 10695: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10696: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 10697: # student's environment
1.297 matthew 10698: $uid = undef if (!$forceid);
1.455 albertel 10699: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 10700: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 10701: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10702: return $reply;
10703: }
10704:
10705: sub modify_student_enrollment {
1.1216 raeburn 10706: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314 raeburn 10707: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10708: my ($cdom,$cnum,$chome);
10709: if (!$cid) {
1.620 albertel 10710: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10711: return 'not_in_class';
10712: }
1.620 albertel 10713: $cdom=$env{'course.'.$cid.'.domain'};
10714: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10715: } else {
10716: ($cdom,$cnum)=split(/_/,$cid);
10717: }
1.620 albertel 10718: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10719: if (!$chome) {
1.457 raeburn 10720: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10721: }
1.455 albertel 10722: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10723: # Make sure the user exists
1.81 www 10724: my $uhome=&homeserver($uname,$udom);
10725: if (($uhome eq '') || ($uhome eq 'no_host')) {
10726: return 'error: no such user';
10727: }
1.297 matthew 10728: # Get student data if we were not given enough information
10729: if (!defined($first) || $first eq '' ||
10730: !defined($last) || $last eq '' ||
10731: !defined($uid) || $uid eq '' ||
10732: !defined($middle) || $middle eq '' ||
10733: !defined($gene) || $gene eq '') {
1.294 matthew 10734: # They did not supply us with enough data to enroll the student, so
10735: # we need to pick up more information.
1.297 matthew 10736: my %tmp = &get('environment',
1.294 matthew 10737: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10738: ,$udom,$uname);
10739:
1.800 albertel 10740: #foreach my $key (keys(%tmp)) {
10741: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10742: #}
1.294 matthew 10743: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10744: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10745: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10746: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10747: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10748: }
1.556 albertel 10749: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10750: my $user = "$uname:$udom";
10751: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10752: my $reply=cput('classlist',
1.1148 raeburn 10753: {$user =>
1.1314 raeburn 10754: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 10755: $cdom,$cnum);
1.1148 raeburn 10756: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10757: &devalidate_getsection_cache($udom,$uname,$cid);
10758: } else {
1.81 www 10759: return 'error: '.$reply;
10760: }
1.297 matthew 10761: # Add student role to user
1.83 www 10762: my $uurl='/'.$cid;
1.81 www 10763: $uurl=~s/\_/\//g;
10764: if ($usec) {
10765: $uurl.='/'.$usec;
10766: }
1.1148 raeburn 10767: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10768: $selfenroll,$context);
10769: if ($result ne 'ok') {
10770: if ($old_entry{$user} ne '') {
10771: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10772: } else {
10773: $reply = &del('classlist',[$user],$cdom,$cnum);
10774: }
10775: }
10776: return $result;
1.21 www 10777: }
10778:
1.556 albertel 10779: sub format_name {
10780: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10781: my $name;
10782: if ($first ne 'lastname') {
10783: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10784: } else {
10785: if ($lastname=~/\S/) {
10786: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10787: $name=~s/\s+,/,/;
10788: } else {
10789: $name.= $firstname.' '.$middlename.' '.$generation;
10790: }
10791: }
10792: $name=~s/^\s+//;
10793: $name=~s/\s+$//;
10794: $name=~s/\s+/ /g;
10795: return $name;
10796: }
10797:
1.84 www 10798: # ------------------------------------------------- Write to course preferences
10799:
10800: sub writecoursepref {
10801: my ($courseid,%prefs)=@_;
10802: $courseid=~s/^\///;
10803: $courseid=~s/\_/\//g;
10804: my ($cdomain,$cnum)=split(/\//,$courseid);
10805: my $chome=homeserver($cnum,$cdomain);
10806: if (($chome eq '') || ($chome eq 'no_host')) {
10807: return 'error: no such course';
10808: }
10809: my $cstring='';
1.800 albertel 10810: foreach my $pref (keys(%prefs)) {
10811: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 10812: }
1.84 www 10813: $cstring=~s/\&$//;
10814: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10815: }
10816:
10817: # ---------------------------------------------------------- Make/modify course
10818:
10819: sub createcourse {
1.741 raeburn 10820: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1423 raeburn 10821: $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84 www 10822: $url=&declutter($url);
10823: my $cid='';
1.1028 raeburn 10824: if ($context eq 'requestcourses') {
10825: my $can_create = 0;
10826: my ($ownername,$ownerdom) = split(':',$course_owner);
10827: if ($udom eq $ownerdom) {
1.1423 raeburn 10828: my $reload;
10829: if (($callercontext eq 'auto') &&
10830: ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
10831: $reload = 'reload';
10832: }
10833: if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028 raeburn 10834: $context)) {
10835: $can_create = 1;
10836: }
10837: } else {
10838: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10839: $category);
10840: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10841: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10842: if (@curr > 0) {
10843: my @options = qw(approval validate autolimit);
10844: my $optregex = join('|',@options);
10845: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10846: $can_create = 1;
10847: }
10848: }
10849: }
10850: }
10851: if ($can_create) {
10852: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10853: unless (&allowed('ccc',$udom)) {
10854: return 'refused';
10855: }
1.1017 raeburn 10856: }
10857: } else {
10858: return 'refused';
10859: }
1.1028 raeburn 10860: } elsif (!&allowed('ccc',$udom)) {
10861: return 'refused';
1.84 www 10862: }
1.1011 raeburn 10863: # --------------------------------------------------------------- Get Unique ID
10864: my $uname;
10865: if ($cnum =~ /^$match_courseid$/) {
10866: my $chome=&homeserver($cnum,$udom,'true');
10867: if (($chome eq '') || ($chome eq 'no_host')) {
10868: $uname = $cnum;
10869: } else {
1.1038 raeburn 10870: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10871: }
10872: } else {
1.1038 raeburn 10873: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10874: }
10875: return $uname if ($uname =~ /^error/);
10876: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 10877: if (!defined($course_server)) {
10878: if (defined(&domain($udom,'primary'))) {
10879: $course_server = &domain($udom,'primary');
10880: } else {
10881: $course_server = $env{'user.home'};
10882: }
10883: }
10884: my %host_servers =
10885: &Apache::lonnet::get_servers($udom,'library');
10886: unless ($host_servers{$course_server}) {
10887: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 10888: }
1.84 www 10889: # ------------------------------------------------------------- Make the course
10890: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 10891: $course_server);
1.84 www 10892: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 10893: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 10894: if (($uhome eq '') || ($uhome eq 'no_host')) {
10895: return 'error: no such course';
10896: }
1.271 www 10897: # ----------------------------------------------------------------- Course made
1.516 raeburn 10898: # log existence
1.1029 raeburn 10899: my $now = time;
1.918 raeburn 10900: my $newcourse = {
10901: $udom.'_'.$uname => {
1.921 raeburn 10902: description => $description,
10903: inst_code => $inst_code,
10904: owner => $course_owner,
10905: type => $crstype,
1.1029 raeburn 10906: creator => $env{'user.name'}.':'.
10907: $env{'user.domain'},
10908: created => $now,
10909: context => $context,
1.918 raeburn 10910: },
10911: };
1.921 raeburn 10912: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 10913: # set toplevel url
1.271 www 10914: my $topurl=$url;
10915: unless ($nonstandard) {
10916: # ------------------------------------------ For standard courses, make top url
10917: my $mapurl=&clutter($url);
1.278 www 10918: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 10919: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 10920: <map>
10921: <resource id="1" type="start"></resource>
10922: <resource id="2" src="$mapurl"></resource>
10923: <resource id="3" type="finish"></resource>
10924: <link index="1" from="1" to="2"></link>
10925: <link index="2" from="2" to="3"></link>
10926: </map>
10927: ENDINITMAP
10928: $topurl=&declutter(
1.638 albertel 10929: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 10930: );
10931: }
10932: # ----------------------------------------------------------- Write preferences
1.84 www 10933: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 10934: ('description' => $description,
10935: 'url' => $topurl,
10936: 'internal.creator' => $env{'user.name'}.':'.
10937: $env{'user.domain'},
10938: 'internal.created' => $now,
10939: 'internal.creationcontext' => $context)
10940: );
1.84 www 10941: return '/'.$udom.'/'.$uname;
10942: }
10943:
1.1011 raeburn 10944: # ------------------------------------------------------------------- Create ID
10945: sub generate_coursenum {
1.1038 raeburn 10946: my ($udom,$crstype) = @_;
1.1011 raeburn 10947: my $domdesc = &domain($udom);
10948: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 10949: my $first;
10950: if ($crstype eq 'Community') {
10951: $first = '0';
10952: } else {
10953: $first = int(1+rand(9));
10954: }
10955: my $uname=$first.
1.1011 raeburn 10956: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10957: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10958: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10959: # ----------------------------------------------- Make sure that does not exist
10960: my $uhome=&homeserver($uname,$udom,'true');
10961: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 10962: if ($crstype eq 'Community') {
10963: $first = '0';
10964: } else {
10965: $first = int(1+rand(9));
10966: }
10967: $uname=$first.
1.1011 raeburn 10968: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10969: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10970: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10971: $uhome=&homeserver($uname,$udom,'true');
10972: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10973: return 'error: unable to generate unique course-ID';
10974: }
10975: }
10976: return $uname;
10977: }
10978:
1.813 albertel 10979: sub is_course {
1.1167 droeschl 10980: my ($cdom, $cnum) = scalar(@_) == 1 ?
10981: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
10982:
1.1381 raeburn 10983: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10984: my $uhome=&homeserver($cnum,$cdom);
10985: my $iscourse;
10986: if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382 raeburn 10987: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381 raeburn 10988: } else {
10989: my $hashid = $cdom.':'.$cnum;
10990: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10991: unless (defined($cached)) {
10992: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10993: $cnum,undef,undef,'.');
10994: $iscourse = 0;
10995: if (exists($courses{$cdom.'_'.$cnum})) {
10996: $iscourse = 1;
10997: }
10998: &do_cache_new('iscourse',$hashid,$iscourse,3600);
10999: }
11000: }
11001: return unless ($iscourse);
1.1167 droeschl 11002: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 11003: }
11004:
1.1015 raeburn 11005: sub store_userdata {
11006: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 11007: my $result;
1.1016 raeburn 11008: if ($datakey ne '') {
1.1013 raeburn 11009: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 11010: if ($udom eq '' || $uname eq '') {
11011: $udom = $env{'user.domain'};
11012: $uname = $env{'user.name'};
11013: }
11014: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 11015: if (($uhome eq '') || ($uhome eq 'no_host')) {
11016: $result = 'error: no_host';
11017: } else {
1.1434 raeburn 11018: $storehash->{'ip'} = &get_requestor_ip();
1.1013 raeburn 11019: $storehash->{'host'} = $perlvar{'lonHostID'};
11020:
11021: my $namevalue='';
11022: foreach my $key (keys(%{$storehash})) {
11023: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11024: }
11025: $namevalue=~s/\&$//;
1.1224 raeburn 11026: unless ($namespace eq 'courserequests') {
11027: $datakey = &escape($datakey);
11028: }
1.1105 raeburn 11029: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
11030: $namevalue,$uhome);
1.1013 raeburn 11031: }
11032: } else {
11033: $result = 'error: data to store was not a hash reference';
11034: }
11035: } else {
11036: $result= 'error: invalid requestkey';
11037: }
11038: return $result;
11039: }
11040:
1.21 www 11041: # ---------------------------------------------------------- Assign Custom Role
11042:
11043: sub assigncustomrole {
1.957 raeburn 11044: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11045: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 11046: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 11047: }
11048:
11049: # ----------------------------------------------------------------- Revoke Role
11050:
11051: sub revokerole {
1.957 raeburn 11052: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11053: my $now=time;
1.965 raeburn 11054: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 11055: }
11056:
11057: # ---------------------------------------------------------- Revoke Custom Role
11058:
11059: sub revokecustomrole {
1.957 raeburn 11060: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 11061: my $now=time;
1.357 www 11062: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 11063: $deleteflag,$selfenroll,$context);
1.17 www 11064: }
11065:
1.533 banghart 11066: # ------------------------------------------------------------ Disk usage
1.535 albertel 11067: sub diskusage {
1.955 raeburn 11068: my ($udom,$uname,$directorypath,$getpropath)=@_;
11069: $directorypath =~ s/\/$//;
11070: my $listing=&reply('du2:'.&escape($directorypath).':'
11071: .&escape($getpropath).':'.&escape($uname).':'
11072: .&escape($udom),homeserver($uname,$udom));
11073: if ($listing eq 'unknown_cmd') {
11074: if ($getpropath) {
11075: $directorypath = &propath($udom,$uname).'/'.$directorypath;
11076: }
11077: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11078: }
1.514 albertel 11079: return $listing;
1.512 banghart 11080: }
11081:
1.566 banghart 11082: sub is_locked {
1.1096 raeburn 11083: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 11084: my @check;
11085: my $is_locked;
1.1093 raeburn 11086: push (@check,$file_name);
1.613 albertel 11087: my %locked = &get('file_permissions',\@check,
1.620 albertel 11088: $env{'user.domain'},$env{'user.name'});
1.615 albertel 11089: my ($tmp)=keys(%locked);
11090: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 11091:
1.566 banghart 11092: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 11093: $is_locked = 'false';
11094: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 11095: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 11096: $is_locked = 'true';
1.1096 raeburn 11097: if (ref($which) eq 'ARRAY') {
11098: push(@{$which},$entry);
11099: } else {
11100: last;
11101: }
1.745 raeburn 11102: }
11103: }
1.566 banghart 11104: } else {
11105: $is_locked = 'false';
11106: }
1.1093 raeburn 11107: return $is_locked;
1.566 banghart 11108: }
11109:
1.759 albertel 11110: sub declutter_portfile {
11111: my ($file) = @_;
1.833 albertel 11112: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 11113: return $file;
11114: }
11115:
1.559 banghart 11116: # ------------------------------------------------------------- Mark as Read Only
11117:
11118: sub mark_as_readonly {
11119: my ($domain,$user,$files,$what) = @_;
1.613 albertel 11120: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11121: my ($tmp)=keys(%current_permissions);
11122: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 11123: foreach my $file (@{$files}) {
1.759 albertel 11124: $file = &declutter_portfile($file);
1.561 banghart 11125: push(@{$current_permissions{$file}},$what);
1.559 banghart 11126: }
1.613 albertel 11127: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11128: return;
11129: }
11130:
1.572 banghart 11131: # ------------------------------------------------------------Save Selected Files
11132:
11133: sub save_selected_files {
11134: my ($user, $path, @files) = @_;
11135: my $filename = $user."savedfiles";
1.573 banghart 11136: my @other_files = &files_not_in_path($user, $path);
1.1359 raeburn 11137: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 11138: foreach my $file (@files) {
1.620 albertel 11139: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 11140: }
11141: foreach my $file (@other_files) {
1.574 banghart 11142: print (OUT $file."\n");
1.572 banghart 11143: }
1.574 banghart 11144: close (OUT);
1.572 banghart 11145: return 'ok';
11146: }
11147:
1.574 banghart 11148: sub clear_selected_files {
11149: my ($user) = @_;
11150: my $filename = $user."savedfiles";
1.1359 raeburn 11151: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 11152: print (OUT undef);
11153: close (OUT);
11154: return ("ok");
11155: }
11156:
1.572 banghart 11157: sub files_in_path {
11158: my ($user, $path) = @_;
11159: my $filename = $user."savedfiles";
11160: my %return_files;
1.1359 raeburn 11161: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 11162: while (my $line_in = <IN>) {
1.574 banghart 11163: chomp ($line_in);
11164: my @paths_and_file = split (m!/!, $line_in);
11165: my $file_part = pop (@paths_and_file);
11166: my $path_part = join ('/', @paths_and_file);
1.573 banghart 11167: $path_part.='/';
11168: my $path_and_file = $path_part.$file_part;
11169: if ($path_part eq $path) {
11170: $return_files{$file_part}= 'selected';
11171: }
11172: }
1.574 banghart 11173: close (IN);
11174: return (\%return_files);
1.572 banghart 11175: }
11176:
11177: # called in portfolio select mode, to show files selected NOT in current directory
11178: sub files_not_in_path {
11179: my ($user, $path) = @_;
11180: my $filename = $user."savedfiles";
11181: my @return_files;
11182: my $path_part;
1.1359 raeburn 11183: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 11184: while (my $line = <IN>) {
1.572 banghart 11185: #ok, I know it's clunky, but I want it to work
1.800 albertel 11186: my @paths_and_file = split(m|/|, $line);
11187: my $file_part = pop(@paths_and_file);
11188: chomp($file_part);
11189: my $path_part = join('/', @paths_and_file);
1.572 banghart 11190: $path_part .= '/';
11191: my $path_and_file = $path_part.$file_part;
11192: if ($path_part ne $path) {
1.800 albertel 11193: push(@return_files, ($path_and_file));
1.572 banghart 11194: }
11195: }
1.800 albertel 11196: close(OUT);
1.574 banghart 11197: return (@return_files);
1.572 banghart 11198: }
11199:
1.1273 raeburn 11200: #------------------------------Submitted/Handedback Portfolio Files Versioning
11201:
11202: sub portfiles_versioning {
11203: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11204: my $portfolio_root = '/userfiles/portfolio';
11205: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11206: foreach my $file (@{$portfiles}) {
11207: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11208: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11209: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11210: my $getpropath = 1;
11211: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11212: $stu_name,$getpropath);
11213: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11214: my $new_answer =
11215: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11216: if ($new_answer ne 'problem getting file') {
11217: push(@{$versioned_portfiles}, $directory.$new_answer);
11218: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11219: [$symb,$env{'request.course.id'},'graded']);
11220: }
11221: }
11222: }
11223:
11224: sub get_next_version {
11225: my ($answer_name, $answer_ext, $dir_list) = @_;
11226: my $version;
11227: if (ref($dir_list) eq 'ARRAY') {
11228: foreach my $row (@{$dir_list}) {
11229: my ($file) = split(/\&/,$row,2);
11230: my ($file_name,$file_version,$file_ext) =
11231: &file_name_version_ext($file);
11232: if (($file_name eq $answer_name) &&
11233: ($file_ext eq $answer_ext)) {
11234: # gets here if filename and extension match,
11235: # regardless of version
11236: if ($file_version ne '') {
11237: # a versioned file is found so save it for later
11238: if ($file_version > $version) {
11239: $version = $file_version;
11240: }
11241: }
11242: }
11243: }
11244: }
11245: $version ++;
11246: return($version);
11247: }
11248:
11249: sub version_selected_portfile {
11250: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11251: my ($answer_name,$answer_ver,$answer_ext) =
11252: &file_name_version_ext($file_name);
11253: my $new_answer;
11254: $env{'form.copy'} =
11255: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11256: if($env{'form.copy'} eq '-1') {
11257: $new_answer = 'problem getting file';
11258: } else {
11259: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11260: my $copy_result =
11261: &finishuserfileupload($stu_name,$domain,'copy',
11262: '/portfolio'.$directory.$new_answer);
11263: }
11264: undef($env{'form.copy'});
11265: return ($new_answer);
11266: }
11267:
11268: sub file_name_version_ext {
11269: my ($file)=@_;
11270: my @file_parts = split(/\./, $file);
11271: my ($name,$version,$ext);
11272: if (@file_parts > 1) {
11273: $ext=pop(@file_parts);
11274: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11275: $version=pop(@file_parts);
11276: }
11277: $name=join('.',@file_parts);
11278: } else {
11279: $name=join('.',@file_parts);
11280: }
11281: return($name,$version,$ext);
11282: }
11283:
1.745 raeburn 11284: #----------------------------------------------Get portfolio file permissions
1.629 banghart 11285:
1.745 raeburn 11286: sub get_portfile_permissions {
11287: my ($domain,$user) = @_;
1.613 albertel 11288: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 11289: my ($tmp)=keys(%current_permissions);
11290: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11291: return \%current_permissions;
11292: }
11293:
11294: #---------------------------------------------Get portfolio file access controls
11295:
1.749 raeburn 11296: sub get_access_controls {
1.745 raeburn 11297: my ($current_permissions,$group,$file) = @_;
1.769 albertel 11298: my %access;
11299: my $real_file = $file;
11300: $file =~ s/\.meta$//;
1.745 raeburn 11301: if (defined($file)) {
1.749 raeburn 11302: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11303: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 11304: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 11305: }
11306: }
1.745 raeburn 11307: } else {
1.749 raeburn 11308: foreach my $key (keys(%{$current_permissions})) {
11309: if ($key =~ /\0accesscontrol$/) {
11310: if (defined($group)) {
11311: if ($key !~ m-^\Q$group\E/-) {
11312: next;
11313: }
11314: }
11315: my ($fullpath) = split(/\0/,$key);
11316: if (ref($$current_permissions{$key}) eq 'HASH') {
11317: foreach my $control (keys(%{$$current_permissions{$key}})) {
11318: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11319: }
11320: }
11321: }
11322: }
11323: }
11324: return %access;
11325: }
11326:
11327: sub modify_access_controls {
11328: my ($file_name,$changes,$domain,$user)=@_;
11329: my ($outcome,$deloutcome);
11330: my %store_permissions;
11331: my %new_values;
11332: my %new_control;
11333: my %translation;
11334: my @deletions = ();
11335: my $now = time;
11336: if (exists($$changes{'activate'})) {
11337: if (ref($$changes{'activate'}) eq 'HASH') {
11338: my @newitems = sort(keys(%{$$changes{'activate'}}));
11339: my $numnew = scalar(@newitems);
11340: for (my $i=0; $i<$numnew; $i++) {
11341: my $newkey = $newitems[$i];
11342: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 11343: if ($newkey =~ /^\d+:/) {
11344: $newkey =~ s/^(\d+)/$newid/;
11345: $translation{$1} = $newid;
11346: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11347: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11348: $translation{$1} = $newid;
11349: }
1.749 raeburn 11350: $new_values{$file_name."\0".$newkey} =
11351: $$changes{'activate'}{$newitems[$i]};
11352: $new_control{$newkey} = $now;
11353: }
11354: }
11355: }
11356: my %todelete;
11357: my %changed_items;
11358: foreach my $action ('delete','update') {
11359: if (exists($$changes{$action})) {
11360: if (ref($$changes{$action}) eq 'HASH') {
11361: foreach my $key (keys(%{$$changes{$action}})) {
11362: my ($itemnum) = ($key =~ /^([^:]+):/);
11363: if ($action eq 'delete') {
11364: $todelete{$itemnum} = 1;
11365: } else {
11366: $changed_items{$itemnum} = $key;
11367: }
11368: }
1.745 raeburn 11369: }
11370: }
1.749 raeburn 11371: }
11372: # get lock on access controls for file.
11373: my $lockhash = {
11374: $file_name."\0".'locked_access_records' => $env{'user.name'}.
11375: ':'.$env{'user.domain'},
11376: };
11377: my $tries = 0;
11378: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11379:
1.1288 damieng 11380: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 11381: $tries ++;
1.1289 damieng 11382: sleep(0.1);
1.749 raeburn 11383: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11384: }
11385: if ($gotlock eq 'ok') {
11386: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11387: my ($tmp)=keys(%curr_permissions);
11388: if ($tmp=~/^error:/) { undef(%curr_permissions); }
11389: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11390: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11391: if (ref($curr_controls) eq 'HASH') {
11392: foreach my $control_item (keys(%{$curr_controls})) {
11393: my ($itemnum) = ($control_item =~ /^([^:]+):/);
11394: if (defined($todelete{$itemnum})) {
11395: push(@deletions,$file_name."\0".$control_item);
11396: } else {
11397: if (defined($changed_items{$itemnum})) {
11398: $new_control{$changed_items{$itemnum}} = $now;
11399: push(@deletions,$file_name."\0".$control_item);
11400: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11401: } else {
11402: $new_control{$control_item} = $$curr_controls{$control_item};
11403: }
11404: }
1.745 raeburn 11405: }
11406: }
11407: }
1.970 raeburn 11408: my ($group);
11409: if (&is_course($domain,$user)) {
11410: ($group,my $file) = split(/\//,$file_name,2);
11411: }
1.749 raeburn 11412: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11413: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11414: $outcome = &put('file_permissions',\%new_values,$domain,$user);
11415: # remove lock
11416: my @del_lock = ($file_name."\0".'locked_access_records');
11417: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 11418: my $sqlresult =
1.970 raeburn 11419: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 11420: $group);
1.749 raeburn 11421: } else {
11422: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 11423: }
1.749 raeburn 11424: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 11425: }
11426:
1.827 raeburn 11427: sub make_public_indefinitely {
1.1271 raeburn 11428: my (@requrl) = @_;
11429: return &automated_portfile_access('public',\@requrl);
11430: }
11431:
11432: sub automated_portfile_access {
11433: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 11434: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11435: return 'invalid';
11436: }
1.1271 raeburn 11437: my %urls;
11438: if (ref($addsref) eq 'ARRAY') {
11439: foreach my $requrl (@{$addsref}) {
11440: if (&is_portfolio_url($requrl)) {
11441: unless (exists($urls{$requrl})) {
11442: $urls{$requrl} = 'add';
11443: }
11444: }
11445: }
11446: }
11447: if (ref($delsref) eq 'ARRAY') {
11448: foreach my $requrl (@{$delsref}) {
11449: if (&is_portfolio_url($requrl)) {
11450: unless (exists($urls{$requrl})) {
11451: $urls{$requrl} = 'delete';
11452: }
11453: }
11454: }
11455: }
11456: unless (keys(%urls)) {
11457: return 'invalid';
11458: }
11459: my $ip;
11460: if ($accesstype eq 'ip') {
11461: if (ref($info) eq 'HASH') {
11462: if ($info->{'ip'} ne '') {
11463: $ip = $info->{'ip'};
11464: }
11465: }
11466: if ($ip eq '') {
11467: return 'invalid';
11468: }
11469: }
11470: my $errors;
1.827 raeburn 11471: my $now = time;
1.1271 raeburn 11472: my %current_perms;
11473: foreach my $requrl (sort(keys(%urls))) {
11474: my $action;
11475: if ($urls{$requrl} eq 'add') {
11476: $action = 'activate';
11477: } else {
11478: $action = 'none';
11479: }
11480: my $aclnum = 0;
1.827 raeburn 11481: my (undef,$udom,$unum,$file_name,$group) =
11482: &parse_portfolio_url($requrl);
1.1271 raeburn 11483: unless (exists($current_perms{$unum.':'.$udom})) {
11484: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11485: }
11486: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 11487: $group,$file_name);
11488: foreach my $key (keys(%{$access_controls{$file_name}})) {
11489: my ($num,$scope,$end,$start) =
11490: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 11491: if ($scope eq $accesstype) {
11492: if (($start <= $now) && ($end == 0)) {
11493: if ($accesstype eq 'ip') {
11494: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11495: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11496: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11497: if ($urls{$requrl} eq 'add') {
11498: $action = 'none';
11499: last;
11500: } else {
11501: $action = 'delete';
11502: $aclnum = $num;
11503: last;
11504: }
11505: }
11506: }
11507: }
11508: } elsif ($accesstype eq 'public') {
11509: if ($urls{$requrl} eq 'add') {
11510: $action = 'none';
11511: last;
11512: } else {
11513: $action = 'delete';
11514: $aclnum = $num;
11515: last;
11516: }
11517: }
11518: } elsif ($accesstype eq 'public') {
1.827 raeburn 11519: $action = 'update';
11520: $aclnum = $num;
1.1271 raeburn 11521: last;
1.827 raeburn 11522: }
11523: }
11524: }
11525: if ($action eq 'none') {
1.1271 raeburn 11526: next;
1.827 raeburn 11527: } else {
11528: my %changes;
11529: my $newend = 0;
11530: my $newstart = $now;
1.1271 raeburn 11531: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 11532: $changes{$action}{$newkey} = {
1.1271 raeburn 11533: type => $accesstype,
1.827 raeburn 11534: time => {
11535: start => $newstart,
11536: end => $newend,
11537: },
11538: };
1.1271 raeburn 11539: if ($accesstype eq 'ip') {
11540: $changes{$action}{$newkey}{'ip'} = [$ip];
11541: }
1.827 raeburn 11542: my ($outcome,$deloutcome,$new_values,$translation) =
11543: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 11544: unless ($outcome eq 'ok') {
11545: $errors .= $outcome.' ';
11546: }
1.827 raeburn 11547: }
1.1271 raeburn 11548: }
11549: if ($errors) {
11550: $errors =~ s/\s$//;
11551: return $errors;
1.827 raeburn 11552: } else {
1.1271 raeburn 11553: return 'ok';
1.827 raeburn 11554: }
11555: }
11556:
1.745 raeburn 11557: #------------------------------------------------------Get Marked as Read Only
11558:
11559: sub get_marked_as_readonly {
11560: my ($domain,$user,$what,$group) = @_;
11561: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 11562: my @readonly_files;
1.629 banghart 11563: my $cmp1=$what;
11564: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 11565: while (my ($file_name,$value) = each(%{$current_permissions})) {
11566: if (defined($group)) {
11567: if ($file_name !~ m-^\Q$group\E/-) {
11568: next;
11569: }
11570: }
1.561 banghart 11571: if (ref($value) eq "ARRAY"){
11572: foreach my $stored_what (@{$value}) {
1.629 banghart 11573: my $cmp2=$stored_what;
1.759 albertel 11574: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 11575: $cmp2=join('',@{$stored_what});
1.745 raeburn 11576: }
1.629 banghart 11577: if ($cmp1 eq $cmp2) {
1.561 banghart 11578: push(@readonly_files, $file_name);
1.745 raeburn 11579: last;
1.563 banghart 11580: } elsif (!defined($what)) {
11581: push(@readonly_files, $file_name);
1.745 raeburn 11582: last;
1.561 banghart 11583: }
11584: }
1.745 raeburn 11585: }
1.561 banghart 11586: }
11587: return @readonly_files;
11588: }
1.577 banghart 11589: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 11590:
1.577 banghart 11591: sub get_marked_as_readonly_hash {
1.745 raeburn 11592: my ($current_permissions,$group,$what) = @_;
1.577 banghart 11593: my %readonly_files;
1.745 raeburn 11594: while (my ($file_name,$value) = each(%{$current_permissions})) {
11595: if (defined($group)) {
11596: if ($file_name !~ m-^\Q$group\E/-) {
11597: next;
11598: }
11599: }
1.577 banghart 11600: if (ref($value) eq "ARRAY"){
11601: foreach my $stored_what (@{$value}) {
1.745 raeburn 11602: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 11603: foreach my $lock_descriptor(@{$stored_what}) {
11604: if ($lock_descriptor eq 'graded') {
11605: $readonly_files{$file_name} = 'graded';
11606: } elsif ($lock_descriptor eq 'handback') {
11607: $readonly_files{$file_name} = 'handback';
11608: } else {
11609: if (!exists($readonly_files{$file_name})) {
11610: $readonly_files{$file_name} = 'locked';
11611: }
11612: }
1.745 raeburn 11613: }
1.750 banghart 11614: }
1.577 banghart 11615: }
11616: }
11617: }
11618: return %readonly_files;
11619: }
1.559 banghart 11620: # ------------------------------------------------------------ Unmark as Read Only
11621:
11622: sub unmark_as_readonly {
1.629 banghart 11623: # unmarks $file_name (if $file_name is defined), or all files locked by $what
11624: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 11625: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 11626: $file_name = &declutter_portfile($file_name);
1.634 albertel 11627: my $symb_crs = $what;
11628: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 11629: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 11630: my ($tmp)=keys(%current_permissions);
11631: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11632: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 11633: foreach my $file (@readonly_files) {
1.759 albertel 11634: my $clean_file = &declutter_portfile($file);
11635: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 11636: my $current_locks = $current_permissions{$file};
1.563 banghart 11637: my @new_locks;
11638: my @del_keys;
11639: if (ref($current_locks) eq "ARRAY"){
11640: foreach my $locker (@{$current_locks}) {
1.632 albertel 11641: my $compare=$locker;
1.749 raeburn 11642: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 11643: $compare=join('',@{$locker});
1.746 raeburn 11644: if ($compare ne $symb_crs) {
11645: push(@new_locks, $locker);
11646: }
1.563 banghart 11647: }
11648: }
1.650 albertel 11649: if (scalar(@new_locks) > 0) {
1.563 banghart 11650: $current_permissions{$file} = \@new_locks;
11651: } else {
11652: push(@del_keys, $file);
1.613 albertel 11653: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 11654: delete($current_permissions{$file});
1.563 banghart 11655: }
11656: }
1.561 banghart 11657: }
1.613 albertel 11658: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11659: return;
11660: }
1.512 banghart 11661:
1.17 www 11662: # ------------------------------------------------------------ Directory lister
11663:
11664: sub dirlist {
1.955 raeburn 11665: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 11666: $uri=~s/^\///;
11667: $uri=~s/\/$//;
1.253 stredwic 11668: my ($udom, $uname);
1.955 raeburn 11669: if ($getuserdir) {
1.253 stredwic 11670: $udom = $userdomain;
11671: $uname = $username;
1.955 raeburn 11672: } else {
11673: (undef,$udom,$uname)=split(/\//,$uri);
11674: if(defined($userdomain)) {
11675: $udom = $userdomain;
11676: }
11677: if(defined($username)) {
11678: $uname = $username;
11679: }
1.253 stredwic 11680: }
1.955 raeburn 11681: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 11682:
1.955 raeburn 11683: $dirRoot = $perlvar{'lonDocRoot'};
11684: if (defined($getpropath)) {
11685: $dirRoot = &propath($udom,$uname);
1.253 stredwic 11686: $dirRoot =~ s/\/$//;
1.955 raeburn 11687: } elsif (defined($getuserdir)) {
11688: my $subdir=$uname.'__';
11689: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11690: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11691: ."/$udom/$subdir/$uname";
11692: } elsif (defined($alternateRoot)) {
11693: $dirRoot = $alternateRoot;
1.751 banghart 11694: }
1.253 stredwic 11695:
11696: if($udom) {
11697: if($uname) {
1.1135 raeburn 11698: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 11699: if ($uhome eq 'no_host') {
11700: return ([],'no_host');
11701: }
1.955 raeburn 11702: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 11703: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 11704: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 11705: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11706: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 11707: } else {
11708: @listing_results = map { &unescape($_); } split(/:/,$listing);
11709: }
1.605 matthew 11710: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11711: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 11712: @listing_results = split(/:/,$listing);
11713: } else {
11714: @listing_results = map { &unescape($_); } split(/:/,$listing);
11715: }
1.1135 raeburn 11716: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 11717: ($listing eq 'rejected') || ($listing eq 'refused') ||
11718: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11719: return ([],$listing);
11720: } else {
11721: return (\@listing_results);
1.1135 raeburn 11722: }
1.955 raeburn 11723: } elsif(!$alternateRoot) {
1.1136 raeburn 11724: my (%allusers,%listerror);
1.841 albertel 11725: my %servers = &get_servers($udom,'library');
1.955 raeburn 11726: foreach my $tryserver (keys(%servers)) {
11727: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11728: &escape($udom),$tryserver);
11729: if ($listing eq 'unknown_cmd') {
11730: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11731: $udom, $tryserver);
11732: } else {
11733: @listing_results = map { &unescape($_); } split(/:/,$listing);
11734: }
1.841 albertel 11735: if ($listing eq 'unknown_cmd') {
11736: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11737: $udom, $tryserver);
11738: @listing_results = split(/:/,$listing);
11739: } else {
11740: @listing_results =
11741: map { &unescape($_); } split(/:/,$listing);
11742: }
1.1136 raeburn 11743: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11744: ($listing eq 'rejected') || ($listing eq 'refused') ||
11745: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11746: $listerror{$tryserver} = $listing;
11747: } else {
1.841 albertel 11748: foreach my $line (@listing_results) {
11749: my ($entry) = split(/&/,$line,2);
11750: $allusers{$entry} = 1;
11751: }
11752: }
1.253 stredwic 11753: }
1.1136 raeburn 11754: my @alluserslist=();
1.800 albertel 11755: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 11756: push(@alluserslist,$user.'&user');
1.253 stredwic 11757: }
1.1318 droeschl 11758:
11759: if (!%listerror) {
11760: # no errors
11761: return (\@alluserslist);
11762: } elsif (scalar(keys(%servers)) == 1) {
11763: # one library server, one error
11764: my ($key) = keys(%listerror);
11765: return (\@alluserslist, $listerror{$key});
11766: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11767: # con_lost indicates that we might miss data from at least one
11768: # library server
11769: return (\@alluserslist, 'con_lost');
11770: } else {
11771: # multiple library servers and no con_lost -> data should be
11772: # complete.
11773: return (\@alluserslist);
11774: }
11775:
1.253 stredwic 11776: } else {
1.1136 raeburn 11777: return ([],'missing username');
1.253 stredwic 11778: }
1.955 raeburn 11779: } elsif(!defined($getpropath)) {
1.1136 raeburn 11780: my $path = $perlvar{'lonDocRoot'}.'/res/';
11781: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11782: return (\@all_domains);
1.955 raeburn 11783: } else {
1.1136 raeburn 11784: return ([],'missing domain');
1.275 stredwic 11785: }
11786: }
11787:
11788: # --------------------------------------------- GetFileTimestamp
11789: # This function utilizes dirlist and returns the date stamp for
11790: # when it was last modified. It will also return an error of -1
11791: # if an error occurs
11792:
11793: sub GetFileTimestamp {
1.955 raeburn 11794: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 11795: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11796: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 11797: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11798: undef,$getuserdir);
11799: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11800: return -1;
11801: }
11802: if (ref($fileref) eq 'ARRAY') {
11803: my @stats = split('&',$fileref->[0]);
1.375 matthew 11804: # @stats contains first the filename, then the stat output
11805: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 11806: } else {
11807: return -1;
1.253 stredwic 11808: }
1.26 www 11809: }
11810:
1.712 albertel 11811: sub stat_file {
11812: my ($uri) = @_;
1.787 albertel 11813: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11814:
1.955 raeburn 11815: my ($udom,$uname,$file);
1.712 albertel 11816: if ($uri =~ m-^/(uploaded|editupload)/-) {
11817: ($udom,$uname,$file) =
1.811 albertel 11818: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11819: $file = 'userfiles/'.$file;
11820: }
11821: if ($uri =~ m-^/res/-) {
11822: ($udom,$uname) =
1.807 albertel 11823: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 11824: $file = $uri;
11825: }
11826:
11827: if (!$udom || !$uname || !$file) {
11828: # unable to handle the uri
11829: return ();
11830: }
1.956 raeburn 11831: my $getpropath;
11832: if ($file =~ /^userfiles\//) {
11833: $getpropath = 1;
11834: }
1.1136 raeburn 11835: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11836: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11837: return ();
11838: } else {
11839: if (ref($listref) eq 'ARRAY') {
11840: my @stats = split('&',$listref->[0]);
11841: shift(@stats); #filename is first
11842: return @stats;
11843: }
1.712 albertel 11844: }
11845: return ();
11846: }
11847:
1.1313 raeburn 11848: # --------------------------------------------------------- recursedirs
11849: # Recursive function to traverse either a specific user's Authoring Space
11850: # or corresponding Published Resource Space, and populate the hash ref:
11851: # $dirhashref with URLs of all directories, and if $filehashref hash
11852: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
11853: # or .rights files in resource space, and .meta, .save, .log, and .bak
11854: # files in Authoring Space.
11855: #
11856: # Inputs:
11857: #
11858: # $is_home - true if current server is home server for user's space
11859: # $context - either: priv, or res respectively for Authoring or Resource Space.
11860: # $docroot - Document root (i.e., /home/httpd/html
11861: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
11862: # $relpath - Current path (relative to top level).
11863: # $dirhashref - reference to hash to populate with URLs of directories (Required)
11864: # $filehashref - reference to hash to populate with URLs of files (Optional)
11865: #
11866: # Returns: nothing
11867: #
11868: # Side Effects: populates $dirhashref, and $filehashref (if provided).
11869: #
11870: # Currently used by interface/londocs.pm to create linked select boxes for
11871: # directory and filename to import a Course "Author" resource into a course, and
11872: # also to create linked select boxes for Authoring Space and Directory to choose
11873: # save location for creation of a new "standard" problem from the Course Editor.
11874: #
11875:
11876: sub recursedirs {
11877: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
11878: return unless (ref($dirhashref) eq 'HASH');
11879: my $currpath = $docroot.$toppath;
11880: if ($relpath) {
11881: $currpath .= "/$relpath";
11882: }
11883: my $savefile;
11884: if (ref($filehashref)) {
11885: $savefile = 1;
11886: }
11887: if ($is_home) {
11888: if (opendir(my $dirh,$currpath)) {
11889: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
11890: next if ($item eq '');
11891: if (-d "$currpath/$item") {
11892: my $newpath;
11893: if ($relpath) {
11894: $newpath = "$relpath/$item";
11895: } else {
11896: $newpath = $item;
11897: }
11898: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11899: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11900: } elsif ($savefile) {
11901: if ($context eq 'priv') {
11902: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11903: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11904: }
11905: } else {
11906: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
11907: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
11908: }
11909: }
11910: }
11911: }
11912: closedir($dirh);
11913: }
11914: } else {
11915: my ($dirlistref,$listerror) =
11916: &dirlist($toppath.$relpath);
11917: my @dir_lines;
11918: my $dirptr=16384;
11919: if (ref($dirlistref) eq 'ARRAY') {
11920: foreach my $dir_line (sort
11921: {
11922: my ($afile)=split('&',$a,2);
11923: my ($bfile)=split('&',$b,2);
11924: return (lc($afile) cmp lc($bfile));
11925: } (@{$dirlistref})) {
11926: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
11927: split(/\&/,$dir_line,16);
11928: $item =~ s/\s+$//;
11929: next if (($item =~ /^\.\.?$/) || ($obs));
11930: if ($dirptr&$testdir) {
11931: my $newpath;
11932: if ($relpath) {
11933: $newpath = "$relpath/$item";
11934: } else {
11935: $relpath = '/';
11936: $newpath = $item;
11937: }
11938: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
11939: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
11940: } elsif ($savefile) {
11941: if ($context eq 'priv') {
11942: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
11943: $filehashref->{$relpath}{$item} = 1;
11944: }
11945: } else {
11946: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
11947: $filehashref->{$relpath}{$item} = 1;
11948: }
11949: }
11950: }
11951: }
11952: }
11953: }
11954: return;
11955: }
11956:
1.26 www 11957: # -------------------------------------------------------- Value of a Condition
11958:
1.713 albertel 11959: # gets the value of a specific preevaluated condition
11960: # stored in the string $env{user.state.<cid>}
11961: # or looks up a condition reference in the bighash and if if hasn't
11962: # already been evaluated recurses into docondval to get the value of
11963: # the condition, then memoizing it to
11964: # $env{user.state.<cid>.<condition>}
1.40 www 11965: sub directcondval {
11966: my $number=shift;
1.620 albertel 11967: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 11968: &Apache::lonuserstate::evalstate();
11969: }
1.713 albertel 11970: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11971: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11972: } elsif ($number =~ /^_/) {
11973: my $sub_condition;
11974: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11975: &GDBM_READER(),0640)) {
11976: $sub_condition=$bighash{'conditions'.$number};
11977: untie(%bighash);
11978: }
11979: my $value = &docondval($sub_condition);
1.949 raeburn 11980: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 11981: return $value;
11982: }
1.620 albertel 11983: if ($env{'user.state.'.$env{'request.course.id'}}) {
11984: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 11985: } else {
11986: return 2;
11987: }
11988: }
11989:
1.713 albertel 11990: # get the collection of conditions for this resource
1.26 www 11991: sub condval {
11992: my $condidx=shift;
1.54 www 11993: my $allpathcond='';
1.713 albertel 11994: foreach my $cond (split(/\|/,$condidx)) {
11995: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11996: $allpathcond.=
11997: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11998: }
1.191 harris41 11999: }
1.54 www 12000: $allpathcond=~s/\|$//;
1.713 albertel 12001: return &docondval($allpathcond);
12002: }
12003:
12004: #evaluates an expression of conditions
12005: sub docondval {
12006: my ($allpathcond) = @_;
12007: my $result=0;
12008: if ($env{'request.course.id'}
12009: && defined($allpathcond)) {
12010: my $operand='|';
12011: my @stack;
12012: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12013: if ($chunk eq '(') {
12014: push @stack,($operand,$result);
12015: } elsif ($chunk eq ')') {
12016: my $before=pop @stack;
12017: if (pop @stack eq '&') {
12018: $result=$result>$before?$before:$result;
12019: } else {
12020: $result=$result>$before?$result:$before;
12021: }
12022: } elsif (($chunk eq '&') || ($chunk eq '|')) {
12023: $operand=$chunk;
12024: } else {
12025: my $new=directcondval($chunk);
12026: if ($operand eq '&') {
12027: $result=$result>$new?$new:$result;
12028: } else {
12029: $result=$result>$new?$result:$new;
12030: }
12031: }
12032: }
1.26 www 12033: }
12034: return $result;
1.421 albertel 12035: }
12036:
12037: # ---------------------------------------------------- Devalidate courseresdata
12038:
12039: sub devalidatecourseresdata {
12040: my ($coursenum,$coursedomain)=@_;
12041: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 12042: &devalidate_cache_new('courseres',$hashid);
1.28 www 12043: }
12044:
1.763 www 12045:
1.200 www 12046: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 12047: #
12048: # Parameters:
12049: # $coursenum - Number of the course.
12050: # $coursedomain - Domain at which the course was created.
12051: # Returns:
12052: # A hash of the course parameters along (I think) with timestamps
12053: # and version info.
1.877 foxr 12054:
1.624 albertel 12055: sub get_courseresdata {
12056: my ($coursenum,$coursedomain)=@_;
1.200 www 12057: my $coursehom=&homeserver($coursenum,$coursedomain);
12058: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 12059: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 12060: my %dumpreply;
1.417 albertel 12061: unless (defined($cached)) {
1.624 albertel 12062: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 12063: $result=\%dumpreply;
1.251 albertel 12064: my ($tmp) = keys(%dumpreply);
12065: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 12066: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 12067: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12068: return $tmp;
1.416 albertel 12069: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 12070: $result=undef;
1.599 albertel 12071: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 12072: }
12073: }
1.624 albertel 12074: return $result;
12075: }
12076:
1.633 albertel 12077: sub devalidateuserresdata {
12078: my ($uname,$udom)=@_;
12079: my $hashid="$udom:$uname";
12080: &devalidate_cache_new('userres',$hashid);
12081: }
12082:
1.624 albertel 12083: sub get_userresdata {
12084: my ($uname,$udom)=@_;
12085: #most student don\'t have any data set, check if there is some data
12086: if (&EXT_cache_status($udom,$uname)) { return undef; }
12087:
12088: my $hashid="$udom:$uname";
12089: my ($result,$cached)=&is_cached_new('userres',$hashid);
12090: if (!defined($cached)) {
12091: my %resourcedata=&dump('resourcedata',$udom,$uname);
12092: $result=\%resourcedata;
12093: &do_cache_new('userres',$hashid,$result,600);
12094: }
12095: my ($tmp)=keys(%$result);
12096: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12097: return $result;
12098: }
12099: #error 2 occurs when the .db doesn't exist
12100: if ($tmp!~/error: 2 /) {
1.1294 raeburn 12101: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12102: &logthis("<font color=\"blue\">WARNING:".
12103: " Trying to get resource data for ".
12104: $uname." at ".$udom.": ".
12105: $tmp."</font>");
12106: }
1.624 albertel 12107: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 12108: #&EXT_cache_set($udom,$uname);
12109: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 12110: undef($tmp); # not really an error so don't send it back
1.624 albertel 12111: }
12112: return $tmp;
12113: }
1.879 foxr 12114: #----------------------------------------------- resdata - return resource data
12115: # Purpose:
12116: # Return resource data for either users or for a course.
12117: # Parameters:
12118: # $name - Course/user name.
12119: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 12120: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 12121: # $mapp - decluttered URL of enclosing map
12122: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
12123: # $recurseup - Ref to array of map URLs, starting with map containing
12124: # $mapp up through hierarchy of nested maps to top level map.
12125: # $courseid - CourseID (first part of param identifier).
12126: # $modifier - Middle part of param identifier.
12127: # $what - Last part of param identifier.
1.879 foxr 12128: # @which - Array of names of resources desired.
12129: # Returns:
12130: # The value of the first reasource in @which that is found in the
12131: # resource hash.
12132: # Exceptional Conditions:
12133: # If the $type passed in is not valid (not the string 'course' or
12134: # 'user', an undefined reference is returned.
12135: # If none of the resources are found, an undef is returned
1.624 albertel 12136: sub resdata {
1.1301 raeburn 12137: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12138: $modifier,$what,@which)=@_;
1.624 albertel 12139: my $result;
12140: if ($type eq 'course') {
12141: $result=&get_courseresdata($name,$domain);
12142: } elsif ($type eq 'user') {
12143: $result=&get_userresdata($name,$domain);
12144: }
12145: if (!ref($result)) { return $result; }
1.251 albertel 12146: foreach my $item (@which) {
1.1301 raeburn 12147: if ($item->[1] eq 'course') {
12148: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12149: unless ($$recursed) {
1.1302 raeburn 12150: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 12151: $$recursed = 1;
12152: }
12153: foreach my $item (@${recurseup}) {
12154: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12155: last if (defined($result->{$norecursechk}));
12156: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12157: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12158: }
12159: }
12160: }
12161: if (defined($result->{$item->[0]})) {
1.927 albertel 12162: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 12163: }
1.250 albertel 12164: }
1.291 albertel 12165: return undef;
1.200 www 12166: }
12167:
1.1360 raeburn 12168: sub get_domain_lti {
12169: my ($cdom,$context) = @_;
12170: my ($name,%lti);
12171: if ($context eq 'consumer') {
12172: $name = 'ltitools';
12173: } elsif ($context eq 'provider') {
12174: $name = 'lti';
12175: } else {
12176: return %lti;
12177: }
12178: my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298 raeburn 12179: if (defined($cached)) {
12180: if (ref($result) eq 'HASH') {
1.1360 raeburn 12181: %lti = %{$result};
1.1298 raeburn 12182: }
12183: } else {
1.1360 raeburn 12184: my %domconfig = &get_dom('configuration',[$name],$cdom);
12185: if (ref($domconfig{$name}) eq 'HASH') {
12186: %lti = %{$domconfig{$name}};
12187: my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
12188: if (ref($encdomconfig{$name}) eq 'HASH') {
12189: foreach my $id (keys(%lti)) {
12190: if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344 raeburn 12191: foreach my $item ('key','secret') {
1.1360 raeburn 12192: $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344 raeburn 12193: }
12194: }
12195: }
12196: }
1.1298 raeburn 12197: }
12198: my $cachetime = 24*60*60;
1.1360 raeburn 12199: &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298 raeburn 12200: }
1.1360 raeburn 12201: return %lti;
1.1298 raeburn 12202: }
12203:
1.1236 raeburn 12204: sub get_numsuppfiles {
12205: my ($cnum,$cdom,$ignorecache)=@_;
12206: my $hashid=$cnum.':'.$cdom;
12207: my ($suppcount,$cached);
12208: unless ($ignorecache) {
12209: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
12210: }
12211: unless (defined($cached)) {
12212: my $chome=&homeserver($cnum,$cdom);
12213: unless ($chome eq 'no_host') {
1.1366 raeburn 12214: ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236 raeburn 12215: my $suppmap = 'supplemental.sequence';
1.1366 raeburn 12216: ($suppcount,$supptools,$errors) =
12217: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
12218: $supptools,$errors);
1.1236 raeburn 12219: }
12220: &do_cache_new('suppcount',$hashid,$suppcount,600);
12221: }
12222: return $suppcount;
12223: }
12224:
1.379 matthew 12225: #
12226: # EXT resource caching routines
12227: #
12228:
1.1302 raeburn 12229: {
12230: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12231: #
12232: # The course for which we cache
12233: my $cachedmapkey='';
12234: # The cached recursive maps for this course
12235: my %cachedmaps=();
12236: # When this was last done
12237: my $cachedmaptime='';
12238:
1.379 matthew 12239: sub clear_EXT_cache_status {
1.383 albertel 12240: &delenv('cache.EXT.');
1.379 matthew 12241: }
12242:
12243: sub EXT_cache_status {
12244: my ($target_domain,$target_user) = @_;
1.383 albertel 12245: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 12246: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 12247: # We know already the user has no data
12248: return 1;
12249: } else {
12250: return 0;
12251: }
12252: }
12253:
12254: sub EXT_cache_set {
12255: my ($target_domain,$target_user) = @_;
1.383 albertel 12256: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 12257: #&appenv({$cachename => time});
1.379 matthew 12258: }
12259:
1.28 www 12260: # --------------------------------------------------------- Value of a Variable
1.58 www 12261: sub EXT {
1.715 albertel 12262:
1.1228 raeburn 12263: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 12264: unless ($varname) { return ''; }
1.218 albertel 12265: #get real user name/domain, courseid and symb
12266: my $courseid;
1.359 albertel 12267: my $publicuser;
1.427 www 12268: if ($symbparm) {
12269: $symbparm=&get_symb_from_alias($symbparm);
12270: }
1.218 albertel 12271: if (!($uname && $udom)) {
1.790 albertel 12272: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 12273: if (!$symbparm) { $symbparm=$cursymb; }
12274: } else {
1.620 albertel 12275: $courseid=$env{'request.course.id'};
1.218 albertel 12276: }
1.48 www 12277: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12278: my $rest;
1.320 albertel 12279: if (defined($therest[0])) {
1.48 www 12280: $rest=join('.',@therest);
12281: } else {
12282: $rest='';
12283: }
1.320 albertel 12284:
1.57 www 12285: my $qualifierrest=$qualifier;
12286: if ($rest) { $qualifierrest.='.'.$rest; }
12287: my $spacequalifierrest=$space;
12288: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 12289: if ($realm eq 'user') {
1.48 www 12290: # --------------------------------------------------------------- user.resource
12291: if ($space eq 'resource') {
1.651 albertel 12292: if ( (defined($Apache::lonhomework::parsing_a_problem)
12293: || defined($Apache::lonhomework::parsing_a_task))
12294: &&
1.744 albertel 12295: ($symbparm eq &symbread()) ) {
12296: # if we are in the middle of processing the resource the
12297: # get the value we are planning on committing
12298: if (defined($Apache::lonhomework::results{$qualifierrest})) {
12299: return $Apache::lonhomework::results{$qualifierrest};
12300: } else {
12301: return $Apache::lonhomework::history{$qualifierrest};
12302: }
1.335 albertel 12303: } else {
1.359 albertel 12304: my %restored;
1.620 albertel 12305: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 12306: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12307: } else {
12308: %restored=&restore($symbparm,$courseid,$udom,$uname);
12309: }
1.335 albertel 12310: return $restored{$qualifierrest};
12311: }
1.48 www 12312: # ----------------------------------------------------------------- user.access
12313: } elsif ($space eq 'access') {
1.218 albertel 12314: # FIXME - not supporting calls for a specific user
1.48 www 12315: return &allowed($qualifier,$rest);
12316: # ------------------------------------------ user.preferences, user.environment
12317: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 12318: if (($uname eq $env{'user.name'}) &&
12319: ($udom eq $env{'user.domain'})) {
12320: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 12321: } else {
1.359 albertel 12322: my %returnhash;
12323: if (!$publicuser) {
12324: %returnhash=&userenvironment($udom,$uname,
12325: $qualifierrest);
12326: }
1.218 albertel 12327: return $returnhash{$qualifierrest};
12328: }
1.48 www 12329: # ----------------------------------------------------------------- user.course
12330: } elsif ($space eq 'course') {
1.218 albertel 12331: # FIXME - not supporting calls for a specific user
1.620 albertel 12332: return $env{join('.',('request.course',$qualifier))};
1.48 www 12333: # ------------------------------------------------------------------- user.role
12334: } elsif ($space eq 'role') {
1.218 albertel 12335: # FIXME - not supporting calls for a specific user
1.620 albertel 12336: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 12337: if ($qualifier eq 'value') {
12338: return $role;
12339: } elsif ($qualifier eq 'extent') {
12340: return $where;
12341: }
12342: # ----------------------------------------------------------------- user.domain
12343: } elsif ($space eq 'domain') {
1.218 albertel 12344: return $udom;
1.48 www 12345: # ------------------------------------------------------------------- user.name
12346: } elsif ($space eq 'name') {
1.218 albertel 12347: return $uname;
1.48 www 12348: # ---------------------------------------------------- Any other user namespace
1.29 www 12349: } else {
1.359 albertel 12350: my %reply;
12351: if (!$publicuser) {
12352: %reply=&get($space,[$qualifierrest],$udom,$uname);
12353: }
12354: return $reply{$qualifierrest};
1.48 www 12355: }
1.236 www 12356: } elsif ($realm eq 'query') {
12357: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 12358: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
12359: [$spacequalifierrest]);
1.620 albertel 12360: return $env{'form.'.$spacequalifierrest};
1.236 www 12361: } elsif ($realm eq 'request') {
1.48 www 12362: # ------------------------------------------------------------- request.browser
12363: if ($space eq 'browser') {
1.1145 bisitz 12364: return $env{'browser.'.$qualifier};
1.57 www 12365: # ------------------------------------------------------------ request.filename
12366: } else {
1.620 albertel 12367: return $env{'request.'.$spacequalifierrest};
1.29 www 12368: }
1.28 www 12369: } elsif ($realm eq 'course') {
1.48 www 12370: # ---------------------------------------------------------- course.description
1.620 albertel 12371: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 12372: } elsif ($realm eq 'resource') {
1.165 www 12373:
1.620 albertel 12374: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 12375: if (!$symbparm) { $symbparm=&symbread(); }
12376: }
1.693 albertel 12377:
1.1232 raeburn 12378: if ($qualifier eq '') {
12379: if ($space eq 'title') {
12380: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
12381: return &gettitle($symbparm);
12382: }
1.693 albertel 12383:
1.1232 raeburn 12384: if ($space eq 'map') {
12385: my ($map) = &decode_symb($symbparm);
12386: return &symbread($map);
12387: }
12388: if ($space eq 'maptitle') {
12389: my ($map) = &decode_symb($symbparm);
12390: return &gettitle($map);
12391: }
12392: if ($space eq 'filename') {
12393: if ($symbparm) {
12394: return &clutter((&decode_symb($symbparm))[2]);
12395: }
12396: return &hreflocation('',$env{'request.filename'});
1.905 albertel 12397: }
1.1232 raeburn 12398:
1.1233 raeburn 12399: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
12400: if ($space eq 'visibleparts') {
12401: my $navmap = Apache::lonnavmaps::navmap->new();
12402: my $item;
12403: if (ref($navmap)) {
12404: my $res = $navmap->getBySymb($symbparm);
12405: my $parts = $res->parts();
12406: if (ref($parts) eq 'ARRAY') {
12407: $item = join(',',@{$parts});
12408: }
12409: undef($navmap);
1.1232 raeburn 12410: }
1.1233 raeburn 12411: return $item;
1.1232 raeburn 12412: }
12413: }
12414: }
1.693 albertel 12415:
1.1301 raeburn 12416: my ($section, $group, @groups, @recurseup, $recursed);
12417: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 12418: if (($courseid eq '') && ($cid)) {
12419: $courseid = $cid;
12420: }
12421: if (($symbparm && $courseid) &&
12422: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 12423:
1.218 albertel 12424: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 12425:
1.60 www 12426: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 12427: my $symbp=$symbparm;
1.1301 raeburn 12428: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 12429: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 12430: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 12431: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 12432: if (($env{'user.name'} eq $uname) &&
12433: ($env{'user.domain'} eq $udom)) {
12434: $section=$env{'request.course.sec'};
1.733 raeburn 12435: @groups = split(/:/,$env{'request.course.groups'});
12436: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 12437: } else {
1.539 albertel 12438: if (! defined($usection)) {
1.551 albertel 12439: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 12440: } else {
12441: $section = $usection;
12442: }
1.733 raeburn 12443: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 12444: }
12445:
12446: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
12447: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 12448: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 12449: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
12450:
1.593 albertel 12451: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 12452: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 12453: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 12454: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 12455:
1.60 www 12456: # ----------------------------------------------------------- first, check user
1.624 albertel 12457:
1.1301 raeburn 12458: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
12459: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 12460: ([$courselevelr,'resource'],
12461: [$courselevelm,'map' ],
1.1301 raeburn 12462: [$courseleveli,'map' ],
1.927 albertel 12463: [$courselevel, 'course' ]));
1.931 albertel 12464: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 12465:
1.594 albertel 12466: # ------------------------------------------------ second, check some of course
1.684 raeburn 12467: my $coursereply;
1.691 raeburn 12468: if (@groups > 0) {
12469: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 12470: $recurseparm,$mapparm,$spacequalifierrest,
12471: $mapp,\$recursed,\@recurseup);
12472: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 12473: }
1.96 www 12474:
1.684 raeburn 12475: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 12476: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12477: 'course',$mapp,\$recursed,\@recurseup,
12478: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 12479: ([$seclevelr, 'resource'],
12480: [$seclevelm, 'map' ],
1.1301 raeburn 12481: [$secleveli, 'map' ],
1.927 albertel 12482: [$seclevel, 'course' ],
12483: [$courselevelr,'resource']));
12484: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 12485:
1.60 www 12486: # ------------------------------------------------------ third, check map parms
1.218 albertel 12487: my %parmhash=();
12488: my $thisparm='';
12489: if (tie(%parmhash,'GDBM_File',
1.620 albertel 12490: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 12491: &GDBM_READER(),0640)) {
1.218 albertel 12492: $thisparm=$parmhash{$symbparm};
12493: untie(%parmhash);
12494: }
1.927 albertel 12495: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 12496: }
1.594 albertel 12497: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 12498:
12499: my $what = $spacequalifierrest;
12500: $what=~s/\./\_/;
1.282 albertel 12501: my $filename;
12502: if (!$symbparm) { $symbparm=&symbread(); }
12503: if ($symbparm) {
1.409 www 12504: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 12505: } else {
1.620 albertel 12506: $filename=$env{'request.filename'};
1.282 albertel 12507: }
1.1362 raeburn 12508: my $toolsymb;
12509: if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
12510: $toolsymb = $symbparm;
12511: }
12512: my $metadata=&metadata($filename,$what,$toolsymb);
1.927 albertel 12513: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362 raeburn 12514: $metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927 albertel 12515: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 12516:
1.1301 raeburn 12517: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 12518: if ($symbparm && defined($courseid) &&
1.620 albertel 12519: $courseid eq $env{'request.course.id'}) {
1.624 albertel 12520: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
12521: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 12522: 'course',$mapp,\$recursed,\@recurseup,
12523: $courseid,'.',$spacequalifierrest,
1.927 albertel 12524: ([$courselevelm,'map' ],
1.1301 raeburn 12525: [$courseleveli,'map' ],
1.927 albertel 12526: [$courselevel, 'course']));
12527: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 12528: }
1.145 www 12529: # ------------------------------------------------------------------ Cascade up
1.218 albertel 12530: unless ($space eq '0') {
1.336 albertel 12531: my @parts=split(/_/,$space);
12532: my $id=pop(@parts);
12533: my $part=join('_',@parts);
12534: if ($part eq '') { $part='0'; }
1.927 albertel 12535: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 12536: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 12537: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 12538: }
1.395 albertel 12539: if ($recurse) { return undef; }
1.1362 raeburn 12540: my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927 albertel 12541: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 12542: # ---------------------------------------------------- Any other user namespace
12543: } elsif ($realm eq 'environment') {
12544: # ----------------------------------------------------------------- environment
1.620 albertel 12545: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
12546: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 12547: } else {
1.770 albertel 12548: if ($uname eq 'anonymous' && $udom eq '') {
12549: return '';
12550: }
1.219 albertel 12551: my %returnhash=&userenvironment($udom,$uname,
12552: $spacequalifierrest);
12553: return $returnhash{$spacequalifierrest};
12554: }
1.28 www 12555: } elsif ($realm eq 'system') {
1.48 www 12556: # ----------------------------------------------------------------- system.time
12557: if ($space eq 'time') {
12558: return time;
12559: }
1.696 albertel 12560: } elsif ($realm eq 'server') {
12561: # ----------------------------------------------------------------- system.time
12562: if ($space eq 'name') {
12563: return $ENV{'SERVER_NAME'};
12564: }
1.1415 raeburn 12565: } elsif ($realm eq 'client') {
12566: if ($space eq 'remote_addr') {
1.1441 raeburn 12567: return &get_requestor_ip();
1.1415 raeburn 12568: }
1.28 www 12569: }
1.48 www 12570: return '';
1.61 www 12571: }
12572:
1.927 albertel 12573: sub get_reply {
12574: my ($reply_value) = @_;
1.940 raeburn 12575: if (ref($reply_value) eq 'ARRAY') {
12576: if (wantarray) {
12577: return @$reply_value;
12578: }
12579: return $reply_value->[0];
12580: } else {
12581: return $reply_value;
1.927 albertel 12582: }
12583: }
12584:
1.691 raeburn 12585: sub check_group_parms {
1.1301 raeburn 12586: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
12587: $recursed,$recurseupref) = @_;
12588: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
12589: [$what,'course']);
12590: my $coursereply;
1.691 raeburn 12591: foreach my $group (@{$groups}) {
1.1301 raeburn 12592: my @groupitems = ();
1.691 raeburn 12593: foreach my $level (@levels) {
1.927 albertel 12594: my $item = $courseid.'.['.$group.'].'.$level->[0];
12595: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 12596: }
1.1301 raeburn 12597: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
12598: $env{'course.'.$courseid.'.domain'},
12599: 'course',$mapp,$recursed,$recurseupref,
12600: $courseid,'.['.$group.'].',$what,
12601: @groupitems);
12602: last if (defined($coursereply));
1.691 raeburn 12603: }
12604: return $coursereply;
12605: }
12606:
1.1301 raeburn 12607: sub get_map_hierarchy {
1.1302 raeburn 12608: my ($mapname,$courseid) = @_;
12609: my @recurseup = ();
1.1301 raeburn 12610: if ($mapname) {
1.1302 raeburn 12611: if (($cachedmapkey eq $courseid) &&
12612: (abs($cachedmaptime-time)<5)) {
12613: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
12614: return @{$cachedmaps{$mapname}};
12615: }
12616: }
1.1301 raeburn 12617: my $navmap = Apache::lonnavmaps::navmap->new();
12618: if (ref($navmap)) {
12619: @recurseup = $navmap->recurseup_maps($mapname);
12620: undef($navmap);
1.1302 raeburn 12621: $cachedmaps{$mapname} = \@recurseup;
12622: $cachedmaptime=time;
12623: $cachedmapkey=$courseid;
1.1301 raeburn 12624: }
12625: }
12626: return @recurseup;
12627: }
12628:
1.1302 raeburn 12629: }
12630:
1.691 raeburn 12631: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 12632: my ($courseid,@groups) = @_;
12633: @groups = sort(@groups);
1.691 raeburn 12634: return @groups;
12635: }
12636:
1.395 albertel 12637: sub packages_tab_default {
1.1362 raeburn 12638: my ($uri,$varname,$toolsymb)=@_;
1.395 albertel 12639: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 12640:
12641: my (@extension,@specifics,$do_default);
1.1362 raeburn 12642: foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395 albertel 12643: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 12644: if ($pack_type eq 'default') {
12645: $do_default=1;
12646: } elsif ($pack_type eq 'extension') {
12647: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 12648: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 12649: # only look at packages defaults for packages that this id is
1.738 albertel 12650: push(@specifics,[$package,$pack_type,$pack_part]);
12651: }
12652: }
12653: # first look for a package that matches the requested part id
12654: foreach my $package (@specifics) {
12655: my (undef,$pack_type,$pack_part)=@{$package};
12656: next if ($pack_part ne $part);
12657: if (defined($packagetab{"$pack_type&$name&default"})) {
12658: return $packagetab{"$pack_type&$name&default"};
12659: }
12660: }
12661: # look for any possible matching non extension_ package
12662: foreach my $package (@specifics) {
12663: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 12664: if (defined($packagetab{"$pack_type&$name&default"})) {
12665: return $packagetab{"$pack_type&$name&default"};
12666: }
1.585 albertel 12667: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 12668: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
12669: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 12670: }
12671: }
1.738 albertel 12672: # look for any posible extension_ match
12673: foreach my $package (@extension) {
12674: my ($package,$pack_type)=@{$package};
12675: if (defined($packagetab{"$pack_type&$name&default"})) {
12676: return $packagetab{"$pack_type&$name&default"};
12677: }
12678: if (defined($packagetab{$package."&$name&default"})) {
12679: return $packagetab{$package."&$name&default"};
12680: }
12681: }
12682: # look for a global default setting
12683: if ($do_default && defined($packagetab{"default&$name&default"})) {
12684: return $packagetab{"default&$name&default"};
12685: }
1.395 albertel 12686: return undef;
12687: }
12688:
1.334 albertel 12689: sub add_prefix_and_part {
12690: my ($prefix,$part)=@_;
12691: my $keyroot;
12692: if (defined($prefix) && $prefix !~ /^__/) {
12693: # prefix that has a part already
12694: $keyroot=$prefix;
12695: } elsif (defined($prefix)) {
12696: # prefix that is missing a part
12697: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
12698: } else {
12699: # no prefix at all
12700: if (defined($part)) { $keyroot='_'.$part; }
12701: }
12702: return $keyroot;
12703: }
12704:
1.71 www 12705: # ---------------------------------------------------------------- Get metadata
12706:
1.599 albertel 12707: my %metaentry;
1.1070 www 12708: my %importedpartids;
1.1369 raeburn 12709: my %importedrespids;
1.71 www 12710: sub metadata {
1.1362 raeburn 12711: my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71 www 12712: $uri=&declutter($uri);
1.288 albertel 12713: # if it is a non metadata possible uri return quickly
1.529 albertel 12714: if (($uri eq '') ||
12715: (($uri =~ m|^/*adm/|) &&
1.1343 raeburn 12716: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 12717: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 12718: return undef;
12719: }
1.1261 raeburn 12720: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 12721: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 12722: return undef;
1.288 albertel 12723: }
1.73 www 12724: my $filename=$uri;
12725: $uri=~s/\.meta$//;
1.172 www 12726: #
12727: # Is the metadata already cached?
1.177 www 12728: # Look at timestamp of caching
1.172 www 12729: # Everything is cached by the main uri, libraries are never directly cached
12730: #
1.428 albertel 12731: if (!defined($liburi)) {
1.599 albertel 12732: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 12733: if (defined($cached)) { return $result->{':'.$what}; }
12734: }
1.1362 raeburn 12735:
12736: #
12737: # If the uri is for an external tool the file from
12738: # which metadata should be retrieved depends on whether
12739: # the tool had been configured to be gradable (set in the Course
12740: # Editor or Resource Editor).
12741: #
12742: # If a valid symb has been included as the third arg in the call
12743: # to &metadata() that can be used to retrieve the value of
12744: # parameter_0_gradable set for the resource, and included in the
12745: # uploaded map containing the tool. The value is retrieved via
12746: # &EXT(), if a valid symb is available. Otherwise the value of
12747: # gradable in the exttool_$marker.db file for the tool instance
1.1364 raeburn 12748: # is retrieved via &get().
12749: #
12750: # When lonuserstate::traceroute() calls lonnet::EXT() for
12751: # hiddenresource and encrypturl (during course initialization)
12752: # the map-level parameter for resource.0.gradable included in the
12753: # uploaded map containing the tool will not yet have been stored
12754: # in the user_course_parms.db file for the user's session, so in
12755: # this case fall back to retrieving gradable status from the
12756: # exttool_$marker.db file.
1.1362 raeburn 12757: #
12758: # In order to avoid an infinite loop, &metadata() will return
12759: # before a call to &EXT(), if the uri is for an external tool
12760: # and the $what for which metadata is being requested is
12761: # parameter_0_gradable or 0_gradable.
12762: #
12763:
12764: if ($uri =~ /ext\.tool$/) {
12765: if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
12766: return;
12767: } else {
12768: my ($checked,$use_passback);
12769: if ($toolsymb ne '') {
12770: (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364 raeburn 12771: if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362 raeburn 12772: $checked = 1;
12773: if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
12774: $use_passback = 1;
12775: }
12776: }
12777: }
12778: unless ($checked) {
12779: my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
12780: $marker=~s/\D//g;
1.1363 raeburn 12781: if ($marker) {
1.1362 raeburn 12782: my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
12783: $use_passback = $toolsettings{'gradable'};
12784: }
12785: }
12786: if ($use_passback) {
12787: $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
12788: } else {
12789: $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
12790: }
12791: }
12792: }
12793:
1.428 albertel 12794: {
1.1069 www 12795: # Imported parts would go here
1.1369 raeburn 12796: my @origfiletagids=();
1.1069 www 12797: my $importedparts=0;
1.1369 raeburn 12798:
12799: # Imported responseids would go here
12800: my $importedresponses=0;
1.172 www 12801: #
12802: # Is this a recursive call for a library?
12803: #
1.599 albertel 12804: # if (! exists($metacache{$uri})) {
12805: # $metacache{$uri}={};
12806: # }
1.924 albertel 12807: my $cachetime = 60*60;
1.171 www 12808: if ($liburi) {
12809: $liburi=&declutter($liburi);
12810: $filename=$liburi;
1.401 bowersj2 12811: } else {
1.599 albertel 12812: &devalidate_cache_new('meta',$uri);
12813: undef(%metaentry);
1.401 bowersj2 12814: }
1.140 www 12815: my %metathesekeys=();
1.73 www 12816: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 12817: my $metastring;
1.1140 www 12818: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 12819: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 12820: $metastring =
1.929 albertel 12821: &Apache::lonnet::ssi_body($which,
1.924 albertel 12822: ('grade_target' => 'meta'));
12823: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 12824: } elsif (($uri !~ m -^(editupload)/-) &&
12825: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 12826: my $file=&filelocation('',&clutter($filename));
1.599 albertel 12827: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 12828: $metastring=&getfile($file);
1.489 albertel 12829: }
1.208 albertel 12830: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 12831: my $token;
1.140 www 12832: undef %metathesekeys;
1.71 www 12833: while ($token=$parser->get_token) {
1.339 albertel 12834: if ($token->[0] eq 'S') {
12835: if (defined($token->[2]->{'package'})) {
1.172 www 12836: #
12837: # This is a package - get package info
12838: #
1.339 albertel 12839: my $package=$token->[2]->{'package'};
12840: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12841: if (defined($token->[2]->{'id'})) {
12842: $keyroot.='_'.$token->[2]->{'id'};
12843: }
1.599 albertel 12844: if ($metaentry{':packages'}) {
12845: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 12846: } else {
1.599 albertel 12847: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 12848: }
1.736 albertel 12849: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 12850: my $part=$keyroot;
12851: $part=~s/^\_//;
1.736 albertel 12852: if ($pack_entry=~/^\Q$package\E\&/ ||
12853: $pack_entry=~/^\Q$package\E_0\&/) {
12854: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 12855: # ignore package.tab specified default values
12856: # here &package_tab_default() will fetch those
12857: if ($subp eq 'default') { next; }
1.736 albertel 12858: my $value=$packagetab{$pack_entry};
1.432 albertel 12859: my $unikey;
12860: if ($pack =~ /_0$/) {
12861: $unikey='parameter_0_'.$name;
12862: $part=0;
12863: } else {
12864: $unikey='parameter'.$keyroot.'_'.$name;
12865: }
1.339 albertel 12866: if ($subp eq 'display') {
12867: $value.=' [Part: '.$part.']';
12868: }
1.599 albertel 12869: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 12870: $metathesekeys{$unikey}=1;
1.599 albertel 12871: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12872: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 12873: }
1.599 albertel 12874: if (defined($metaentry{':'.$unikey.'.default'})) {
12875: $metaentry{':'.$unikey}=
12876: $metaentry{':'.$unikey.'.default'};
1.356 albertel 12877: }
1.339 albertel 12878: }
12879: }
12880: } else {
1.172 www 12881: #
12882: # This is not a package - some other kind of start tag
1.339 albertel 12883: #
12884: my $entry=$token->[1];
1.1068 www 12885: my $unikey='';
1.175 www 12886:
1.339 albertel 12887: if ($entry eq 'import') {
1.175 www 12888: #
12889: # Importing a library here
1.339 albertel 12890: #
1.1067 www 12891: my $location=$parser->get_text('/import');
12892: my $dir=$filename;
12893: $dir=~s|[^/]*$||;
12894: $location=&filelocation($dir,$location);
1.1369 raeburn 12895:
12896: my $importid=$token->[2]->{'id'};
1.1068 www 12897: my $importmode=$token->[2]->{'importmode'};
1.1369 raeburn 12898: #
12899: # Check metadata for imported file to
12900: # see if it contained response items
12901: #
1.1372 raeburn 12902: my ($origfile,@libfilekeys);
1.1370 raeburn 12903: my %currmetaentry = %metaentry;
1.1372 raeburn 12904: @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
12905: $depthcount+1));
12906: if (grep(/^responseorder$/,@libfilekeys)) {
12907: my $libresponseorder = &metadata($location,'responseorder',undef,undef,
12908: undef,$depthcount+1);
12909: if ($libresponseorder ne '') {
12910: if ($#origfiletagids<0) {
12911: undef(%importedrespids);
12912: undef(%importedpartids);
12913: }
1.1373 raeburn 12914: my @respids = split(/\s*,\s*/,$libresponseorder);
12915: if (@respids) {
12916: $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
12917: }
12918: if ($importedrespids{$importid} ne '') {
1.1372 raeburn 12919: $importedresponses = 1;
1.1369 raeburn 12920: # We need to get the original file and the imported file to get the response order correct
12921: # Load and inspect original file
1.1372 raeburn 12922: if ($#origfiletagids<0) {
12923: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12924: $origfile=&getfile($origfilelocation);
12925: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12926: }
1.1369 raeburn 12927: }
12928: }
12929: }
1.1370 raeburn 12930: # Do not overwrite contents of %metaentry hash for resource itself with
12931: # hash populated for imported library file
12932: %metaentry = %currmetaentry;
12933: undef(%currmetaentry);
1.1374 raeburn 12934: if ($importmode eq 'part') {
1.1068 www 12935: # Import as part(s)
1.1069 www 12936: $importedparts=1;
12937: # We need to get the original file and the imported file to get the part order correct
12938: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369 raeburn 12939: # Load and inspect original file if we didn't do that already
12940: if ($#origfiletagids<0) {
12941: undef(%importedrespids);
12942: undef(%importedpartids);
12943: if ($origfile eq '') {
12944: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12945: $origfile=&getfile($origfilelocation);
12946: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12947: }
1.1070 www 12948: }
1.1372 raeburn 12949: my @impfilepartids;
12950: # If <partorder> tag is included in metadata for the imported file
12951: # get the parts in the imported file from that.
12952: if (grep(/^partorder$/,@libfilekeys)) {
12953: %currmetaentry = %metaentry;
12954: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12955: $depthcount+1);
12956: %metaentry = %currmetaentry;
12957: undef(%currmetaentry);
12958: if ($libpartorder ne '') {
12959: @impfilepartids=split(/\s*,\s*/,$libpartorder);
12960: }
12961: } else {
12962: # If no <partorder> tag available, load and inspect imported file
12963: my $impfile=&getfile($location);
12964: @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12965: }
1.1069 www 12966: if ($#impfilepartids>=0) {
12967: # This problem had parts
1.1070 www 12968: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 12969: } else {
12970: # Importing by turning a single problem into a problem part
12971: # It gets the import-tags ID as part-ID
12972: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 12973: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 12974: }
1.1068 www 12975: } else {
1.1374 raeburn 12976: # Import as problem or as normal import
12977: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12978: unless ($importmode eq 'problem') {
1.1068 www 12979: # Normal import
1.1374 raeburn 12980: if (defined($token->[2]->{'id'})) {
12981: $unikey.='_'.$token->[2]->{'id'};
12982: }
12983: }
12984: # Check metadata for imported file to
12985: # see if it contained parts
12986: if (grep(/^partorder$/,@libfilekeys)) {
12987: %currmetaentry = %metaentry;
12988: my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
12989: $depthcount+1);
12990: %metaentry = %currmetaentry;
12991: undef(%currmetaentry);
12992: if ($libpartorder ne '') {
12993: $importedparts = 1;
12994: $importedpartids{$token->[2]->{'id'}}=$libpartorder;
12995: }
12996: }
1.1067 www 12997: }
1.339 albertel 12998: if ($depthcount<20) {
1.736 albertel 12999: my $metadata =
1.1362 raeburn 13000: &metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736 albertel 13001: $depthcount+1);
13002: foreach my $meta (split(',',$metadata)) {
13003: $metaentry{':'.$meta}=$metaentry{':'.$meta};
13004: $metathesekeys{$meta}=1;
1.339 albertel 13005: }
1.1068 www 13006: }
1.1067 www 13007: } else {
13008: #
13009: # Not importing, some other kind of non-package, non-library start tag
13010: #
13011: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13012: if (defined($token->[2]->{'id'})) {
13013: $unikey.='_'.$token->[2]->{'id'};
13014: }
1.339 albertel 13015: if (defined($token->[2]->{'name'})) {
13016: $unikey.='_'.$token->[2]->{'name'};
13017: }
13018: $metathesekeys{$unikey}=1;
1.736 albertel 13019: foreach my $param (@{$token->[3]}) {
13020: $metaentry{':'.$unikey.'.'.$param} =
13021: $token->[2]->{$param};
1.339 albertel 13022: }
13023: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 13024: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 13025: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13026: # only ws inside the tag, and not in default, so use default
13027: # as value
1.599 albertel 13028: $metaentry{':'.$unikey}=$default;
1.908 albertel 13029: } elsif ( $internaltext =~ /\S/ ) {
13030: # something interesting inside the tag
13031: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 13032: } else {
1.908 albertel 13033: # no interesting values, don't set a default
1.339 albertel 13034: }
1.172 www 13035: # end of not-a-package not-a-library import
1.339 albertel 13036: }
1.172 www 13037: # end of not-a-package start tag
1.339 albertel 13038: }
1.172 www 13039: # the next is the end of "start tag"
1.339 albertel 13040: }
13041: }
1.483 albertel 13042: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 13043: $extension = lc($extension);
13044: if ($extension eq 'htm') { $extension='html'; }
13045:
1.737 albertel 13046: foreach my $key (keys(%packagetab)) {
1.483 albertel 13047: #no specific packages #how's our extension
13048: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 13049: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 13050: \%metathesekeys);
13051: }
1.883 albertel 13052:
13053: if (!exists($metaentry{':packages'})
13054: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 13055: foreach my $key (keys(%packagetab)) {
1.483 albertel 13056: #no specific packages well let's get default then
13057: if ($key!~/^default&/) { next; }
1.488 albertel 13058: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 13059: \%metathesekeys);
13060: }
13061: }
1.338 www 13062: # are there custom rights to evaluate
1.599 albertel 13063: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 13064:
1.338 www 13065: #
13066: # Importing a rights file here
1.339 albertel 13067: #
13068: unless ($depthcount) {
1.599 albertel 13069: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 13070: my $dir=$filename;
13071: $dir=~s|[^/]*$||;
13072: $location=&filelocation($dir,$location);
1.736 albertel 13073: my $rights_metadata =
1.1362 raeburn 13074: &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736 albertel 13075: $depthcount+1);
13076: foreach my $rights (split(',',$rights_metadata)) {
13077: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13078: $metathesekeys{$rights}=1;
1.339 albertel 13079: }
13080: }
13081: }
1.737 albertel 13082: # uniqifiy package listing
13083: my %seen;
13084: my @uniq_packages =
13085: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13086: $metaentry{':packages'} = join(',',@uniq_packages);
13087:
1.1369 raeburn 13088: if (($importedresponses) || ($importedparts)) {
13089: if ($importedparts) {
1.1070 www 13090: # We had imported parts and need to rebuild partorder
1.1369 raeburn 13091: $metaentry{':partorder'}='';
13092: $metathesekeys{'partorder'}=1;
13093: }
13094: if ($importedresponses) {
13095: # We had imported responses and need to rebuil responseorder
13096: $metaentry{':responseorder'}='';
13097: $metathesekeys{'responseorder'}=1;
13098: }
13099: for (my $index=0;$index<$#origfiletagids;$index+=2) {
13100: my $origid = $origfiletagids[$index+1];
13101: if ($origfiletagids[$index] eq 'part') {
13102: # Original part, part of the problem
13103: if ($importedparts) {
13104: $metaentry{':partorder'}.=','.$origid;
13105: }
13106: } elsif ($origfiletagids[$index] eq 'import') {
13107: if ($importedparts) {
13108: # We have imported parts at this position
1.1373 raeburn 13109: if ($importedpartids{$origid} ne '') {
13110: $metaentry{':partorder'}.=','.$importedpartids{$origid};
13111: }
1.1369 raeburn 13112: }
13113: if ($importedresponses) {
13114: # We have imported responses at this position
1.1373 raeburn 13115: if ($importedrespids{$origid} ne '') {
13116: $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369 raeburn 13117: }
13118: }
13119: } else {
13120: # Original response item, part of the problem
13121: if ($importedresponses) {
13122: $metaentry{':responseorder'}.=','.$origid;
13123: }
13124: }
13125: }
13126: if ($importedparts) {
13127: $metaentry{':partorder'}=~s/^\,//;
13128: }
13129: if ($importedresponses) {
13130: $metaentry{':responseorder'}=~s/^\,//;
13131: }
1.1070 www 13132: }
1.737 albertel 13133: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 13134: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 13135: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371 raeburn 13136: unless ($liburi) {
13137: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13138: }
1.177 www 13139: # this is the end of "was not already recently cached
1.71 www 13140: }
1.599 albertel 13141: return $metaentry{':'.$what};
1.261 albertel 13142: }
13143:
1.488 albertel 13144: sub metadata_create_package_def {
1.483 albertel 13145: my ($uri,$key,$package,$metathesekeys)=@_;
13146: my ($pack,$name,$subp)=split(/\&/,$key);
13147: if ($subp eq 'default') { next; }
13148:
1.599 albertel 13149: if (defined($metaentry{':packages'})) {
13150: $metaentry{':packages'}.=','.$package;
1.483 albertel 13151: } else {
1.599 albertel 13152: $metaentry{':packages'}=$package;
1.483 albertel 13153: }
13154: my $value=$packagetab{$key};
13155: my $unikey;
13156: $unikey='parameter_0_'.$name;
1.599 albertel 13157: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 13158: $$metathesekeys{$unikey}=1;
1.599 albertel 13159: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13160: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 13161: }
1.599 albertel 13162: if (defined($metaentry{':'.$unikey.'.default'})) {
13163: $metaentry{':'.$unikey}=
13164: $metaentry{':'.$unikey.'.default'};
1.483 albertel 13165: }
13166: }
13167:
1.261 albertel 13168: sub metadata_generate_part0 {
13169: my ($metadata,$metacache,$uri) = @_;
13170: my %allnames;
1.737 albertel 13171: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 13172: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 13173: my $part=$$metacache{':'.$metakey.'.part'};
13174: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 13175: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 13176: $allnames{$name}=$part;
13177: }
13178: }
13179: }
13180: foreach my $name (keys(%allnames)) {
13181: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 13182: my $key=":parameter_0_$name";
1.261 albertel 13183: $$metacache{"$key.part"}='0';
13184: $$metacache{"$key.name"}=$name;
1.428 albertel 13185: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 13186: $allnames{$name}.'_'.$name.
13187: '.type'};
1.428 albertel 13188: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 13189: '.display'};
1.644 www 13190: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 13191: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 13192: $$metacache{"$key.display"}=$olddis;
13193: }
1.71 www 13194: }
13195:
1.764 albertel 13196: # ------------------------------------------------------ Devalidate title cache
13197:
13198: sub devalidate_title_cache {
13199: my ($url)=@_;
13200: if (!$env{'request.course.id'}) { return; }
13201: my $symb=&symbread($url);
13202: if (!$symb) { return; }
13203: my $key=$env{'request.course.id'}."\0".$symb;
13204: &devalidate_cache_new('title',$key);
13205: }
13206:
1.1014 droeschl 13207: # ------------------------------------------------- Get the title of a course
13208:
13209: sub current_course_title {
13210: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13211: }
1.301 www 13212: # ------------------------------------------------- Get the title of a resource
13213:
13214: sub gettitle {
13215: my $urlsymb=shift;
13216: my $symb=&symbread($urlsymb);
1.534 albertel 13217: if ($symb) {
1.620 albertel 13218: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 13219: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 13220: if (defined($cached)) {
13221: return $result;
13222: }
1.534 albertel 13223: my ($map,$resid,$url)=&decode_symb($symb);
13224: my $title='';
1.907 albertel 13225: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13226: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13227: } else {
13228: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13229: &GDBM_READER(),0640)) {
13230: my $mapid=$bighash{'map_pc_'.&clutter($map)};
13231: $title=$bighash{'title_'.$mapid.'.'.$resid};
13232: untie(%bighash);
13233: }
1.534 albertel 13234: }
13235: $title=~s/\&colon\;/\:/gs;
13236: if ($title) {
1.1159 www 13237: # Remember both $symb and $title for dynamic metadata
13238: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 13239: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 13240: # Cache this title and then return it
1.599 albertel 13241: return &do_cache_new('title',$key,$title,600);
1.534 albertel 13242: }
13243: $urlsymb=$url;
13244: }
13245: my $title=&metadata($urlsymb,'title');
13246: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
13247: return $title;
1.301 www 13248: }
1.613 albertel 13249:
1.614 albertel 13250: sub get_slot {
13251: my ($which,$cnum,$cdom)=@_;
13252: if (!$cnum || !$cdom) {
1.790 albertel 13253: (undef,my $courseid)=&whichuser();
1.620 albertel 13254: $cdom=$env{'course.'.$courseid.'.domain'};
13255: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 13256: }
1.703 albertel 13257: my $key=join("\0",'slots',$cdom,$cnum,$which);
13258: my %slotinfo;
13259: if (exists($remembered{$key})) {
13260: $slotinfo{$which} = $remembered{$key};
13261: } else {
13262: %slotinfo=&get('slots',[$which],$cdom,$cnum);
13263: &Apache::lonhomework::showhash(%slotinfo);
13264: my ($tmp)=keys(%slotinfo);
13265: if ($tmp=~/^error:/) { return (); }
13266: $remembered{$key} = $slotinfo{$which};
13267: }
1.616 albertel 13268: if (ref($slotinfo{$which}) eq 'HASH') {
13269: return %{$slotinfo{$which}};
13270: }
13271: return $slotinfo{$which};
1.614 albertel 13272: }
1.1150 raeburn 13273:
13274: sub get_reservable_slots {
13275: my ($cnum,$cdom,$uname,$udom) = @_;
13276: my $now = time;
13277: my $reservable_info;
13278: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13279: if (exists($remembered{$key})) {
13280: $reservable_info = $remembered{$key};
13281: } else {
13282: my %resv;
13283: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13284: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13285: $reservable_info = \%resv;
13286: $remembered{$key} = $reservable_info;
13287: }
13288: return $reservable_info;
13289: }
13290:
13291: sub get_course_slots {
13292: my ($cnum,$cdom) = @_;
13293: my $hashid=$cnum.':'.$cdom;
13294: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
13295: if (defined($cached)) {
13296: if (ref($result) eq 'HASH') {
13297: return %{$result};
13298: }
13299: } else {
13300: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
13301: my ($tmp) = keys(%slots);
13302: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 13303: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 13304: return %slots;
13305: }
13306: }
13307: return;
13308: }
13309:
13310: sub devalidate_slots_cache {
13311: my ($cnum,$cdom)=@_;
13312: my $hashid=$cnum.':'.$cdom;
13313: &devalidate_cache_new('allslots',$hashid);
13314: }
13315:
1.1181 raeburn 13316: sub get_coursechange {
13317: my ($cdom,$cnum) = @_;
13318: if ($cdom eq '' || $cnum eq '') {
13319: return unless ($env{'request.course.id'});
13320: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
13321: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
13322: }
13323: my $hashid=$cdom.'_'.$cnum;
13324: my ($change,$cached)=&is_cached_new('crschange',$hashid);
13325: if ((defined($cached)) && ($change ne '')) {
13326: return $change;
13327: } else {
13328: my %crshash;
13329: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
13330: if ($crshash{'internal.contentchange'} eq '') {
13331: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
13332: if ($change eq '') {
13333: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
13334: $change = $crshash{'internal.created'};
13335: }
13336: } else {
13337: $change = $crshash{'internal.contentchange'};
13338: }
13339: my $cachetime = 600;
13340: &do_cache_new('crschange',$hashid,$change,$cachetime);
13341: }
13342: return $change;
13343: }
13344:
13345: sub devalidate_coursechange_cache {
13346: my ($cnum,$cdom)=@_;
13347: my $hashid=$cnum.':'.$cdom;
13348: &devalidate_cache_new('crschange',$hashid);
13349: }
13350:
1.31 www 13351: # ------------------------------------------------- Update symbolic store links
13352:
13353: sub symblist {
13354: my ($mapname,%newhash)=@_;
1.438 www 13355: $mapname=&deversion(&declutter($mapname));
1.31 www 13356: my %hash;
1.620 albertel 13357: if (($env{'request.course.fn'}) && (%newhash)) {
13358: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 13359: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 13360: foreach my $url (keys(%newhash)) {
1.711 albertel 13361: next if ($url eq 'last_known'
13362: && $env{'form.no_update_last_known'});
13363: $hash{declutter($url)}=&encode_symb($mapname,
13364: $newhash{$url}->[1],
13365: $newhash{$url}->[0]);
1.191 harris41 13366: }
1.31 www 13367: if (untie(%hash)) {
13368: return 'ok';
13369: }
13370: }
13371: }
13372: return 'error';
1.212 www 13373: }
13374:
13375: # --------------------------------------------------------------- Verify a symb
13376:
13377: sub symbverify {
1.1190 raeburn 13378: my ($symb,$thisurl,$encstate)=@_;
1.510 www 13379: my $thisfn=$thisurl;
1.439 www 13380: $thisfn=&declutter($thisfn);
1.215 www 13381: # direct jump to resource in page or to a sequence - will construct own symbs
13382: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
13383: # check URL part
1.409 www 13384: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 13385:
1.431 www 13386: unless ($url eq $thisfn) { return 0; }
1.213 www 13387:
1.216 www 13388: $symb=&symbclean($symb);
1.510 www 13389: $thisurl=&deversion($thisurl);
1.439 www 13390: $thisfn=&deversion($thisfn);
1.213 www 13391:
13392: my %bighash;
13393: my $okay=0;
1.431 www 13394:
1.620 albertel 13395: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13396: &GDBM_READER(),0640)) {
1.1032 raeburn 13397: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
13398: $thisurl =~ s/\?.+$//;
1.1204 raeburn 13399: if ($map =~ m{^uploaded/.+\.page$}) {
13400: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
13401: $thisurl =~ s{^\Qhttp://https://\E}{https://};
13402: }
13403: }
13404: my $ids;
1.1419 raeburn 13405: if ($map =~ m{^uploaded/.+\.page$}) {
13406: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204 raeburn 13407: } else {
13408: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 13409: }
1.1102 raeburn 13410: unless ($ids) {
13411: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
13412: $ids=$bighash{$idkey};
1.216 www 13413: }
13414: if ($ids) {
13415: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 13416: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 13417: $symb =~ s/\?.+$//;
1.1202 raeburn 13418: }
1.800 albertel 13419: foreach my $id (split(/\,/,$ids)) {
13420: my ($mapid,$resid)=split(/\./,$id);
1.216 www 13421: if (
13422: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 13423: eq $symb) {
13424: if (ref($encstate)) {
13425: $$encstate = $bighash{'encrypted_'.$id};
13426: }
1.620 albertel 13427: if (($env{'request.role.adv'}) ||
1.1101 raeburn 13428: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
13429: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 13430: $okay=1;
1.1202 raeburn 13431: last;
1.582 albertel 13432: }
13433: }
1.216 www 13434: }
13435: }
1.213 www 13436: untie(%bighash);
13437: }
13438: return $okay;
1.31 www 13439: }
13440:
1.210 www 13441: # --------------------------------------------------------------- Clean-up symb
13442:
13443: sub symbclean {
13444: my $symb=shift;
1.568 albertel 13445: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 13446: # remove version from map
13447: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 13448:
1.210 www 13449: # remove version from URL
13450: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 13451:
1.507 www 13452: # remove wrapper
13453:
1.510 www 13454: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 13455: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 13456: return $symb;
1.409 www 13457: }
13458:
13459: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 13460:
13461: sub encode_symb {
13462: my ($map,$resid,$url)=@_;
13463: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
13464: }
1.409 www 13465:
13466: sub decode_symb {
1.568 albertel 13467: my $symb=shift;
13468: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
13469: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 13470: return (&fixversion($map),$resid,&fixversion($url));
13471: }
13472:
13473: sub fixversion {
13474: my $fn=shift;
1.609 banghart 13475: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 13476: my %bighash;
13477: my $uri=&clutter($fn);
1.620 albertel 13478: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 13479: # is this cached?
1.599 albertel 13480: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 13481: if (defined($cached)) { return $result; }
13482: # unfortunately not cached, or expired
1.620 albertel 13483: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 13484: &GDBM_READER(),0640)) {
13485: if ($bighash{'version_'.$uri}) {
13486: my $version=$bighash{'version_'.$uri};
1.444 www 13487: unless (($version eq 'mostrecent') ||
13488: ($version==&getversion($uri))) {
1.440 www 13489: $uri=~s/\.(\w+)$/\.$version\.$1/;
13490: }
13491: }
13492: untie %bighash;
1.413 www 13493: }
1.599 albertel 13494: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 13495: }
13496:
13497: sub deversion {
13498: my $url=shift;
13499: $url=~s/\.\d+\.(\w+)$/\.$1/;
13500: return $url;
1.210 www 13501: }
13502:
1.31 www 13503: # ------------------------------------------------------ Return symb list entry
13504:
13505: sub symbread {
1.1424 raeburn 13506: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1427 raeburn 13507: $ignoresymbdb,$noenccheck)=@_;
1.1265 raeburn 13508: my $cache_str='request.symbread.cached.'.$thisfn;
1.1427 raeburn 13509: if (defined($env{$cache_str})) {
1.1424 raeburn 13510: unless (ref($possibles) eq 'HASH') {
13511: if ($ignorecachednull) {
13512: return $env{$cache_str} unless ($env{$cache_str} eq '');
13513: } else {
13514: return $env{$cache_str};
13515: }
1.1282 raeburn 13516: }
13517: }
1.242 www 13518: # no filename provided? try from environment
1.1265 raeburn 13519: unless ($thisfn) {
1.620 albertel 13520: if ($env{'request.symb'}) {
1.1427 raeburn 13521: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 13522: }
1.620 albertel 13523: $thisfn=$env{'request.filename'};
1.44 www 13524: }
1.569 albertel 13525: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 13526: # is that filename actually a symb? Verify, clean, and return
13527: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 13528: if (&symbverify($thisfn,$1)) {
1.1427 raeburn 13529: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 13530: }
1.242 www 13531: }
1.44 www 13532: $thisfn=declutter($thisfn);
1.31 www 13533: my %hash;
1.37 www 13534: my %bighash;
13535: my $syval='';
1.620 albertel 13536: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 13537: my $targetfn = $thisfn;
1.609 banghart 13538: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 13539: $targetfn = 'adm/wrapper/'.$thisfn;
13540: }
1.687 albertel 13541: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
13542: $targetfn=$1;
13543: }
1.1427 raeburn 13544: unless ($ignoresymbdb) {
1.1424 raeburn 13545: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
13546: &GDBM_READER(),0640)) {
13547: $syval=$hash{$targetfn};
13548: untie(%hash);
13549: }
1.1427 raeburn 13550: if ($syval && $checkforblock) {
13551: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1424 raeburn 13552: if (@blockers) {
13553: $syval='';
13554: }
13555: }
1.37 www 13556: }
13557: # ---------------------------------------------------------- There was an entry
13558: if ($syval) {
1.601 albertel 13559: #unless ($syval=~/\_\d+$/) {
1.620 albertel 13560: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 13561: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 13562: #return $env{$cache_str}='';
1.601 albertel 13563: #}
13564: #$syval.=$1;
13565: #}
1.37 www 13566: } else {
13567: # ------------------------------------------------------- Was not in symb table
1.620 albertel 13568: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 13569: &GDBM_READER(),0640)) {
1.37 www 13570: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 13571: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 13572: unless ($ids) {
13573: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 13574: }
13575: unless ($ids) {
13576: # alias?
13577: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 13578: }
1.37 www 13579: if ($ids) {
13580: # ------------------------------------------------------------------- Has ID(s)
13581: my @possibilities=split(/\,/,$ids);
1.39 www 13582: if ($#possibilities==0) {
13583: # ----------------------------------------------- There is only one possibility
1.37 www 13584: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 13585: $syval=&encode_symb($bighash{'map_id_'.$mapid},
13586: $resid,$thisfn);
1.1282 raeburn 13587: if (ref($possibles) eq 'HASH') {
1.1424 raeburn 13588: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
13589: $possibles->{$syval} = 1;
13590: }
1.1282 raeburn 13591: }
13592: if ($checkforblock) {
1.1424 raeburn 13593: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1426 raeburn 13594: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1424 raeburn 13595: if (@blockers) {
13596: $syval = '';
1.1425 raeburn 13597: untie(%bighash);
13598: return $env{$cache_str}='';
1.1424 raeburn 13599: }
1.1282 raeburn 13600: }
13601: }
13602: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 13603: # ------------------------------------------ There is more than one possibility
13604: my $realpossible=0;
1.800 albertel 13605: foreach my $id (@possibilities) {
13606: my $file=$bighash{'src_'.$id};
1.1282 raeburn 13607: my $canaccess;
13608: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
13609: $canaccess = 1;
13610: } else {
13611: $canaccess = &allowed('bre',$file);
13612: }
13613: if ($canaccess) {
13614: my ($mapid,$resid)=split(/\./,$id);
13615: if ($bighash{'map_type_'.$mapid} ne 'page') {
13616: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
13617: $resid,$thisfn);
1.1424 raeburn 13618: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1426 raeburn 13619: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1282 raeburn 13620: if ($checkforblock) {
1.1426 raeburn 13621: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1424 raeburn 13622: if (@blockers > 0) {
13623: $syval = '';
13624: } else {
1.1282 raeburn 13625: $syval = $poss_syval;
13626: $realpossible++;
13627: }
13628: } else {
13629: $syval = $poss_syval;
13630: $realpossible++;
13631: }
1.1424 raeburn 13632: if ($syval) {
13633: if (ref($possibles) eq 'HASH') {
13634: $possibles->{$syval} = 1;
13635: }
13636: }
1.1282 raeburn 13637: }
1.39 www 13638: }
1.191 harris41 13639: }
1.39 www 13640: if ($realpossible!=1) { $syval=''; }
1.249 www 13641: } else {
13642: $syval='';
1.37 www 13643: }
13644: }
1.1282 raeburn 13645: untie(%bighash);
1.481 raeburn 13646: }
1.31 www 13647: }
1.62 www 13648: if ($syval) {
1.1427 raeburn 13649: return $env{$cache_str}=$syval;
1.62 www 13650: }
1.31 www 13651: }
1.949 raeburn 13652: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 13653: return $env{$cache_str}='';
1.31 www 13654: }
13655:
13656: # ---------------------------------------------------------- Return random seed
13657:
1.32 www 13658: sub numval {
13659: my $txt=shift;
13660: $txt=~tr/A-J/0-9/;
13661: $txt=~tr/a-j/0-9/;
13662: $txt=~tr/K-T/0-9/;
13663: $txt=~tr/k-t/0-9/;
13664: $txt=~tr/U-Z/0-5/;
13665: $txt=~tr/u-z/0-5/;
13666: $txt=~s/\D//g;
1.564 albertel 13667: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 13668: return int($txt);
1.368 albertel 13669: }
13670:
1.484 albertel 13671: sub numval2 {
13672: my $txt=shift;
13673: $txt=~tr/A-J/0-9/;
13674: $txt=~tr/a-j/0-9/;
13675: $txt=~tr/K-T/0-9/;
13676: $txt=~tr/k-t/0-9/;
13677: $txt=~tr/U-Z/0-5/;
13678: $txt=~tr/u-z/0-5/;
13679: $txt=~s/\D//g;
13680: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13681: my $total;
13682: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 13683: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 13684: return int($total);
13685: }
13686:
1.575 albertel 13687: sub numval3 {
13688: use integer;
13689: my $txt=shift;
13690: $txt=~tr/A-J/0-9/;
13691: $txt=~tr/a-j/0-9/;
13692: $txt=~tr/K-T/0-9/;
13693: $txt=~tr/k-t/0-9/;
13694: $txt=~tr/U-Z/0-5/;
13695: $txt=~tr/u-z/0-5/;
13696: $txt=~s/\D//g;
13697: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
13698: my $total;
13699: foreach my $val (@txts) { $total+=$val; }
13700: if ($_64bit) { $total=(($total<<32)>>32); }
13701: return $total;
13702: }
13703:
1.675 albertel 13704: sub digest {
13705: my ($data)=@_;
13706: my $digest=&Digest::MD5::md5($data);
13707: my ($a,$b,$c,$d)=unpack("iiii",$digest);
13708: my ($e,$f);
13709: {
13710: use integer;
13711: $e=($a+$b);
13712: $f=($c+$d);
13713: if ($_64bit) {
13714: $e=(($e<<32)>>32);
13715: $f=(($f<<32)>>32);
13716: }
13717: }
13718: if (wantarray) {
13719: return ($e,$f);
13720: } else {
13721: my $g;
13722: {
13723: use integer;
13724: $g=($e+$f);
13725: if ($_64bit) {
13726: $g=(($g<<32)>>32);
13727: }
13728: }
13729: return $g;
13730: }
13731: }
13732:
1.368 albertel 13733: sub latest_rnd_algorithm_id {
1.675 albertel 13734: return '64bit5';
1.366 albertel 13735: }
1.32 www 13736:
1.503 albertel 13737: sub get_rand_alg {
13738: my ($courseid)=@_;
1.790 albertel 13739: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 13740: if ($courseid) {
1.620 albertel 13741: return $env{"course.$courseid.rndseed"};
1.503 albertel 13742: }
13743: return &latest_rnd_algorithm_id();
13744: }
13745:
1.562 albertel 13746: sub validCODE {
13747: my ($CODE)=@_;
13748: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
13749: return 0;
13750: }
13751:
1.491 albertel 13752: sub getCODE {
1.620 albertel 13753: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 13754: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
13755: defined($Apache::lonhomework::parsing_a_task) ) &&
13756: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 13757: return $Apache::lonhomework::history{'resource.CODE'};
13758: }
13759: return undef;
13760: }
1.1133 foxr 13761: #
13762: # Determines the random seed for a specific context:
13763: #
13764: # parameters:
13765: # symb - in course context the symb for the seed.
13766: # course_id - The course id of the form domain_coursenum.
13767: # domain - Domain for the user.
13768: # course - Course for the user.
13769: # cenv - environment of the course.
13770: #
13771: # NOTE:
13772: # All parameters are picked out of the environment if missing
13773: # or not defined.
13774: # If a symb cannot be determined the current time is used instead.
13775: #
13776: # For a given well defined symb, courside, domain, username,
13777: # and course environment, the seed is reproducible.
13778: #
1.31 www 13779: sub rndseed {
1.1133 foxr 13780: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 13781: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 13782: if (!defined($symb)) {
1.366 albertel 13783: unless ($symb=$wsymb) { return time; }
13784: }
1.1146 foxr 13785: if (!defined $courseid) {
13786: $courseid=$wcourseid;
13787: }
13788: if (!defined $domain) { $domain=$wdomain; }
13789: if (!defined $username) { $username=$wusername }
1.1133 foxr 13790:
13791: my $which;
13792: if (defined($cenv->{'rndseed'})) {
13793: $which = $cenv->{'rndseed'};
13794: } else {
13795: $which =&get_rand_alg($courseid);
13796: }
1.491 albertel 13797: if (defined(&getCODE())) {
1.1133 foxr 13798:
1.675 albertel 13799: if ($which eq '64bit5') {
13800: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
13801: } elsif ($which eq '64bit4') {
1.575 albertel 13802: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
13803: } else {
13804: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
13805: }
1.675 albertel 13806: } elsif ($which eq '64bit5') {
13807: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 13808: } elsif ($which eq '64bit4') {
13809: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 13810: } elsif ($which eq '64bit3') {
13811: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 13812: } elsif ($which eq '64bit2') {
13813: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 13814: } elsif ($which eq '64bit') {
13815: return &rndseed_64bit($symb,$courseid,$domain,$username);
13816: }
13817: return &rndseed_32bit($symb,$courseid,$domain,$username);
13818: }
13819:
13820: sub rndseed_32bit {
13821: my ($symb,$courseid,$domain,$username)=@_;
13822: {
13823: use integer;
13824: my $symbchck=unpack("%32C*",$symb) << 27;
13825: my $symbseed=numval($symb) << 22;
13826: my $namechck=unpack("%32C*",$username) << 17;
13827: my $nameseed=numval($username) << 12;
13828: my $domainseed=unpack("%32C*",$domain) << 7;
13829: my $courseseed=unpack("%32C*",$courseid);
13830: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 13831: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13832: #&logthis("rndseed :$num:$symb");
1.564 albertel 13833: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 13834: return $num;
13835: }
13836: }
13837:
13838: sub rndseed_64bit {
13839: my ($symb,$courseid,$domain,$username)=@_;
13840: {
13841: use integer;
13842: my $symbchck=unpack("%32S*",$symb) << 21;
13843: my $symbseed=numval($symb) << 10;
13844: my $namechck=unpack("%32S*",$username);
13845:
13846: my $nameseed=numval($username) << 21;
13847: my $domainseed=unpack("%32S*",$domain) << 10;
13848: my $courseseed=unpack("%32S*",$courseid);
13849:
13850: my $num1=$symbchck+$symbseed+$namechck;
13851: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13852: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13853: #&logthis("rndseed :$num:$symb");
1.564 albertel 13854: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 13855: return "$num1,$num2";
1.155 albertel 13856: }
1.366 albertel 13857: }
13858:
1.443 albertel 13859: sub rndseed_64bit2 {
13860: my ($symb,$courseid,$domain,$username)=@_;
13861: {
13862: use integer;
13863: # strings need to be an even # of cahracters long, it it is odd the
13864: # last characters gets thrown away
13865: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13866: my $symbseed=numval($symb) << 10;
13867: my $namechck=unpack("%32S*",$username.' ');
13868:
13869: my $nameseed=numval($username) << 21;
1.501 albertel 13870: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13871: my $courseseed=unpack("%32S*",$courseid.' ');
13872:
13873: my $num1=$symbchck+$symbseed+$namechck;
13874: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13875: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13876: #&logthis("rndseed :$num:$symb");
1.803 albertel 13877: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 13878: return "$num1,$num2";
13879: }
13880: }
13881:
13882: sub rndseed_64bit3 {
13883: my ($symb,$courseid,$domain,$username)=@_;
13884: {
13885: use integer;
13886: # strings need to be an even # of cahracters long, it it is odd the
13887: # last characters gets thrown away
13888: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13889: my $symbseed=numval2($symb) << 10;
13890: my $namechck=unpack("%32S*",$username.' ');
13891:
13892: my $nameseed=numval2($username) << 21;
1.443 albertel 13893: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13894: my $courseseed=unpack("%32S*",$courseid.' ');
13895:
13896: my $num1=$symbchck+$symbseed+$namechck;
13897: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13898: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13899: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 13900: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13901:
1.503 albertel 13902: return "$num1:$num2";
1.443 albertel 13903: }
13904: }
13905:
1.575 albertel 13906: sub rndseed_64bit4 {
13907: my ($symb,$courseid,$domain,$username)=@_;
13908: {
13909: use integer;
13910: # strings need to be an even # of cahracters long, it it is odd the
13911: # last characters gets thrown away
13912: my $symbchck=unpack("%32S*",$symb.' ') << 21;
13913: my $symbseed=numval3($symb) << 10;
13914: my $namechck=unpack("%32S*",$username.' ');
13915:
13916: my $nameseed=numval3($username) << 21;
13917: my $domainseed=unpack("%32S*",$domain.' ') << 10;
13918: my $courseseed=unpack("%32S*",$courseid.' ');
13919:
13920: my $num1=$symbchck+$symbseed+$namechck;
13921: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 13922: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
13923: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 13924: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 13925:
1.575 albertel 13926: return "$num1:$num2";
13927: }
13928: }
13929:
1.675 albertel 13930: sub rndseed_64bit5 {
13931: my ($symb,$courseid,$domain,$username)=@_;
13932: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
13933: return "$num1:$num2";
13934: }
13935:
1.366 albertel 13936: sub rndseed_CODE_64bit {
13937: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 13938: {
1.366 albertel 13939: use integer;
1.443 albertel 13940: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 13941: my $symbseed=numval2($symb);
1.491 albertel 13942: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13943: my $CODEseed=numval(&getCODE());
1.443 albertel 13944: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 13945: my $num1=$symbseed+$CODEchck;
13946: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13947: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13948: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 13949: if ($_64bit) { $num1=(($num1<<32)>>32); }
13950: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 13951: return "$num1:$num2";
1.366 albertel 13952: }
13953: }
13954:
1.575 albertel 13955: sub rndseed_CODE_64bit4 {
13956: my ($symb,$courseid,$domain,$username)=@_;
13957: {
13958: use integer;
13959: my $symbchck=unpack("%32S*",$symb.' ') << 16;
13960: my $symbseed=numval3($symb);
13961: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13962: my $CODEseed=numval3(&getCODE());
13963: my $courseseed=unpack("%32S*",$courseid.' ');
13964: my $num1=$symbseed+$CODEchck;
13965: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13966: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13967: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 13968: if ($_64bit) { $num1=(($num1<<32)>>32); }
13969: if ($_64bit) { $num2=(($num2<<32)>>32); }
13970: return "$num1:$num2";
13971: }
13972: }
13973:
1.675 albertel 13974: sub rndseed_CODE_64bit5 {
13975: my ($symb,$courseid,$domain,$username)=@_;
13976: my $code = &getCODE();
13977: my ($num1,$num2)=&digest("$symb,$courseid,$code");
13978: return "$num1:$num2";
13979: }
13980:
1.366 albertel 13981: sub setup_random_from_rndseed {
13982: my ($rndseed)=@_;
1.503 albertel 13983: if ($rndseed =~/([,:])/) {
1.1262 raeburn 13984: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13985: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13986: &Math::Random::random_set_seed_from_phrase($rndseed);
13987: } else {
13988: &Math::Random::random_set_seed($num1,$num2);
13989: }
1.366 albertel 13990: } else {
13991: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 13992: }
1.36 albertel 13993: }
13994:
1.474 albertel 13995: sub latest_receipt_algorithm_id {
1.835 albertel 13996: return 'receipt3';
1.474 albertel 13997: }
13998:
1.480 www 13999: sub recunique {
14000: my $fucourseid=shift;
14001: my $unique;
1.835 albertel 14002: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14003: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 14004: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 14005: } else {
14006: $unique=$perlvar{'lonReceipt'};
14007: }
14008: return unpack("%32C*",$unique);
14009: }
14010:
14011: sub recprefix {
14012: my $fucourseid=shift;
14013: my $prefix;
1.835 albertel 14014: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14015: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 14016: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 14017: } else {
14018: $prefix=$perlvar{'lonHostID'};
14019: }
14020: return unpack("%32C*",$prefix);
14021: }
14022:
1.76 www 14023: sub ireceipt {
1.474 albertel 14024: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 14025:
14026: my $return =&recprefix($fucourseid).'-';
14027:
14028: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14029: $env{'request.state'} eq 'construct') {
14030: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14031: return $return;
14032: }
14033:
1.76 www 14034: my $cuname=unpack("%32C*",$funame);
14035: my $cudom=unpack("%32C*",$fudom);
14036: my $cucourseid=unpack("%32C*",$fucourseid);
14037: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 14038: my $cunique=&recunique($fucourseid);
1.474 albertel 14039: my $cpart=unpack("%32S*",$part);
1.835 albertel 14040: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14041:
1.790 albertel 14042: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 14043:
14044: $return.= ($cunique%$cuname+
14045: $cunique%$cudom+
14046: $cusymb%$cuname+
14047: $cusymb%$cudom+
14048: $cucourseid%$cuname+
14049: $cucourseid%$cudom+
14050: $cpart%$cuname+
14051: $cpart%$cudom);
14052: } else {
14053: $return.= ($cunique%$cuname+
14054: $cunique%$cudom+
14055: $cusymb%$cuname+
14056: $cusymb%$cudom+
14057: $cucourseid%$cuname+
14058: $cucourseid%$cudom);
14059: }
14060: return $return;
1.76 www 14061: }
14062:
14063: sub receipt {
1.474 albertel 14064: my ($part)=@_;
1.790 albertel 14065: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 14066: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 14067: }
1.260 ng 14068:
1.790 albertel 14069: sub whichuser {
14070: my ($passedsymb)=@_;
14071: my ($symb,$courseid,$domain,$name,$publicuser);
14072: if (defined($env{'form.grade_symb'})) {
14073: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14074: my $allowed=&allowed('vgr',$tmp_courseid);
14075: if (!$allowed &&
14076: exists($env{'request.course.sec'}) &&
14077: $env{'request.course.sec'} !~ /^\s*$/) {
14078: $allowed=&allowed('vgr',$tmp_courseid.
14079: '/'.$env{'request.course.sec'});
14080: }
14081: if ($allowed) {
14082: ($symb)=&get_env_multiple('form.grade_symb');
14083: $courseid=$tmp_courseid;
14084: ($domain)=&get_env_multiple('form.grade_domain');
14085: ($name)=&get_env_multiple('form.grade_username');
14086: return ($symb,$courseid,$domain,$name,$publicuser);
14087: }
14088: }
14089: if (!$passedsymb) {
14090: $symb=&symbread();
14091: } else {
14092: $symb=$passedsymb;
14093: }
14094: $courseid=$env{'request.course.id'};
14095: $domain=$env{'user.domain'};
14096: $name=$env{'user.name'};
14097: if ($name eq 'public' && $domain eq 'public') {
14098: if (!defined($env{'form.username'})) {
14099: $env{'form.username'}.=time.rand(10000000);
14100: }
14101: $name.=$env{'form.username'};
14102: }
14103: return ($symb,$courseid,$domain,$name,$publicuser);
14104:
14105: }
14106:
1.36 albertel 14107: # ------------------------------------------------------------ Serves up a file
1.472 albertel 14108: # returns either the contents of the file or
14109: # -1 if the file doesn't exist
1.481 raeburn 14110: #
14111: # if the target is a file that was uploaded via DOCS,
14112: # a check will be made to see if a current copy exists on the local server,
14113: # if it does this will be served, otherwise a copy will be retrieved from
14114: # the home server for the course and stored in /home/httpd/html/userfiles on
14115: # the local server.
1.472 albertel 14116:
1.36 albertel 14117: sub getfile {
1.538 albertel 14118: my ($file) = @_;
1.609 banghart 14119: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 14120: &repcopy($file);
14121: return &readfile($file);
14122: }
14123:
14124: sub repcopy_userfile {
14125: my ($file)=@_;
1.1142 raeburn 14126: my $londocroot = $perlvar{'lonDocRoot'};
14127: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 14128: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 14129: my ($cdom,$cnum,$filename) =
1.811 albertel 14130: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 14131: my $uri="/uploaded/$cdom/$cnum/$filename";
14132: if (-e "$file") {
1.828 www 14133: # we already have a local copy, check it out
1.538 albertel 14134: my @fileinfo = stat($file);
1.828 www 14135: my $rtncode;
14136: my $info;
1.538 albertel 14137: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 14138: if ($lwpresp ne 'ok') {
1.828 www 14139: # there is no such file anymore, even though we had a local copy
1.482 albertel 14140: if ($rtncode eq '404') {
1.538 albertel 14141: unlink($file);
1.482 albertel 14142: }
14143: return -1;
14144: }
14145: if ($info < $fileinfo[9]) {
1.828 www 14146: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 14147: return 'ok';
1.828 www 14148: } else {
14149: # the file is outdated, get rid of it
14150: unlink($file);
1.482 albertel 14151: }
1.828 www 14152: }
14153: # one way or the other, at this point, we don't have the file
14154: # construct the correct path for the file
14155: my @parts = ($cdom,$cnum);
14156: if ($filename =~ m|^(.+)/[^/]+$|) {
14157: push @parts, split(/\//,$1);
14158: }
14159: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14160: foreach my $part (@parts) {
14161: $path .= '/'.$part;
14162: if (!-e $path) {
14163: mkdir($path,0770);
1.482 albertel 14164: }
14165: }
1.828 www 14166: # now the path exists for sure
14167: # get a user agent
14168: my $transferfile=$file.'.in.transfer';
14169: # FIXME: this should flock
14170: if (-e $transferfile) { return 'ok'; }
14171: my $request;
14172: $uri=~s/^\///;
1.980 raeburn 14173: my $homeserver = &homeserver($cnum,$cdom);
1.1398 raeburn 14174: my $hostname = &hostname($homeserver);
1.980 raeburn 14175: my $protocol = $protocol{$homeserver};
14176: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14177: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345 raeburn 14178: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828 www 14179: # did it work?
14180: if ($response->is_error()) {
14181: unlink($transferfile);
14182: &logthis("Userfile repcopy failed for $uri");
14183: return -1;
14184: }
14185: # worked, rename the transfer file
14186: rename($transferfile,$file);
1.607 raeburn 14187: return 'ok';
1.481 raeburn 14188: }
14189:
1.517 albertel 14190: sub tokenwrapper {
14191: my $uri=shift;
1.980 raeburn 14192: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 14193: $uri=~s|^/||;
1.620 albertel 14194: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 14195: my $token=$1;
1.552 albertel 14196: my (undef,$udom,$uname,$file)=split('/',$uri,4);
14197: if ($udom && $uname && $file) {
14198: $file=~s|(\?\.*)*$||;
1.949 raeburn 14199: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 14200: my $homeserver = &homeserver($uname,$udom);
1.1397 raeburn 14201: my $hostname = &hostname($homeserver);
1.980 raeburn 14202: my $protocol = $protocol{$homeserver};
14203: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14204: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 14205: (($uri=~/\?/)?'&':'?').'token='.$token.
14206: '&tokenissued='.$perlvar{'lonHostID'};
14207: } else {
14208: return '/adm/notfound.html';
14209: }
14210: }
14211:
1.828 www 14212: # call with reqtype HEAD: get last modification time
14213: # call with reqtype GET: get the file contents
14214: # Do not call this with reqtype GET for large files! It loads everything into memory
14215: #
1.481 raeburn 14216: sub getuploaded {
14217: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14218: $uri=~s/^\///;
1.980 raeburn 14219: my $homeserver = &homeserver($cnum,$cdom);
1.1397 raeburn 14220: my $hostname = &hostname($homeserver);
1.980 raeburn 14221: my $protocol = $protocol{$homeserver};
14222: $protocol = 'http' if ($protocol ne 'https');
1.1397 raeburn 14223: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 14224: my $request=new HTTP::Request($reqtype,$uri);
1.1345 raeburn 14225: my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481 raeburn 14226: $$rtncode = $response->code;
1.482 albertel 14227: if (! $response->is_success()) {
14228: return 'failed';
14229: }
14230: if ($reqtype eq 'HEAD') {
1.486 www 14231: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 14232: } elsif ($reqtype eq 'GET') {
14233: $$info = $response->content;
1.472 albertel 14234: }
1.482 albertel 14235: return 'ok';
1.36 albertel 14236: }
14237:
1.481 raeburn 14238: sub readfile {
14239: my $file = shift;
14240: if ( (! -e $file ) || ($file eq '') ) { return -1; };
14241: my $fh;
1.1359 raeburn 14242: open($fh,"<",$file);
1.481 raeburn 14243: my $a='';
1.800 albertel 14244: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 14245: return $a;
14246: }
14247:
1.36 albertel 14248: sub filelocation {
1.590 banghart 14249: my ($dir,$file) = @_;
14250: my $location;
14251: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 14252:
14253: if ($file =~ m-^/adm/-) {
14254: $file=~s-^/adm/wrapper/-/-;
14255: $file=~s-^/adm/coursedocs/showdoc/-/-;
14256: }
1.882 albertel 14257:
1.1139 www 14258: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 14259: $location = $file;
1.609 banghart 14260: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 14261: my ($udom,$uname,$filename)=
1.811 albertel 14262: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 14263: my $home=&homeserver($uname,$udom);
14264: my $is_me=0;
14265: my @ids=¤t_machine_ids();
14266: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
14267: if ($is_me) {
1.1117 foxr 14268: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 14269: } else {
14270: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
14271: $udom.'/'.$uname.'/'.$filename;
14272: }
1.882 albertel 14273: } elsif ($file =~ m-^/adm/-) {
14274: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 14275: } else {
14276: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 14277: $file=~s:^/(res|priv)/:/:;
14278: my $space=$1;
1.590 banghart 14279: if ( !( $file =~ m:^/:) ) {
14280: $location = $dir. '/'.$file;
14281: } else {
1.1142 raeburn 14282: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 14283: }
1.59 albertel 14284: }
1.590 banghart 14285: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 14286: while ($location=~m{/\.\./}) {
14287: if ($location =~ m{/[^/]+/\.\./}) {
14288: $location=~ s{/[^/]+/\.\./}{/}g;
14289: } else {
14290: $location=~ s{/\.\./}{/}g;
14291: }
14292: } #remove dir/..
1.590 banghart 14293: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
14294: return $location;
1.46 www 14295: }
1.36 albertel 14296:
1.46 www 14297: sub hreflocation {
14298: my ($dir,$file)=@_;
1.980 raeburn 14299: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 14300: $file=filelocation($dir,$file);
1.700 albertel 14301: } elsif ($file=~m-^/adm/-) {
14302: $file=~s-^/adm/wrapper/-/-;
14303: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 14304: }
14305: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
14306: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
14307: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 14308: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
14309: {/uploaded/$1/$2/}x;
1.46 www 14310: }
1.913 albertel 14311: if ($file=~ m{^/userfiles/}) {
14312: $file =~ s{^/userfiles/}{/uploaded/};
14313: }
1.462 albertel 14314: return $file;
1.465 albertel 14315: }
14316:
1.1139 www 14317:
14318:
14319:
14320:
1.465 albertel 14321: sub current_machine_domains {
1.853 albertel 14322: return &machine_domains(&hostname($perlvar{'lonHostID'}));
14323: }
14324:
14325: sub machine_domains {
14326: my ($hostname) = @_;
1.465 albertel 14327: my @domains;
1.838 albertel 14328: my %hostname = &all_hostnames();
1.465 albertel 14329: while( my($id, $name) = each(%hostname)) {
1.467 matthew 14330: # &logthis("-$id-$name-$hostname-");
1.465 albertel 14331: if ($hostname eq $name) {
1.844 albertel 14332: push(@domains,&host_domain($id));
1.465 albertel 14333: }
14334: }
14335: return @domains;
14336: }
14337:
14338: sub current_machine_ids {
1.853 albertel 14339: return &machine_ids(&hostname($perlvar{'lonHostID'}));
14340: }
14341:
14342: sub machine_ids {
14343: my ($hostname) = @_;
14344: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 14345: my @ids;
1.888 albertel 14346: my %name_to_host = &all_names();
1.889 albertel 14347: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
14348: return @{ $name_to_host{$hostname} };
14349: }
14350: return;
1.31 www 14351: }
14352:
1.824 raeburn 14353: sub additional_machine_domains {
14354: my @domains;
1.1359 raeburn 14355: open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824 raeburn 14356: while( my $line = <$fh>) {
14357: $line =~ s/\s//g;
14358: push(@domains,$line);
14359: }
14360: return @domains;
14361: }
14362:
14363: sub default_login_domain {
14364: my $domain = $perlvar{'lonDefDomain'};
14365: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
14366: foreach my $posdom (¤t_machine_domains(),
14367: &additional_machine_domains()) {
14368: if (lc($posdom) eq lc($testdomain)) {
14369: $domain=$posdom;
14370: last;
14371: }
14372: }
14373: return $domain;
14374: }
14375:
1.1414 raeburn 14376: sub shared_institution {
1.1439 raeburn 14377: my ($dom,$lonhost) = @_;
14378: if ($lonhost eq '') {
14379: $lonhost = $perlvar{'lonHostID'};
14380: }
1.1414 raeburn 14381: my $same_intdom;
1.1439 raeburn 14382: my $hostintdom = &internet_dom($lonhost);
1.1414 raeburn 14383: if ($hostintdom ne '') {
14384: my %iphost = &get_iphost();
14385: my $primary_id = &domain($dom,'primary');
14386: my $primary_ip = &get_host_ip($primary_id);
14387: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
14388: foreach my $id (@{$iphost{$primary_ip}}) {
14389: my $intdom = &internet_dom($id);
14390: if ($intdom eq $hostintdom) {
14391: $same_intdom = 1;
14392: last;
14393: }
14394: }
14395: }
14396: }
14397: return $same_intdom;
14398: }
14399:
1.1398 raeburn 14400: sub uses_sts {
14401: my ($ignore_cache) = @_;
14402: my $lonhost = $perlvar{'lonHostID'};
14403: my $hostname = &hostname($lonhost);
14404: my $sts_on;
14405: if ($protocol{$lonhost} eq 'https') {
14406: my $cachetime = 12*3600;
14407: if (!$ignore_cache) {
14408: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
14409: if (defined($cached)) {
14410: return $sts_on;
14411: }
14412: }
14413: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
14414: my $request=new HTTP::Request('HEAD',$url);
14415: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
14416: if ($response->is_success) {
14417: my $has_sts = $response->header('Strict-Transport-Security');
14418: if ($has_sts eq '') {
14419: $sts_on = 0;
14420: } else {
14421: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
14422: my $maxage = $1;
14423: if ($maxage) {
14424: $sts_on = 1;
14425: } else {
14426: $sts_on = 0;
14427: }
14428: } else {
14429: $sts_on = 0;
14430: }
14431: }
14432: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
14433: }
14434: }
14435: return;
14436: }
14437:
1.1449 raeburn 14438: sub waf_allssl {
14439: my ($host_name) = @_;
14440: my $alias = &get_proxy_alias();
14441: if ($host_name eq '') {
14442: $host_name = $ENV{'SERVER_NAME'};
14443: }
14444: if (($host_name ne '') && ($alias eq $host_name)) {
14445: my $serverhomedom = &host_domain($perlvar{'lonHostID'});
14446: my %defdomdefaults = &get_domain_defaults($serverhomedom);
14447: if ($defdomdefaults{'waf_sslopt'}) {
14448: return $defdomdefaults{'waf_sslopt'};
14449: }
14450: }
14451: return;
14452: }
14453:
1.1434 raeburn 14454: sub get_requestor_ip {
14455: my ($r,$nolookup,$noproxy) = @_;
14456: my $from_ip;
14457: if (ref($r)) {
1.1447 raeburn 14458: if ($r->can('useragent_ip')) {
14459: if ($noproxy && $r->can('client_ip')) {
14460: $from_ip = $r->client_ip();
14461: } else {
14462: $from_ip = $r->useragent_ip();
14463: }
14464: } elsif ($r->connection->can('remote_ip')) {
14465: $from_ip = $r->connection->remote_ip();
14466: } else {
14467: $from_ip = $r->get_remote_host($nolookup);
14468: }
1.1434 raeburn 14469: } else {
14470: $from_ip = $ENV{'REMOTE_ADDR'};
14471: }
14472: return $from_ip if ($noproxy);
14473: # Who controls proxy settings for server
14474: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
14475: my $proxyinfo = &get_proxy_settings($dom_in_use);
14476: if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
1.1437 raeburn 14477: if ($proxyinfo->{'vpnint'}) {
14478: if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
1.1434 raeburn 14479: return $from_ip;
14480: }
14481: }
14482: if ($proxyinfo->{'trusted'}) {
14483: if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
14484: my $ipheader = $proxyinfo->{'ipheader'};
14485: my ($ip,$xfor);
14486: if (ref($r)) {
14487: if ($ipheader) {
14488: $ip = $r->headers_in->{$ipheader};
14489: }
14490: $xfor = $r->headers_in->{'X-Forwarded-For'};
14491: } else {
14492: if ($ipheader) {
14493: $ip = $ENV{'HTTP_'.uc($ipheader)};
14494: }
14495: $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
14496: }
14497: if (($ip eq '') && ($xfor ne '')) {
14498: foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
14499: unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
14500: $ip = $poss_ip;
1.1435 raeburn 14501: last;
1.1434 raeburn 14502: }
14503: }
14504: }
14505: if ($ip ne '') {
14506: return $ip;
14507: }
14508: }
14509: }
14510: }
14511: return $from_ip;
14512: }
14513:
14514: sub get_proxy_settings {
14515: my ($dom_in_use) = @_;
14516: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
14517: my $proxyinfo = {
14518: ipheader => $domdefaults{'waf_ipheader'},
14519: trusted => $domdefaults{'waf_trusted'},
1.1437 raeburn 14520: vpnint => $domdefaults{'waf_vpnint'},
1.1438 raeburn 14521: vpnext => $domdefaults{'waf_vpnext'},
1.1449 raeburn 14522: sslopt => $domdefaults{'waf_sslopt'},
1.1434 raeburn 14523: };
14524: return $proxyinfo;
14525: }
14526:
14527: sub ip_match {
14528: my ($ip,$pattern_str) = @_;
14529: $ip=Net::CIDR::cidrvalidate($ip);
14530: if ($ip) {
14531: return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
14532: }
14533: return;
14534: }
14535:
14536: sub get_proxy_alias {
1.1450 raeburn 14537: my ($lonid) = @_;
14538: if ($lonid eq '') {
14539: $lonid = $perlvar{'lonHostID'};
14540: }
14541: if (!defined(&hostname($lonid))) {
14542: return;
14543: }
14544: if ($lonid ne '') {
14545: my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
1.1434 raeburn 14546: if ($cached) {
14547: return $alias;
14548: }
1.1450 raeburn 14549: my $dom = &Apache::lonnet::host_domain($lonid);
1.1434 raeburn 14550: if ($dom ne '') {
14551: my $cachetime = 60*60*24;
14552: my %domconfig =
1.1437 raeburn 14553: &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
1.1434 raeburn 14554: my $alias;
1.1437 raeburn 14555: if (ref($domconfig{'wafproxy'}) eq 'HASH') {
14556: if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
1.1450 raeburn 14557: $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
14558: }
14559: }
14560: return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
14561: }
14562: }
14563: return;
14564: }
14565:
14566: sub use_proxy_alias {
14567: my ($r,$lonid) = @_;
14568: my $alias = &get_proxy_alias($lonid);
14569: if ($alias) {
14570: my $dom = &host_domain($lonid);
14571: if ($dom ne '') {
14572: my $proxyinfo = &get_proxy_settings($dom );
14573: my ($vpnint,$remote_ip);
14574: if (ref($proxyinfo) eq 'HASH') {
14575: $vpnint = $proxyinfo->{'vpnint'};
14576: if ($vpnint) {
14577: $remote_ip = &get_requestor_ip($r,1,1);
1.1434 raeburn 14578: }
14579: }
1.1450 raeburn 14580: unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
14581: return $alias;
14582: }
1.1434 raeburn 14583: }
14584: }
14585: return;
14586: }
14587:
1.31 www 14588: # ------------------------------------------------------------- Declutters URLs
14589:
14590: sub declutter {
14591: my $thisfn=shift;
1.569 albertel 14592: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 14593: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
14594: $thisfn=~s{^/home/httpd/html}{};
14595: }
1.31 www 14596: $thisfn=~s/^\///;
1.697 albertel 14597: $thisfn=~s|^adm/wrapper/||;
14598: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 14599: $thisfn=~s/^res\///;
1.1172 bisitz 14600: $thisfn=~s/^priv\///;
1.1032 raeburn 14601: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
14602: $thisfn=~s/\?.+$//;
14603: }
1.268 www 14604: return $thisfn;
14605: }
14606:
14607: # ------------------------------------------------------------- Clutter up URLs
14608:
14609: sub clutter {
14610: my $thisfn='/'.&declutter(shift);
1.887 albertel 14611: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 14612: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 14613: $thisfn='/res'.$thisfn;
14614: }
1.1031 raeburn 14615: if ($thisfn !~m|^/adm|) {
14616: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 14617: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 14618: } else {
14619: my ($ext) = ($thisfn =~ /\.(\w+)$/);
14620: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 14621: if ($embstyle eq 'ssi'
14622: || ($embstyle eq 'hdn')
14623: || ($embstyle eq 'rat')
14624: || ($embstyle eq 'prv')
14625: || ($embstyle eq 'ign')) {
14626: #do nothing with these
14627: } elsif (($embstyle eq 'img')
1.695 albertel 14628: || ($embstyle eq 'emb')
14629: || ($embstyle eq 'wrp')) {
14630: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 14631: } elsif ($embstyle eq 'unk'
14632: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 14633: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 14634: } else {
1.718 www 14635: # &logthis("Got a blank emb style");
1.695 albertel 14636: }
1.694 albertel 14637: }
1.1343 raeburn 14638: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298 raeburn 14639: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 14640: }
1.31 www 14641: return $thisfn;
1.12 www 14642: }
14643:
1.787 albertel 14644: sub clutter_with_no_wrapper {
14645: my $uri = &clutter(shift);
14646: if ($uri =~ m-^/adm/-) {
14647: $uri =~ s-^/adm/wrapper/-/-;
14648: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
14649: }
14650: return $uri;
14651: }
14652:
1.557 albertel 14653: sub freeze_escape {
14654: my ($value)=@_;
14655: if (ref($value)) {
14656: $value=&nfreeze($value);
14657: return '__FROZEN__'.&escape($value);
14658: }
14659: return &escape($value);
14660: }
14661:
1.11 www 14662:
1.557 albertel 14663: sub thaw_unescape {
14664: my ($value)=@_;
14665: if ($value =~ /^__FROZEN__/) {
14666: substr($value,0,10,undef);
14667: $value=&unescape($value);
14668: return &thaw($value);
14669: }
14670: return &unescape($value);
14671: }
14672:
1.436 albertel 14673: sub correct_line_ends {
14674: my ($result)=@_;
14675: $$result =~s/\r\n/\n/mg;
14676: $$result =~s/\r/\n/mg;
1.415 albertel 14677: }
1.1 albertel 14678: # ================================================================ Main Program
14679:
1.184 www 14680: sub goodbye {
1.204 albertel 14681: &logthis("Starting Shut down");
1.443 albertel 14682: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 14683: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 14684: #converted
1.599 albertel 14685: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 14686: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
14687: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
14688: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 14689: #1.1 only
1.870 albertel 14690: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
14691: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
14692: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
14693: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
14694: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 14695: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
14696: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 14697: &flushcourselogs();
14698: &logthis("Shutting down");
14699: }
14700:
1.852 albertel 14701: sub get_dns {
1.1210 raeburn 14702: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 14703: if (!$ignore_cache) {
14704: my ($content,$cached)=
14705: &Apache::lonnet::is_cached_new('dns',$url);
14706: if ($cached) {
1.1210 raeburn 14707: &$func($content,$hashref);
1.869 albertel 14708: return;
14709: }
14710: }
14711:
14712: my %alldns;
1.1379 raeburn 14713: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
14714: foreach my $dns (<$config>) {
14715: next if ($dns !~ /^\^(\S*)/x);
14716: my $line = $1;
14717: my ($host,$protocol) = split(/:/,$line);
14718: if ($protocol ne 'https') {
14719: $protocol = 'http';
14720: }
14721: $alldns{$host} = $protocol;
1.979 raeburn 14722: }
1.1379 raeburn 14723: close($config);
1.869 albertel 14724: }
14725: while (%alldns) {
1.1263 raeburn 14726: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1456 raeburn 14727: my ($contents,@content);
14728: if ($dns eq Sys::Hostname::FQDN::fqdn()) {
14729: my $command = (split('/',$url))[3];
14730: my ($dir,$file) = &parse_getdns_url($command,$url);
14731: delete($alldns{$dns});
14732: next if (($dir eq '') || ($file eq ''));
14733: if (open(my $config,'<',"$dir/$file")) {
1.1457 raeburn 14734: @content = <$config>;
1.1456 raeburn 14735: close($config);
14736: }
14737: if ($url eq '/adm/dns/loncapaCRL') {
14738: $contents = join('',@content);
14739: }
14740: } else {
14741: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
14742: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
14743: delete($alldns{$dns});
14744: next if ($response->is_error());
14745: if ($url eq '/adm/dns/loncapaCRL') {
14746: $contents = $response->content;
14747: } else {
14748: @content = split("\n",$response->content);
14749: }
14750: }
1.1379 raeburn 14751: if ($url eq '/adm/dns/loncapaCRL') {
1.1456 raeburn 14752: return &$func($contents);
1.1379 raeburn 14753: } else {
14754: unless ($nocache) {
14755: &do_cache_new('dns',$url,\@content,30*24*60*60);
14756: }
14757: &$func(\@content,$hashref);
14758: return;
14759: }
14760: }
14761: my $which = (split('/',$url,4))[3];
14762: if ($which eq 'loncapaCRL') {
14763: my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
14764: if (-e $diskfile) {
14765: &logthis("unable to contact DNS, on disk file $diskfile not updated");
14766: } else {
14767: &logthis("unable to contact DNS, no on disk file $diskfile available");
14768: }
14769: } else {
14770: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
14771: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
14772: my @content = <$config>;
14773: close($config);
14774: &$func(\@content,$hashref);
14775: }
1.852 albertel 14776: }
1.1210 raeburn 14777: return;
14778: }
14779:
14780: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 14781: sub parse_dns_checksums_tab {
1.1210 raeburn 14782: my ($lines,$hashref) = @_;
1.1264 raeburn 14783: my $lonhost = $perlvar{'lonHostID'};
14784: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 14785: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 14786: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
14787: my $webconfdir = '/etc/httpd/conf';
14788: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
14789: $webconfdir = '/etc/apache2';
14790: } elsif ($distro =~ /^sles(\d+)$/) {
14791: if ($1 >= 10) {
14792: $webconfdir = '/etc/apache2';
14793: }
14794: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
14795: if ($1 >= 10.0) {
14796: $webconfdir = '/etc/apache2';
14797: }
14798: }
1.1210 raeburn 14799: my ($release,$timestamp) = split(/\-/,$loncaparev);
14800: my (%chksum,%revnum);
14801: if (ref($lines) eq 'ARRAY') {
14802: chomp(@{$lines});
1.1238 raeburn 14803: my $version = shift(@{$lines});
14804: if ($version eq $release) {
1.1210 raeburn 14805: foreach my $line (@{$lines}) {
1.1238 raeburn 14806: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 14807: if ($file =~ m{^/etc/httpd/conf}) {
14808: if ($webconfdir eq '/etc/apache2') {
14809: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
14810: }
14811: }
1.1238 raeburn 14812: $chksum{$file} = $shasum;
14813: $revnum{$file} = $version;
1.1210 raeburn 14814: }
14815: if (ref($hashref) eq 'HASH') {
14816: %{$hashref} = (
14817: sums => \%chksum,
14818: versions => \%revnum,
14819: );
14820: }
14821: }
14822: }
1.869 albertel 14823: return;
1.852 albertel 14824: }
1.1210 raeburn 14825:
14826: sub fetch_dns_checksums {
1.1238 raeburn 14827: my %checksums;
14828: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 14829: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 14830: my ($release,$timestamp) = split(/\-/,$loncaparev);
14831: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 14832: \%checksums);
1.1210 raeburn 14833: return \%checksums;
14834: }
14835:
1.1379 raeburn 14836: sub fetch_crl_pemfile {
14837: return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
14838: }
14839:
14840: sub save_crl_pem {
1.1456 raeburn 14841: my ($content) = @_;
1.1380 raeburn 14842: my ($msg,$hadchanges);
1.1456 raeburn 14843: if ($content ne '') {
1.1379 raeburn 14844: my $now = time;
14845: my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
14846: my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
14847: if (open(my $fh,'>',"$tmpcrl")) {
1.1456 raeburn 14848: print $fh $content;
1.1379 raeburn 14849: close($fh);
14850: if (-e $lonca) {
14851: if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
14852: my $check = <PIPE>;
14853: close(PIPE);
14854: chomp($check);
14855: if ($check eq 'verify OK') {
14856: my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380 raeburn 14857: my $backup;
1.1379 raeburn 14858: if (-e $dest) {
1.1380 raeburn 14859: if (&File::Copy::move($dest,"$dest.bak")) {
14860: $backup = 'ok';
14861: }
1.1379 raeburn 14862: }
14863: if (&File::Copy::move($tmpcrl,$dest)) {
14864: $msg = 'ok';
1.1380 raeburn 14865: if ($backup) {
14866: my (%oldnums,%newnums);
14867: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
14868: while (<PIPE>) {
14869: $oldnums{(split(/:/))[1]} = 1;
14870: }
14871: close(PIPE);
14872: }
14873: if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
14874: while(<PIPE>) {
14875: $newnums{(split(/:/))[1]} = 1;
14876: }
14877: close(PIPE);
14878: }
14879: foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
14880: unless (exists($oldnums{$key})) {
14881: $hadchanges = 1;
14882: last;
14883: }
14884: }
14885: unless ($hadchanges) {
14886: foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
14887: unless (exists($newnums{$key})) {
14888: $hadchanges = 1;
14889: last;
14890: }
14891: }
14892: }
14893: }
1.1379 raeburn 14894: }
14895: } else {
14896: unlink($tmpcrl);
14897: }
14898: } else {
14899: unlink($tmpcrl);
14900: }
14901: } else {
14902: unlink($tmpcrl);
14903: }
14904: }
14905: }
1.1380 raeburn 14906: return ($msg,$hadchanges);
1.1379 raeburn 14907: }
14908:
1.1456 raeburn 14909: sub parse_getdns_url {
14910: my ($command,$url) = @_;
14911: my $dir = $perlvar{'lonTabDir'};
14912: my $file;
14913: if ($command eq 'hosts') {
14914: $file = 'dns_hosts.tab';
14915: } elsif ($command eq 'domain') {
14916: $file = 'dns_domain.tab';
14917: } elsif ($command eq 'checksums') {
14918: my $version = (split('/',$url))[4];
14919: $file = "dns_checksums/$version.tab",
14920: } elsif ($command eq 'loncapaCRL') {
14921: $dir = $perlvar{'lonCertificateDirectory'};
14922: $file = $perlvar{'lonnetCertRevocationList'};
14923: }
14924: return ($dir,$file);
14925: }
14926:
1.327 albertel 14927: # ------------------------------------------------------------ Read domain file
14928: {
1.852 albertel 14929: my $loaded;
1.846 albertel 14930: my %domain;
14931:
1.852 albertel 14932: sub parse_domain_tab {
14933: my ($lines) = @_;
14934: foreach my $line (@$lines) {
14935: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 14936:
1.846 albertel 14937: chomp($line);
1.852 albertel 14938: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 14939: my %this_domain;
14940: foreach my $field ('description', 'auth_def', 'auth_arg_def',
14941: 'lang_def', 'city', 'longi', 'lati',
14942: 'primary') {
14943: $this_domain{$field} = shift(@elements);
14944: }
14945: $domain{$name} = \%this_domain;
1.852 albertel 14946: }
14947: }
1.864 albertel 14948:
14949: sub reset_domain_info {
14950: undef($loaded);
14951: undef(%domain);
14952: }
14953:
1.852 albertel 14954: sub load_domain_tab {
1.1293 raeburn 14955: my ($ignore_cache,$nocache) = @_;
14956: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 14957: my $fh;
1.1359 raeburn 14958: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 14959: my @lines = <$fh>;
14960: &parse_domain_tab(\@lines);
1.448 albertel 14961: }
1.852 albertel 14962: close($fh);
14963: $loaded = 1;
1.327 albertel 14964: }
1.846 albertel 14965:
14966: sub domain {
1.852 albertel 14967: &load_domain_tab() if (!$loaded);
14968:
1.846 albertel 14969: my ($name,$what) = @_;
14970: return if ( !exists($domain{$name}) );
14971:
14972: if (!$what) {
14973: return $domain{$name}{'description'};
14974: }
14975: return $domain{$name}{$what};
14976: }
1.974 raeburn 14977:
14978: sub domain_info {
14979: &load_domain_tab() if (!$loaded);
14980: return %domain;
14981: }
14982:
1.327 albertel 14983: }
14984:
14985:
1.1 albertel 14986: # ------------------------------------------------------------- Read hosts file
14987: {
1.838 albertel 14988: my %hostname;
1.844 albertel 14989: my %hostdom;
1.845 albertel 14990: my %libserv;
1.852 albertel 14991: my $loaded;
1.888 albertel 14992: my %name_to_host;
1.1074 raeburn 14993: my %internetdom;
1.1107 raeburn 14994: my %LC_dns_serv;
1.852 albertel 14995:
14996: sub parse_hosts_tab {
14997: my ($file) = @_;
14998: foreach my $configline (@$file) {
14999: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 15000: chomp($configline);
15001: if ($configline =~ /^\^/) {
15002: if ($configline =~ /^\^([\w.\-]+)/) {
15003: $LC_dns_serv{$1} = 1;
15004: }
15005: next;
15006: }
1.1074 raeburn 15007: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 15008: $name=~s/\s//g;
15009: if ($id && $domain && $role && $name) {
1.1351 raeburn 15010: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15011: my $curr = $hostname{$id};
15012: my $skip;
15013: if (ref($name_to_host{$curr}) eq 'ARRAY') {
15014: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15015: $skip = 1;
15016: } else {
15017: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15018: }
15019: }
15020: unless ($skip) {
15021: push(@{$name_to_host{$name}},$id);
15022: }
15023: } else {
15024: push(@{$name_to_host{$name}},$id);
15025: }
1.852 albertel 15026: $hostname{$id}=$name;
15027: $hostdom{$id}=$domain;
15028: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 15029: if (defined($protocol)) {
15030: if ($protocol eq 'https') {
15031: $protocol{$id} = $protocol;
15032: } else {
15033: $protocol{$id} = 'http';
15034: }
1.968 raeburn 15035: } else {
1.969 raeburn 15036: $protocol{$id} = 'http';
1.968 raeburn 15037: }
1.1074 raeburn 15038: if (defined($intdom)) {
15039: $internetdom{$id} = $intdom;
15040: }
1.852 albertel 15041: }
15042: }
15043: }
1.864 albertel 15044:
15045: sub reset_hosts_info {
1.897 albertel 15046: &purge_remembered();
1.864 albertel 15047: &reset_domain_info();
15048: &reset_hosts_ip_info();
1.1339 raeburn 15049: undef(%internetdom);
1.892 albertel 15050: undef(%name_to_host);
1.864 albertel 15051: undef(%hostname);
15052: undef(%hostdom);
15053: undef(%libserv);
15054: undef($loaded);
15055: }
1.1 albertel 15056:
1.852 albertel 15057: sub load_hosts_tab {
1.1293 raeburn 15058: my ($ignore_cache,$nocache) = @_;
15059: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359 raeburn 15060: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 15061: my @config = <$config>;
15062: &parse_hosts_tab(\@config);
15063: close($config);
15064: $loaded=1;
1.1 albertel 15065: }
1.852 albertel 15066:
1.838 albertel 15067: sub hostname {
1.852 albertel 15068: &load_hosts_tab() if (!$loaded);
15069:
1.838 albertel 15070: my ($lonid) = @_;
15071: return $hostname{$lonid};
15072: }
1.845 albertel 15073:
1.838 albertel 15074: sub all_hostnames {
1.852 albertel 15075: &load_hosts_tab() if (!$loaded);
15076:
1.838 albertel 15077: return %hostname;
15078: }
1.845 albertel 15079:
1.888 albertel 15080: sub all_names {
1.1293 raeburn 15081: my ($ignore_cache,$nocache) = @_;
15082: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 15083:
15084: return %name_to_host;
15085: }
15086:
1.974 raeburn 15087: sub all_host_domain {
15088: &load_hosts_tab() if (!$loaded);
15089: return %hostdom;
15090: }
15091:
1.1339 raeburn 15092: sub all_host_intdom {
15093: &load_hosts_tab() if (!$loaded);
15094: return %internetdom;
15095: }
15096:
1.845 albertel 15097: sub is_library {
1.852 albertel 15098: &load_hosts_tab() if (!$loaded);
15099:
1.845 albertel 15100: return exists($libserv{$_[0]});
15101: }
15102:
15103: sub all_library {
1.852 albertel 15104: &load_hosts_tab() if (!$loaded);
15105:
1.845 albertel 15106: return %libserv;
15107: }
15108:
1.1062 droeschl 15109: sub unique_library {
15110: #2x reverse removes all hostnames that appear more than once
15111: my %unique = reverse &all_library();
15112: return reverse %unique;
15113: }
15114:
1.841 albertel 15115: sub get_servers {
1.852 albertel 15116: &load_hosts_tab() if (!$loaded);
15117:
1.841 albertel 15118: my ($domain,$type) = @_;
15119: my %possible_hosts = ($type eq 'library') ? %libserv
15120: : %hostname;
15121: my %result;
1.842 albertel 15122: if (ref($domain) eq 'ARRAY') {
15123: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 15124: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 15125: $result{$host} = $hostname;
15126: }
15127: }
15128: } else {
15129: while ( my ($host,$hostname) = each(%possible_hosts)) {
15130: if ($hostdom{$host} eq $domain) {
15131: $result{$host} = $hostname;
15132: }
1.841 albertel 15133: }
15134: }
15135: return %result;
15136: }
1.845 albertel 15137:
1.1062 droeschl 15138: sub get_unique_servers {
15139: my %unique = reverse &get_servers(@_);
15140: return reverse %unique;
15141: }
15142:
1.844 albertel 15143: sub host_domain {
1.852 albertel 15144: &load_hosts_tab() if (!$loaded);
15145:
1.844 albertel 15146: my ($lonid) = @_;
15147: return $hostdom{$lonid};
15148: }
15149:
1.841 albertel 15150: sub all_domains {
1.852 albertel 15151: &load_hosts_tab() if (!$loaded);
15152:
1.841 albertel 15153: my %seen;
15154: my @uniq = grep(!$seen{$_}++, values(%hostdom));
15155: return @uniq;
15156: }
1.1074 raeburn 15157:
15158: sub internet_dom {
15159: &load_hosts_tab() if (!$loaded);
15160:
15161: my ($lonid) = @_;
15162: return $internetdom{$lonid};
15163: }
1.1107 raeburn 15164:
15165: sub is_LC_dns {
15166: &load_hosts_tab() if (!$loaded);
15167:
15168: my ($hostname) = @_;
15169: return exists($LC_dns_serv{$hostname});
15170: }
15171:
1.1 albertel 15172: }
15173:
1.847 albertel 15174: {
15175: my %iphost;
1.856 albertel 15176: my %name_to_ip;
15177: my %lonid_to_ip;
1.869 albertel 15178:
1.847 albertel 15179: sub get_hosts_from_ip {
15180: my ($ip) = @_;
15181: my %iphosts = &get_iphost();
15182: if (ref($iphosts{$ip})) {
15183: return @{$iphosts{$ip}};
15184: }
15185: return;
1.839 albertel 15186: }
1.864 albertel 15187:
15188: sub reset_hosts_ip_info {
15189: undef(%iphost);
15190: undef(%name_to_ip);
15191: undef(%lonid_to_ip);
15192: }
1.856 albertel 15193:
15194: sub get_host_ip {
15195: my ($lonid) = @_;
15196: if (exists($lonid_to_ip{$lonid})) {
15197: return $lonid_to_ip{$lonid};
15198: }
15199: my $name=&hostname($lonid);
15200: my $ip = gethostbyname($name);
15201: return if (!$ip || length($ip) ne 4);
15202: $ip=inet_ntoa($ip);
15203: $name_to_ip{$name} = $ip;
15204: $lonid_to_ip{$lonid} = $ip;
15205: return $ip;
15206: }
1.847 albertel 15207:
15208: sub get_iphost {
1.1293 raeburn 15209: my ($ignore_cache,$nocache) = @_;
1.894 albertel 15210:
1.869 albertel 15211: if (!$ignore_cache) {
15212: if (%iphost) {
15213: return %iphost;
15214: }
15215: my ($ip_info,$cached)=
15216: &Apache::lonnet::is_cached_new('iphost','iphost');
15217: if ($cached) {
15218: %iphost = %{$ip_info->[0]};
15219: %name_to_ip = %{$ip_info->[1]};
15220: %lonid_to_ip = %{$ip_info->[2]};
15221: return %iphost;
15222: }
15223: }
1.894 albertel 15224:
15225: # get yesterday's info for fallback
15226: my %old_name_to_ip;
15227: my ($ip_info,$cached)=
15228: &Apache::lonnet::is_cached_new('iphost','iphost');
15229: if ($cached) {
15230: %old_name_to_ip = %{$ip_info->[1]};
15231: }
15232:
1.1293 raeburn 15233: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 15234: foreach my $name (keys(%name_to_host)) {
1.847 albertel 15235: my $ip;
15236: if (!exists($name_to_ip{$name})) {
15237: $ip = gethostbyname($name);
15238: if (!$ip || length($ip) ne 4) {
1.894 albertel 15239: if (defined($old_name_to_ip{$name})) {
15240: $ip = $old_name_to_ip{$name};
15241: &logthis("Can't find $name defaulting to old $ip");
15242: } else {
15243: &logthis("Name $name no IP found");
15244: next;
15245: }
15246: } else {
15247: $ip=inet_ntoa($ip);
1.847 albertel 15248: }
15249: $name_to_ip{$name} = $ip;
15250: } else {
15251: $ip = $name_to_ip{$name};
1.653 albertel 15252: }
1.888 albertel 15253: foreach my $id (@{ $name_to_host{$name} }) {
15254: $lonid_to_ip{$id} = $ip;
15255: }
15256: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 15257: }
1.1293 raeburn 15258: unless ($nocache) {
15259: &do_cache_new('iphost','iphost',
15260: [\%iphost,\%name_to_ip,\%lonid_to_ip],
15261: 48*60*60);
15262: }
1.869 albertel 15263:
1.847 albertel 15264: return %iphost;
1.598 albertel 15265: }
15266:
1.992 raeburn 15267: #
15268: # Given a DNS returns the loncapa host name for that DNS
15269: #
15270: sub host_from_dns {
15271: my ($dns) = @_;
15272: my @hosts;
15273: my $ip;
15274:
1.993 raeburn 15275: if (exists($name_to_ip{$dns})) {
1.992 raeburn 15276: $ip = $name_to_ip{$dns};
15277: }
15278: if (!$ip) {
15279: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
15280: if (length($ip) == 4) {
15281: $ip = &IO::Socket::inet_ntoa($ip);
15282: }
15283: }
15284: if ($ip) {
15285: @hosts = get_hosts_from_ip($ip);
15286: return $hosts[0];
15287: }
15288: return undef;
1.986 foxr 15289: }
1.992 raeburn 15290:
1.1074 raeburn 15291: sub get_internet_names {
15292: my ($lonid) = @_;
15293: return if ($lonid eq '');
15294: my ($idnref,$cached)=
15295: &Apache::lonnet::is_cached_new('internetnames',$lonid);
15296: if ($cached) {
15297: return $idnref;
15298: }
15299: my $ip = &get_host_ip($lonid);
15300: my @hosts = &get_hosts_from_ip($ip);
15301: my %iphost = &get_iphost();
15302: my (@idns,%seen);
15303: foreach my $id (@hosts) {
15304: my $dom = &host_domain($id);
15305: my $prim_id = &domain($dom,'primary');
15306: my $prim_ip = &get_host_ip($prim_id);
15307: next if ($seen{$prim_ip});
15308: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
15309: foreach my $id (@{$iphost{$prim_ip}}) {
15310: my $intdom = &internet_dom($id);
15311: unless (grep(/^\Q$intdom\E$/,@idns)) {
15312: push(@idns,$intdom);
15313: }
15314: }
15315: }
15316: $seen{$prim_ip} = 1;
15317: }
1.1219 raeburn 15318: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 15319: }
15320:
1.986 foxr 15321: }
15322:
1.1079 raeburn 15323: sub all_loncaparevs {
1.1249 raeburn 15324: 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 15325: }
15326:
1.1227 raeburn 15327: # ---------------------------------------------------------- Read loncaparev table
15328: {
15329: sub load_loncaparevs {
15330: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359 raeburn 15331: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227 raeburn 15332: while (my $configline=<$config>) {
15333: chomp($configline);
15334: my ($hostid,$loncaparev)=split(/:/,$configline);
15335: $loncaparevs{$hostid}=$loncaparev;
15336: }
15337: close($config);
15338: }
15339: }
15340: }
15341: }
15342:
15343: # ---------------------------------------------------------- Read serverhostID table
15344: {
15345: sub load_serverhomeIDs {
15346: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359 raeburn 15347: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227 raeburn 15348: while (my $configline=<$config>) {
15349: chomp($configline);
15350: my ($name,$id)=split(/:/,$configline);
15351: $serverhomeIDs{$name}=$id;
15352: }
15353: close($config);
15354: }
15355: }
15356: }
15357: }
15358:
15359:
1.862 albertel 15360: BEGIN {
15361:
15362: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
15363: unless ($readit) {
15364: {
15365: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
15366: %perlvar = (%perlvar,%{$configvars});
15367: }
15368:
15369:
1.1 albertel 15370: # ------------------------------------------------------ Read spare server file
15371: {
1.1359 raeburn 15372: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 15373:
15374: while (my $configline=<$config>) {
15375: chomp($configline);
1.284 matthew 15376: if ($configline) {
1.784 albertel 15377: my ($host,$type) = split(':',$configline,2);
1.785 albertel 15378: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 15379: push(@{ $spareid{$type} }, $host);
1.1 albertel 15380: }
15381: }
1.448 albertel 15382: close($config);
1.1 albertel 15383: }
1.11 www 15384: # ------------------------------------------------------------ Read permissions
15385: {
1.1359 raeburn 15386: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 15387:
15388: while (my $configline=<$config>) {
1.448 albertel 15389: chomp($configline);
15390: if ($configline) {
15391: my ($role,$perm)=split(/ /,$configline);
15392: if ($perm ne '') { $pr{$role}=$perm; }
15393: }
1.11 www 15394: }
1.448 albertel 15395: close($config);
1.11 www 15396: }
15397:
15398: # -------------------------------------------- Read plain texts for permissions
15399: {
1.1359 raeburn 15400: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 15401:
15402: while (my $configline=<$config>) {
1.448 albertel 15403: chomp($configline);
15404: if ($configline) {
1.742 raeburn 15405: my ($short,@plain)=split(/:/,$configline);
15406: %{$prp{$short}} = ();
15407: if (@plain > 0) {
15408: $prp{$short}{'std'} = $plain[0];
15409: for (my $i=1; $i<@plain; $i++) {
15410: $prp{$short}{'alt'.$i} = $plain[$i];
15411: }
15412: }
1.448 albertel 15413: }
1.135 www 15414: }
1.448 albertel 15415: close($config);
1.135 www 15416: }
15417:
15418: # ---------------------------------------------------------- Read package table
15419: {
1.1359 raeburn 15420: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 15421:
15422: while (my $configline=<$config>) {
1.483 albertel 15423: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 15424: chomp($configline);
15425: my ($short,$plain)=split(/:/,$configline);
15426: my ($pack,$name)=split(/\&/,$short);
15427: if ($plain ne '') {
15428: $packagetab{$pack.'&'.$name.'&name'}=$name;
15429: $packagetab{$short}=$plain;
15430: }
1.11 www 15431: }
1.448 albertel 15432: close($config);
1.329 matthew 15433: }
15434:
1.1073 raeburn 15435: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 15436:
15437: &load_loncaparevs();
1.1073 raeburn 15438:
1.1074 raeburn 15439: # ---------------------------------------------------------- Read serverhostID table
15440:
1.1227 raeburn 15441: &load_serverhomeIDs();
15442:
15443: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 15444: {
15445: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
15446: if (-e $file) {
15447: my $parser = HTML::LCParser->new($file);
15448: while (my $token = $parser->get_token()) {
15449: if ($token->[0] eq 'S') {
15450: my $item = $token->[1];
15451: my $name = $token->[2]{'name'};
15452: my $value = $token->[2]{'value'};
1.1285 raeburn 15453: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 15454: my $namematch = $token->[2]{'namematch'};
15455: if ($item eq 'parameter') {
15456: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
15457: my $release = $parser->get_text();
15458: $release =~ s/(^\s*|\s*$ )//gx;
15459: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
15460: }
15461: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 15462: my $release = $parser->get_text();
15463: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 15464: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 15465: }
15466: }
15467: }
15468: }
1.1073 raeburn 15469: }
15470:
1.1138 raeburn 15471: # ---------------------------------------------------------- Read managers table
15472: {
15473: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359 raeburn 15474: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 15475: while (my $configline=<$config>) {
15476: chomp($configline);
15477: next if ($configline =~ /^\#/);
15478: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
15479: $managerstab{$configline} = 1;
15480: }
15481: }
15482: close($config);
15483: }
15484: }
15485: }
15486:
1.329 matthew 15487: # ------------- set up temporary directory
15488: {
1.1117 foxr 15489: $tmpdir = LONCAPA::tempdir();
1.329 matthew 15490:
1.11 www 15491: }
15492:
1.1405 raeburn 15493: # ------------- set default texengine (domain default overrides this)
15494: {
15495: $deftex = LONCAPA::texengine();
15496: }
15497:
1.1416 raeburn 15498: # ------------- set default minimum length for passwords for internal auth users
15499: {
15500: $passwdmin = LONCAPA::passwd_min();
15501: }
15502:
1.794 albertel 15503: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
15504: 'compress_threshold'=> 20_000,
15505: });
1.185 www 15506:
1.281 www 15507: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 15508: $dumpcount=0;
1.958 www 15509: $locknum=0;
1.22 www 15510:
1.163 harris41 15511: &logtouch();
1.672 albertel 15512: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 15513: $readit=1;
1.564 albertel 15514: {
15515: use integer;
15516: my $test=(2**32)+1;
1.568 albertel 15517: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 15518: &logthis(" Detected 64bit platform ($_64bit)");
15519: }
1.195 www 15520: }
1.1 albertel 15521: }
1.179 www 15522:
1.1 albertel 15523: 1;
1.191 harris41 15524: __END__
15525:
1.243 albertel 15526: =pod
15527:
1.191 harris41 15528: =head1 NAME
15529:
1.243 albertel 15530: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 15531:
15532: =head1 SYNOPSIS
15533:
1.243 albertel 15534: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 15535:
15536: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
15537:
1.243 albertel 15538: Common parameters:
15539:
15540: =over 4
15541:
15542: =item *
15543:
15544: $uname : an internal username (if $cname expecting a course Id specifically)
15545:
15546: =item *
15547:
15548: $udom : a domain (if $cdom expecting a course's domain specifically)
15549:
15550: =item *
15551:
15552: $symb : a resource instance identifier
15553:
15554: =item *
15555:
15556: $namespace : the name of a .db file that contains the data needed or
15557: being set.
15558:
15559: =back
15560:
1.394 bowersj2 15561: =head1 OVERVIEW
1.191 harris41 15562:
1.394 bowersj2 15563: lonnet provides subroutines which interact with the
15564: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
15565: about classes, users, and resources.
1.243 albertel 15566:
15567: For many of these objects you can also use this to store data about
15568: them or modify them in various ways.
1.191 harris41 15569:
1.394 bowersj2 15570: =head2 Symbs
1.191 harris41 15571:
1.394 bowersj2 15572: To identify a specific instance of a resource, LON-CAPA uses symbols
15573: or "symbs"X<symb>. These identifiers are built from the URL of the
15574: map, the resource number of the resource in the map, and the URL of
15575: the resource itself. The latter is somewhat redundant, but might help
15576: if maps change.
15577:
15578: An example is
15579:
15580: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
15581:
15582: The respective map entry is
15583:
15584: <resource id="19" src="/res/msu/korte/tests/part12.problem"
15585: title="Problem 2">
15586: </resource>
15587:
15588: Symbs are used by the random number generator, as well as to store and
15589: restore data specific to a certain instance of for example a problem.
15590:
15591: =head2 Storing And Retrieving Data
15592:
15593: X<store()>X<cstore()>X<restore()>Three of the most important functions
15594: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
15595: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
15596: is is the non-critical message twin of cstore. These functions are for
15597: handlers to store a perl hash to a user's permanent data space in an
15598: easy manner, and to retrieve it again on another call. It is expected
15599: that a handler would use this once at the beginning to retrieve data,
15600: and then again once at the end to send only the new data back.
15601:
15602: The data is stored in the user's data directory on the user's
15603: homeserver under the ID of the course.
15604:
15605: The hash that is returned by restore will have all of the previous
15606: value for all of the elements of the hash.
15607:
15608: Example:
15609:
15610: #creating a hash
15611: my %hash;
15612: $hash{'foo'}='bar';
15613:
15614: #storing it
15615: &Apache::lonnet::cstore(\%hash);
15616:
15617: #changing a value
15618: $hash{'foo'}='notbar';
15619:
15620: #adding a new value
15621: $hash{'bar'}='foo';
15622: &Apache::lonnet::cstore(\%hash);
15623:
15624: #retrieving the hash
15625: my %history=&Apache::lonnet::restore();
15626:
15627: #print the hash
15628: foreach my $key (sort(keys(%history))) {
15629: print("\%history{$key} = $history{$key}");
15630: }
15631:
15632: Will print out:
1.191 harris41 15633:
1.394 bowersj2 15634: %history{1:foo} = bar
15635: %history{1:keys} = foo:timestamp
15636: %history{1:timestamp} = 990455579
15637: %history{2:bar} = foo
15638: %history{2:foo} = notbar
15639: %history{2:keys} = foo:bar:timestamp
15640: %history{2:timestamp} = 990455580
15641: %history{bar} = foo
15642: %history{foo} = notbar
15643: %history{timestamp} = 990455580
15644: %history{version} = 2
15645:
15646: Note that the special hash entries C<keys>, C<version> and
15647: C<timestamp> were added to the hash. C<version> will be equal to the
15648: total number of versions of the data that have been stored. The
15649: C<timestamp> attribute will be the UNIX time the hash was
15650: stored. C<keys> is available in every historical section to list which
15651: keys were added or changed at a specific historical revision of a
15652: hash.
15653:
15654: B<Warning>: do not store the hash that restore returns directly. This
15655: will cause a mess since it will restore the historical keys as if the
15656: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 15657:
1.394 bowersj2 15658: Calling convention:
1.191 harris41 15659:
1.1225 raeburn 15660: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 15661: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 15662:
1.394 bowersj2 15663: For more detailed information, see lonnet specific documentation.
1.191 harris41 15664:
1.394 bowersj2 15665: =head1 RETURN MESSAGES
1.191 harris41 15666:
1.394 bowersj2 15667: =over 4
1.191 harris41 15668:
1.394 bowersj2 15669: =item * B<con_lost>: unable to contact remote host
1.191 harris41 15670:
1.394 bowersj2 15671: =item * B<con_delayed>: unable to contact remote host, message will be delivered
15672: when the connection is brought back up
1.191 harris41 15673:
1.394 bowersj2 15674: =item * B<con_failed>: unable to contact remote host and unable to save message
15675: for later delivery
1.191 harris41 15676:
1.967 bisitz 15677: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 15678:
1.394 bowersj2 15679: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 15680: that was requested
1.191 harris41 15681:
1.243 albertel 15682: =back
1.191 harris41 15683:
1.243 albertel 15684: =head1 PUBLIC SUBROUTINES
1.191 harris41 15685:
1.243 albertel 15686: =head2 Session Environment Functions
1.191 harris41 15687:
1.243 albertel 15688: =over 4
1.191 harris41 15689:
1.394 bowersj2 15690: =item *
15691: X<appenv()>
1.949 raeburn 15692: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 15693: the user envirnoment file, and will be restored for each access this
1.620 albertel 15694: user makes during this session, also modifies the %env for the current
1.949 raeburn 15695: process. Optional rolesarrayref - if defined contains a reference to an array
15696: of roles which are exempt from the restriction on modifying user.role entries
15697: in the user's environment.db and in %env.
1.191 harris41 15698:
15699: =item *
1.394 bowersj2 15700: X<delenv()>
1.987 raeburn 15701: B<delenv($delthis,$regexp)>: removes all items from the session
15702: environment file that begin with $delthis. If the
15703: optional second arg - $regexp - is true, $delthis is treated as a
15704: regular expression, otherwise \Q$delthis\E is used.
15705: The values are also deleted from the current processes %env.
1.191 harris41 15706:
1.795 albertel 15707: =item * get_env_multiple($name)
15708:
15709: gets $name from the %env hash, it seemlessly handles the cases where multiple
15710: values may be defined and end up as an array ref.
15711:
15712: returns an array of values
15713:
1.243 albertel 15714: =back
15715:
15716: =head2 User Information
1.191 harris41 15717:
1.243 albertel 15718: =over 4
1.191 harris41 15719:
15720: =item *
1.394 bowersj2 15721: X<queryauthenticate()>
15722: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 15723: authentication scheme
15724:
15725: =item *
1.394 bowersj2 15726: X<authenticate()>
1.1073 raeburn 15727: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 15728: authenticate user from domain's lib servers (first use the current
15729: one). C<$upass> should be the users password.
1.1073 raeburn 15730: $checkdefauth is optional (value is 1 if a check should be made to
15731: authenticate user using default authentication method, and allow
15732: account creation if username does not have account in the domain).
15733: $clientcancheckhost is optional (value is 1 if checking whether the
15734: server can host will occur on the client side in lonauth.pm).
1.191 harris41 15735:
15736: =item *
1.394 bowersj2 15737: X<homeserver()>
15738: B<homeserver($uname,$udom)>: find the server which has
15739: the user's directory and files (there must be only one), this caches
15740: the answer, and also caches if there is a borken connection.
1.191 harris41 15741:
15742: =item *
1.394 bowersj2 15743: X<idget()>
1.1300 raeburn 15744: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
15745: a list of student/employee IDs or clicker IDs
15746: (student/employee IDs are a unique resource in a domain, there must be
15747: only 1 ID per username, and only 1 username per ID in a specific domain).
15748: clickerIDs are not necessarily unique, as students might share clickers.
15749: (returns hash: id=>name,id=>name)
1.191 harris41 15750:
15751: =item *
1.394 bowersj2 15752: X<idrget()>
15753: B<idrget($udom,@unames)>: find the IDs behind a list of
15754: usernames (returns hash: name=>id,name=>id)
1.191 harris41 15755:
15756: =item *
1.394 bowersj2 15757: X<idput()>
1.1300 raeburn 15758: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
15759: names and associated student/employee IDs or clicker IDs.
15760:
15761: =item *
15762: X<iddel()>
15763: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
15764: student/employee ID or clicker ID username look-ups from domain.
15765: The homeserver ($uhome) and namespace ($namespace) are optional.
15766: If no $uhome is provided, it will be determined usig &homeserver()
15767: for each user. If no $namespace is provided, the default is ids.
15768:
15769: =item *
15770: X<updateclickers()>
15771: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
15772: clicker ID-to-username look-ups in clickers.db on library server.
15773: Permitted actions are add or del (i.e., add or delete). The
15774: clickers.db contains clickerID as keys (escaped), and each corresponding
15775: value is an escaped comma-separated list of usernames (for whom the
15776: library server is the homeserver), who registered that particular ID.
15777: If $critical is true, the update will be sent via &critical, otherwise
15778: &reply() will be used.
1.191 harris41 15779:
15780: =item *
1.394 bowersj2 15781: X<rolesinit()>
1.1169 droeschl 15782: B<rolesinit($udom,$username)>: get user privileges.
15783: returns user role, first access and timer interval hashes
1.243 albertel 15784:
15785: =item *
1.1171 droeschl 15786: X<privileged()>
15787: B<privileged($username,$domain)>: returns a true if user has a
15788: privileged and active role (i.e. su or dc), false otherwise.
15789:
15790: =item *
1.551 albertel 15791: X<getsection()>
15792: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 15793: course $cname, return section name/number or '' for "not in course"
15794: and '-1' for "no section"
15795:
15796: =item *
1.394 bowersj2 15797: X<userenvironment()>
15798: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 15799: passed in @what from the requested user's environment, returns a hash
15800:
1.858 raeburn 15801: =item *
15802: X<userlog_query()>
1.859 albertel 15803: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
15804: activity.log file. %filters defines filters applied when parsing the
15805: log file. These can be start or end timestamps, or the type of action
15806: - log to look for Login or Logout events, check for Checkin or
15807: Checkout, role for role selection. The response is in the form
15808: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
15809: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 15810:
1.243 albertel 15811: =back
15812:
15813: =head2 User Roles
15814:
15815: =over 4
15816:
15817: =item *
15818:
1.1284 raeburn 15819: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
15820: returns codes for allowed actions.
15821:
15822: The first argument is required, all others are optional.
15823:
15824: $priv is the privilege being checked.
15825: $uri contains additional information about what is being checked for access (e.g.,
15826: URL, course ID etc.).
15827: $symb is the unique resource instance identifier in a course; if needed,
15828: but not provided, it will be retrieved via a call to &symbread().
15829: $role is the role for which a priv is being checked (only used if priv is evb).
15830: $clientip is the user's IP address (only used when checking for access to portfolio
15831: files).
15832: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
15833: prevents recursive calls to &allowed.
15834:
1.243 albertel 15835: F: full access
15836: U,I,K: authentication modes (cxx only)
15837: '': forbidden
15838: 1: user needs to choose course
15839: 2: browse allowed
1.766 albertel 15840: A: passphrase authentication needed
1.1284 raeburn 15841: B: access temporarily blocked because of a blocking event in a course.
1.1402 raeburn 15842: D: access blocked because access is required via session initiated via deep-link
1.243 albertel 15843:
15844: =item *
15845:
1.1192 raeburn 15846: constructaccess($url,$setpriv) : check for access to construction space URL
15847:
15848: See if the owner domain and name in the URL match those in the
15849: expected environment. If so, return three element list
15850: ($ownername,$ownerdomain,$ownerhome).
15851:
15852: Otherwise return the null string.
15853:
15854: If second argument 'setpriv' is true, it assigns the privileges,
15855: and returns the same three element list, unless the owner has
15856: blocked "ad hoc" Domain Coordinator access to the Author Space,
15857: in which case the null string is returned.
15858:
15859: =item *
15860:
1.1326 raeburn 15861: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
15862: define a custom role rolename set privileges in format of lonTabs/roles.tab
15863: for system, domain, and course level. $uname and $udom are optional (current
15864: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 15865:
15866: =item *
15867:
1.988 raeburn 15868: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
15869: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 15870: $type is Course (default) or Community.
1.988 raeburn 15871: If $forcedefault evaluates to true, text returned will be default
15872: text for $type. Otherwise, if this is a course, the text returned
15873: will be a custom name for the role (if defined in the course's
15874: environment). If no custom name is defined the default is returned.
15875:
1.832 raeburn 15876: =item *
15877:
1.1219 raeburn 15878: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 15879: All arguments are optional. Returns a hash of a roles, either for
15880: co-author/assistant author roles for a user's Construction Space
1.906 albertel 15881: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 15882: In the hash, keys are set to colon-separated $uname,$udom,$role, and
15883: (optionally) if $withsec is true, a fourth colon-separated item - $section.
15884: For each key, value is set to colon-separated start and end times for
15885: the role. If no username and domain are specified, will default to
1.934 raeburn 15886: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 15887: of role statuses (active, future or previous), roles
15888: (e.g., cc,in, st etc.) and domains of the roles which can be used
15889: to restrict the list of roles reported. If no array ref is
15890: provided for types, will default to return only active roles.
1.834 albertel 15891:
1.1195 raeburn 15892: =item *
15893:
15894: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 15895: user: $uname:$udom has a role in the course: $cdom_$cnum.
15896:
15897: Additional optional arguments are: $type (if role checking is to be restricted
15898: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 15899: available roles) or future (roles available in the future), and
15900: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 15901: have active Domain Coordinator role in course's domain or in additional
15902: domains (specified in 'Domains to check for privileged users' in course
15903: environment -- set via: Course Settings -> Classlists and staff listing).
15904:
15905: =item *
15906:
15907: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
15908: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
15909: $possdomains and $possroles are optional array refs -- to domains to check and
15910: roles to check. If $possdomains is not specified, a dump will be done of the
15911: users' roles.db to check for a dc or su role in any domain. This can be
15912: time consuming if &privileged is called repeatedly (e.g., when displaying a
15913: classlist), so in such cases, supplying a $possdomains array is preferred, as
15914: this then allows &privileged_by_domain() to be used, which caches the identity
15915: of privileged users, eliminating the need for repeated calls to &dump().
15916:
15917: =item *
15918:
15919: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
15920: where the outer hash keys are domains specified in the $possdomains array ref,
15921: next inner hash keys are privileged roles specified in the $roles array ref,
15922: and the innermost hash contains key = value pairs for username:domain = end:start
15923: for active or future "privileged" users with that role in that domain. To avoid
15924: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
15925: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 15926:
1.243 albertel 15927: =back
15928:
15929: =head2 User Modification
15930:
15931: =over 4
15932:
15933: =item *
15934:
1.957 raeburn 15935: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 15936: user for the level given by URL. Optional start and end dates (leave empty
15937: string or zero for "no date")
1.191 harris41 15938:
15939: =item *
15940:
1.243 albertel 15941: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
15942: change a users, password, possible return values are: ok,
15943: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
15944: refused
1.191 harris41 15945:
15946: =item *
15947:
1.243 albertel 15948: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 15949:
15950: =item *
15951:
1.1058 raeburn 15952: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
15953: $forceid,$desiredhome,$email,$inststatus,$candelete) :
15954:
15955: will update user information (firstname,middlename,lastname,generation,
15956: permanentemail), and if forceid is true, student/employee ID also.
15957: A user's institutional affiliation(s) can also be updated.
15958: User information fields will not be overwritten with empty entries
15959: unless the field is included in the $candelete array reference.
15960: This array is included when a single user is modified via "Manage Users",
15961: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 15962:
15963: =item *
15964:
1.286 matthew 15965: modifystudent
15966:
1.957 raeburn 15967: modify a student's enrollment and identification information.
1.1235 raeburn 15968: The course id is resolved based on the current user's environment.
15969: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 15970: associated with a course.
15971:
1.297 matthew 15972: This call is essentially a wrapper for lonnet::modifyuser and
15973: lonnet::modify_student_enrollment
1.286 matthew 15974:
15975: Inputs:
15976:
15977: =over 4
15978:
1.957 raeburn 15979: =item B<$udom> Student's loncapa domain
1.286 matthew 15980:
1.957 raeburn 15981: =item B<$uname> Student's loncapa login name
1.286 matthew 15982:
1.964 bisitz 15983: =item B<$uid> Student/Employee ID
1.286 matthew 15984:
1.957 raeburn 15985: =item B<$umode> Student's authentication mode
1.286 matthew 15986:
1.957 raeburn 15987: =item B<$upass> Student's password
1.286 matthew 15988:
1.957 raeburn 15989: =item B<$first> Student's first name
1.286 matthew 15990:
1.957 raeburn 15991: =item B<$middle> Student's middle name
1.286 matthew 15992:
1.957 raeburn 15993: =item B<$last> Student's last name
1.286 matthew 15994:
1.957 raeburn 15995: =item B<$gene> Student's generation
1.286 matthew 15996:
1.957 raeburn 15997: =item B<$usec> Student's section in course
1.286 matthew 15998:
15999: =item B<$end> Unix time of the roles expiration
16000:
16001: =item B<$start> Unix time of the roles start date
16002:
16003: =item B<$forceid> If defined, allow $uid to be changed
16004:
16005: =item B<$desiredhome> server to use as home server for student
16006:
1.957 raeburn 16007: =item B<$email> Student's permanent e-mail address
16008:
16009: =item B<$type> Type of enrollment (auto or manual)
16010:
1.963 raeburn 16011: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
16012:
16013: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 16014:
1.963 raeburn 16015: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 16016:
1.963 raeburn 16017: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 16018:
1.1216 raeburn 16019: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16020:
16021: =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 16022:
1.286 matthew 16023: =back
1.297 matthew 16024:
16025: =item *
16026:
16027: modify_student_enrollment
16028:
1.1235 raeburn 16029: Change a student's enrollment status in a class. The environment variable
1.297 matthew 16030: 'role.request.course' must be defined for this function to proceed.
16031:
16032: Inputs:
16033:
16034: =over 4
16035:
1.1235 raeburn 16036: =item $udom, student's domain
1.297 matthew 16037:
1.1235 raeburn 16038: =item $uname, student's name
1.297 matthew 16039:
1.1235 raeburn 16040: =item $uid, student's user id
1.297 matthew 16041:
1.1235 raeburn 16042: =item $first, student's first name
1.297 matthew 16043:
16044: =item $middle
16045:
16046: =item $last
16047:
16048: =item $gene
16049:
16050: =item $usec
16051:
16052: =item $end
16053:
16054: =item $start
16055:
1.957 raeburn 16056: =item $type
16057:
16058: =item $locktype
16059:
16060: =item $cid
16061:
16062: =item $selfenroll
16063:
16064: =item $context
16065:
1.1216 raeburn 16066: =item $credits, number of credits student will earn from this class
16067:
1.1314 raeburn 16068: =item $instsec, institutional course section code for student
16069:
1.297 matthew 16070: =back
16071:
1.191 harris41 16072:
16073: =item *
16074:
1.243 albertel 16075: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
16076: custom role; give a custom role to a user for the level given by URL. Specify
16077: name and domain of role author, and role name
1.191 harris41 16078:
16079: =item *
16080:
1.243 albertel 16081: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 16082:
16083: =item *
16084:
1.243 albertel 16085: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
16086:
16087: =back
16088:
16089: =head2 Course Infomation
16090:
16091: =over 4
1.191 harris41 16092:
16093: =item *
16094:
1.1118 foxr 16095: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 16096: specified course id, including all environment settings for the
16097: course, the description of the course will be in the hash under the
16098: key 'description'
1.191 harris41 16099:
1.1118 foxr 16100: $options is an optional parameter that if supplied is a hash reference that controls
16101: what how this function works. It has the following key/values:
16102:
16103: =over 4
16104:
16105: =item freshen_cache
16106:
16107: If defined, and the environment cache for the course is valid, it is
16108: returned in the returned hash.
16109:
16110: =item one_time
16111:
16112: If defined, the last cache time is set to _now_
16113:
16114: =item user
16115:
16116: If defined, the supplied username is used instead of the current user.
16117:
16118:
16119: =back
16120:
1.191 harris41 16121: =item *
16122:
1.624 albertel 16123: resdata($name,$domain,$type,@which) : request for current parameter
16124: setting for a specific $type, where $type is either 'course' or 'user',
16125: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 16126: answers for 10 minutes.
1.243 albertel 16127:
1.877 foxr 16128: =item *
16129:
16130: get_courseresdata($courseid, $domain) : dump the entire course resource
16131: data base, returning a hash that is keyed by the resource name and has
16132: values that are the resource value. I believe that the timestamps and
16133: versions are also returned.
16134:
1.1236 raeburn 16135: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
16136: supplemental content area. This routine caches the number of files for
16137: 10 minutes.
16138:
1.243 albertel 16139: =back
16140:
16141: =head2 Course Modification
16142:
16143: =over 4
1.191 harris41 16144:
16145: =item *
16146:
1.243 albertel 16147: writecoursepref($courseid,%prefs) : write preferences (environment
16148: database) for a course
1.191 harris41 16149:
16150: =item *
16151:
1.1011 raeburn 16152: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
16153:
16154: =item *
16155:
1.1038 raeburn 16156: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 16157:
1.1167 droeschl 16158: =item *
16159:
16160: is_course($courseid), is_course($cdom, $cnum)
16161:
16162: Accepts either a combined $courseid (in the form of domain_courseid) or the
16163: two component version $cdom, $cnum. It checks if the specified course exists.
16164:
16165: Returns:
16166: undef if the course doesn't exist, otherwise
16167: in scalar context the combined courseid.
16168: in list context the two components of the course identifier, domain and
16169: courseid.
16170:
1.243 albertel 16171: =back
16172:
1.1401 raeburn 16173: =head2 Bubblesheet Configuration
16174:
16175: =over 4
16176:
16177: =item *
16178:
16179: get_scantron_config($which)
16180:
16181: $which - the name of the configuration to parse from the file.
16182:
16183: Parses and returns the bubblesheet configuration line selected as a
16184: hash of configuration file fields.
16185:
16186:
16187: Returns:
16188: If the named configuration is not in the file, an empty
16189: hash is returned.
16190:
16191: a hash with the fields
16192: name - internal name for the this configuration setup
16193: description - text to display to operator that describes this config
16194: CODElocation - if 0 or the string 'none'
16195: - no CODE exists for this config
16196: if -1 || the string 'letter'
16197: - a CODE exists for this config and is
16198: a string of letters
16199: Unsupported value (but planned for future support)
16200: if a positive integer
16201: - The CODE exists as the first n items from
16202: the question section of the form
16203: if the string 'number'
16204: - The CODE exists for this config and is
16205: a string of numbers
16206: CODEstart - (only matter if a CODE exists) column in the line where
16207: the CODE starts
16208: CODElength - length of the CODE
16209: IDstart - column where the student/employee ID starts
16210: IDlength - length of the student/employee ID info
16211: Qstart - column where the information from the bubbled
16212: 'questions' start
16213: Qlength - number of columns comprising a single bubble line from
16214: the sheet. (usually either 1 or 10)
16215: Qon - either a single character representing the character used
16216: to signal a bubble was chosen in the positional setup, or
16217: the string 'letter' if the letter of the chosen bubble is
16218: in the final, or 'number' if a number representing the
16219: chosen bubble is in the file (1->A 0->J)
16220: Qoff - the character used to represent that a bubble was
16221: left blank
16222: PaperID - if the scanning process generates a unique number for each
16223: sheet scanned the column that this ID number starts in
16224: PaperIDlength - number of columns that comprise the unique ID number
16225: for the sheet of paper
16226: FirstName - column that the first name starts in
16227: FirstNameLength - number of columns that the first name spans
16228: LastName - column that the last name starts in
16229: LastNameLength - number of columns that the last name spans
16230: BubblesPerRow - number of bubbles available in each row used to
16231: bubble an answer. (If not specified, 10 assumed).
16232:
16233:
16234: =item *
16235:
16236: get_scantronformat_file($cdom)
16237:
16238: $cdom - the course's domain (optional); if not supplied, uses
16239: domain for current $env{'request.course.id'}.
16240:
16241: Returns an array containing lines from the scantron format file for
16242: the domain of the course.
16243:
16244: If a url for a custom.tab file is listed in domain's configuration.db,
16245: lines are from this file.
16246:
16247: Otherwise, if a default.tab has been published in RES space by the
16248: domainconfig user, lines are from this file.
16249:
16250: Otherwise, fall back to getting lines from the legacy file on the
16251: local server: /home/httpd/lonTabs/default_scantronformat.tab
16252:
16253: =back
16254:
1.243 albertel 16255: =head2 Resource Subroutines
16256:
16257: =over 4
1.191 harris41 16258:
16259: =item *
16260:
1.243 albertel 16261: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 16262:
16263: =item *
16264:
1.243 albertel 16265: repcopy($filename) : subscribes to the requested file, and attempts to
16266: replicate from the owning library server, Might return
1.607 raeburn 16267: 'unavailable', 'not_found', 'forbidden', 'ok', or
16268: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 16269: resource. Expects the local filesystem pathname
16270: (/home/httpd/html/res/....)
16271:
16272: =back
16273:
16274: =head2 Resource Information
16275:
16276: =over 4
1.191 harris41 16277:
16278: =item *
16279:
1.1228 raeburn 16280: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
16281: and returns the value of a variety of different possible values,
16282: $varname should be a request string, and the other parameters can be
16283: used to specify who and what one is asking about. Ordinarily, $cid
16284: does not need to be specified, as it is retrived from
16285: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
16286: within lonuserstate::loadmap() when initializing a course, before
16287: $env{'request.course.id'} has been set, so it needs to be provided
16288: in that one case.
1.243 albertel 16289:
16290: Possible values for $varname are environment.lastname (or other item
16291: from the envirnment hash), user.name (or someother aspect about the
16292: user), resource.0.maxtries (or some other part and parameter of a
16293: resource)
1.204 albertel 16294:
16295: =item *
16296:
1.243 albertel 16297: directcondval($number) : get current value of a condition; reads from a state
16298: string
1.204 albertel 16299:
16300: =item *
16301:
1.243 albertel 16302: condval($condidx) : value of condition index based on state
1.204 albertel 16303:
16304: =item *
16305:
1.1362 raeburn 16306: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243 albertel 16307: resource's metadata, $what should be either a specific key, or either
16308: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362 raeburn 16309: packages that this resource currently uses, the last 3 arguments are
16310: only used internally for recursive metadata.
16311:
16312: the toolsymb is only used where the uri is for an external tool (for which
16313: the uri as well as the symb are guaranteed to be unique).
1.243 albertel 16314:
1.1371 raeburn 16315: this function automatically caches all requests except any made recursively
16316: to retrieve a list of metadata keys for an imported library file ($liburi is
16317: defined).
1.191 harris41 16318:
16319: =item *
16320:
1.243 albertel 16321: metadata_query($query,$custom,$customshow) : make a metadata query against the
16322: network of library servers; returns file handle of where SQL and regex results
16323: will be stored for query
1.191 harris41 16324:
16325: =item *
16326:
1.1282 raeburn 16327: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
16328: return symbolic list entry (all arguments optional).
16329:
16330: Args: filename is the filename (including path) for the file for which a symb
16331: is required; donotrecurse, if true will prevent calls to allowed() being made
16332: to check access status if more than one resource was found in the bighash
16333: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
16334: a randompick); ignorecachednull, if true will prevent a symb of '' being
16335: returned if $env{$cache_str} is defined as ''; checkforblock if true will
16336: cause possible symbs to be checked to determine if they are subject to content
16337: blocking, if so they will not be included as possible symbs; possibles is a
16338: ref to a hash, which, as a side effect, will be populated with all possible
16339: symbs (content blocking not tested).
16340:
1.243 albertel 16341: returns the data handle
1.191 harris41 16342:
16343: =item *
16344:
1.1190 raeburn 16345: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
16346: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 16347: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 16348: on failure, user must be in a course, as it assumes the existence of
16349: the course initial hash, and uses $env('request.course.id'}. The third
16350: arg is an optional reference to a scalar. If this arg is passed in the
16351: call to symbverify, it will be set to 1 if the symb has been set to be
16352: encrypted; otherwise it will be null.
1.191 harris41 16353:
16354: =item *
16355:
1.243 albertel 16356: symbclean($symb) : removes versions numbers from a symb, returns the
16357: cleaned symb
1.191 harris41 16358:
16359: =item *
16360:
1.243 albertel 16361: is_on_map($uri) : checks if the $uri is somewhere on the current
16362: course map, user must be in a course for it to work.
1.191 harris41 16363:
16364: =item *
16365:
1.243 albertel 16366: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 16367:
16368: =item *
16369:
1.243 albertel 16370: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
16371: a random seed, all arguments are optional, if they aren't sent it uses the
16372: environment to derive them. Note: if symb isn't sent and it can't get one
16373: from &symbread it will use the current time as its return value
1.191 harris41 16374:
16375: =item *
16376:
1.243 albertel 16377: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
16378: unfakeable, receipt
1.191 harris41 16379:
16380: =item *
16381:
1.620 albertel 16382: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 16383:
16384: =item *
16385:
1.243 albertel 16386: countacc($url) : count the number of accesses to a given URL
1.191 harris41 16387:
16388: =item *
16389:
1.243 albertel 16390: 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 16391:
16392: =item *
16393:
1.243 albertel 16394: 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 16395:
16396: =item *
16397:
1.243 albertel 16398: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 16399:
16400: =item *
16401:
1.243 albertel 16402: devalidate($symb) : devalidate temporary spreadsheet calculations,
16403: forcing spreadsheet to reevaluate the resource scores next time.
16404:
1.1195 raeburn 16405: =item *
16406:
1.1196 raeburn 16407: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
16408: when viewing in course context.
1.1195 raeburn 16409:
1.1196 raeburn 16410: input: six args -- filename (decluttered), course number, course domain,
16411: url, symb (if registered) and group (if this is a
16412: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 16413:
1.1196 raeburn 16414: output: array of five scalars --
1.1195 raeburn 16415: $cfile -- url for file editing if editable on current server
16416: $home -- homeserver of resource (i.e., for author if published,
16417: or course if uploaded.).
16418: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 16419: $forceedit -- 1 if icon/link should be to go to edit mode
16420: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 16421:
16422: =item *
16423:
16424: is_course_upload($file,$cnum,$cdom)
16425:
16426: Used in course context to determine if current file was uploaded to
16427: the course (i.e., would be found in /userfiles/docs on the course's
16428: homeserver.
16429:
16430: input: 3 args -- filename (decluttered), course number and course domain.
16431: output: boolean -- 1 if file was uploaded.
16432:
1.243 albertel 16433: =back
16434:
16435: =head2 Storing/Retreiving Data
16436:
16437: =over 4
1.191 harris41 16438:
16439: =item *
16440:
1.1269 raeburn 16441: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
16442: permanently for this url; hashref needs to be given and should be a \%hashname;
16443: the remaining args aren't required and if they aren't passed or are '' they will
16444: be derived from the env (with the exception of $laststore, which is an
16445: optional arg used when a user's submission is stored in grading).
16446: $laststore is $version=$timestamp, where $version is the most recent version
16447: number retrieved for the corresponding $symb in the $namespace db file, and
16448: $timestamp is the timestamp for that transaction (UNIX time).
16449: $laststore is currently only passed when cstore() is called by
16450: structuretags::finalize_storage().
1.191 harris41 16451:
16452: =item *
16453:
1.1269 raeburn 16454: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
16455: but uses critical subroutine
1.191 harris41 16456:
16457: =item *
16458:
1.243 albertel 16459: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
16460: all args are optional
1.191 harris41 16461:
16462: =item *
16463:
1.717 albertel 16464: dumpstore($namespace,$udom,$uname,$regexp,$range) :
16465: dumps the complete (or key matching regexp) namespace into a hash
16466: ($udom, $uname, $regexp, $range are optional) for a namespace that is
16467: normally &store()ed into
16468:
16469: $range should be either an integer '100' (give me the first 100
16470: matching records)
16471: or be two integers sperated by a - with no spaces
16472: '30-50' (give me the 30th through the 50th matching
16473: records)
16474:
16475:
16476: =item *
16477:
1.1269 raeburn 16478: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 16479: replaces a &store() version of data with a replacement set of data
16480: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 16481: reference. If $tolog is true, the transaction is logged in the courselog
16482: with an action=PUTSTORE.
1.717 albertel 16483:
16484: =item *
16485:
1.243 albertel 16486: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
16487: works very similar to store/cstore, but all data is stored in a
16488: temporary location and can be reset using tmpreset, $storehash should
16489: be a hash reference, returns nothing on success
1.191 harris41 16490:
16491: =item *
16492:
1.243 albertel 16493: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
16494: similar to restore, but all data is stored in a temporary location and
16495: can be reset using tmpreset. Returns a hash of values on success,
16496: error string otherwise.
1.191 harris41 16497:
16498: =item *
16499:
1.243 albertel 16500: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
16501: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 16502:
16503: =item *
16504:
1.243 albertel 16505: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16506: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 16507:
16508: =item *
16509:
1.243 albertel 16510: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
16511: namesp ($udom and $uname are optional)
1.191 harris41 16512:
16513: =item *
16514:
1.702 albertel 16515: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 16516: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 16517: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 16518:
1.702 albertel 16519: $range should be either an integer '100' (give me the first 100
16520: matching records)
16521: or be two integers sperated by a - with no spaces
16522: '30-50' (give me the 30th through the 50th matching
16523: records)
1.449 matthew 16524: =item *
16525:
16526: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
16527: $store can be a scalar, an array reference, or if the amount to be
16528: incremented is > 1, a hash reference.
16529:
16530: ($udom and $uname are optional)
1.191 harris41 16531:
16532: =item *
16533:
1.243 albertel 16534: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
16535: ($udom and $uname are optional)
1.191 harris41 16536:
16537: =item *
16538:
1.243 albertel 16539: cput($namespace,$storehash,$udom,$uname) : critical put
16540: ($udom and $uname are optional)
1.191 harris41 16541:
16542: =item *
16543:
1.748 albertel 16544: newput($namespace,$storehash,$udom,$uname) :
16545:
16546: Attempts to store the items in the $storehash, but only if they don't
16547: currently exist, if this succeeds you can be certain that you have
16548: successfully created a new key value pair in the $namespace db.
16549:
16550:
16551: Args:
16552: $namespace: name of database to store values to
16553: $storehash: hashref to store to the db
16554: $udom: (optional) domain of user containing the db
16555: $uname: (optional) name of user caontaining the db
16556:
16557: Returns:
16558: 'ok' -> succeeded in storing all keys of $storehash
16559: 'key_exists: <key>' -> failed to anything out of $storehash, as at
16560: least <key> already existed in the db (other
16561: requested keys may also already exist)
1.967 bisitz 16562: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 16563: 'con_lost' -> unable to contact request server
16564: 'refused' -> action was not allowed by remote machine
16565:
16566:
16567: =item *
16568:
1.243 albertel 16569: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
16570: reference filled in from namesp (encrypts the return communication)
16571: ($udom and $uname are optional)
1.191 harris41 16572:
16573: =item *
16574:
1.243 albertel 16575: log($udom,$name,$home,$message) : write to permanent log for user; use
16576: critical subroutine
16577:
1.806 raeburn 16578: =item *
16579:
1.860 raeburn 16580: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
16581: array reference filled in from namespace found in domain level on either
16582: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 16583:
16584: =item *
16585:
1.860 raeburn 16586: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
16587: domain level either on specified domain server ($uhome) or primary domain
16588: server ($udom and $uhome are optional)
1.806 raeburn 16589:
1.943 raeburn 16590: =item *
16591:
1.1240 raeburn 16592: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
16593: for: authentication, language, quotas, timezone, date locale, and portal URL in
16594: the target domain.
16595:
16596: May also include additional key => value pairs for the following groups:
16597:
16598: =over
16599:
16600: =item
16601: disk quotas (MB allocated by default to portfolios and authoring spaces).
16602:
16603: =over
16604:
16605: =item defaultquota, authorquota
16606:
16607: =back
16608:
16609: =item
16610: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
16611: portfolio for users).
16612:
16613: =over
16614:
16615: =item
16616: aboutme, blog, webdav, portfolio
16617:
16618: =back
16619:
16620: =item
16621: requestcourses: ability to request courses, and how requests are processed.
16622:
16623: =over
16624:
16625: =item
1.1305 raeburn 16626: official, unofficial, community, textbook, placement
1.1240 raeburn 16627:
16628: =back
16629:
16630: =item
16631: inststatus: types of institutional affiliation, and order in which they are displayed.
16632:
16633: =over
16634:
16635: =item
1.1256 raeburn 16636: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 16637:
16638: =back
16639:
16640: =item
16641: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
16642: for course's uploaded content.
16643:
16644: =over
16645:
16646: =item
1.1246 raeburn 16647: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 16648: communityquota, textbookquota, placementquota
1.1240 raeburn 16649:
16650: =back
16651:
16652: =item
16653: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
16654: on your servers.
16655:
16656: =over
16657:
16658: =item
16659: remotesessions, hostedsessions
16660:
16661: =back
16662:
16663: =back
16664:
16665: In cases where a domain coordinator has never used the "Set Domain Configuration"
16666: utility to create a configuration.db file on a domain's primary library server
16667: only the following domain defaults: auth_def, auth_arg_def, lang_def
16668: -- corresponding values are authentication type (internal, krb4, krb5,
16669: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
16670: will be available. Values are retrieved from cache (if current), unless the
16671: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
16672: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
16673:
16674: Typical usage:
1.943 raeburn 16675:
1.1240 raeburn 16676: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 16677:
1.243 albertel 16678: =back
16679:
16680: =head2 Network Status Functions
16681:
16682: =over 4
1.191 harris41 16683:
16684: =item *
16685:
1.1137 raeburn 16686: dirlist() : return directory list based on URI (first arg).
16687:
16688: Inputs: 1 required, 5 optional.
16689:
16690: =over
16691:
16692: =item
16693: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
16694:
16695: =item
16696: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
16697:
16698: =item
16699: $username - username of user/course to be listed. Extracted from $uri if absent.
16700:
16701: =item
16702: $getpropath - boolean: 1 if prepend path using &propath().
16703:
16704: =item
16705: $getuserdir - boolean: 1 if prepend path for "userfiles".
16706:
16707: =item
16708: $alternateRoot - path to prepend in place of path from $uri.
16709:
16710: =back
16711:
16712: Returns: Array of up to two items.
16713:
16714: =over
16715:
16716: a reference to an array of files/subdirectories
16717:
16718: =over
16719:
16720: Each element in the array of files/subdirectories is a & separated list of
16721: item name and the result of running stat on the item. If dirlist was requested
16722: for a file instead of a directory, the item name will be ''. For a directory
16723: listing, if the item is a metadata file, the element will end &N&M
16724: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
16725: default copyright set (1).
16726:
16727: =back
16728:
16729: a scalar containing error condition (if encountered).
16730:
16731: =over
16732:
16733: =item
16734: no_host (no homeserver identified for $username:$domain).
16735:
16736: =item
16737: no_such_host (server contacted for listing not identified as valid host).
16738:
16739: =item
16740: con_lost (connection to remote server failed).
16741:
16742: =item
16743: refused (invalid $username:$domain received on lond side).
16744:
16745: =item
16746: no_such_dir (directory at specified path on lond side does not exist).
16747:
16748: =item
16749: empty (directory at specified path on lond side is empty).
16750:
16751: =over
16752:
16753: This is currently not encountered because the &ls3, &ls2,
16754: &ls (_handler) routines on the lond side do not filter out
16755: . and .. from a directory listing.
16756:
16757: =back
16758:
16759: =back
16760:
16761: =back
1.191 harris41 16762:
16763: =item *
16764:
1.243 albertel 16765: spareserver() : find server with least workload from spare.tab
16766:
1.986 foxr 16767:
16768: =item *
16769:
16770: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
16771: if there is no corresponding loncapa host.
16772:
1.243 albertel 16773: =back
16774:
1.986 foxr 16775:
1.243 albertel 16776: =head2 Apache Request
16777:
16778: =over 4
1.191 harris41 16779:
16780: =item *
16781:
1.243 albertel 16782: ssi($url,%hash) : server side include, does a complete request cycle on url to
16783: localhost, posts hash
16784:
16785: =back
16786:
16787: =head2 Data to String to Data
16788:
16789: =over 4
1.191 harris41 16790:
16791: =item *
16792:
1.243 albertel 16793: hash2str(%hash) : convert a hash into a string complete with escaping and '='
16794: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 16795:
16796: =item *
16797:
1.243 albertel 16798: hashref2str($hashref) : convert a hashref into a string complete with
16799: escaping and '=' and '&' separators, supports elements that are
16800: arrayrefs and hashrefs
1.191 harris41 16801:
16802: =item *
16803:
1.243 albertel 16804: arrayref2str($arrayref) : convert an arrayref into a string complete
16805: with escaping and '&' separators, supports elements that are arrayrefs
16806: and hashrefs
1.191 harris41 16807:
16808: =item *
16809:
1.243 albertel 16810: str2hash($string) : convert string to hash using unescaping and
16811: splitting on '=' and '&', supports elements that are arrayrefs and
16812: hashrefs
1.191 harris41 16813:
16814: =item *
16815:
1.243 albertel 16816: str2array($string) : convert string to hash using unescaping and
16817: splitting on '&', supports elements that are arrayrefs and hashrefs
16818:
16819: =back
16820:
16821: =head2 Logging Routines
16822:
16823:
16824: These routines allow one to make log messages in the lonnet.log and
16825: lonnet.perm logfiles.
1.191 harris41 16826:
1.1119 foxr 16827: =over 4
16828:
1.191 harris41 16829: =item *
16830:
1.243 albertel 16831: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 16832:
16833: =item *
16834:
1.243 albertel 16835: logthis() : append message to the normal lonnet.log file, it gets
16836: preiodically rolled over and deleted.
1.191 harris41 16837:
16838: =item *
16839:
1.243 albertel 16840: logperm() : append a permanent message to lonnet.perm.log, this log
16841: file never gets deleted by any automated portion of the system, only
16842: messages of critical importance should go in here.
16843:
1.1119 foxr 16844:
1.243 albertel 16845: =back
16846:
16847: =head2 General File Helper Routines
16848:
16849: =over 4
1.191 harris41 16850:
16851: =item *
16852:
1.481 raeburn 16853: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
16854: (a) files in /uploaded
16855: (i) If a local copy of the file exists -
16856: compares modification date of local copy with last-modified date for
16857: definitive version stored on home server for course. If local copy is
16858: stale, requests a new version from the home server and stores it.
16859: If the original has been removed from the home server, then local copy
16860: is unlinked.
16861: (ii) If local copy does not exist -
16862: requests the file from the home server and stores it.
16863:
16864: If $caller is 'uploadrep':
16865: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
16866: for request for files originally uploaded via DOCS.
16867: - returns 'ok' if fresh local copy now available, -1 otherwise.
16868:
16869: Otherwise:
16870: This indicates a call from the content generation phase of the request.
16871: - returns the entire contents of the file or -1.
16872:
16873: (b) files in /res
16874: - returns the entire contents of a file or -1;
16875: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 16876:
1.712 albertel 16877:
16878: =item *
16879:
16880: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
16881: reference
16882:
16883: returns either a stat() list of data about the file or an empty list
16884: if the file doesn't exist or couldn't find out about it (connection
16885: problems or user unknown)
16886:
1.191 harris41 16887: =item *
16888:
1.243 albertel 16889: filelocation($dir,$file) : returns file system location of a file
16890: based on URI; meant to be "fairly clean" absolute reference, $dir is a
16891: directory that relative $file lookups are to looked in ($dir of /a/dir
16892: and a file of ../bob will become /a/bob)
1.191 harris41 16893:
16894: =item *
16895:
16896: hreflocation($dir,$file) : returns file system location or a URL; same as
16897: filelocation except for hrefs
16898:
16899: =item *
16900:
1.1261 raeburn 16901: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
16902: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 16903:
1.243 albertel 16904: =back
16905:
1.608 albertel 16906: =head2 Usererfile file routines (/uploaded*)
16907:
16908: =over 4
16909:
16910: =item *
16911:
16912: userfileupload(): main rotine for putting a file in a user or course's
16913: filespace, arguments are,
16914:
1.620 albertel 16915: formname - required - this is the name of the element in $env where the
1.608 albertel 16916: filename, and the contents of the file to create/modifed exist
1.620 albertel 16917: the filename is in $env{'form.'.$formname.'.filename'} and the
16918: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 16919: context - if coursedoc, store the file in the course of the active role
16920: of the current user;
16921: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
16922: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 16923: subdir - required - subdirectory to put the file in under ../userfiles/
16924: if undefined, it will be placed in "unknown"
16925:
16926: (This routine calls clean_filename() to remove any dangerous
16927: characters from the filename, and then calls finuserfileupload() to
16928: complete the transaction)
16929:
16930: returns either the url of the uploaded file (/uploaded/....) if successful
16931: and /adm/notfound.html if unsuccessful
16932:
16933: =item *
16934:
16935: clean_filename(): routine for cleaing a filename up for storage in
16936: userfile space, argument is:
16937:
16938: filename - proposed filename
16939:
16940: returns: the new clean filename
16941:
16942: =item *
16943:
1.1090 raeburn 16944: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 16945: userspace, probably shouldn't be called directly
16946:
16947: docuname: username or courseid of destination for the file
16948: docudom: domain of user/course of destination for the file
16949: formname: same as for userfileupload()
1.1090 raeburn 16950: fname: filename (including subdirectories) for the file
16951: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401 raeburn 16952: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 16953: allfiles: reference to hash used to store objects found by parser
16954: codebase: reference to hash used for codebases of java objects found by parser
16955: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
16956: thumbheight: height (pixels) of thumbnail to be created for uploaded image
16957: resizewidth: width to be used to resize image using resizeImage from ImageMagick
16958: resizeheight: height to be used to resize image using resizeImage from ImageMagick
16959: context: if 'overwrite', will move the uploaded file from its temporary location to
16960: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 16961: mimetype: reference to scalar to accommodate mime type determined
16962: from File::MMagic if $parser = parse.
1.608 albertel 16963:
16964: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 16965: and /adm/notfound.html if unsuccessful (or an error message if context
16966: was 'overwrite').
16967:
1.608 albertel 16968:
16969: =item *
16970:
16971: renameuserfile(): renames an existing userfile to a new name
16972:
16973: Args:
16974: docuname: username or courseid of destination for the file
16975: docudom: domain of user/course of destination for the file
16976: old: current file name (including any subdirs under userfiles)
16977: new: desired file name (including any subdirs under userfiles)
16978:
16979: =item *
16980:
16981: mkdiruserfile(): creates a directory is a userfiles dir
16982:
16983: Args:
16984: docuname: username or courseid of destination for the file
16985: docudom: domain of user/course of destination for the file
16986: dir: dir to create (including any subdirs under userfiles)
16987:
16988: =item *
16989:
16990: removeuserfile(): removes a file that exists in userfiles
16991:
16992: Args:
16993: docuname: username or courseid of destination for the file
16994: docudom: domain of user/course of destination for the file
16995: fname: filname to delete (including any subdirs under userfiles)
16996:
16997: =item *
16998:
16999: removeuploadedurl(): convience function for removeuserfile()
17000:
17001: Args:
17002: url: a full /uploaded/... url to delete
17003:
1.747 albertel 17004: =item *
17005:
17006: get_portfile_permissions():
17007: Args:
17008: domain: domain of user or course contain the portfolio files
17009: user: name of user or num of course contain the portfolio files
17010: Returns:
17011: hashref of a dump of the proper file_permissions.db
17012:
17013:
17014: =item *
17015:
17016: get_access_controls():
17017:
17018: Args:
17019: current_permissions: the hash ref returned from get_portfile_permissions()
17020: group: (optional) the group you want the files associated with
17021: file: (optional) the file you want access info on
17022:
17023: Returns:
1.749 raeburn 17024: a hash (keys are file names) of hashes containing
17025: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17026: values are XML containing access control settings (see below)
1.747 albertel 17027:
17028: Internal notes:
17029:
1.749 raeburn 17030: access controls are stored in file_permissions.db as key=value pairs.
17031: key -> path to file/file_name\0uniqueID:scope_end_start
17032: where scope -> public,guest,course,group,domains or users.
17033: end -> UNIX time for end of access (0 -> no end date)
17034: start -> UNIX time for start of access
17035:
17036: value -> XML description of access control
17037: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
17038: <start></start>
17039: <end></end>
17040:
17041: <password></password> for scope type = guest
17042:
17043: <domain></domain> for scope type = course or group
17044: <number></number>
17045: <roles id="">
17046: <role></role>
17047: <access></access>
17048: <section></section>
17049: <group></group>
17050: </roles>
17051:
17052: <dom></dom> for scope type = domains
17053:
17054: <users> for scope type = users
17055: <user>
17056: <uname></uname>
17057: <udom></udom>
17058: </user>
17059: </users>
17060: </scope>
17061:
17062: Access data is also aggregated for each file in an additional key=value pair:
17063: key -> path to file/file_name\0accesscontrol
17064: value -> reference to hash
17065: hash contains key = value pairs
17066: where key = uniqueID:scope_end_start
17067: value = UNIX time record was last updated
17068:
17069: Used to improve speed of look-ups of access controls for each file.
17070:
17071: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
17072:
1.1198 raeburn 17073: =item *
17074:
1.749 raeburn 17075: modify_access_controls():
17076:
17077: Modifies access controls for a portfolio file
17078: Args
17079: 1. file name
17080: 2. reference to hash of required changes,
17081: 3. domain
17082: 4. username
17083: where domain,username are the domain of the portfolio owner
17084: (either a user or a course)
17085:
17086: Returns:
17087: 1. result of additions or updates ('ok' or 'error', with error message).
17088: 2. result of deletions ('ok' or 'error', with error message).
17089: 3. reference to hash of any new or updated access controls.
17090: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
17091: key = integer (inbound ID)
1.1198 raeburn 17092: value = uniqueID
17093:
17094: =item *
17095:
17096: get_timebased_id():
17097:
17098: Attempts to get a unique timestamp-based suffix for use with items added to a
17099: course via the Course Editor (e.g., folders, composite pages,
17100: group bulletin boards).
17101:
17102: Args: (first three required; six others optional)
17103:
17104: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
17105: docssequence, or name of group
17106:
17107: 2. keyid (alphanumeric): name of temporary locking key in hash,
17108: e.g., num, boardids
17109:
17110: 3. namespace: name of gdbm file used to store suffixes already assigned;
17111: file will be named nohist_namespace.db
17112:
17113: 4. cdom: domain of course; default is current course domain from %env
17114:
17115: 5. cnum: course number; default is current course number from %env
17116:
17117: 6. idtype: set to concat if an additional digit is to be appended to the
17118: unix timestamp to form the suffix, if the plain timestamp is already
17119: in use. Default is to not do this, but simply increment the unix
17120: timestamp by 1 until a unique key is obtained.
17121:
17122: 7. who: holder of locking key; defaults to user:domain for user.
17123:
17124: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
17125: retrying); default is 3.
17126:
17127: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
17128:
17129: Returns:
17130:
17131: 1. suffix obtained (numeric)
17132:
17133: 2. result of deleting locking key (ok if deleted, or lock never obtained)
17134:
17135: 3. error: contains (localized) error message if an error occurred.
17136:
1.747 albertel 17137:
1.608 albertel 17138: =back
17139:
1.243 albertel 17140: =head2 HTTP Helper Routines
17141:
17142: =over 4
17143:
1.191 harris41 17144: =item *
17145:
17146: escape() : unpack non-word characters into CGI-compatible hex codes
17147:
17148: =item *
17149:
17150: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
17151:
1.243 albertel 17152: =back
17153:
17154: =head1 PRIVATE SUBROUTINES
17155:
17156: =head2 Underlying communication routines (Shouldn't call)
17157:
17158: =over 4
17159:
17160: =item *
17161:
17162: subreply() : tries to pass a message to lonc, returns con_lost if incapable
17163:
17164: =item *
17165:
17166: reply() : uses subreply to send a message to remote machine, logs all failures
17167:
17168: =item *
17169:
17170: critical() : passes a critical message to another server; if cannot
17171: get through then place message in connection buffer directory and
17172: returns con_delayed, if incapable of saving message, returns
17173: con_failed
17174:
17175: =item *
17176:
17177: reconlonc() : tries to reconnect lonc client processes.
17178:
17179: =back
17180:
17181: =head2 Resource Access Logging
17182:
17183: =over 4
17184:
17185: =item *
17186:
17187: flushcourselogs() : flush (save) buffer logs and access logs
17188:
17189: =item *
17190:
17191: courselog($what) : save message for course in hash
17192:
17193: =item *
17194:
17195: courseacclog($what) : save message for course using &courselog(). Perform
17196: special processing for specific resource types (problems, exams, quizzes, etc).
17197:
1.191 harris41 17198: =item *
17199:
17200: goodbye() : flush course logs and log shutting down; it is called in srm.conf
17201: as a PerlChildExitHandler
1.243 albertel 17202:
17203: =back
17204:
17205: =head2 Other
17206:
17207: =over 4
17208:
17209: =item *
17210:
17211: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 17212:
17213: =back
17214:
17215: =cut
1.877 foxr 17216:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>