Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.141
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.141! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.140 2021/02/11 20:01:55 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.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
1.1172.2.107 raeburn 77: use CGI::Cookie;
1.977 amueller 78:
1.1172.2.104 raeburn 79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138 raeburn 80: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1172.2.114 raeburn 81: %managerstab $passwdmin);
1.871 albertel 82:
83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
84: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
85: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 86: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 87:
1.1 albertel 88: use IO::Socket;
1.31 www 89: use GDBM_File;
1.208 albertel 90: use HTML::LCParser;
1.88 www 91: use Fcntl qw(:flock);
1.870 albertel 92: use Storable qw(thaw nfreeze);
1.1172.2.79 raeburn 93: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599 albertel 94: use Cache::Memcached;
1.676 albertel 95: use Digest::MD5;
1.790 albertel 96: use Math::Random;
1.1024 raeburn 97: use File::MMagic;
1.807 albertel 98: use LONCAPA qw(:DEFAULT :match);
1.740 www 99: use LONCAPA::Configuration;
1.1160 www 100: use LONCAPA::lonmetadata;
1.1172.2.22 raeburn 101: use LONCAPA::Lond;
1.1172.2.110 raeburn 102: use LONCAPA::transliterate;
1.1117 foxr 103:
1.1090 raeburn 104: use File::Copy;
1.676 albertel 105:
1.195 www 106: my $readit;
1.1172.2.79 raeburn 107: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 108:
1.619 albertel 109: require Exporter;
110:
111: our @ISA = qw (Exporter);
112: our @EXPORT = qw(%env);
113:
1.1172.2.9 raeburn 114: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 115: {
116: my $logid;
1.1172.2.9 raeburn 117: sub write_log {
118: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
119: if ($context eq 'course') {
120: if (($cnum eq '') || ($cdom eq '')) {
121: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
122: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
123: }
1.957 raeburn 124: }
1.1172.2.13 raeburn 125: $logid ++;
1.957 raeburn 126: my $now = time();
127: my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.134 raeburn 128: my $ip = &get_requestor_ip();
1.1172.2.9 raeburn 129: my $logentry = {
130: $id => {
131: 'exe_uname' => $env{'user.name'},
132: 'exe_udom' => $env{'user.domain'},
133: 'exe_time' => $now,
1.1172.2.134 raeburn 134: 'exe_ip' => $ip,
1.1172.2.9 raeburn 135: 'delflag' => $delflag,
136: 'logentry' => $storehash,
137: 'uname' => $uname,
138: 'udom' => $udom,
139: }
140: };
141: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 142: }
143: }
1.1 albertel 144:
1.163 harris41 145: sub logtouch {
146: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 147: unless (-e "$execdir/logs/lonnet.log") {
1.1172.2.96 raeburn 148: open(my $fh,">>","$execdir/logs/lonnet.log");
1.163 harris41 149: close $fh;
150: }
151: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
152: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
153: }
154:
1.1 albertel 155: sub logthis {
156: my $message=shift;
157: my $execdir=$perlvar{'lonDaemons'};
158: my $now=time;
159: my $local=localtime($now);
1.1172.2.96 raeburn 160: if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986 foxr 161: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
162: print $fh $logstring;
1.448 albertel 163: close($fh);
164: }
1.1 albertel 165: return 1;
166: }
167:
168: sub logperm {
169: my $message=shift;
170: my $execdir=$perlvar{'lonDaemons'};
171: my $now=time;
172: my $local=localtime($now);
1.1172.2.96 raeburn 173: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448 albertel 174: print $fh "$now:$message:$local\n";
175: close($fh);
176: }
1.1 albertel 177: return 1;
178: }
179:
1.850 albertel 180: sub create_connection {
1.853 albertel 181: my ($hostname,$lonid) = @_;
1.851 albertel 182: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 183: Type => SOCK_STREAM,
184: Timeout => 10);
185: return 0 if (!$client);
1.890 albertel 186: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 187: my $result = <$client>;
188: chomp($result);
189: return 1 if ($result eq 'done');
190: return 0;
191: }
192:
1.983 raeburn 193: sub get_server_timezone {
194: my ($cnum,$cdom) = @_;
195: my $home=&homeserver($cnum,$cdom);
196: if ($home ne 'no_host') {
197: my $cachetime = 24*3600;
198: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
199: if (defined($cached)) {
200: return $timezone;
201: } else {
202: my $timezone = &reply('servertimezone',$home);
203: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
204: }
205: }
206: }
1.850 albertel 207:
1.1106 raeburn 208: sub get_server_distarch {
209: my ($lonhost,$ignore_cache) = @_;
210: if (defined($lonhost)) {
211: if (!defined(&hostname($lonhost))) {
212: return;
213: }
214: my $cachetime = 12*3600;
215: if (!$ignore_cache) {
216: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
217: if (defined($cached)) {
218: return $distarch;
219: }
220: }
221: my $rep = &reply('serverdistarch',$lonhost);
222: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
223: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
224: $rep eq '') {
225: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
226: }
227: }
228: return;
229: }
230:
1.993 raeburn 231: sub get_server_loncaparev {
1.1073 raeburn 232: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 233: if (defined($lonhost)) {
234: if (!defined(&hostname($lonhost))) {
235: undef($lonhost);
236: }
237: }
238: if (!defined($lonhost)) {
239: if (defined(&domain($dom,'primary'))) {
240: $lonhost=&domain($dom,'primary');
241: if ($lonhost eq 'no_host') {
242: undef($lonhost);
243: }
244: }
245: }
246: if (defined($lonhost)) {
1.1073 raeburn 247: my $cachetime = 12*3600;
248: if (!$ignore_cache) {
249: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
250: if (defined($cached)) {
251: return $loncaparev;
252: }
253: }
254: my ($answer,$loncaparev);
255: my @ids=¤t_machine_ids();
256: if (grep(/^\Q$lonhost\E$/,@ids)) {
257: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 258: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 259: $loncaparev = $1;
260: }
261: } else {
262: $answer = &reply('serverloncaparev',$lonhost);
263: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
264: if ($caller eq 'loncron') {
265: my $ua=new LWP::UserAgent;
1.1082 raeburn 266: $ua->timeout(4);
1.1172.2.120 raeburn 267: my $hostname = &hostname($lonhost);
1.1073 raeburn 268: my $protocol = $protocol{$lonhost};
269: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 270: my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073 raeburn 271: my $request=new HTTP::Request('GET',$url);
272: my $response=$ua->request($request);
273: unless ($response->is_error()) {
274: my $content = $response->content;
1.1081 raeburn 275: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 276: $loncaparev = $1;
277: }
278: }
279: } else {
280: $loncaparev = $loncaparevs{$lonhost};
281: }
1.1081 raeburn 282: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 283: $loncaparev = $1;
284: }
1.993 raeburn 285: }
1.1073 raeburn 286: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 287: }
288: }
289:
1.1074 raeburn 290: sub get_server_homeID {
291: my ($hostname,$ignore_cache,$caller) = @_;
292: unless ($ignore_cache) {
293: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
294: if (defined($cached)) {
295: return $serverhomeID;
296: }
297: }
298: my $cachetime = 12*3600;
299: my $serverhomeID;
300: if ($caller eq 'loncron') {
301: my @machine_ids = &machine_ids($hostname);
302: foreach my $id (@machine_ids) {
303: my $response = &reply('serverhomeID',$id);
304: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
305: $serverhomeID = $response;
306: last;
307: }
308: }
309: if ($serverhomeID eq '') {
310: $serverhomeID = $machine_ids[-1];
311: }
312: } else {
313: $serverhomeID = $serverhomeIDs{$hostname};
314: }
315: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
316: }
317:
1.1121 raeburn 318: sub get_remote_globals {
319: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 320: my ($result,%returnhash,%whatneeded);
321: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 322: foreach my $what (sort(keys(%{$whathash}))) {
323: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 324: my ($response,$cached);
1.1121 raeburn 325: unless ($ignore_cache) {
1.1125 raeburn 326: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 327: }
328: if (defined($cached)) {
1.1125 raeburn 329: $returnhash{$what} = $response;
1.1121 raeburn 330: } else {
1.1125 raeburn 331: $whatneeded{$what} = 1;
1.1121 raeburn 332: }
333: }
1.1125 raeburn 334: if (keys(%whatneeded) == 0) {
335: $result = 'ok';
336: } else {
1.1121 raeburn 337: my $requested = &freeze_escape(\%whatneeded);
338: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 339: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
340: ($rep eq 'unknown_cmd')) {
341: $result = $rep;
342: } else {
343: $result = 'ok';
1.1121 raeburn 344: my @pairs=split(/\&/,$rep);
1.1125 raeburn 345: foreach my $item (@pairs) {
346: my ($key,$value)=split(/=/,$item,2);
347: my $what = &unescape($key);
348: my $hashid = $lonhost.'-'.$what;
349: $returnhash{$what}=&thaw_unescape($value);
350: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 351: }
352: }
353: }
354: }
1.1125 raeburn 355: return ($result,\%returnhash);
1.1121 raeburn 356: }
357:
1.1124 raeburn 358: sub remote_devalidate_cache {
1.1172.2.35 raeburn 359: my ($lonhost,$cachekeys) = @_;
360: my $items;
361: return unless (ref($cachekeys) eq 'ARRAY');
362: my $cachestr = join('&',@{$cachekeys});
363: return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 364: }
365:
1.1 albertel 366: # -------------------------------------------------- Non-critical communication
367: sub subreply {
368: my ($cmd,$server)=@_;
1.838 albertel 369: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 370: #
371: # With loncnew process trimming, there's a timing hole between lonc server
372: # process exit and the master server picking up the listen on the AF_UNIX
373: # socket. In that time interval, a lock file will exist:
374:
375: my $lockfile=$peerfile.".lock";
376: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1172.2.79 raeburn 377: sleep(0.1);
1.549 foxr 378: }
379: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 380: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 381: #
1.550 foxr 382: # We'll give the connection a few tries before abandoning it. If
383: # connection is not possible, we'll con_lost back to the client.
384: #
385: my $client;
386: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
387: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
388: Type => SOCK_STREAM,
389: Timeout => 10);
1.869 albertel 390: if ($client) {
1.550 foxr 391: last; # Connected!
1.850 albertel 392: } else {
1.853 albertel 393: &create_connection(&hostname($server),$server);
1.550 foxr 394: }
1.1172.2.79 raeburn 395: sleep(0.1); # Try again later if failed connection.
1.550 foxr 396: }
397: my $answer;
398: if ($client) {
1.704 albertel 399: print $client "sethost:$server:$cmd\n";
1.550 foxr 400: $answer=<$client>;
401: if (!$answer) { $answer="con_lost"; }
402: chomp($answer);
403: } else {
404: $answer = 'con_lost'; # Failed connection.
405: }
1.1 albertel 406: return $answer;
407: }
408:
409: sub reply {
410: my ($cmd,$server)=@_;
1.838 albertel 411: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 412: my $answer=subreply($cmd,$server);
1.65 www 413: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111 raeburn 414: my $logged = $cmd;
415: if ($cmd =~ /^encrypt:([^:]+):/) {
416: my $subcmd = $1;
417: if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
418: ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
419: ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
420: (undef,undef,my @rest) = split(/:/,$cmd);
421: if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
422: splice(@rest,2,1,'Hidden');
423: } elsif ($subcmd eq 'passwd') {
424: splice(@rest,2,2,('Hidden','Hidden'));
425: } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
426: ($subcmd eq 'autoexportgrades')) {
427: splice(@rest,3,1,'Hidden');
428: }
429: $logged = join(':',('encrypt:'.$subcmd,@rest));
430: }
431: }
432: &logthis("<font color=\"blue\">WARNING:".
433: " $logged to $server returned $answer</font>");
1.12 www 434: }
1.1 albertel 435: return $answer;
436: }
437:
438: # ----------------------------------------------------------- Send USR1 to lonc
439:
440: sub reconlonc {
1.891 albertel 441: my ($lonid) = @_;
442: if ($lonid) {
1.1172.2.72 raeburn 443: my $hostname = &hostname($lonid);
1.891 albertel 444: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
445: if ($hostname && -e $peerfile) {
446: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
447: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
448: Type => SOCK_STREAM,
449: Timeout => 10);
450: if ($client) {
451: print $client ("reset_retries\n");
452: my $answer=<$client>;
453: #reset just this one.
454: }
455: }
456: return;
457: }
458:
1.836 www 459: &logthis("Trying to reconnect lonc");
1.1 albertel 460: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96 raeburn 461: if (open(my $fh,"<",$loncfile)) {
1.1 albertel 462: my $loncpid=<$fh>;
463: chomp($loncpid);
464: if (kill 0 => $loncpid) {
465: &logthis("lonc at pid $loncpid responding, sending USR1");
466: kill USR1 => $loncpid;
467: sleep 1;
1.836 www 468: } else {
1.12 www 469: &logthis(
1.672 albertel 470: "<font color=\"blue\">WARNING:".
1.12 www 471: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 472: }
473: } else {
1.836 www 474: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 475: }
476: }
477:
478: # ------------------------------------------------------ Critical communication
1.12 www 479:
1.1 albertel 480: sub critical {
481: my ($cmd,$server)=@_;
1.838 albertel 482: unless (&hostname($server)) {
1.672 albertel 483: &logthis("<font color=\"blue\">WARNING:".
1.89 www 484: " Critical message to unknown server ($server)</font>");
485: return 'no_such_host';
486: }
1.1 albertel 487: my $answer=reply($cmd,$server);
488: if ($answer eq 'con_lost') {
1.1172.2.72 raeburn 489: &reconlonc($server);
1.589 albertel 490: my $answer=reply($cmd,$server);
1.1 albertel 491: if ($answer eq 'con_lost') {
492: my $now=time;
493: my $middlename=$cmd;
1.5 www 494: $middlename=substr($middlename,0,16);
1.1 albertel 495: $middlename=~s/\W//g;
496: my $dfilename=
1.305 www 497: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
498: $dumpcount++;
1.1 albertel 499: {
1.448 albertel 500: my $dfh;
1.1172.2.96 raeburn 501: if (open($dfh,">",$dfilename)) {
1.448 albertel 502: print $dfh "$cmd\n";
503: close($dfh);
504: }
1.1 albertel 505: }
1.1172.2.79 raeburn 506: sleep 1;
1.1 albertel 507: my $wcmd='';
508: {
1.448 albertel 509: my $dfh;
1.1172.2.96 raeburn 510: if (open($dfh,"<",$dfilename)) {
1.448 albertel 511: $wcmd=<$dfh>;
512: close($dfh);
513: }
1.1 albertel 514: }
515: chomp($wcmd);
1.7 www 516: if ($wcmd eq $cmd) {
1.672 albertel 517: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 518: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 519: &logperm("D:$server:$cmd");
520: return 'con_delayed';
521: } else {
1.672 albertel 522: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 523: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 524: &logperm("F:$server:$cmd");
525: return 'con_failed';
526: }
527: }
528: }
529: return $answer;
1.405 albertel 530: }
531:
1.755 albertel 532: # ------------------------------------------- check if return value is an error
533:
534: sub error {
535: my ($result) = @_;
1.756 albertel 536: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 537: if ($2 == 2) { return undef; }
538: return $1;
539: }
540: return undef;
541: }
542:
1.783 albertel 543: sub convert_and_load_session_env {
544: my ($lonidsdir,$handle)=@_;
545: my @profile;
546: {
1.917 albertel 547: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
548: if (!$opened) {
1.915 albertel 549: return 0;
550: }
1.783 albertel 551: flock($idf,LOCK_SH);
552: @profile=<$idf>;
553: close($idf);
554: }
555: my %temp_env;
556: foreach my $line (@profile) {
1.786 albertel 557: if ($line !~ m/=/) {
558: return 0;
559: }
1.783 albertel 560: chomp($line);
561: my ($envname,$envvalue)=split(/=/,$line,2);
562: $temp_env{&unescape($envname)} = &unescape($envvalue);
563: }
564: unlink("$lonidsdir/$handle.id");
565: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
566: 0640)) {
567: %disk_env = %temp_env;
568: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
569: untie(%disk_env);
570: }
1.786 albertel 571: return 1;
1.783 albertel 572: }
573:
1.374 www 574: # ------------------------------------------- Transfer profile into environment
1.780 albertel 575: my $env_loaded;
576: sub transfer_profile_to_env {
1.788 albertel 577: my ($lonidsdir,$handle,$force_transfer) = @_;
578: if (!$force_transfer && $env_loaded) { return; }
1.374 www 579:
1.720 albertel 580: if (!defined($lonidsdir)) {
581: $lonidsdir = $perlvar{'lonIDsDir'};
582: }
583: if (!defined($handle)) {
584: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
585: }
586:
1.786 albertel 587: my $convert;
588: {
1.917 albertel 589: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
590: if (!$opened) {
1.915 albertel 591: return;
592: }
1.786 albertel 593: flock($idf,LOCK_SH);
594: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
595: &GDBM_READER(),0640)) {
596: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
597: untie(%disk_env);
598: } else {
599: $convert = 1;
600: }
601: }
602: if ($convert) {
603: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
604: &logthis("Failed to load session, or convert session.");
605: }
1.374 www 606: }
1.783 albertel 607:
1.786 albertel 608: my %remove;
1.783 albertel 609: while ( my $envname = each(%env) ) {
1.433 matthew 610: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
611: if ($time < time-300) {
1.783 albertel 612: $remove{$key}++;
1.433 matthew 613: }
614: }
615: }
1.783 albertel 616:
1.619 albertel 617: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 618: $env_loaded=1;
1.783 albertel 619: foreach my $expired_key (keys(%remove)) {
1.433 matthew 620: &delenv($expired_key);
1.374 www 621: }
1.1 albertel 622: }
623:
1.916 albertel 624: # ---------------------------------------------------- Check for valid session
625: sub check_for_valid_session {
1.1172.2.96 raeburn 626: my ($r,$name,$userhashref,$domref) = @_;
1.916 albertel 627: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108 raeburn 628: my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155 raeburn 629: if ($name eq 'lonDAV') {
630: $lonidsdir=$r->dir_config('lonDAVsessDir');
631: } else {
632: $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108 raeburn 633: if ($name eq '') {
634: $name = 'lonID';
635: }
636: }
637: if ($name eq 'lonID') {
638: $secure = 'lonSID';
639: $linkname = 'lonLinkID';
640: $pubname = 'lonPubID';
641: if (exists($cookies{$secure})) {
642: $lonid=$cookies{$secure};
643: } elsif (exists($cookies{$name})) {
644: $lonid=$cookies{$name};
645: } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
646: $lonid=$cookies{$linkname};
647: } elsif (exists($cookies{$pubname})) {
648: $lonid=$cookies{$pubname};
649: }
650: } else {
651: $lonid=$cookies{$name};
652: }
653: return undef if (!$lonid);
654:
655: my $handle=&LONCAPA::clean_handle($lonid->value);
656: if (-l "$lonidsdir/$handle.id") {
657: my $link = readlink("$lonidsdir/$handle.id");
658: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
659: $handle = $1;
660: }
1.1155 raeburn 661: }
1.1172.2.96 raeburn 662: if (!-e "$lonidsdir/$handle.id") {
663: if ((ref($domref)) && ($name eq 'lonID') &&
664: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
665: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
666: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
667: $$domref = $possudom;
668: }
669: }
670: return undef;
671: }
1.916 albertel 672:
1.917 albertel 673: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
674: return undef if (!$opened);
1.916 albertel 675:
676: flock($idf,LOCK_SH);
677: my %disk_env;
678: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
679: &GDBM_READER(),0640)) {
680: return undef;
681: }
682:
683: if (!defined($disk_env{'user.name'})
684: || !defined($disk_env{'user.domain'})) {
1.1172.2.107 raeburn 685: untie(%disk_env);
1.916 albertel 686: return undef;
687: }
1.1172.2.18 raeburn 688:
1.1172.2.36 raeburn 689: if (ref($userhashref) eq 'HASH') {
690: $userhashref->{'name'} = $disk_env{'user.name'};
691: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18 raeburn 692: }
1.1172.2.107 raeburn 693: untie(%disk_env);
1.1172.2.18 raeburn 694:
1.916 albertel 695: return $handle;
696: }
697:
1.830 albertel 698: sub timed_flock {
699: my ($file,$lock_type) = @_;
700: my $failed=0;
701: eval {
702: local $SIG{__DIE__}='DEFAULT';
703: local $SIG{ALRM}=sub {
704: $failed=1;
705: die("failed lock");
706: };
707: alarm(13);
708: flock($file,$lock_type);
709: alarm(0);
710: };
711: if ($failed) {
712: return undef;
713: } else {
714: return 1;
715: }
716: }
717:
1.1172.2.107 raeburn 718: sub get_sessionfile_vars {
719: my ($handle,$lonidsdir,$storearr) = @_;
720: my %returnhash;
721: unless (ref($storearr) eq 'ARRAY') {
722: return %returnhash;
723: }
724: if (-l "$lonidsdir/$handle.id") {
725: my $link = readlink("$lonidsdir/$handle.id");
726: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
727: $handle = $1;
728: }
729: }
730: if ((-e "$lonidsdir/$handle.id") &&
731: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
732: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
733: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
734: if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
735: flock($idf,LOCK_SH);
736: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
737: &GDBM_READER(),0640)) {
738: foreach my $item (@{$storearr}) {
739: $returnhash{$item} = $disk_env{$item};
740: }
741: untie(%disk_env);
742: }
743: }
744: }
745: }
746: return %returnhash;
747: }
748:
1.5 www 749: # ---------------------------------------------------------- Append Environment
750:
751: sub appenv {
1.949 raeburn 752: my ($newenv,$roles) = @_;
753: if (ref($newenv) eq 'HASH') {
754: foreach my $key (keys(%{$newenv})) {
755: my $refused = 0;
756: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
757: $refused = 1;
758: if (ref($roles) eq 'ARRAY') {
1.1172.2.40 raeburn 759: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 760: if (grep(/^\Q$role\E$/,@{$roles})) {
761: $refused = 0;
762: }
763: }
764: }
765: if ($refused) {
766: &logthis("<font color=\"blue\">WARNING: ".
767: "Attempt to modify environment ".$key." to ".$newenv->{$key}
768: .'</font>');
769: delete($newenv->{$key});
770: } else {
771: $env{$key}=$newenv->{$key};
772: }
773: }
1.1172.2.96 raeburn 774: my $lonids = $perlvar{'lonIDsDir'};
775: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
776: my $opened = open(my $env_file,'+<',$env{'user.environment'});
777: if ($opened
778: && &timed_flock($env_file,LOCK_EX)
779: &&
780: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
781: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
782: while (my ($key,$value) = each(%{$newenv})) {
783: $disk_env{$key} = $value;
784: }
785: untie(%disk_env);
786: }
1.35 www 787: }
1.191 harris41 788: }
1.56 www 789: return 'ok';
790: }
791: # ----------------------------------------------------- Delete from Environment
792:
793: sub delenv {
1.1104 raeburn 794: my ($delthis,$regexp,$roles) = @_;
795: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
796: my $refused = 1;
797: if (ref($roles) eq 'ARRAY') {
798: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
799: if (grep(/^\Q$role\E$/,@{$roles})) {
800: $refused = 0;
801: }
802: }
803: if ($refused) {
804: &logthis("<font color=\"blue\">WARNING: ".
805: "Attempt to delete from environment ".$delthis);
806: return 'error';
807: }
1.56 www 808: }
1.917 albertel 809: my $opened = open(my $env_file,'+<',$env{'user.environment'});
810: if ($opened
1.915 albertel 811: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 812: &&
813: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
814: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 815: foreach my $key (keys(%disk_env)) {
1.987 raeburn 816: if ($regexp) {
817: if ($key=~/^$delthis/) {
818: delete($env{$key});
819: delete($disk_env{$key});
820: }
821: } else {
822: if ($key=~/^\Q$delthis\E/) {
823: delete($env{$key});
824: delete($disk_env{$key});
825: }
826: }
1.448 albertel 827: }
1.783 albertel 828: untie(%disk_env);
1.5 www 829: }
830: return 'ok';
1.369 albertel 831: }
832:
1.790 albertel 833: sub get_env_multiple {
834: my ($name) = @_;
835: my @values;
836: if (defined($env{$name})) {
837: # exists is it an array
838: if (ref($env{$name})) {
839: @values=@{ $env{$name} };
840: } else {
841: $values[0]=$env{$name};
842: }
843: }
844: return(@values);
845: }
846:
1.958 www 847: # ------------------------------------------------------------------- Locking
848:
849: sub set_lock {
850: my ($text)=@_;
851: $locknum++;
852: my $id=$$.'-'.$locknum;
853: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
854: 'session.lock.'.$id => $text});
855: return $id;
856: }
857:
858: sub get_locks {
859: my $num=0;
860: my %texts=();
861: foreach my $lock (split(/\,/,$env{'session.locks'})) {
862: if ($lock=~/\w/) {
863: $num++;
864: $texts{$lock}=$env{'session.lock.'.$lock};
865: }
866: }
867: return ($num,%texts);
868: }
869:
870: sub remove_lock {
871: my ($id)=@_;
872: my $newlocks='';
873: foreach my $lock (split(/\,/,$env{'session.locks'})) {
874: if (($lock=~/\w/) && ($lock ne $id)) {
875: $newlocks.=','.$lock;
876: }
877: }
878: &appenv({'session.locks' => $newlocks});
879: &delenv('session.lock.'.$id);
880: }
881:
882: sub remove_all_locks {
883: my $activelocks=$env{'session.locks'};
884: foreach my $lock (split(/\,/,$env{'session.locks'})) {
885: if ($lock=~/\w/) {
886: &remove_lock($lock);
887: }
888: }
889: }
890:
891:
1.369 albertel 892: # ------------------------------------------ Find out current server userload
893: sub userload {
894: my $numusers=0;
895: {
896: opendir(LONIDS,$perlvar{'lonIDsDir'});
897: my $filename;
898: my $curtime=time;
899: while ($filename=readdir(LONIDS)) {
1.925 albertel 900: next if ($filename eq '.' || $filename eq '..');
901: next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112 raeburn 902: next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404 albertel 903: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 904: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 905: }
906: closedir(LONIDS);
907: }
908: my $userloadpercent=0;
909: my $maxuserload=$perlvar{'lonUserLoadLim'};
910: if ($maxuserload) {
1.371 albertel 911: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 912: }
1.372 albertel 913: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 914: return $userloadpercent;
1.283 www 915: }
916:
1.1 albertel 917: # ------------------------------ Find server with least workload from spare.tab
1.11 www 918:
1.1 albertel 919: sub spareserver {
1.1083 raeburn 920: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 921: my $spare_server;
1.370 albertel 922: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 923: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
924: : $userloadpercent;
1.1083 raeburn 925: my ($uint_dom,$remotesessions);
926: if (($udom ne '') && (&domain($udom) ne '')) {
927: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
928: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
929: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
930: $remotesessions = $udomdefaults{'remotesessions'};
931: }
1.1123 raeburn 932: my $spareshash = &this_host_spares($udom);
933: if (ref($spareshash) eq 'HASH') {
934: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
935: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62 raeburn 936: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
937: $try_server));
1.1123 raeburn 938: ($spare_server, $lowest_load) =
939: &compare_server_load($try_server, $spare_server, $lowest_load);
940: }
1.1083 raeburn 941: }
1.784 albertel 942:
1.1123 raeburn 943: my $found_server = ($spare_server ne '' && $lowest_load < 100);
944:
945: if (!$found_server) {
946: if (ref($spareshash->{'default'}) eq 'ARRAY') {
947: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62 raeburn 948: next unless (&spare_can_host($udom,$uint_dom,
949: $remotesessions,$try_server));
1.1123 raeburn 950: ($spare_server, $lowest_load) =
951: &compare_server_load($try_server, $spare_server, $lowest_load);
952: }
953: }
954: }
1.784 albertel 955: }
956:
957: if (!$want_server_name) {
1.1001 raeburn 958: if (defined($spare_server)) {
959: my $hostname = &hostname($spare_server);
1.1083 raeburn 960: if (defined($hostname)) {
1.1172.2.120 raeburn 961: my $protocol = 'http';
962: if ($protocol{$spare_server} eq 'https') {
963: $protocol = $protocol{$spare_server};
964: }
1.1001 raeburn 965: $spare_server = $protocol.'://'.$hostname;
966: }
967: }
1.784 albertel 968: }
969: return $spare_server;
970: }
971:
972: sub compare_server_load {
1.1172.2.41 raeburn 973: my ($try_server, $spare_server, $lowest_load, $required) = @_;
974:
975: if ($required) {
976: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
977: my $remoterev = &get_server_loncaparev(undef,$try_server);
978: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
979: if (($major eq '' && $minor eq '') ||
980: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
981: return ($spare_server,$lowest_load);
982: }
983: }
1.784 albertel 984:
985: my $loadans = &reply('load', $try_server);
986: my $userloadans = &reply('userload',$try_server);
987:
988: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 989: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 990: }
991:
992: my $load;
993: if ($loadans =~ /\d/) {
994: if ($userloadans =~ /\d/) {
995: #both are numbers, pick the bigger one
996: $load = ($loadans > $userloadans) ? $loadans
997: : $userloadans;
1.411 albertel 998: } else {
1.784 albertel 999: $load = $loadans;
1.411 albertel 1000: }
1.784 albertel 1001: } else {
1002: $load = $userloadans;
1003: }
1004:
1005: if (($load =~ /\d/) && ($load < $lowest_load)) {
1006: $spare_server = $try_server;
1007: $lowest_load = $load;
1.370 albertel 1008: }
1.784 albertel 1009: return ($spare_server,$lowest_load);
1.202 matthew 1010: }
1.914 albertel 1011:
1012: # --------------------------- ask offload servers if user already has a session
1013: sub find_existing_session {
1014: my ($udom,$uname) = @_;
1.1123 raeburn 1015: my $spareshash = &this_host_spares($udom);
1016: if (ref($spareshash) eq 'HASH') {
1017: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1018: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1019: return $try_server if (&has_user_session($try_server, $udom, $uname));
1020: }
1021: }
1022: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1023: foreach my $try_server (@{ $spareshash->{'default'} }) {
1024: return $try_server if (&has_user_session($try_server, $udom, $uname));
1025: }
1026: }
1.914 albertel 1027: }
1028: return;
1029: }
1030:
1.1172.2.107 raeburn 1031: # check if user's browser sent load balancer cookie and server still has session
1032: # and is not overloaded.
1033: sub check_for_balancer_cookie {
1034: my ($r,$update_mtime) = @_;
1035: my ($otherserver,$cookie);
1036: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1037: if (exists($cookies{'balanceID'})) {
1038: my $balid = $cookies{'balanceID'};
1039: $cookie=&LONCAPA::clean_handle($balid->value);
1040: my $balancedir=$r->dir_config('lonBalanceDir');
1041: if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
1042: if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
1043: my ($possudom,$possuname) = ($1,$2);
1044: my $has_session = 0;
1045: if ((&domain($possudom) ne '') &&
1046: (&homeserver($possuname,$possudom) ne 'no_host')) {
1047: my $try_server;
1048: my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
1049: if ($opened) {
1050: flock($idf,LOCK_SH);
1051: while (my $line = <$idf>) {
1052: chomp($line);
1053: if (&hostname($line) ne '') {
1054: $try_server = $line;
1055: last;
1056: }
1057: }
1058: close($idf);
1059: if (($try_server) &&
1060: (&has_user_session($try_server,$possudom,$possuname))) {
1061: my $lowest_load = 30000;
1062: ($otherserver,$lowest_load) =
1063: &compare_server_load($try_server,undef,$lowest_load);
1064: if ($otherserver ne '' && $lowest_load < 100) {
1065: $has_session = 1;
1066: } else {
1067: undef($otherserver);
1068: }
1069: }
1070: }
1071: }
1072: if ($has_session) {
1073: if ($update_mtime) {
1074: my $atime = my $mtime = time;
1075: utime($atime,$mtime,"$balancedir/$cookie.id");
1076: }
1077: } else {
1078: unlink("$balancedir/$cookie.id");
1079: }
1080: }
1081: }
1082: }
1083: return ($otherserver,$cookie);
1084: }
1085:
1.1172.2.130 raeburn 1086: sub updatebalcookie {
1087: my ($cookie,$balancer,$lastentry)=@_;
1088: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1089: my ($udom,$uname) = ($1,$2);
1090: my $uprimary_id = &domain($udom,'primary');
1091: my $uintdom = &internet_dom($uprimary_id);
1092: my $intdom = &internet_dom($balancer);
1093: my $serverhomedom = &host_domain($balancer);
1094: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1095: return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
1096: }
1097: }
1098: return;
1099: }
1100:
1.1172.2.107 raeburn 1101: sub delbalcookie {
1102: my ($cookie,$balancer) =@_;
1103: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1104: my ($udom,$uname) = ($1,$2);
1105: my $uprimary_id = &domain($udom,'primary');
1106: my $uintdom = &internet_dom($uprimary_id);
1107: my $intdom = &internet_dom($balancer);
1108: my $serverhomedom = &host_domain($balancer);
1109: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1172.2.130 raeburn 1110: return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1172.2.107 raeburn 1111: }
1112: }
1113: }
1114:
1.914 albertel 1115: # -------------------------------- ask if server already has a session for user
1116: sub has_user_session {
1117: my ($lonid,$udom,$uname) = @_;
1118: my $result = &reply(join(':','userhassession',
1119: map {&escape($_)} ($udom,$uname)),$lonid);
1120: return 1 if ($result eq 'ok');
1121:
1122: return 0;
1123: }
1124:
1.1076 raeburn 1125: # --------- determine least loaded server in a user's domain which allows login
1126:
1127: sub choose_server {
1.1172.2.47 raeburn 1128: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1129: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1130: my %servers = &get_servers($udom);
1.1076 raeburn 1131: my $lowest_load = 30000;
1.1172.2.47 raeburn 1132: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1133: if ($skiploadbal) {
1134: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1135: unless (defined($cached)) {
1136: my $cachetime = 60*60*24;
1137: my %domconfig =
1138: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1139: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1140: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1141: $cachetime);
1142: }
1143: }
1144: }
1.1076 raeburn 1145: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 1146: my $loginvia;
1.1172.2.47 raeburn 1147: if ($skiploadbal) {
1148: if (ref($balancers) eq 'HASH') {
1149: next if (exists($balancers->{$lonhost}));
1150: }
1151: }
1.1115 raeburn 1152: if ($checkloginvia) {
1153: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1154: if ($loginvia) {
1155: my ($server,$path) = split(/:/,$loginvia);
1156: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1157: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1158: if ($login_host eq $server) {
1159: $portal_path = $path;
1.1151 raeburn 1160: $isredirect = 1;
1.1116 raeburn 1161: }
1162: } else {
1163: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1164: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1165: if ($login_host eq $lonhost) {
1166: $portal_path = '';
1.1151 raeburn 1167: $isredirect = '';
1.1116 raeburn 1168: }
1169: }
1170: } else {
1.1076 raeburn 1171: ($login_host, $lowest_load) =
1.1172.2.41 raeburn 1172: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1173: }
1174: }
1175: if ($login_host ne '') {
1.1116 raeburn 1176: $hostname = &hostname($login_host);
1.1076 raeburn 1177: }
1.1172.2.88 raeburn 1178: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1179: }
1180:
1.1172.2.123 raeburn 1181: sub get_course_sessions {
1182: my ($cnum,$cdom,$lastactivity) = @_;
1183: my %servers = &internet_dom_servers($cdom);
1184: my %returnhash;
1185: foreach my $server (sort(keys(%servers))) {
1186: my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
1187: my @pairs=split(/\&/,$rep);
1188: unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
1189: foreach my $item (@pairs) {
1190: my ($key,$value)=split(/=/,$item,2);
1191: $key = &unescape($key);
1192: next if ($key =~ /^error: 2 /);
1193: if (exists($returnhash{$key})) {
1194: next if ($value < $returnhash{$key});
1195: }
1196: $returnhash{$key}=$value;
1197: }
1198: }
1199: }
1200: return %returnhash;
1201: }
1202:
1.202 matthew 1203: # --------------------------------------------- Try to change a user's password
1204:
1205: sub changepass {
1.799 raeburn 1206: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1207: $currentpass = &escape($currentpass);
1208: $newpass = &escape($newpass);
1.1030 raeburn 1209: my $lonhost = $perlvar{'lonHostID'};
1210: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1211: $server);
1212: if (! $answer) {
1213: &logthis("No reply on password change request to $server ".
1214: "by $uname in domain $udom.");
1215: } elsif ($answer =~ "^ok") {
1216: &logthis("$uname in $udom successfully changed their password ".
1217: "on $server.");
1218: } elsif ($answer =~ "^pwchange_failure") {
1219: &logthis("$uname in $udom was unable to change their password ".
1220: "on $server. The action was blocked by either lcpasswd ".
1221: "or pwchange");
1222: } elsif ($answer =~ "^non_authorized") {
1223: &logthis("$uname in $udom did not get their password correct when ".
1224: "attempting to change it on $server.");
1225: } elsif ($answer =~ "^auth_mode_error") {
1226: &logthis("$uname in $udom attempted to change their password despite ".
1227: "not being locally or internally authenticated on $server.");
1228: } elsif ($answer =~ "^unknown_user") {
1229: &logthis("$uname in $udom attempted to change their password ".
1230: "on $server but were unable to because $server is not ".
1231: "their home server.");
1232: } elsif ($answer =~ "^refused") {
1233: &logthis("$server refused to change $uname in $udom password because ".
1234: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1235: } elsif ($answer =~ "invalid_client") {
1236: &logthis("$server refused to change $uname in $udom password because ".
1237: "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113 raeburn 1238: } elsif ($answer =~ "^prioruse") {
1239: &logthis("$server refused to change $uname in $udom password because ".
1240: "the password had been used before");
1.202 matthew 1241: }
1242: return $answer;
1.1 albertel 1243: }
1244:
1.169 harris41 1245: # ----------------------- Try to determine user's current authentication scheme
1246:
1247: sub queryauthenticate {
1248: my ($uname,$udom)=@_;
1.456 albertel 1249: my $uhome=&homeserver($uname,$udom);
1250: if (!$uhome) {
1251: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1252: return 'no_host';
1253: }
1254: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1255: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1256: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1257: }
1.456 albertel 1258: return $answer;
1.169 harris41 1259: }
1260:
1.1 albertel 1261: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1262:
1.1 albertel 1263: sub authenticate {
1.1073 raeburn 1264: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1265: $upass=&escape($upass);
1266: $uname= &LONCAPA::clean_username($uname);
1.836 www 1267: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1268: my $newhome;
1.836 www 1269: if ((!$uhome) || ($uhome eq 'no_host')) {
1270: # Maybe the machine was offline and only re-appeared again recently?
1271: &reconlonc();
1272: # One more
1.952 raeburn 1273: $uhome=&homeserver($uname,$udom,1);
1274: if (($uhome eq 'no_host') && $checkdefauth) {
1275: if (defined(&domain($udom,'primary'))) {
1276: $newhome=&domain($udom,'primary');
1277: }
1278: if ($newhome ne '') {
1279: $uhome = $newhome;
1280: }
1281: }
1.836 www 1282: if ((!$uhome) || ($uhome eq 'no_host')) {
1283: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1284: return 'no_host';
1285: }
1.1 albertel 1286: }
1.1073 raeburn 1287: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1288: if ($answer eq 'authorized') {
1.952 raeburn 1289: if ($newhome) {
1290: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1291: return 'no_account_on_host';
1292: } else {
1293: &logthis("User $uname at $udom authorized by $uhome");
1294: return $uhome;
1295: }
1.471 albertel 1296: }
1297: if ($answer eq 'non_authorized') {
1298: &logthis("User $uname at $udom rejected by $uhome");
1299: return 'no_host';
1.9 www 1300: }
1.471 albertel 1301: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1302: return 'no_host';
1303: }
1304:
1.1073 raeburn 1305: sub can_host_session {
1.1074 raeburn 1306: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1307: my $canhost = 1;
1.1074 raeburn 1308: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1309: if (ref($remotesessions) eq 'HASH') {
1310: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1311: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1312: $canhost = 0;
1313: } else {
1314: $canhost = 1;
1315: }
1316: }
1317: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1318: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1319: $canhost = 1;
1320: } else {
1321: $canhost = 0;
1322: }
1323: }
1324: if ($canhost) {
1325: if ($remotesessions->{'version'} ne '') {
1326: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1327: if ($reqmajor ne '' && $reqminor ne '') {
1328: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1329: my $major = $1;
1330: my $minor = $2;
1331: if (($major < $reqmajor ) ||
1332: (($major == $reqmajor) && ($minor < $reqminor))) {
1333: $canhost = 0;
1334: }
1335: } else {
1336: $canhost = 0;
1337: }
1338: }
1339: }
1340: }
1341: }
1342: if ($canhost) {
1343: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1344: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1345: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1346: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1347: if (($uint_dom ne '') &&
1348: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1349: $canhost = 0;
1350: } else {
1351: $canhost = 1;
1352: }
1353: }
1354: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1355: if (($uint_dom ne '') &&
1356: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1357: $canhost = 1;
1358: } else {
1359: $canhost = 0;
1360: }
1361: }
1362: }
1363: }
1364: return $canhost;
1365: }
1366:
1.1083 raeburn 1367: sub spare_can_host {
1368: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1369: my $canhost=1;
1.1172.2.62 raeburn 1370: my $try_server_hostname = &hostname($try_server);
1371: my $serverhomeID = &get_server_homeID($try_server_hostname);
1372: my $serverhomedom = &host_domain($serverhomeID);
1373: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1374: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1375: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1376: $canhost = 0;
1377: }
1378: }
1.1172.2.136 raeburn 1379: if ($canhost) {
1380: if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
1381: if ($defdomdefaults{'offloadoth'}{$try_server}) {
1382: unless (&shared_institution($udom,$try_server)) {
1383: $canhost = 0;
1384: }
1385: }
1386: }
1387: }
1.1172.2.62 raeburn 1388: if (($canhost) && ($uint_dom)) {
1389: my @intdoms;
1390: my $internet_names = &get_internet_names($try_server);
1391: if (ref($internet_names) eq 'ARRAY') {
1392: @intdoms = @{$internet_names};
1393: }
1394: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1395: my $remoterev = &get_server_loncaparev(undef,$try_server);
1396: $canhost = &can_host_session($udom,$try_server,$remoterev,
1397: $remotesessions,
1398: $defdomdefaults{'hostedsessions'});
1399: }
1.1083 raeburn 1400: }
1401: return $canhost;
1402: }
1403:
1.1123 raeburn 1404: sub this_host_spares {
1405: my ($dom) = @_;
1.1126 raeburn 1406: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1407: my @hosts = ¤t_machine_ids();
1408: foreach my $lonhost (@hosts) {
1409: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1410: $dom_in_use = $dom;
1411: $lonhost_in_use = $lonhost;
1.1123 raeburn 1412: last;
1413: }
1414: }
1.1126 raeburn 1415: if ($dom_in_use ne '') {
1416: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1417: }
1418: if (ref($result) ne 'HASH') {
1419: $lonhost_in_use = $perlvar{'lonHostID'};
1420: $dom_in_use = &host_domain($lonhost_in_use);
1421: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1422: if (ref($result) ne 'HASH') {
1423: $result = \%spareid;
1424: }
1425: }
1426: return $result;
1427: }
1428:
1429: sub spares_for_offload {
1430: my ($dom_in_use,$lonhost_in_use) = @_;
1431: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1432: if (defined($cached)) {
1433: return $result;
1434: } else {
1.1126 raeburn 1435: my $cachetime = 60*60*24;
1436: my %domconfig =
1437: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1438: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1439: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1440: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1441: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1442: }
1443: }
1444: }
1445: }
1.1126 raeburn 1446: return;
1.1123 raeburn 1447: }
1448:
1.1129 raeburn 1449: sub get_lonbalancer_config {
1450: my ($servers) = @_;
1451: my ($currbalancer,$currtargets);
1452: if (ref($servers) eq 'HASH') {
1453: foreach my $server (keys(%{$servers})) {
1454: my %what = (
1455: spareid => 1,
1456: perlvar => 1,
1457: );
1458: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1459: if ($result eq 'ok') {
1460: if (ref($returnhash) eq 'HASH') {
1461: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1462: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1463: $currbalancer = $server;
1464: $currtargets = {};
1465: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1466: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1467: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1468: }
1469: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1470: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1471: }
1472: }
1473: last;
1474: }
1475: }
1476: }
1477: }
1478: }
1479: }
1480: return ($currbalancer,$currtargets);
1481: }
1482:
1483: sub check_loadbalancing {
1.1172.2.88 raeburn 1484: my ($uname,$udom,$caller) = @_;
1.1172.2.12 raeburn 1485: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107 raeburn 1486: $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129 raeburn 1487: my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4 raeburn 1488: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1489: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1490: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1491: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1492: my $serverhomedom = &host_domain($lonhost);
1.1172.2.75 raeburn 1493: my $domneedscache;
1.1129 raeburn 1494: my $cachetime = 60*60*24;
1495:
1496: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1497: $dom_in_use = $udom;
1498: $homeintdom = 1;
1499: } else {
1500: $dom_in_use = $serverhomedom;
1501: }
1502: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1503: unless (defined($cached)) {
1504: my %domconfig =
1505: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1506: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1507: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75 raeburn 1508: } else {
1509: $domneedscache = $dom_in_use;
1.1129 raeburn 1510: }
1511: }
1512: if (ref($result) eq 'HASH') {
1.1172.2.107 raeburn 1513: ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12 raeburn 1514: &check_balancer_result($result,@hosts);
1.1129 raeburn 1515: if ($is_balancer) {
1516: if (ref($currrules) eq 'HASH') {
1517: if ($homeintdom) {
1518: if ($uname ne '') {
1519: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1520: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1521: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1522: $rule_in_effect = $currrules->{'_LC_author'};
1523: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1524: $rule_in_effect = $currrules->{'_LC_adv'}
1525: }
1526: }
1527: if ($rule_in_effect eq '') {
1528: my %userenv = &userenvironment($udom,$uname,'inststatus');
1529: if ($userenv{'inststatus'} ne '') {
1530: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1531: my ($othertitle,$usertypes,$types) =
1532: &Apache::loncommon::sorted_inst_types($udom);
1533: if (ref($types) eq 'ARRAY') {
1534: foreach my $type (@{$types}) {
1535: if (grep(/^\Q$type\E$/,@statuses)) {
1536: if (exists($currrules->{$type})) {
1537: $rule_in_effect = $currrules->{$type};
1538: }
1539: }
1540: }
1541: }
1542: } else {
1543: if (exists($currrules->{'default'})) {
1544: $rule_in_effect = $currrules->{'default'};
1545: }
1546: }
1547: }
1548: } else {
1549: if (exists($currrules->{'default'})) {
1550: $rule_in_effect = $currrules->{'default'};
1551: }
1552: }
1553: } else {
1554: if ($currrules->{'_LC_external'} ne '') {
1555: $rule_in_effect = $currrules->{'_LC_external'};
1556: }
1557: }
1558: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1559: $uname,$udom);
1560: }
1561: }
1562: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35 raeburn 1563: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1564: unless (defined($cached)) {
1565: my %domconfig =
1566: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1567: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75 raeburn 1568: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1569: } else {
1570: $domneedscache = $serverhomedom;
1.1129 raeburn 1571: }
1572: }
1573: if (ref($result) eq 'HASH') {
1.1172.2.107 raeburn 1574: ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12 raeburn 1575: &check_balancer_result($result,@hosts);
1576: if ($is_balancer) {
1.1129 raeburn 1577: if (ref($currrules) eq 'HASH') {
1578: if ($currrules->{'_LC_internetdom'} ne '') {
1579: $rule_in_effect = $currrules->{'_LC_internetdom'};
1580: }
1581: }
1582: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1583: $uname,$udom);
1584: }
1585: } else {
1586: if ($perlvar{'lonBalancer'} eq 'yes') {
1587: $is_balancer = 1;
1588: $offloadto = &this_host_spares($dom_in_use);
1589: }
1.1172.2.75 raeburn 1590: unless (defined($cached)) {
1591: $domneedscache = $serverhomedom;
1592: }
1.1129 raeburn 1593: }
1594: } else {
1595: if ($perlvar{'lonBalancer'} eq 'yes') {
1596: $is_balancer = 1;
1597: $offloadto = &this_host_spares($dom_in_use);
1598: }
1.1172.2.75 raeburn 1599: unless (defined($cached)) {
1600: $domneedscache = $serverhomedom;
1601: }
1602: }
1603: if ($domneedscache) {
1604: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1605: }
1.1172.2.130 raeburn 1606: if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5 raeburn 1607: my $lowest_load = 30000;
1608: if (ref($offloadto) eq 'HASH') {
1609: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1610: foreach my $try_server (@{$offloadto->{'primary'}}) {
1611: ($otherserver,$lowest_load) =
1612: &compare_server_load($try_server,$otherserver,$lowest_load);
1613: }
1.1129 raeburn 1614: }
1.1172.2.5 raeburn 1615: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1616:
1.1172.2.5 raeburn 1617: if (!$found_server) {
1618: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1619: foreach my $try_server (@{$offloadto->{'default'}}) {
1620: ($otherserver,$lowest_load) =
1621: &compare_server_load($try_server,$otherserver,$lowest_load);
1622: }
1623: }
1624: }
1625: } elsif (ref($offloadto) eq 'ARRAY') {
1626: if (@{$offloadto} == 1) {
1627: $otherserver = $offloadto->[0];
1628: } elsif (@{$offloadto} > 1) {
1629: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1630: ($otherserver,$lowest_load) =
1631: &compare_server_load($try_server,$otherserver,$lowest_load);
1632: }
1633: }
1634: }
1.1172.2.88 raeburn 1635: unless ($caller eq 'login') {
1636: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1637: $is_balancer = 0;
1638: if ($uname ne '' && $udom ne '') {
1639: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1640: &appenv({'user.loadbalexempt' => $lonhost,
1641: 'user.loadbalcheck.time' => time});
1642: }
1.1172.2.5 raeburn 1643: }
1.1129 raeburn 1644: }
1645: }
1.1172.2.130 raeburn 1646: }
1647: if (($is_balancer) && (!$homeintdom)) {
1648: undef($setcookie);
1.1129 raeburn 1649: }
1.1172.2.107 raeburn 1650: return ($is_balancer,$otherserver,$setcookie);
1.1129 raeburn 1651: }
1652:
1.1172.2.12 raeburn 1653: sub check_balancer_result {
1654: my ($result,@hosts) = @_;
1.1172.2.107 raeburn 1655: my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12 raeburn 1656: if (ref($result) eq 'HASH') {
1657: if ($result->{'lonhost'} ne '') {
1658: my $currbalancer = $result->{'lonhost'};
1659: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1660: $is_balancer = 1;
1661: $currtargets = $result->{'targets'};
1662: $currrules = $result->{'rules'};
1663: }
1664: } else {
1665: foreach my $key (keys(%{$result})) {
1666: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1667: (ref($result->{$key}) eq 'HASH')) {
1668: $is_balancer = 1;
1669: $currrules = $result->{$key}{'rules'};
1670: $currtargets = $result->{$key}{'targets'};
1.1172.2.107 raeburn 1671: $setcookie = $result->{$key}{'cookie'};
1.1172.2.12 raeburn 1672: last;
1673: }
1674: }
1675: }
1676: }
1.1172.2.107 raeburn 1677: return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12 raeburn 1678: }
1679:
1.1129 raeburn 1680: sub get_loadbalancer_targets {
1681: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1682: my $offloadto;
1.1172.2.4 raeburn 1683: if ($rule_in_effect eq 'none') {
1684: return [$perlvar{'lonHostID'}];
1685: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1686: $offloadto = $currtargets;
1687: } else {
1688: if ($rule_in_effect eq 'homeserver') {
1689: my $homeserver = &homeserver($uname,$udom);
1690: if ($homeserver ne 'no_host') {
1691: $offloadto = [$homeserver];
1692: }
1693: } elsif ($rule_in_effect eq 'externalbalancer') {
1694: my %domconfig =
1695: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1696: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1697: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1698: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1699: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1700: }
1701: }
1702: } else {
1.1172.2.7 raeburn 1703: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1704: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1705: if (&hostname($remotebalancer) ne '') {
1706: $offloadto = [$remotebalancer];
1707: }
1708: }
1709: } elsif (&hostname($rule_in_effect) ne '') {
1710: $offloadto = [$rule_in_effect];
1711: }
1712: }
1713: return $offloadto;
1714: }
1715:
1.1127 raeburn 1716: sub internet_dom_servers {
1717: my ($dom) = @_;
1718: my (%uniqservers,%servers);
1719: my $primaryserver = &hostname(&domain($dom,'primary'));
1720: my @machinedoms = &machine_domains($primaryserver);
1721: foreach my $mdom (@machinedoms) {
1722: my %currservers = %servers;
1723: my %server = &get_servers($mdom);
1724: %servers = (%currservers,%server);
1725: }
1726: my %by_hostname;
1727: foreach my $id (keys(%servers)) {
1728: push(@{$by_hostname{$servers{$id}}},$id);
1729: }
1730: foreach my $hostname (sort(keys(%by_hostname))) {
1731: if (@{$by_hostname{$hostname}} > 1) {
1732: my $match = 0;
1733: foreach my $id (@{$by_hostname{$hostname}}) {
1734: if (&host_domain($id) eq $dom) {
1735: $uniqservers{$id} = $hostname;
1736: $match = 1;
1737: }
1738: }
1739: unless ($match) {
1740: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1741: }
1742: } else {
1743: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1744: }
1745: }
1746: return %uniqservers;
1747: }
1748:
1.1 albertel 1749: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1750:
1.599 albertel 1751: my %homecache;
1.1 albertel 1752: sub homeserver {
1.230 stredwic 1753: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1754: my $index="$uname:$udom";
1.426 albertel 1755:
1.599 albertel 1756: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1757:
1758: my %servers = &get_servers($udom,'library');
1759: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1760: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1761: exists($badServerCache{$tryserver}));
1.841 albertel 1762:
1763: my $answer=reply("home:$udom:$uname",$tryserver);
1764: if ($answer eq 'found') {
1765: delete($badServerCache{$tryserver});
1766: return $homecache{$index}=$tryserver;
1767: } elsif ($answer eq 'no_host') {
1768: $badServerCache{$tryserver}=1;
1769: }
1.1 albertel 1770: }
1771: return 'no_host';
1.70 www 1772: }
1773:
1774: # ------------------------------------- Find the usernames behind a list of IDs
1775:
1776: sub idget {
1777: my ($udom,@ids)=@_;
1778: my %returnhash=();
1779:
1.841 albertel 1780: my %servers = &get_servers($udom,'library');
1781: foreach my $tryserver (keys(%servers)) {
1.1172.2.73 raeburn 1782: my $idlist=join('&', map { &escape($_); } @ids);
1.841 albertel 1783: $idlist=~tr/A-Z/a-z/;
1784: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1785: my @answer=();
1786: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1787: @answer=split(/\&/,$reply);
1788: } ;
1789: my $i;
1790: for ($i=0;$i<=$#ids;$i++) {
1791: if ($answer[$i]) {
1.1172.2.73 raeburn 1792: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841 albertel 1793: }
1794: }
1795: }
1.70 www 1796: return %returnhash;
1797: }
1798:
1799: # ------------------------------------- Find the IDs behind a list of usernames
1800:
1801: sub idrget {
1802: my ($udom,@unames)=@_;
1803: my %returnhash=();
1.800 albertel 1804: foreach my $uname (@unames) {
1805: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1806: }
1.70 www 1807: return %returnhash;
1808: }
1809:
1810: # ------------------------------- Store away a list of names and associated IDs
1811:
1812: sub idput {
1813: my ($udom,%ids)=@_;
1814: my %servers=();
1.800 albertel 1815: foreach my $uname (keys(%ids)) {
1816: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1817: my $uhom=&homeserver($uname,$udom);
1.70 www 1818: if ($uhom ne 'no_host') {
1.800 albertel 1819: my $id=&escape($ids{$uname});
1.70 www 1820: $id=~tr/A-Z/a-z/;
1.800 albertel 1821: my $esc_unam=&escape($uname);
1.70 www 1822: if ($servers{$uhom}) {
1.800 albertel 1823: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1824: } else {
1.800 albertel 1825: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1826: }
1827: }
1.191 harris41 1828: }
1.800 albertel 1829: foreach my $server (keys(%servers)) {
1830: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1831: }
1.344 www 1832: }
1833:
1.1172.2.30 raeburn 1834: # ---------------------------------------- Delete unwanted IDs from ids.db file
1835:
1836: sub iddel {
1837: my ($udom,$idshashref,$uhome)=@_;
1838: my %result=();
1839: unless (ref($idshashref) eq 'HASH') {
1840: return %result;
1841: }
1842: my %servers=();
1843: while (my ($id,$uname) = each(%{$idshashref})) {
1844: my $uhom;
1845: if ($uhome) {
1846: $uhom = $uhome;
1847: } else {
1848: $uhom=&homeserver($uname,$udom);
1849: }
1850: if ($uhom ne 'no_host') {
1851: if ($servers{$uhom}) {
1852: $servers{$uhom}.='&'.&escape($id);
1853: } else {
1854: $servers{$uhom}=&escape($id);
1855: }
1856: }
1857: }
1858: foreach my $server (keys(%servers)) {
1859: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1860: }
1861: return %result;
1862: }
1863:
1.1023 raeburn 1864: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1865: sub dump_dom {
1.1165 droeschl 1866: my ($namespace, $udom, $regexp) = @_;
1867:
1868: $udom ||= $env{'user.domain'};
1869:
1870: return () unless $udom;
1871:
1872: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1873: }
1874:
1.1023 raeburn 1875: # ------------------------------------------ get items from domain db files
1.806 raeburn 1876:
1877: sub get_dom {
1.860 raeburn 1878: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57 raeburn 1879: return if ($udom eq 'public');
1.806 raeburn 1880: my $items='';
1881: foreach my $item (@$storearr) {
1882: $items.=&escape($item).'&';
1883: }
1884: $items=~s/\&$//;
1.860 raeburn 1885: if (!$udom) {
1886: $udom=$env{'user.domain'};
1.1172.2.57 raeburn 1887: return if ($udom eq 'public');
1.860 raeburn 1888: if (defined(&domain($udom,'primary'))) {
1889: $uhome=&domain($udom,'primary');
1890: } else {
1.874 albertel 1891: undef($uhome);
1.860 raeburn 1892: }
1893: } else {
1894: if (!$uhome) {
1895: if (defined(&domain($udom,'primary'))) {
1896: $uhome=&domain($udom,'primary');
1897: }
1898: }
1899: }
1900: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.139 raeburn 1901: my $rep;
1902: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
1903: # domain information is hosted on this machine
1904: $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1905: } else {
1906: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1907: }
1.866 raeburn 1908: my %returnhash;
1.875 albertel 1909: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1910: return %returnhash;
1911: }
1.806 raeburn 1912: my @pairs=split(/\&/,$rep);
1913: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1914: return @pairs;
1915: }
1916: my $i=0;
1917: foreach my $item (@$storearr) {
1918: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1919: $i++;
1920: }
1921: return %returnhash;
1922: } else {
1.880 banghart 1923: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1924: }
1925: }
1926:
1927: # -------------------------------------------- put items in domain db files
1928:
1929: sub put_dom {
1.860 raeburn 1930: my ($namespace,$storehash,$udom,$uhome)=@_;
1931: if (!$udom) {
1932: $udom=$env{'user.domain'};
1933: if (defined(&domain($udom,'primary'))) {
1934: $uhome=&domain($udom,'primary');
1935: } else {
1.874 albertel 1936: undef($uhome);
1.860 raeburn 1937: }
1938: } else {
1939: if (!$uhome) {
1940: if (defined(&domain($udom,'primary'))) {
1941: $uhome=&domain($udom,'primary');
1942: }
1943: }
1944: }
1945: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1946: my $items='';
1947: foreach my $item (keys(%$storehash)) {
1948: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1949: }
1950: $items=~s/\&$//;
1951: return &reply("putdom:$udom:$namespace:$items",$uhome);
1952: } else {
1.860 raeburn 1953: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1954: }
1955: }
1956:
1.1023 raeburn 1957: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1958: sub newput_dom {
1.1023 raeburn 1959: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1960: my $result;
1961: if (!$udom) {
1962: $udom=$env{'user.domain'};
1963: }
1.1023 raeburn 1964: if ($udom) {
1965: my $uname = &get_domainconfiguser($udom);
1966: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1967: }
1968: return $result;
1969: }
1970:
1.1023 raeburn 1971: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1972: sub del_dom {
1.1023 raeburn 1973: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1974: if (ref($storearr) eq 'ARRAY') {
1975: if (!$udom) {
1976: $udom=$env{'user.domain'};
1977: }
1.1023 raeburn 1978: if ($udom) {
1979: my $uname = &get_domainconfiguser($udom);
1980: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1981: }
1982: }
1983: }
1984:
1.1023 raeburn 1985: # ----------------------------------construct domainconfig user for a domain
1986: sub get_domainconfiguser {
1987: my ($udom) = @_;
1988: return $udom.'-domainconfig';
1989: }
1990:
1.837 raeburn 1991: sub retrieve_inst_usertypes {
1992: my ($udom) = @_;
1993: my (%returnhash,@order);
1.989 raeburn 1994: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1995: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1996: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44 raeburn 1997: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1998: } else {
1999: if (defined(&domain($udom,'primary'))) {
2000: my $uhome=&domain($udom,'primary');
2001: my $rep=&reply("inst_usertypes:$udom",$uhome);
2002: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44 raeburn 2003: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 2004: return (\%returnhash,\@order);
2005: }
2006: my ($hashitems,$orderitems) = split(/:/,$rep);
2007: my @pairs=split(/\&/,$hashitems);
2008: foreach my $item (@pairs) {
2009: my ($key,$value)=split(/=/,$item,2);
2010: $key = &unescape($key);
2011: next if ($key =~ /^error: 2 /);
2012: $returnhash{$key}=&thaw_unescape($value);
2013: }
2014: my @esc_order = split(/\&/,$orderitems);
2015: foreach my $item (@esc_order) {
2016: push(@order,&unescape($item));
2017: }
2018: } else {
1.1172.2.44 raeburn 2019: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 2020: }
1.1172.2.44 raeburn 2021: return (\%returnhash,\@order);
1.837 raeburn 2022: }
2023: }
2024:
1.868 raeburn 2025: sub is_domainimage {
2026: my ($url) = @_;
1.1172.2.74 raeburn 2027: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 2028: if (&domain($1) ne '') {
2029: return '1';
2030: }
2031: }
2032: return;
2033: }
2034:
1.899 raeburn 2035: sub inst_directory_query {
2036: my ($srch) = @_;
2037: my $udom = $srch->{'srchdomain'};
2038: my %results;
2039: my $homeserver = &domain($udom,'primary');
1.909 raeburn 2040: my $outcome;
1.899 raeburn 2041: if ($homeserver ne '') {
1.1172.2.116 raeburn 2042: unless ($homeserver eq $perlvar{'lonHostID'}) {
2043: if ($srch->{'srchby'} eq 'email') {
1.1172.2.117 raeburn 2044: my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116 raeburn 2045: my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
2046: if (($major eq '' && $minor eq '') || ($major < 2) ||
2047: (($major == 2) && ($minor < 11)) ||
2048: (($major == 2) && ($minor == 11) && ($subver < 3))) {
2049: return;
2050: }
2051: }
2052: }
1.904 albertel 2053: my $queryid=&reply("querysend:instdirsearch:".
2054: &escape($srch->{'srchby'}).':'.
2055: &escape($srch->{'srchterm'}).':'.
2056: &escape($srch->{'srchtype'}),$homeserver);
2057: my $host=&hostname($homeserver);
2058: if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96 raeburn 2059: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 2060: return;
2061: }
2062: my $response = &get_query_reply($queryid);
2063: my $maxtries = 5;
2064: my $tries = 1;
2065: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2066: $response = &get_query_reply($queryid);
2067: $tries ++;
2068: }
2069:
2070: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2071: if ($response eq 'unavailable') {
2072: $outcome = $response;
2073: } else {
2074: $outcome = 'ok';
2075: my @matches = split(/\n/,$response);
2076: foreach my $match (@matches) {
2077: my ($key,$value) = split(/=/,$match);
2078: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2079: }
1.899 raeburn 2080: }
2081: }
2082: }
1.909 raeburn 2083: return ($outcome,%results);
1.899 raeburn 2084: }
2085:
2086: sub usersearch {
2087: my ($srch) = @_;
2088: my $dom = $srch->{'srchdomain'};
2089: my %results;
2090: my %libserv = &all_library();
2091: my $query = 'usersearch';
2092: foreach my $tryserver (keys(%libserv)) {
2093: if (&host_domain($tryserver) eq $dom) {
1.1172.2.116 raeburn 2094: unless ($tryserver eq $perlvar{'lonHostID'}) {
2095: if ($srch->{'srchby'} eq 'email') {
1.1172.2.117 raeburn 2096: my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119 raeburn 2097: my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116 raeburn 2098: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2099: (($major == 2) && ($minor < 11)) ||
2100: (($major == 2) && ($minor == 11) && ($subver < 3)));
2101: }
2102: }
1.899 raeburn 2103: my $host=&hostname($tryserver);
2104: my $queryid=
1.911 raeburn 2105: &reply("querysend:".&escape($query).':'.
2106: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2107: &escape($srch->{'srchtype'}).':'.
2108: &escape($srch->{'srchterm'}),$tryserver);
2109: if ($queryid !~/^\Q$host\E\_/) {
2110: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2111: next;
1.899 raeburn 2112: }
2113: my $reply = &get_query_reply($queryid);
2114: my $maxtries = 1;
2115: my $tries = 1;
2116: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2117: $reply = &get_query_reply($queryid);
2118: $tries ++;
2119: }
2120: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2121: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2122: } else {
1.911 raeburn 2123: my @matches;
2124: if ($reply =~ /\n/) {
2125: @matches = split(/\n/,$reply);
2126: } else {
2127: @matches = split(/\&/,$reply);
2128: }
1.899 raeburn 2129: foreach my $match (@matches) {
2130: my ($uname,$udom,%userhash);
1.911 raeburn 2131: foreach my $entry (split(/:/,$match)) {
2132: my ($key,$value) =
2133: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2134: $userhash{$key} = $value;
2135: if ($key eq 'username') {
2136: $uname = $value;
2137: } elsif ($key eq 'domain') {
2138: $udom = $value;
1.911 raeburn 2139: }
1.899 raeburn 2140: }
2141: $results{$uname.':'.$udom} = \%userhash;
2142: }
2143: }
2144: }
2145: }
2146: return %results;
2147: }
2148:
1.912 raeburn 2149: sub get_instuser {
2150: my ($udom,$uname,$id) = @_;
2151: my $homeserver = &domain($udom,'primary');
2152: my ($outcome,%results);
2153: if ($homeserver ne '') {
2154: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2155: &escape($id).':'.&escape($udom),$homeserver);
2156: my $host=&hostname($homeserver);
2157: if ($queryid !~/^\Q$host\E\_/) {
2158: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2159: return;
2160: }
2161: my $response = &get_query_reply($queryid);
2162: my $maxtries = 5;
2163: my $tries = 1;
2164: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2165: $response = &get_query_reply($queryid);
2166: $tries ++;
2167: }
2168: if (!&error($response) && $response ne 'refused') {
2169: if ($response eq 'unavailable') {
2170: $outcome = $response;
2171: } else {
2172: $outcome = 'ok';
2173: my @matches = split(/\n/,$response);
2174: foreach my $match (@matches) {
2175: my ($key,$value) = split(/=/,$match);
2176: $results{&unescape($key)} = &thaw_unescape($value);
2177: }
2178: }
2179: }
2180: }
2181: my %userinfo;
2182: if (ref($results{$uname}) eq 'HASH') {
2183: %userinfo = %{$results{$uname}};
2184: }
2185: return ($outcome,%userinfo);
2186: }
2187:
1.1172.2.69 raeburn 2188: sub get_multiple_instusers {
2189: my ($udom,$users,$caller) = @_;
2190: my ($outcome,$results);
2191: if (ref($users) eq 'HASH') {
2192: my $count = keys(%{$users});
2193: my $requested = &freeze_escape($users);
2194: my $homeserver = &domain($udom,'primary');
2195: if ($homeserver ne '') {
2196: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2197: my $host=&hostname($homeserver);
2198: if ($queryid !~/^\Q$host\E\_/) {
2199: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2200: ' for host: '.$homeserver.'in domain '.$udom);
2201: return ($outcome,$results);
2202: }
2203: my $response = &get_query_reply($queryid);
2204: my $maxtries = 5;
2205: if ($count > 100) {
2206: $maxtries = 1+int($count/20);
2207: }
2208: my $tries = 1;
2209: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2210: $response = &get_query_reply($queryid);
2211: $tries ++;
2212: }
2213: if ($response eq '') {
2214: $results = {};
2215: foreach my $key (keys(%{$users})) {
2216: my ($uname,$id);
2217: if ($caller eq 'id') {
2218: $id = $key;
2219: } else {
2220: $uname = $key;
2221: }
2222: my ($resp,%info) = &get_instuser($udom,$uname,$id);
2223: $outcome = $resp;
2224: if ($resp eq 'ok') {
2225: %{$results} = (%{$results}, %info);
2226: } else {
2227: last;
2228: }
2229: }
2230: } elsif(!&error($response) && ($response ne 'refused')) {
2231: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2232: $outcome = $response;
2233: } else {
2234: ($outcome,my $userdata) = split(/=/,$response,2);
2235: if ($outcome eq 'ok') {
2236: $results = &thaw_unescape($userdata);
2237: }
2238: }
2239: }
2240: }
2241: }
2242: return ($outcome,$results);
2243: }
2244:
1.912 raeburn 2245: sub inst_rulecheck {
1.923 raeburn 2246: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2247: my %returnhash;
2248: if ($udom ne '') {
2249: if (ref($rules) eq 'ARRAY') {
2250: @{$rules} = map {&escape($_);} (@{$rules});
2251: my $rulestr = join(':',@{$rules});
2252: my $homeserver=&domain($udom,'primary');
2253: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2254: my $response;
2255: if ($item eq 'username') {
2256: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2257: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2258: $homeserver));
1.923 raeburn 2259: } elsif ($item eq 'id') {
2260: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2261: ':'.&escape($id).':'.$rulestr,
2262: $homeserver));
1.945 raeburn 2263: } elsif ($item eq 'selfcreate') {
2264: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2265: &escape($udom).':'.&escape($uname).
2266: ':'.$rulestr,$homeserver));
1.923 raeburn 2267: }
1.912 raeburn 2268: if ($response ne 'refused') {
2269: my @pairs=split(/\&/,$response);
2270: foreach my $item (@pairs) {
2271: my ($key,$value)=split(/=/,$item,2);
2272: $key = &unescape($key);
2273: next if ($key =~ /^error: 2 /);
2274: $returnhash{$key}=&thaw_unescape($value);
2275: }
2276: }
2277: }
2278: }
2279: }
2280: return %returnhash;
2281: }
2282:
2283: sub inst_userrules {
1.923 raeburn 2284: my ($udom,$check) = @_;
1.912 raeburn 2285: my (%ruleshash,@ruleorder);
2286: if ($udom ne '') {
2287: my $homeserver=&domain($udom,'primary');
2288: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2289: my $response;
2290: if ($check eq 'id') {
2291: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2292: $homeserver);
1.943 raeburn 2293: } elsif ($check eq 'email') {
2294: $response=&reply('instemailrules:'.&escape($udom),
2295: $homeserver);
1.923 raeburn 2296: } else {
2297: $response=&reply('instuserrules:'.&escape($udom),
2298: $homeserver);
2299: }
1.912 raeburn 2300: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2301: ($response ne 'unknown_cmd') &&
1.912 raeburn 2302: ($response ne 'no_such_host')) {
2303: my ($hashitems,$orderitems) = split(/:/,$response);
2304: my @pairs=split(/\&/,$hashitems);
2305: foreach my $item (@pairs) {
2306: my ($key,$value)=split(/=/,$item,2);
2307: $key = &unescape($key);
2308: next if ($key =~ /^error: 2 /);
2309: $ruleshash{$key}=&thaw_unescape($value);
2310: }
2311: my @esc_order = split(/\&/,$orderitems);
2312: foreach my $item (@esc_order) {
2313: push(@ruleorder,&unescape($item));
2314: }
2315: }
2316: }
2317: }
2318: return (\%ruleshash,\@ruleorder);
2319: }
2320:
1.976 raeburn 2321: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2322:
2323: sub get_domain_defaults {
1.1172.2.35 raeburn 2324: my ($domain,$ignore_cache) = @_;
2325: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2326: my $cachetime = 60*60*24;
1.1172.2.35 raeburn 2327: unless ($ignore_cache) {
2328: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2329: if (defined($cached)) {
2330: if (ref($result) eq 'HASH') {
2331: return %{$result};
2332: }
1.943 raeburn 2333: }
2334: }
2335: my %domdefaults;
2336: my %domconfig =
1.989 raeburn 2337: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2338: 'requestcourses','inststatus',
1.1172.2.9 raeburn 2339: 'coursedefaults','usersessions',
1.1172.2.46 raeburn 2340: 'requestauthor','selfenrollment',
1.1172.2.89 raeburn 2341: 'coursecategories','autoenroll',
2342: 'helpsettings'],$domain);
1.1172.2.41 raeburn 2343: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2344: if (ref($domconfig{'defaults'}) eq 'HASH') {
2345: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2346: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2347: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2348: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2349: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2350: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91 raeburn 2351: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2352: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2353: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943 raeburn 2354: } else {
2355: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2356: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2357: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2358: }
1.976 raeburn 2359: if (ref($domconfig{'quotas'}) eq 'HASH') {
2360: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2361: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2362: } else {
2363: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29 raeburn 2364: }
1.1172.2.6 raeburn 2365: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2366: foreach my $item (@usertools) {
2367: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2368: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2369: }
2370: }
1.1172.2.29 raeburn 2371: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2372: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2373: }
1.976 raeburn 2374: }
1.985 raeburn 2375: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37 raeburn 2376: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2377: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2378: }
2379: }
1.1172.2.9 raeburn 2380: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2381: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2382: }
1.989 raeburn 2383: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44 raeburn 2384: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2385: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2386: }
2387: }
1.1047 raeburn 2388: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60 raeburn 2389: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2390: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2391: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2392: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2393: }
1.1172.2.41 raeburn 2394: foreach my $type (@coursetypes) {
2395: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2396: unless ($type eq 'community') {
2397: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2398: }
2399: }
2400: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2401: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2402: }
1.1172.2.60 raeburn 2403: if ($domdefaults{'postsubmit'} eq 'on') {
2404: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2405: $domdefaults{$type.'postsubtimeout'} =
2406: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2407: }
2408: }
1.1172.2.30 raeburn 2409: }
1.1172.2.67 raeburn 2410: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2411: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2412: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2413: if (@clonecodes) {
2414: $domdefaults{'canclone'} = join('+',@clonecodes);
2415: }
2416: }
2417: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2418: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2419: }
1.1172.2.103 raeburn 2420: if ($domconfig{'coursedefaults'}{'texengine'}) {
2421: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
2422: }
1.1047 raeburn 2423: }
1.1073 raeburn 2424: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2425: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2426: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2427: }
2428: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2429: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2430: }
1.1172.2.62 raeburn 2431: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2432: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2433: }
1.1172.2.137 raeburn 2434: if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1172.2.136 raeburn 2435: $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
2436: }
1.1073 raeburn 2437: }
1.1172.2.41 raeburn 2438: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2439: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2440: my @settings = ('types','registered','enroll_dates','access_dates','section',
2441: 'approval','limit');
2442: foreach my $type (@coursetypes) {
2443: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2444: my @mgrdc = ();
2445: foreach my $item (@settings) {
2446: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2447: push(@mgrdc,$item);
2448: }
2449: }
2450: if (@mgrdc) {
2451: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2452: }
2453: }
2454: }
2455: }
2456: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2457: foreach my $type (@coursetypes) {
2458: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2459: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2460: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2461: }
2462: }
2463: }
2464: }
2465: }
1.1172.2.46 raeburn 2466: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2467: $domdefaults{'catauth'} = 'std';
2468: $domdefaults{'catunauth'} = 'std';
2469: if ($domconfig{'coursecategories'}{'auth'}) {
2470: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2471: }
2472: if ($domconfig{'coursecategories'}{'unauth'}) {
2473: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2474: }
2475: }
1.1172.2.76 raeburn 2476: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2477: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2478: }
1.1172.2.89 raeburn 2479: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2480: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2481: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2482: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2483: }
2484: }
1.1172.2.23 raeburn 2485: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2486: return %domdefaults;
2487: }
2488:
1.1172.2.106 raeburn 2489: sub get_dom_cats {
2490: my ($dom) = @_;
2491: return unless (&domain($dom));
2492: my ($cats,$cached)=&is_cached_new('cats',$dom);
2493: unless (defined($cached)) {
2494: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2495: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2496: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2497: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2498: } else {
2499: $cats = {};
2500: }
2501: } else {
2502: $cats = {};
2503: }
2504: &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
2505: }
2506: return $cats;
2507: }
2508:
2509: sub get_dom_instcats {
2510: my ($dom) = @_;
2511: return unless (&domain($dom));
2512: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2513: unless (defined($cached)) {
2514: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2515: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2516: if ($totcodes > 0) {
2517: my $caller = 'global';
2518: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2519: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2520: $instcats = {
2521: codes => \%codes,
2522: codetitles => \@codetitles,
2523: cat_titles => \%cat_titles,
2524: cat_order => \%cat_order,
2525: };
2526: &do_cache_new('instcats',$dom,$instcats,3600);
2527: }
2528: }
2529: }
2530: return $instcats;
2531: }
2532:
2533: sub retrieve_instcodes {
2534: my ($coursecodes,$dom) = @_;
2535: my $totcodes;
2536: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2537: foreach my $course (keys(%courses)) {
2538: if (ref($courses{$course}) eq 'HASH') {
2539: if ($courses{$course}{'inst_code'} ne '') {
2540: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2541: $totcodes ++;
2542: }
2543: }
2544: }
2545: return $totcodes;
2546: }
2547:
1.1172.2.113 raeburn 2548: # --------------------------------------------- Get domain config for passwords
2549:
2550: sub get_passwdconf {
2551: my ($dom) = @_;
2552: my (%passwdconf,$gotconf,$lookup);
2553: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2554: if (defined($cached)) {
2555: if (ref($result) eq 'HASH') {
2556: %passwdconf = %{$result};
2557: $gotconf = 1;
2558: }
2559: }
2560: unless ($gotconf) {
2561: my %domconfig = &get_dom('configuration',['passwords'],$dom);
2562: if (ref($domconfig{'passwords'}) eq 'HASH') {
2563: %passwdconf = %{$domconfig{'passwords'}};
2564: }
2565: my $cachetime = 24*60*60;
2566: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
2567: }
2568: return %passwdconf;
2569: }
2570:
1.344 www 2571: # --------------------------------------------------- Assign a key to a student
2572:
2573: sub assign_access_key {
1.364 www 2574: #
2575: # a valid key looks like uname:udom#comments
2576: # comments are being appended
2577: #
1.498 www 2578: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2579: $kdom=
1.620 albertel 2580: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2581: $knum=
1.620 albertel 2582: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2583: $cdom=
1.620 albertel 2584: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2585: $cnum=
1.620 albertel 2586: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2587: $udom=$env{'user.name'} unless (defined($udom));
2588: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2589: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2590: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2591: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2592: # assigned to this person
2593: # - this should not happen,
1.345 www 2594: # unless something went wrong
2595: # the first time around
2596: # ready to assign
1.364 www 2597: $logentry=$1.'; '.$logentry;
1.496 www 2598: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2599: $kdom,$knum) eq 'ok') {
1.345 www 2600: # key now belongs to user
1.346 www 2601: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2602: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2603: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2604: return 'ok';
2605: } else {
2606: return
2607: 'error: Count not permanently assign key, will need to be re-entered later.';
2608: }
2609: } else {
2610: return 'error: Could not assign key, try again later.';
2611: }
1.364 www 2612: } elsif (!$existing{$ckey}) {
1.345 www 2613: # the key does not exist
2614: return 'error: The key does not exist';
2615: } else {
2616: # the key is somebody else's
2617: return 'error: The key is already in use';
2618: }
1.344 www 2619: }
2620:
1.364 www 2621: # ------------------------------------------ put an additional comment on a key
2622:
2623: sub comment_access_key {
2624: #
2625: # a valid key looks like uname:udom#comments
2626: # comments are being appended
2627: #
2628: my ($ckey,$cdom,$cnum,$logentry)=@_;
2629: $cdom=
1.620 albertel 2630: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2631: $cnum=
1.620 albertel 2632: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2633: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2634: if ($existing{$ckey}) {
2635: $existing{$ckey}.='; '.$logentry;
2636: # ready to assign
1.367 www 2637: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2638: $cdom,$cnum) eq 'ok') {
2639: return 'ok';
2640: } else {
2641: return 'error: Count not store comment.';
2642: }
2643: } else {
2644: # the key does not exist
2645: return 'error: The key does not exist';
2646: }
2647: }
2648:
1.344 www 2649: # ------------------------------------------------------ Generate a set of keys
2650:
2651: sub generate_access_keys {
1.364 www 2652: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2653: $cdom=
1.620 albertel 2654: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2655: $cnum=
1.620 albertel 2656: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2657: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2658: unless (($cdom) && ($cnum)) { return 0; }
2659: if ($number>10000) { return 0; }
2660: sleep(2); # make sure don't get same seed twice
2661: srand(time()^($$+($$<<15))); # from "Programming Perl"
2662: my $total=0;
2663: for (my $i=1;$i<=$number;$i++) {
2664: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2665: sprintf("%lx",int(100000*rand)).'-'.
2666: sprintf("%lx",int(100000*rand));
2667: $newkey=~s/1/g/g; # folks mix up 1 and l
2668: $newkey=~s/0/h/g; # and also 0 and O
2669: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2670: if ($existing{$newkey}) {
2671: $i--;
2672: } else {
1.364 www 2673: if (&put('accesskeys',
2674: { $newkey => '# generated '.localtime().
1.620 albertel 2675: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2676: '; '.$logentry },
2677: $cdom,$cnum) eq 'ok') {
1.344 www 2678: $total++;
2679: }
2680: }
2681: }
1.620 albertel 2682: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2683: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2684: return $total;
2685: }
2686:
2687: # ------------------------------------------------------- Validate an accesskey
2688:
2689: sub validate_access_key {
2690: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2691: $cdom=
1.620 albertel 2692: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2693: $cnum=
1.620 albertel 2694: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2695: $udom=$env{'user.domain'} unless (defined($udom));
2696: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2697: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2698: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2699: }
2700:
2701: # ------------------------------------- Find the section of student in a course
1.652 albertel 2702: sub devalidate_getsection_cache {
2703: my ($udom,$unam,$courseid)=@_;
2704: my $hashid="$udom:$unam:$courseid";
2705: &devalidate_cache_new('getsection',$hashid);
2706: }
1.298 matthew 2707:
1.815 albertel 2708: sub courseid_to_courseurl {
2709: my ($courseid) = @_;
2710: #already url style courseid
2711: return $courseid if ($courseid =~ m{^/});
2712:
2713: if (exists($env{'course.'.$courseid.'.num'})) {
2714: my $cnum = $env{'course.'.$courseid.'.num'};
2715: my $cdom = $env{'course.'.$courseid.'.domain'};
2716: return "/$cdom/$cnum";
2717: }
2718:
2719: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2720: if (exists($courseinfo{'num'})) {
2721: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2722: }
2723:
2724: return undef;
2725: }
2726:
1.298 matthew 2727: sub getsection {
2728: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2729: my $cachetime=1800;
1.551 albertel 2730:
2731: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2732: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2733: if (defined($cached)) { return $result; }
2734:
1.298 matthew 2735: my %Pending;
2736: my %Expired;
2737: #
2738: # Each role can either have not started yet (pending), be active,
2739: # or have expired.
2740: #
2741: # If there is an active role, we are done.
2742: #
2743: # If there is more than one role which has not started yet,
2744: # choose the one which will start sooner
2745: # If there is one role which has not started yet, return it.
2746: #
2747: # If there is more than one expired role, choose the one which ended last.
2748: # If there is a role which has expired, return it.
2749: #
1.815 albertel 2750: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2751: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2752: foreach my $key (keys(%roleshash)) {
1.479 albertel 2753: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2754: my $section=$1;
2755: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2756: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2757: my $now=time;
1.548 albertel 2758: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2759: $Expired{$end}=$section;
2760: next;
2761: }
1.548 albertel 2762: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2763: $Pending{$start}=$section;
2764: next;
2765: }
1.599 albertel 2766: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2767: }
2768: #
2769: # Presumedly there will be few matching roles from the above
2770: # loop and the sorting time will be negligible.
2771: if (scalar(keys(%Pending))) {
2772: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2773: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2774: }
2775: if (scalar(keys(%Expired))) {
2776: my @sorted = sort {$a <=> $b} keys(%Expired);
2777: my $time = pop(@sorted);
1.599 albertel 2778: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2779: }
1.599 albertel 2780: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2781: }
1.70 www 2782:
1.599 albertel 2783: sub save_cache {
2784: &purge_remembered();
1.722 albertel 2785: #&Apache::loncommon::validate_page();
1.620 albertel 2786: undef(%env);
1.780 albertel 2787: undef($env_loaded);
1.599 albertel 2788: }
1.452 albertel 2789:
1.599 albertel 2790: my $to_remember=-1;
2791: my %remembered;
2792: my %accessed;
2793: my $kicks=0;
2794: my $hits=0;
1.849 albertel 2795: sub make_key {
2796: my ($name,$id) = @_;
1.872 albertel 2797: if (length($id) > 65
2798: && length(&escape($id)) > 200) {
2799: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2800: }
1.849 albertel 2801: return &escape($name.':'.$id);
2802: }
2803:
1.599 albertel 2804: sub devalidate_cache_new {
2805: my ($name,$id,$debug) = @_;
2806: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81 raeburn 2807: my $remembered_id=$name.':'.$id;
1.849 albertel 2808: $id=&make_key($name,$id);
1.599 albertel 2809: $memcache->delete($id);
1.1172.2.81 raeburn 2810: delete($remembered{$remembered_id});
2811: delete($accessed{$remembered_id});
1.599 albertel 2812: }
2813:
2814: sub is_cached_new {
2815: my ($name,$id,$debug) = @_;
1.1172.2.81 raeburn 2816: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for
2817: # keys in %remembered hash, which persists for
2818: # duration of request (no restriction on key length).
2819: if (exists($remembered{$remembered_id})) {
2820: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2821: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2822: $hits++;
1.1172.2.81 raeburn 2823: return ($remembered{$remembered_id},1);
1.599 albertel 2824: }
1.1172.2.81 raeburn 2825: $id=&make_key($name,$id);
1.599 albertel 2826: my $value = $memcache->get($id);
2827: if (!(defined($value))) {
2828: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2829: return (undef,undef);
1.416 albertel 2830: }
1.599 albertel 2831: if ($value eq '__undef__') {
2832: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2833: $value=undef;
2834: }
1.1172.2.81 raeburn 2835: &make_room($remembered_id,$value,$debug);
1.599 albertel 2836: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2837: return ($value,1);
2838: }
2839:
2840: sub do_cache_new {
2841: my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81 raeburn 2842: my $remembered_id=$name.':'.$id;
1.849 albertel 2843: $id=&make_key($name,$id);
1.599 albertel 2844: my $setvalue=$value;
2845: if (!defined($setvalue)) {
2846: $setvalue='__undef__';
2847: }
1.623 albertel 2848: if (!defined($time) ) {
2849: $time=600;
2850: }
1.599 albertel 2851: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2852: my $result = $memcache->set($id,$setvalue,$time);
2853: if (! $result) {
1.872 albertel 2854: &logthis("caching of id -> $id failed");
1.910 albertel 2855: $memcache->disconnect_all();
1.872 albertel 2856: }
1.600 albertel 2857: # need to make a copy of $value
1.1172.2.81 raeburn 2858: &make_room($remembered_id,$value,$debug);
1.599 albertel 2859: return $value;
2860: }
2861:
2862: sub make_room {
1.1172.2.81 raeburn 2863: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2864:
1.1172.2.81 raeburn 2865: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2866: : $value;
1.599 albertel 2867: if ($to_remember<0) { return; }
1.1172.2.81 raeburn 2868: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2869: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2870: my $to_kick;
2871: my $max_time=0;
2872: foreach my $other (keys(%accessed)) {
2873: if (&tv_interval($accessed{$other}) > $max_time) {
2874: $to_kick=$other;
2875: $max_time=&tv_interval($accessed{$other});
2876: }
2877: }
2878: delete($remembered{$to_kick});
2879: delete($accessed{$to_kick});
2880: $kicks++;
2881: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2882: return;
2883: }
2884:
1.599 albertel 2885: sub purge_remembered {
1.604 albertel 2886: #&logthis("Tossing ".scalar(keys(%remembered)));
2887: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2888: undef(%remembered);
2889: undef(%accessed);
1.428 albertel 2890: }
1.70 www 2891: # ------------------------------------- Read an entry from a user's environment
2892:
2893: sub userenvironment {
2894: my ($udom,$unam,@what)=@_;
1.976 raeburn 2895: my $items;
2896: foreach my $item (@what) {
2897: $items.=&escape($item).'&';
2898: }
2899: $items=~s/\&$//;
1.70 www 2900: my %returnhash=();
1.1009 raeburn 2901: my $uhome = &homeserver($unam,$udom);
2902: unless ($uhome eq 'no_host') {
2903: my @answer=split(/\&/,
2904: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2905: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2906: return %returnhash;
2907: }
1.1009 raeburn 2908: my $i;
2909: for ($i=0;$i<=$#what;$i++) {
2910: $returnhash{$what[$i]}=&unescape($answer[$i]);
2911: }
1.70 www 2912: }
2913: return %returnhash;
1.1 albertel 2914: }
2915:
1.617 albertel 2916: # ---------------------------------------------------------- Get a studentphoto
2917: sub studentphoto {
2918: my ($udom,$unam,$ext) = @_;
2919: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2920: if (defined($env{'request.course.id'})) {
1.708 raeburn 2921: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2922: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2923: return(&retrievestudentphoto($udom,$unam,$ext));
2924: } else {
2925: my ($result,$perm_reqd)=
1.707 albertel 2926: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2927: if ($result eq 'ok') {
2928: if (!($perm_reqd eq 'yes')) {
2929: return(&retrievestudentphoto($udom,$unam,$ext));
2930: }
2931: }
2932: }
2933: }
2934: } else {
2935: my ($result,$perm_reqd) =
1.707 albertel 2936: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2937: if ($result eq 'ok') {
2938: if (!($perm_reqd eq 'yes')) {
2939: return(&retrievestudentphoto($udom,$unam,$ext));
2940: }
2941: }
2942: }
2943: return '/adm/lonKaputt/lonlogo_broken.gif';
2944: }
2945:
2946: sub retrievestudentphoto {
2947: my ($udom,$unam,$ext,$type) = @_;
2948: my $home=&Apache::lonnet::homeserver($unam,$udom);
2949: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2950: if ($ret eq 'ok') {
2951: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2952: if ($type eq 'thumbnail') {
2953: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2954: }
2955: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2956: return $tokenurl;
2957: } else {
2958: if ($type eq 'thumbnail') {
2959: return '/adm/lonKaputt/genericstudent_tn.gif';
2960: } else {
2961: return '/adm/lonKaputt/lonlogo_broken.gif';
2962: }
1.617 albertel 2963: }
2964: }
2965:
1.263 www 2966: # -------------------------------------------------------------------- New chat
2967:
2968: sub chatsend {
1.724 raeburn 2969: my ($newentry,$anon,$group)=@_;
1.620 albertel 2970: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2971: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2972: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2973: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2974: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2975: &escape($newentry)).':'.$group,$chome);
1.292 www 2976: }
2977:
2978: # ------------------------------------------ Find current version of a resource
2979:
2980: sub getversion {
2981: my $fname=&clutter(shift);
1.1172.2.10 raeburn 2982: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2983: return ¤tversion(&filelocation('',$fname));
2984: }
2985:
2986: sub currentversion {
2987: my $fname=shift;
2988: my $author=$fname;
2989: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2990: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2991: my $home=&homeserver($uname,$udom);
1.292 www 2992: if ($home eq 'no_host') {
2993: return -1;
2994: }
1.1112 www 2995: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2996: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2997: return -1;
2998: }
1.1112 www 2999: return $answer;
1.263 www 3000: }
3001:
1.1111 www 3002: #
3003: # Return special version number of resource if set by override, empty otherwise
3004: #
3005: sub usedversion {
3006: my $fname=shift;
3007: unless ($fname) { $fname=$env{'request.uri'}; }
3008: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3009: if ($urlversion) { return $urlversion; }
3010: return '';
3011: }
3012:
1.1 albertel 3013: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 3014:
1.1 albertel 3015: sub subscribe {
3016: my $fname=shift;
1.761 raeburn 3017: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 3018: $fname=~s/[\n\r]//g;
1.1 albertel 3019: my $author=$fname;
3020: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3021: my ($udom,$uname)=split(/\//,$author);
3022: my $home=homeserver($uname,$udom);
1.335 albertel 3023: if ($home eq 'no_host') {
3024: return 'not_found';
1.1 albertel 3025: }
3026: my $answer=reply("sub:$fname",$home);
1.64 www 3027: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3028: $answer.=' by '.$home;
3029: }
1.1 albertel 3030: return $answer;
3031: }
3032:
1.8 www 3033: # -------------------------------------------------------------- Replicate file
3034:
3035: sub repcopy {
3036: my $filename=shift;
1.23 www 3037: $filename=~s/\/+/\//g;
1.1142 raeburn 3038: my $londocroot = $perlvar{'lonDocRoot'};
3039: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3040: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3041: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3042: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3043: return &repcopy_userfile($filename);
3044: }
1.532 albertel 3045: $filename=~s/[\n\r]//g;
1.8 www 3046: my $transname="$filename.in.transfer";
1.828 www 3047: # FIXME: this should flock
1.607 raeburn 3048: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3049: my $remoteurl=subscribe($filename);
1.64 www 3050: if ($remoteurl =~ /^con_lost by/) {
3051: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3052: return 'unavailable';
1.8 www 3053: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3054: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3055: return 'not_found';
1.64 www 3056: } elsif ($remoteurl =~ /^rejected by/) {
3057: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3058: return 'forbidden';
1.20 www 3059: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3060: return 'ok';
1.8 www 3061: } else {
1.290 www 3062: my $author=$filename;
3063: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3064: my ($udom,$uname)=split(/\//,$author);
3065: my $home=homeserver($uname,$udom);
3066: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3067: my @parts=split(/\//,$filename);
3068: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3069: if ($path ne "$londocroot/res") {
1.8 www 3070: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3071: return 'bad_request';
1.8 www 3072: }
3073: my $count;
3074: for ($count=5;$count<$#parts;$count++) {
3075: $path.="/$parts[$count]";
3076: if ((-e $path)!=1) {
3077: mkdir($path,0777);
3078: }
3079: }
3080: my $ua=new LWP::UserAgent;
3081: my $request=new HTTP::Request('GET',"$remoteurl");
3082: my $response=$ua->request($request,$transname);
3083: if ($response->is_error()) {
3084: unlink($transname);
3085: my $message=$response->status_line;
1.672 albertel 3086: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3087: ." LWP get: $message: $filename</font>");
1.607 raeburn 3088: return 'unavailable';
1.8 www 3089: } else {
1.16 www 3090: if ($remoteurl!~/\.meta$/) {
3091: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
3092: my $mresponse=$ua->request($mrequest,$filename.'.meta');
3093: if ($mresponse->is_error()) {
3094: unlink($filename.'.meta');
3095: &logthis(
1.672 albertel 3096: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3097: }
3098: }
1.8 www 3099: rename($transname,$filename);
1.607 raeburn 3100: return 'ok';
1.8 www 3101: }
1.290 www 3102: }
1.8 www 3103: }
1.330 www 3104: }
3105:
1.1172.2.124 raeburn 3106: # ------------------------------------------------- Unsubscribe from a resource
3107:
3108: sub unsubscribe {
3109: my ($fname) = @_;
3110: my $answer;
3111: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3112: $fname=~s/[\n\r]//g;
3113: my $author=$fname;
3114: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3115: my ($udom,$uname)=split(/\//,$author);
3116: my $home=homeserver($uname,$udom);
3117: if ($home eq 'no_host') {
3118: $answer = 'no_host';
3119: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3120: $answer = 'home';
3121: } else {
1.1172.2.125 raeburn 3122: $answer = reply("unsub:$fname",$home);
1.1172.2.124 raeburn 3123: }
3124: return $answer;
3125: }
3126:
1.330 www 3127: # ------------------------------------------------ Get server side include body
3128: sub ssi_body {
1.381 albertel 3129: my ($filelink,%form)=@_;
1.606 matthew 3130: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3131: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3132: }
1.953 www 3133: my $output='';
3134: my $response;
1.980 raeburn 3135: if ($filelink=~/^https?\:/) {
1.954 raeburn 3136: ($output,$response)=&externalssi($filelink);
1.953 www 3137: } else {
1.1004 droeschl 3138: $filelink .= $filelink=~/\?/ ? '&' : '?';
3139: $filelink .= 'inhibitmenu=yes';
1.953 www 3140: ($output,$response)=&ssi($filelink,%form);
3141: }
1.778 albertel 3142: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3143: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3144: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3145: if (wantarray) {
3146: return ($output, $response);
3147: } else {
3148: return $output;
3149: }
1.8 www 3150: }
3151:
1.15 www 3152: # --------------------------------------------------------- Server Side Include
3153:
1.782 albertel 3154: sub absolute_url {
3155: my ($host_name) = @_;
3156: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3157: if ($host_name eq '') {
3158: $host_name = $ENV{'SERVER_NAME'};
3159: }
3160: return $protocol.$host_name;
3161: }
3162:
1.942 foxr 3163: #
3164: # Server side include.
3165: # Parameters:
3166: # fn Possibly encrypted resource name/id.
3167: # form Hash that describes how the rendering should be done
3168: # and other things.
1.944 foxr 3169: # Returns:
1.950 raeburn 3170: # Scalar context: The content of the response.
3171: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3172: #
1.15 www 3173: sub ssi {
3174:
1.944 foxr 3175: my ($fn,%form)=@_;
1.1172.2.100 raeburn 3176: my ($request,$response);
1.711 albertel 3177:
3178: $form{'no_update_last_known'}=1;
1.895 albertel 3179: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3180: if (%form) {
1.782 albertel 3181: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58 raeburn 3182: $request->content(join('&',map {
3183: my $name = escape($_);
3184: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3185: ? join("&$name=", map {escape($_) } @{$form{$_}})
3186: : &escape($form{$_}) );
3187: } keys(%form)));
1.23 www 3188: } else {
1.782 albertel 3189: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 3190: }
3191:
1.15 www 3192: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100 raeburn 3193:
1.1172.2.101 raeburn 3194: if (($env{'request.course.id'}) &&
3195: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3196: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3197: ($form{'grade_symb'} ne '') &&
3198: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3199: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100 raeburn 3200: if (LWP::UserAgent->VERSION >= 5.834) {
3201: my $ua=new LWP::UserAgent;
3202: $ua->local_address('127.0.0.1');
3203: $response = $ua->request($request);
3204: } else {
3205: {
3206: require LWP::Protocol::http;
3207: local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
3208: my $ua=new LWP::UserAgent;
3209: $response = $ua->request($request);
3210: @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
3211: }
3212: }
3213: } else {
3214: my $ua=new LWP::UserAgent;
3215: $response = $ua->request($request);
3216: }
1.944 foxr 3217: if (wantarray) {
1.1172.2.3 raeburn 3218: return ($response->content, $response);
1.944 foxr 3219: } else {
1.1172.2.3 raeburn 3220: return $response->content;
1.942 foxr 3221: }
1.324 www 3222: }
3223:
3224: sub externalssi {
3225: my ($url)=@_;
3226: my $ua=new LWP::UserAgent;
3227: my $request=new HTTP::Request('GET',$url);
3228: my $response=$ua->request($request);
1.954 raeburn 3229: if (wantarray) {
3230: return ($response->content, $response);
3231: } else {
3232: return $response->content;
3233: }
1.15 www 3234: }
1.254 www 3235:
1.1172.2.98 raeburn 3236: # If the local copy of a replicated resource is outdated, trigger a
3237: # connection from the homeserver to flush the delayed queue. If no update
3238: # happens, remove local copies of outdated resource (and corresponding
3239: # metadata file).
3240:
3241: sub remove_stale_resfile {
3242: my ($url) = @_;
3243: my $removed;
3244: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3245: my $audom = $1;
3246: my $auname = $2;
3247: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
3248: my $homeserver = &homeserver($auname,$audom);
3249: unless (($homeserver eq 'no_host') ||
3250: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3251: my $fname = &filelocation('',$url);
3252: if (-e $fname) {
3253: my $hostname = &hostname($homeserver);
3254: if ($hostname) {
1.1172.2.120 raeburn 3255: my $protocol = $protocol{$homeserver};
3256: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98 raeburn 3257: my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120 raeburn 3258: my $ua=new LWP::UserAgent;
3259: $ua->timeout(5);
1.1172.2.98 raeburn 3260: my $request=new HTTP::Request('HEAD',$uri);
3261: my $response=$ua->request($request);
3262: if ($response->is_success()) {
3263: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3264: my $locmodtime = (stat($fname))[9];
3265: if ($locmodtime < $remmodtime) {
3266: my $stale;
3267: my $answer = &reply('pong',$homeserver);
3268: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3269: sleep(0.2);
3270: $locmodtime = (stat($fname))[9];
3271: if ($locmodtime < $remmodtime) {
3272: my $posstransfer = $fname.'.in.transfer';
3273: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3274: $removed = 1;
3275: } else {
3276: $stale = 1;
3277: }
3278: } else {
3279: $removed = 1;
3280: }
3281: } else {
3282: $stale = 1;
3283: }
3284: if ($stale) {
1.1172.2.124 raeburn 3285: if (unlink($fname)) {
3286: if ($uri!~/\.meta$/) {
3287: if (-e $fname.'.meta') {
3288: unlink($fname.'.meta');
3289: }
3290: }
3291: my $unsubresult = &unsubscribe($fname);
3292: unless ($unsubresult eq 'ok') {
3293: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3294: }
3295: $removed = 1;
1.1172.2.98 raeburn 3296: }
3297: }
3298: }
3299: }
3300: }
3301: }
3302: }
3303: }
3304: }
3305: return $removed;
3306: }
3307:
1.492 albertel 3308: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3309:
3310: sub allowuploaded {
3311: my ($srcurl,$url)=@_;
3312: $url=&clutter(&declutter($url));
3313: my $dir=$url;
3314: $dir=~s/\/[^\/]+$//;
3315: my %httpref=();
3316: my $httpurl=&hreflocation('',$url);
3317: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3318: &Apache::lonnet::appenv(\%httpref);
1.254 www 3319: }
1.477 raeburn 3320:
1.1172.2.13 raeburn 3321: #
3322: # Determine if the current user should be able to edit a particular resource,
3323: # when viewing in course context.
3324: # (a) When viewing resource used to determine if "Edit" item is included in
3325: # Functions.
3326: # (b) When displaying folder contents in course editor, used to determine if
3327: # "Edit" link will be displayed alongside resource.
3328: #
3329: # input: six args -- filename (decluttered), course number, course domain,
3330: # url, symb (if registered) and group (if this is a group
3331: # item -- e.g., bulletin board, group page etc.).
3332: # output: array of five scalars --
3333: # $cfile -- url for file editing if editable on current server
3334: # $home -- homeserver of resource (i.e., for author if published,
3335: # or course if uploaded.).
3336: # $switchserver -- 1 if server switch will be needed.
3337: # $forceedit -- 1 if icon/link should be to go to edit mode
3338: # $forceview -- 1 if icon/link should be to go to view mode
3339: #
3340:
3341: sub can_edit_resource {
3342: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3343: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3344: #
3345: # For aboutme pages user can only edit his/her own.
3346: #
3347: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
3348: my ($sdom,$sname) = ($1,$2);
3349: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3350: $home = $env{'user.home'};
3351: $cfile = $resurl;
3352: if ($env{'form.forceedit'}) {
3353: $forceview = 1;
3354: } else {
3355: $forceedit = 1;
3356: }
3357: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3358: } else {
3359: return;
3360: }
3361: }
3362:
3363: if ($env{'request.course.id'}) {
3364: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3365: if ($group ne '') {
3366: # if this is a group homepage or group bulletin board, check group privs
3367: my $allowed = 0;
3368: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3369: if ((&allowed('mdg',$env{'request.course.id'}.
3370: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3371: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3372: $allowed = 1;
3373: }
3374: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3375: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3376: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3377: $allowed = 1;
3378: }
3379: }
3380: if ($allowed) {
3381: $home=&homeserver($cnum,$cdom);
3382: if ($env{'form.forceedit'}) {
3383: $forceview = 1;
3384: } else {
3385: $forceedit = 1;
3386: }
3387: $cfile = $resurl;
3388: } else {
3389: return;
3390: }
3391: } else {
1.1172.2.15 raeburn 3392: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3393: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3394: return;
3395: }
3396: } elsif (!$crsedit) {
1.1172.2.13 raeburn 3397: #
3398: # No edit allowed where CC has switched to student role.
3399: #
3400: return;
3401: }
3402: }
3403: }
3404:
3405: if ($file ne '') {
3406: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3407: if (&is_course_upload($file,$cnum,$cdom)) {
3408: $uploaded = 1;
3409: $incourse = 1;
3410: if ($file =~/\.(htm|html|css|js|txt)$/) {
3411: $cfile = &hreflocation('',$file);
3412: if ($env{'form.forceedit'}) {
3413: $forceview = 1;
3414: } else {
3415: $forceedit = 1;
3416: }
3417: }
3418: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3419: $incourse = 1;
3420: if ($env{'form.forceedit'}) {
3421: $forceview = 1;
3422: } else {
3423: $forceedit = 1;
3424: }
3425: $cfile = $resurl;
3426: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3427: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3428: $incourse = 1;
3429: if ($env{'form.forceedit'}) {
3430: $forceview = 1;
3431: } else {
3432: $forceedit = 1;
3433: }
3434: $cfile = $resurl;
3435: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3436: $incourse = 1;
3437: $cfile = $resurl.'/smpedit';
3438: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3439: $incourse = 1;
3440: if ($env{'form.forceedit'}) {
3441: $forceview = 1;
3442: } else {
3443: $forceedit = 1;
3444: }
3445: $cfile = $resurl;
1.1172.2.122 raeburn 3446: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3447: my ($map,$id,$res) = &decode_symb($symb);
3448: if ($map =~ /\.page$/) {
3449: $incourse = 1;
3450: if ($env{'form.forceedit'}) {
3451: $forceview = 1;
3452: $cfile = $map;
3453: } else {
3454: $forceedit = 1;
3455: $cfile = '/adm/wrapper'.$resurl;
3456: }
3457: }
1.1172.2.15 raeburn 3458: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3459: $incourse = 1;
3460: if ($env{'form.forceedit'}) {
3461: $forceview = 1;
3462: } else {
3463: $forceedit = 1;
3464: }
3465: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3466: }
3467: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3468: my $template = '/res/lib/templates/simpleproblem.problem';
3469: if (&is_on_map($template)) {
3470: $incourse = 1;
3471: $forceview = 1;
3472: $cfile = $template;
3473: }
3474: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118 raeburn 3475: $incourse = 1;
3476: if ($env{'form.forceedit'}) {
3477: $forceview = 1;
3478: } else {
3479: $forceedit = 1;
3480: }
3481: $cfile = $resurl;
1.1172.2.13 raeburn 3482: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3483: $incourse = 1;
3484: $forceview = 1;
3485: if ($symb) {
3486: my ($map,$id,$res)=&decode_symb($symb);
3487: $env{'request.symb'} = $symb;
3488: $cfile = &clutter($res);
3489: } else {
3490: $cfile = $env{'form.suppurl'};
3491: $cfile =~ s{^http://}{};
3492: $cfile = '/adm/wrapper/ext/'.$cfile;
3493: }
1.1172.2.31 raeburn 3494: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3495: if ($env{'form.forceedit'}) {
3496: $forceview = 1;
3497: } else {
3498: $forceedit = 1;
3499: }
3500: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13 raeburn 3501: }
3502: }
3503: if ($uploaded || $incourse) {
3504: $home=&homeserver($cnum,$cdom);
1.1172.2.14 raeburn 3505: } elsif ($file !~ m{/$}) {
1.1172.2.13 raeburn 3506: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3507: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3508: # Check that the user has permission to edit this resource
3509: my $setpriv = 1;
3510: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3511: if (defined($cfudom)) {
3512: $home=&homeserver($cfuname,$cfudom);
3513: $cfile=$file;
3514: }
3515: }
3516: if (($cfile ne '') && (!$incourse || $uploaded) &&
3517: (($home ne '') && ($home ne 'no_host'))) {
3518: my @ids=¤t_machine_ids();
3519: unless (grep(/^\Q$home\E$/,@ids)) {
3520: $switchserver=1;
3521: }
3522: }
3523: }
3524: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3525: }
3526:
3527: sub is_course_upload {
3528: my ($file,$cnum,$cdom) = @_;
3529: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3530: $uploadpath =~ s{^\/}{};
3531: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3532: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3533: return 1;
3534: }
3535: return;
3536: }
3537:
3538: sub in_course {
3539: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3540: if ($hideprivileged) {
3541: my $skipuser;
1.1172.2.23 raeburn 3542: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3543: my @possdoms = ($cdom);
3544: if ($coursehash{'checkforpriv'}) {
3545: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3546: }
3547: if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13 raeburn 3548: $skipuser = 1;
3549: if ($coursehash{'nothideprivileged'}) {
3550: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3551: my $user;
3552: if ($item =~ /:/) {
3553: $user = $item;
3554: } else {
3555: $user = join(':',split(/[\@]/,$item));
3556: }
3557: if ($user eq $uname.':'.$udom) {
3558: undef($skipuser);
3559: last;
3560: }
3561: }
3562: }
3563: if ($skipuser) {
3564: return 0;
3565: }
3566: }
3567: }
3568: $type ||= 'any';
3569: if (!defined($cdom) || !defined($cnum)) {
3570: my $cid = $env{'request.course.id'};
3571: $cdom = $env{'course.'.$cid.'.domain'};
3572: $cnum = $env{'course.'.$cid.'.num'};
3573: }
3574: my $typesref;
3575: if (($type eq 'any') || ($type eq 'all')) {
3576: $typesref = ['active','previous','future'];
3577: } elsif ($type eq 'previous' || $type eq 'future') {
3578: $typesref = [$type];
3579: }
3580: my %roles = &get_my_roles($uname,$udom,'userroles',
3581: $typesref,undef,[$cdom]);
3582: my ($tmp) = keys(%roles);
3583: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3584: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3585: if (@course_roles > 0) {
3586: return 1;
3587: }
3588: return 0;
3589: }
3590:
1.478 albertel 3591: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3592: # input: action, courseID, current domain, intended
1.637 raeburn 3593: # path to file, source of file, instruction to parse file for objects,
3594: # ref to hash for embedded objects,
3595: # ref to hash for codebase of java objects.
1.1095 raeburn 3596: # reference to scalar to accommodate mime type determined
3597: # from File::MMagic if $parser = parse.
1.637 raeburn 3598: #
1.485 raeburn 3599: # output: url to file (if action was uploaddoc),
3600: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3601: #
1.478 albertel 3602: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3603: # course.
1.477 raeburn 3604: #
1.478 albertel 3605: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3606: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3607: # course's home server.
1.477 raeburn 3608: #
1.478 albertel 3609: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3610: # be copied from $source (current location) to
3611: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3612: # and will then be copied to
3613: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3614: # course's home server.
1.485 raeburn 3615: #
1.481 raeburn 3616: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3617: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3618: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3619: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3620: # in course's home server.
1.637 raeburn 3621: #
1.477 raeburn 3622:
3623: sub process_coursefile {
1.1095 raeburn 3624: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3625: $mimetype)=@_;
1.477 raeburn 3626: my $fetchresult;
1.638 albertel 3627: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3628: if ($action eq 'propagate') {
1.638 albertel 3629: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3630: $home);
1.481 raeburn 3631: } else {
1.477 raeburn 3632: my $fpath = '';
3633: my $fname = $file;
1.478 albertel 3634: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3635: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3636: my $filepath = &build_filepath($fpath);
1.481 raeburn 3637: if ($action eq 'copy') {
3638: if ($source eq '') {
3639: $fetchresult = 'no source file';
3640: return $fetchresult;
3641: } else {
3642: my $destination = $filepath.'/'.$fname;
3643: rename($source,$destination);
3644: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3645: $home);
1.481 raeburn 3646: }
3647: } elsif ($action eq 'uploaddoc') {
1.1172.2.96 raeburn 3648: open(my $fh,'>',$filepath.'/'.$fname);
1.620 albertel 3649: print $fh $env{'form.'.$source};
1.481 raeburn 3650: close($fh);
1.637 raeburn 3651: if ($parser eq 'parse') {
1.1024 raeburn 3652: my $mm = new File::MMagic;
1.1095 raeburn 3653: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3654: if ($type eq 'text/html') {
1.1024 raeburn 3655: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3656: unless ($parse_result eq 'ok') {
3657: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3658: }
1.637 raeburn 3659: }
1.1095 raeburn 3660: if (ref($mimetype)) {
3661: $$mimetype = $type;
3662: }
1.637 raeburn 3663: }
1.477 raeburn 3664: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3665: $home);
1.481 raeburn 3666: if ($fetchresult eq 'ok') {
3667: return '/uploaded/'.$fpath.'/'.$fname;
3668: } else {
3669: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3670: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3671: return '/adm/notfound.html';
3672: }
1.477 raeburn 3673: }
3674: }
1.485 raeburn 3675: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3676: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3677: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3678: }
3679: return $fetchresult;
3680: }
3681:
1.637 raeburn 3682: sub build_filepath {
3683: my ($fpath) = @_;
3684: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3685: unless ($fpath eq '') {
3686: my @parts=split('/',$fpath);
3687: foreach my $part (@parts) {
3688: $filepath.= '/'.$part;
3689: if ((-e $filepath)!=1) {
3690: mkdir($filepath,0777);
3691: }
3692: }
3693: }
3694: return $filepath;
3695: }
3696:
3697: sub store_edited_file {
1.638 albertel 3698: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3699: my $file = $primary_url;
3700: $file =~ s#^/uploaded/$docudom/$docuname/##;
3701: my $fpath = '';
3702: my $fname = $file;
3703: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3704: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3705: my $filepath = &build_filepath($fpath);
1.1172.2.96 raeburn 3706: open(my $fh,'>',$filepath.'/'.$fname);
1.637 raeburn 3707: print $fh $content;
3708: close($fh);
1.638 albertel 3709: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3710: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3711: $home);
1.637 raeburn 3712: if ($$fetchresult eq 'ok') {
3713: return '/uploaded/'.$fpath.'/'.$fname;
3714: } else {
1.638 albertel 3715: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3716: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3717: return '/adm/notfound.html';
3718: }
3719: }
3720:
1.531 albertel 3721: sub clean_filename {
1.831 albertel 3722: my ($fname,$args)=@_;
1.315 www 3723: # Replace Windows backslashes by forward slashes
1.257 www 3724: $fname=~s/\\/\//g;
1.831 albertel 3725: if (!$args->{'keep_path'}) {
3726: # Get rid of everything but the actual filename
3727: $fname=~s/^.*\/([^\/]+)$/$1/;
3728: }
1.315 www 3729: # Replace spaces by underscores
3730: $fname=~s/\s+/\_/g;
1.1172.2.110 raeburn 3731: # Transliterate non-ascii text to ascii
3732: my $lang = &Apache::lonlocal::current_language();
3733: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315 www 3734: # Replace all other weird characters by nothing
1.831 albertel 3735: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3736: # Replace all .\d. sequences with _\d. so they no longer look like version
3737: # numbers
3738: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140 raeburn 3739: # Replace three or more adjacent underscores with one for consistency
3740: # with loncfile::filename_check() so complete url can be extracted by
3741: # lonnet::decode_symb()
3742: $fname=~s/_{3,}/_/g;
1.531 albertel 3743: return $fname;
3744: }
1.1172.2.110 raeburn 3745:
1.1051 raeburn 3746: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3747: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3748: # image with the same aspect ratio as the original, but with dimensions which do
3749: # not exceed $resizewidth and $resizeheight.
3750:
1.984 neumanie 3751: sub resizeImage {
1.1051 raeburn 3752: my ($img_path,$resizewidth,$resizeheight) = @_;
3753: my $ima = Image::Magick->new;
3754: my $resized;
3755: if (-e $img_path) {
3756: $ima->Read($img_path);
3757: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3758: my $width = $ima->Get('width');
3759: my $height = $ima->Get('height');
3760: if ($width > $resizewidth) {
3761: my $factor = $width/$resizewidth;
3762: my $newheight = $height/$factor;
3763: $ima->Scale(width=>$resizewidth,height=>$newheight);
3764: $resized = 1;
3765: }
3766: }
3767: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3768: my $width = $ima->Get('width');
3769: my $height = $ima->Get('height');
3770: if ($height > $resizeheight) {
3771: my $factor = $height/$resizeheight;
3772: my $newwidth = $width/$factor;
3773: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3774: $resized = 1;
3775: }
3776: }
3777: if ($resized) {
3778: $ima->Write($img_path);
3779: }
3780: }
3781: return;
1.977 amueller 3782: }
3783:
1.608 albertel 3784: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3785: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3786: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3787: # $context - possible values: coursedoc, existingfile, overwrite,
1.1172.2.109 raeburn 3788: # canceloverwrite, scantron or ''.
1.1090 raeburn 3789: # if 'coursedoc': upload to the current course
3790: # if 'existingfile': write file to tmp/overwrites directory
3791: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3792: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3793: # $subdir - directory in userfile to store the file into
1.1172.2.109 raeburn 3794: # $parser - instruction to parse file for objects ($parser = parse) or
3795: # if context is 'scantron', $parser is hashref of csv column mapping
3796: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
3797: # Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858 raeburn 3798: # $allfiles - reference to hash for embedded objects
3799: # $codebase - reference to hash for codebase of java objects
3800: # $desuname - username for permanent storage of uploaded file
3801: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3802: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3803: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3804: # $resizewidth - width (pixels) to which to resize uploaded image
3805: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3806: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3807: # from File::MMagic.
1.858 raeburn 3808: #
1.686 albertel 3809: # output: url of file in userspace, or error: <message>
3810: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3811:
1.531 albertel 3812: sub userfileupload {
1.1090 raeburn 3813: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3814: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3815: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3816: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3817: $fname=&clean_filename($fname);
1.1090 raeburn 3818: # See if there is anything left
1.257 www 3819: unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110 raeburn 3820: # If filename now begins with a . prepend unix timestamp _ milliseconds
3821: if ($fname =~ /^\./) {
3822: my ($s,$usec) = &gettimeofday();
3823: while (length($usec) < 6) {
3824: $usec = '0'.$usec;
3825: }
3826: $fname = $s.'_'.substr($usec,0,3).$fname;
3827: }
1.1090 raeburn 3828: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3829: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3830: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3831: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3832: my $now = time;
1.1090 raeburn 3833: my $filepath;
1.1095 raeburn 3834: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3835: $filepath = 'tmp/helprequests/'.$now;
3836: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3837: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3838: '_'.$env{'user.domain'}.'/pending';
3839: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3840: my ($docuname,$docudom);
1.1172.2.96 raeburn 3841: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 3842: $docudom = $destudom;
3843: } else {
3844: $docudom = $env{'user.domain'};
3845: }
1.1172.2.96 raeburn 3846: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 3847: $docuname = $destuname;
3848: } else {
3849: $docuname = $env{'user.name'};
3850: }
3851: if (exists($env{'form.group'})) {
3852: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3853: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3854: }
3855: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3856: if ($context eq 'canceloverwrite') {
3857: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3858: if (-e $tempfile) {
3859: my @info = stat($tempfile);
3860: if ($info[9] eq $env{'form.timestamp'}) {
3861: unlink($tempfile);
3862: }
3863: }
3864: return;
1.523 raeburn 3865: }
3866: }
1.1090 raeburn 3867: # Create the directory if not present
1.741 raeburn 3868: my @parts=split(/\//,$filepath);
3869: my $fullpath = $perlvar{'lonDaemons'};
3870: for (my $i=0;$i<@parts;$i++) {
3871: $fullpath .= '/'.$parts[$i];
3872: if ((-e $fullpath)!=1) {
3873: mkdir($fullpath,0777);
3874: }
3875: }
1.1172.2.96 raeburn 3876: open(my $fh,'>',$fullpath.'/'.$fname);
1.741 raeburn 3877: print $fh $env{'form.'.$formname};
3878: close($fh);
1.1090 raeburn 3879: if ($context eq 'existingfile') {
3880: my @info = stat($fullpath.'/'.$fname);
3881: return ($fullpath.'/'.$fname,$info[9]);
3882: } else {
3883: return $fullpath.'/'.$fname;
3884: }
1.523 raeburn 3885: }
1.995 raeburn 3886: if ($subdir eq 'scantron') {
3887: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3888: } else {
1.995 raeburn 3889: $fname="$subdir/$fname";
3890: }
1.1090 raeburn 3891: if ($context eq 'coursedoc') {
1.638 albertel 3892: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3893: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3894: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3895: return &finishuserfileupload($docuname,$docudom,
3896: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3897: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3898: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3899: } else {
1.1172.2.21 raeburn 3900: if ($env{'form.folder'}) {
3901: $fname=$env{'form.folder'}.'/'.$fname;
3902: }
1.638 albertel 3903: return &process_coursefile('uploaddoc',$docuname,$docudom,
3904: $fname,$formname,$parser,
1.1095 raeburn 3905: $allfiles,$codebase,$mimetype);
1.481 raeburn 3906: }
1.719 banghart 3907: } elsif (defined($destuname)) {
3908: my $docuname=$destuname;
3909: my $docudom=$destudom;
1.860 raeburn 3910: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3911: $parser,$allfiles,$codebase,
1.1051 raeburn 3912: $thumbwidth,$thumbheight,
1.1095 raeburn 3913: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3914: } else {
1.638 albertel 3915: my $docuname=$env{'user.name'};
3916: my $docudom=$env{'user.domain'};
1.1172.2.23 raeburn 3917: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3918: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3919: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3920: }
1.860 raeburn 3921: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3922: $parser,$allfiles,$codebase,
1.1051 raeburn 3923: $thumbwidth,$thumbheight,
1.1095 raeburn 3924: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3925: }
1.271 www 3926: }
3927:
3928: sub finishuserfileupload {
1.860 raeburn 3929: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3930: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3931: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3932: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3933:
1.860 raeburn 3934: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3935: $file=$fname;
3936: if ($fname=~m|/|) {
3937: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3938: $path.=$fnamepath.'/';
3939: }
1.259 www 3940: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3941: my $count;
3942: for ($count=4;$count<=$#parts;$count++) {
3943: $filepath.="/$parts[$count]";
3944: if ((-e $filepath)!=1) {
3945: mkdir($filepath,0777);
3946: }
3947: }
1.984 neumanie 3948:
1.258 www 3949: # Save the file
3950: {
1.1172.2.96 raeburn 3951: if (!open(FH,'>',$filepath.'/'.$file)) {
1.701 albertel 3952: &logthis('Failed to create '.$filepath.'/'.$file);
3953: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3954: return '/adm/notfound.html';
3955: }
1.1090 raeburn 3956: if ($context eq 'overwrite') {
1.1117 foxr 3957: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3958: my $target = $filepath.'/'.$file;
3959: if (-e $source) {
3960: my @info = stat($source);
3961: if ($info[9] eq $env{'form.timestamp'}) {
3962: unless (&File::Copy::move($source,$target)) {
3963: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3964: return "Moving from $source failed";
3965: }
3966: } else {
3967: return "Temporary file: $source had unexpected date/time for last modification";
3968: }
3969: } else {
3970: return "Temporary file: $source missing";
3971: }
3972: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3973: &logthis('Failed to write to '.$filepath.'/'.$file);
3974: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3975: return '/adm/notfound.html';
3976: }
1.570 albertel 3977: close(FH);
1.1051 raeburn 3978: if ($resizewidth && $resizeheight) {
3979: my $mm = new File::MMagic;
3980: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3981: if ($mime_type =~ m{^image/}) {
3982: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3983: }
1.977 amueller 3984: }
1.258 www 3985: }
1.1152 raeburn 3986: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3987: if (ref($mimetype)) {
3988: if ($$mimetype eq '') {
3989: my $mm = new File::MMagic;
3990: my $type = $mm->checktype_filename($filepath.'/'.$file);
3991: $$mimetype = $type;
3992: }
3993: }
3994: }
1.1172.2.109 raeburn 3995: if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152 raeburn 3996: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3997: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3998: $allfiles,$codebase);
3999: unless ($parse_result eq 'ok') {
4000: &logthis('Failed to parse '.$filepath.$file.
4001: ' for embedded media: '.$parse_result);
4002: }
1.637 raeburn 4003: }
1.1172.2.109 raeburn 4004: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4005: my $format = $env{'form.scantron_format'};
4006: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637 raeburn 4007: }
1.860 raeburn 4008: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4009: my $input = $filepath.'/'.$file;
4010: my $output = $filepath.'/'.'tn-'.$file;
4011: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96 raeburn 4012: my @args = ('convert','-sample',$thumbsize,$input,$output);
4013: system({$args[0]} @args);
1.860 raeburn 4014: if (-e $filepath.'/'.'tn-'.$file) {
4015: $fetchthumb = 1;
4016: }
4017: }
1.858 raeburn 4018:
1.259 www 4019: # Notify homeserver to grep it
4020: #
1.984 neumanie 4021: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 4022: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 4023: if ($fetchresult eq 'ok') {
1.860 raeburn 4024: if ($fetchthumb) {
4025: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4026: if ($thumbresult ne 'ok') {
4027: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4028: $docuhome.': '.$thumbresult);
4029: }
4030: }
1.259 www 4031: #
1.258 www 4032: # Return the URL to it
1.494 albertel 4033: return '/uploaded/'.$path.$file;
1.263 www 4034: } else {
1.494 albertel 4035: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4036: ': '.$fetchresult);
1.263 www 4037: return '/adm/notfound.html';
1.858 raeburn 4038: }
1.493 albertel 4039: }
4040:
1.637 raeburn 4041: sub extract_embedded_items {
1.961 raeburn 4042: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 4043: my @state = ();
1.1164 raeburn 4044: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 4045: my %javafiles = (
4046: codebase => '',
4047: code => '',
4048: archive => ''
4049: );
4050: my %mediafiles = (
4051: src => '',
4052: movie => '',
4053: );
1.648 raeburn 4054: my $p;
4055: if ($content) {
4056: $p = HTML::LCParser->new($content);
4057: } else {
1.961 raeburn 4058: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 4059: }
1.641 albertel 4060: while (my $t=$p->get_token()) {
1.640 albertel 4061: if ($t->[0] eq 'S') {
4062: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 4063: push(@state, $tagname);
1.648 raeburn 4064: if (lc($tagname) eq 'allow') {
4065: &add_filetype($allfiles,$attr->{'src'},'src');
4066: }
1.640 albertel 4067: if (lc($tagname) eq 'img') {
4068: &add_filetype($allfiles,$attr->{'src'},'src');
4069: }
1.886 albertel 4070: if (lc($tagname) eq 'a') {
1.1172.2.24 raeburn 4071: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
4072: &add_filetype($allfiles,$attr->{'href'},'href');
4073: }
1.886 albertel 4074: }
1.645 raeburn 4075: if (lc($tagname) eq 'script') {
1.1164 raeburn 4076: my $src;
1.645 raeburn 4077: if ($attr->{'archive'} =~ /\.jar$/i) {
4078: &add_filetype($allfiles,$attr->{'archive'},'archive');
4079: } else {
1.1164 raeburn 4080: if ($attr->{'src'} ne '') {
4081: $src = $attr->{'src'};
4082: &add_filetype($allfiles,$src,'src');
4083: }
4084: }
4085: my $text = $p->get_trimmed_text();
4086: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4087: my @swfargs = split(/,/,$1);
4088: foreach my $item (@swfargs) {
4089: $item =~ s/["']//g;
4090: $item =~ s/^\s+//;
4091: $item =~ s/\s+$//;
4092: }
4093: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4094: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4095: push(@{$related{$swfargs[0]}},$swfargs[2]);
4096: } else {
4097: $related{$swfargs[0]} = [$swfargs[2]];
4098: }
4099: }
1.645 raeburn 4100: }
4101: }
4102: if (lc($tagname) eq 'link') {
4103: if (lc($attr->{'rel'}) eq 'stylesheet') {
4104: &add_filetype($allfiles,$attr->{'href'},'href');
4105: }
4106: }
1.640 albertel 4107: if (lc($tagname) eq 'object' ||
4108: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4109: foreach my $item (keys(%javafiles)) {
4110: $javafiles{$item} = '';
4111: }
1.1164 raeburn 4112: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4113: $lastids{lc($tagname)} = $attr->{'id'};
4114: }
1.640 albertel 4115: }
4116: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4117: my $name = lc($attr->{'name'});
4118: foreach my $item (keys(%javafiles)) {
4119: if ($name eq $item) {
4120: $javafiles{$item} = $attr->{'value'};
4121: last;
4122: }
4123: }
1.1164 raeburn 4124: my $pathfrom;
1.640 albertel 4125: foreach my $item (keys(%mediafiles)) {
4126: if ($name eq $item) {
1.1164 raeburn 4127: $pathfrom = $attr->{'value'};
4128: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4129: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4130: last;
4131: }
4132: }
1.1164 raeburn 4133: if ($name eq 'flashvars') {
4134: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4135: }
4136: if ($pathfrom ne '') {
4137: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4138: $pathfrom);
4139: }
1.640 albertel 4140: }
4141: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4142: foreach my $item (keys(%javafiles)) {
4143: if ($attr->{$item}) {
4144: $javafiles{$item} = $attr->{$item};
4145: last;
4146: }
4147: }
4148: foreach my $item (keys(%mediafiles)) {
4149: if ($attr->{$item}) {
4150: &add_filetype($allfiles,$attr->{$item},$item);
4151: last;
4152: }
4153: }
1.1164 raeburn 4154: if (lc($tagname) eq 'embed') {
4155: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4156: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4157: $attr->{'src'});
4158: }
4159: }
1.640 albertel 4160: }
1.1172.2.35 raeburn 4161: if (lc($tagname) eq 'iframe') {
4162: my $src = $attr->{'src'} ;
4163: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4164: &add_filetype($allfiles,$src,'src');
4165: } elsif ($src =~ m{^/}) {
4166: if ($env{'request.course.id'}) {
4167: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4168: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4169: my $url = &hreflocation('',$fullpath);
4170: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4171: my $relpath = $1;
4172: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4173: &add_filetype($allfiles,$1,'src');
4174: }
4175: }
4176: }
4177: }
4178: }
1.1164 raeburn 4179: if ($t->[4] =~ m{/>$}) {
1.1172.2.35 raeburn 4180: pop(@state);
1.1164 raeburn 4181: }
1.640 albertel 4182: } elsif ($t->[0] eq 'E') {
4183: my ($tagname) = ($t->[1]);
4184: if ($javafiles{'codebase'} ne '') {
4185: $javafiles{'codebase'} .= '/';
4186: }
4187: if (lc($tagname) eq 'applet' ||
4188: lc($tagname) eq 'object' ||
4189: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4190: ) {
4191: foreach my $item (keys(%javafiles)) {
4192: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4193: my $file=$javafiles{'codebase'}.$javafiles{$item};
4194: &add_filetype($allfiles,$file,$item);
4195: }
4196: }
4197: }
4198: pop @state;
4199: }
4200: }
1.1164 raeburn 4201: foreach my $id (sort(keys(%flashvars))) {
4202: if ($shockwave{$id} ne '') {
4203: my @pairs = split(/\&/,$flashvars{$id});
4204: foreach my $pair (@pairs) {
4205: my ($key,$value) = split(/\=/,$pair);
4206: if ($key eq 'thumb') {
4207: &add_filetype($allfiles,$value,$key);
4208: } elsif ($key eq 'content') {
4209: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4210: my ($ext) = ($value =~ /\.([^.]+)$/);
4211: if ($ext ne '') {
4212: &add_filetype($allfiles,$path.$value,$ext);
4213: }
4214: }
4215: }
4216: }
4217: }
1.637 raeburn 4218: return 'ok';
4219: }
4220:
1.639 albertel 4221: sub add_filetype {
4222: my ($allfiles,$file,$type)=@_;
4223: if (exists($allfiles->{$file})) {
4224: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4225: push(@{$allfiles->{$file}}, &escape($type));
4226: }
4227: } else {
4228: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4229: }
4230: }
4231:
1.1164 raeburn 4232: sub embedded_dependency {
4233: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4234: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4235: if (($identifier ne '') &&
4236: (ref($related->{$identifier}) eq 'ARRAY') &&
4237: ($pathfrom ne '')) {
4238: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4239: foreach my $dep (@{$related->{$identifier}}) {
4240: &add_filetype($allfiles,$path.$dep,'object');
4241: }
4242: }
4243: }
4244: return;
4245: }
4246:
1.1172.2.109 raeburn 4247: sub bubblesheet_converter {
4248: my ($cdom,$fullpath,$config,$format) = @_;
4249: if ((&domain($cdom) ne '') &&
4250: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
4251: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
4252: my (%csvcols,%csvoptions);
4253: if (ref($config->{'fields'}) eq 'HASH') {
4254: %csvcols = %{$config->{'fields'}};
4255: }
4256: if (ref($config->{'options'}) eq 'HASH') {
4257: %csvoptions = %{$config->{'options'}};
4258: }
4259: my %csvbynum = reverse(%csvcols);
4260: my %scantronconf = &get_scantron_config($format,$cdom);
4261: if (keys(%scantronconf)) {
4262: my %bynum = (
4263: $scantronconf{CODEstart} => 'CODEstart',
4264: $scantronconf{IDstart} => 'IDstart',
4265: $scantronconf{PaperID} => 'PaperID',
4266: $scantronconf{FirstName} => 'FirstName',
4267: $scantronconf{LastName} => 'LastName',
4268: $scantronconf{Qstart} => 'Qstart',
4269: );
4270: my @ordered;
4271: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
4272: push(@ordered,$bynum{$item});
4273: }
4274: my %mapstart = (
4275: CODEstart => 'CODE',
4276: IDstart => 'ID',
4277: PaperID => 'PaperID',
4278: FirstName => 'FirstName',
4279: LastName => 'LastName',
4280: Qstart => 'FirstQuestion',
4281: );
4282: my %maplength = (
4283: CODEstart => 'CODElength',
4284: IDstart => 'IDlength',
4285: PaperID => 'PaperIDlength',
4286: FirstName => 'FirstNamelength',
4287: LastName => 'LastNamelength',
4288: );
4289: if (open(my $fh,'<',$fullpath)) {
4290: my $output;
4291: my %lettdig = &letter_to_digits();
4292: my %diglett = reverse(%lettdig);
4293: my $numletts = scalar(keys(%lettdig));
4294: my $num = 0;
4295: while (my $line=<$fh>) {
4296: $num ++;
4297: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
4298: $line =~ s{[\r\n]+$}{};
4299: my %found;
4300: my @values = split(/,/,$line);
4301: my ($qstart,$record);
4302: for (my $i=0; $i<@values; $i++) {
4303: if ((($qstart ne '') && ($i > $qstart)) ||
4304: ($csvbynum{$i} eq 'FirstQuestion')) {
4305: if ($values[$i] eq '') {
4306: $values[$i] = $scantronconf{'Qoff'};
4307: } elsif ($scantronconf{'Qon'} eq 'number') {
4308: if ($values[$i] =~ /^[A-Ja-j]$/) {
4309: $values[$i] = $lettdig{uc($values[$i])};
4310: }
4311: } elsif ($scantronconf{'Qon'} eq 'letter') {
4312: if ($values[$i] =~ /^[0-9]$/) {
4313: $values[$i] = $diglett{$values[$i]};
4314: }
4315: } else {
4316: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4317: my $digit;
4318: if ($values[$i] =~ /^[A-Ja-j]$/) {
4319: $digit = $lettdig{uc($values[$i])}-1;
4320: if ($values[$i] eq 'J') {
4321: $digit += $numletts;
4322: }
4323: } elsif ($values[$i] =~ /^[0-9]$/) {
4324: $digit = $values[$i]-1;
4325: if ($values[$i] eq '0') {
4326: $digit += $numletts;
4327: }
4328: }
4329: my $qval='';
4330: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4331: if ($j == $digit) {
4332: $qval .= $scantronconf{'Qon'};
4333: } else {
4334: $qval .= $scantronconf{'Qoff'};
4335: }
4336: }
4337: $values[$i] = $qval;
4338: }
4339: }
4340: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4341: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4342: }
4343: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4344: if ($numblank > 0) {
4345: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4346: }
4347: if ($csvbynum{$i} eq 'FirstQuestion') {
4348: $qstart = $i;
4349: $found{$csvbynum{$i}} = $values[$i];
4350: } else {
4351: $found{'FirstQuestion'} .= $values[$i];
4352: }
4353: } elsif (exists($csvbynum{$i})) {
4354: if ($csvoptions{'rem'}) {
4355: $values[$i] =~ s/^\s+//;
4356: }
4357: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
4358: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4359: $values[$i] = '0'.$values[$i];
4360: }
4361: }
4362: $found{$csvbynum{$i}} = $values[$i];
4363: }
4364: }
4365: foreach my $item (@ordered) {
4366: my $currlength = 1+length($record);
4367: my $numspaces = $scantronconf{$item} - $currlength;
4368: if ($numspaces > 0) {
4369: $record .= (' ' x $numspaces);
4370: }
4371: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4372: unless ($item eq 'Qstart') {
4373: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4374: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4375: }
4376: }
4377: $record .= $found{$mapstart{$item}};
4378: }
4379: }
4380: $output .= "$record\n";
4381: }
4382: close($fh);
4383: if ($output) {
4384: if (open(my $fh,'>',$fullpath)) {
4385: print $fh $output;
4386: close($fh);
4387: }
4388: }
4389: }
4390: }
4391: return;
4392: }
4393: }
4394:
4395: sub letter_to_digits {
4396: my %lettdig = (
4397: A => 1,
4398: B => 2,
4399: C => 3,
4400: D => 4,
4401: E => 5,
4402: F => 6,
4403: G => 7,
4404: H => 8,
4405: I => 9,
4406: J => 0,
4407: );
4408: return %lettdig;
4409: }
4410:
4411: sub get_scantron_config {
4412: my ($which,$cdom) = @_;
4413: my @lines = &get_scantronformat_file($cdom);
4414: my %config;
4415: #FIXME probably should move to XML it has already gotten a bit much now
4416: foreach my $line (@lines) {
4417: my ($name,$descrip)=split(/:/,$line);
4418: if ($name ne $which ) { next; }
4419: chomp($line);
4420: my @config=split(/:/,$line);
4421: $config{'name'}=$config[0];
4422: $config{'description'}=$config[1];
4423: $config{'CODElocation'}=$config[2];
4424: $config{'CODEstart'}=$config[3];
4425: $config{'CODElength'}=$config[4];
4426: $config{'IDstart'}=$config[5];
4427: $config{'IDlength'}=$config[6];
4428: $config{'Qstart'}=$config[7];
4429: $config{'Qlength'}=$config[8];
4430: $config{'Qoff'}=$config[9];
4431: $config{'Qon'}=$config[10];
4432: $config{'PaperID'}=$config[11];
4433: $config{'PaperIDlength'}=$config[12];
4434: $config{'FirstName'}=$config[13];
4435: $config{'FirstNamelength'}=$config[14];
4436: $config{'LastName'}=$config[15];
4437: $config{'LastNamelength'}=$config[16];
4438: $config{'BubblesPerRow'}=$config[17];
4439: last;
4440: }
4441: return %config;
4442: }
4443:
4444: sub get_scantronformat_file {
4445: my ($cdom) = @_;
4446: if ($cdom eq '') {
4447: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4448: }
4449: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4450: my $gottab = 0;
4451: my @lines;
4452: if (ref($domconfig{'scantron'}) eq 'HASH') {
4453: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4454: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4455: if ($formatfile ne '-1') {
4456: @lines = split("\n",$formatfile,-1);
4457: $gottab = 1;
4458: }
4459: }
4460: }
4461: if (!$gottab) {
4462: my $confname = $cdom.'-domainconfig';
4463: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4464: my $formatfile = &getfile($default);
4465: if ($formatfile ne '-1') {
4466: @lines = split("\n",$formatfile,-1);
4467: $gottab = 1;
4468: }
4469: }
4470: if (!$gottab) {
4471: my @domains = ¤t_machine_domains();
4472: if (grep(/^\Q$cdom\E$/,@domains)) {
4473: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4474: @lines = <$fh>;
4475: close($fh);
4476: }
4477: } else {
4478: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4479: @lines = <$fh>;
4480: close($fh);
4481: }
4482: }
4483: }
4484: return @lines;
4485: }
4486:
1.493 albertel 4487: sub removeuploadedurl {
1.984 neumanie 4488: my ($url)=@_;
4489: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4490: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4491: }
4492:
4493: sub removeuserfile {
4494: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4495: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4496: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4497: if ($result eq 'ok') {
1.798 raeburn 4498: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4499: my $metafile = $fname.'.meta';
4500: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4501: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4502: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4503: my $sqlresult =
1.823 albertel 4504: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4505: 'portfolio_metadata',$group,
4506: 'delete');
1.798 raeburn 4507: }
4508: }
4509: return $result;
1.257 www 4510: }
1.15 www 4511:
1.530 albertel 4512: sub mkdiruserfile {
4513: my ($docuname,$docudom,$dir)=@_;
4514: my $home=&homeserver($docuname,$docudom);
4515: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4516: }
4517:
1.531 albertel 4518: sub renameuserfile {
4519: my ($docuname,$docudom,$old,$new)=@_;
4520: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4521: my $result = &reply("renameuserfile:$docudom:$docuname:".
4522: &escape("$old").':'.&escape("$new"),$home);
4523: if ($result eq 'ok') {
4524: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4525: my $oldmeta = $old.'.meta';
4526: my $newmeta = $new.'.meta';
4527: my $metaresult =
4528: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4529: my $url = "/uploaded/$docudom/$docuname/$old";
4530: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4531: my $sqlresult =
1.823 albertel 4532: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4533: 'portfolio_metadata',$group,
4534: 'delete');
1.798 raeburn 4535: }
4536: }
4537: return $result;
1.531 albertel 4538: }
4539:
1.14 www 4540: # ------------------------------------------------------------------------- Log
4541:
4542: sub log {
4543: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4544: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4545: }
4546:
4547: # ------------------------------------------------------------------ Course Log
1.352 www 4548: #
4549: # This routine flushes several buffers of non-mission-critical nature
4550: #
1.157 www 4551:
4552: sub flushcourselogs {
1.352 www 4553: &logthis('Flushing log buffers');
4554: #
4555: # course logs
4556: # This is a log of all transactions in a course, which can be used
4557: # for data mining purposes
4558: #
4559: # It also collects the courseid database, which lists last transaction
4560: # times and course titles for all courseids
4561: #
4562: my %courseidbuffer=();
1.921 raeburn 4563: foreach my $crsid (keys(%courselogs)) {
1.352 www 4564: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4565: &escape($courselogs{$crsid}),
4566: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4567: delete $courselogs{$crsid};
4568: } else {
4569: &logthis('Failed to flush log buffer for '.$crsid);
4570: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4571: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4572: " exceeded maximum size, deleting.</font>");
4573: delete $courselogs{$crsid};
4574: }
1.352 www 4575: }
1.920 raeburn 4576: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4577: 'description' => $coursedescrbuf{$crsid},
4578: 'inst_code' => $courseinstcodebuf{$crsid},
4579: 'type' => $coursetypebuf{$crsid},
4580: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4581: };
1.191 harris41 4582: }
1.352 www 4583: #
4584: # Write course id database (reverse lookup) to homeserver of courses
4585: # Is used in pickcourse
4586: #
1.840 albertel 4587: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4588: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4589: $courseidbuffer{$crs_home},
4590: $crs_home,'timeonly');
1.352 www 4591: }
4592: #
4593: # File accesses
4594: # Writes to the dynamic metadata of resources to get hit counts, etc.
4595: #
1.449 matthew 4596: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4597: if ($entry =~ /___count$/) {
4598: my ($dom,$name);
1.807 albertel 4599: ($dom,$name,undef)=
1.811 albertel 4600: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4601: if (! defined($dom) || $dom eq '' ||
4602: ! defined($name) || $name eq '') {
1.620 albertel 4603: my $cid = $env{'request.course.id'};
4604: $dom = $env{'request.'.$cid.'.domain'};
4605: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4606: }
1.450 matthew 4607: my $value = $accesshash{$entry};
4608: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4609: my %temphash=($url => $value);
1.449 matthew 4610: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4611: if ($result eq 'ok') {
4612: delete $accesshash{$entry};
4613: }
4614: } else {
1.811 albertel 4615: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4616: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4617: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4618: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4619: delete $accesshash{$entry};
4620: }
1.185 www 4621: }
1.191 harris41 4622: }
1.352 www 4623: #
4624: # Roles
4625: # Reverse lookup of user roles for course faculty/staff and co-authorship
4626: #
1.800 albertel 4627: foreach my $entry (keys(%userrolehash)) {
1.351 www 4628: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4629: split(/\:/,$entry);
4630: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4631: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4632: $rudom,$runame) eq 'ok') {
4633: delete $userrolehash{$entry};
4634: }
4635: }
1.662 raeburn 4636: #
1.1172.2.90 raeburn 4637: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4638: #
4639: my %domrolebuffer = ();
1.1000 raeburn 4640: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4641: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4642: if ($domrolebuffer{$rudom}) {
4643: $domrolebuffer{$rudom}.='&'.&escape($entry).
4644: '='.&escape($domainrolehash{$entry});
4645: } else {
4646: $domrolebuffer{$rudom}.=&escape($entry).
4647: '='.&escape($domainrolehash{$entry});
4648: }
4649: delete $domainrolehash{$entry};
4650: }
4651: foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82 raeburn 4652: my %servers;
4653: if (defined(&domain($dom,'primary'))) {
4654: my $primary=&domain($dom,'primary');
4655: my $hostname=&hostname($primary);
4656: $servers{$primary} = $hostname;
4657: } else {
4658: %servers = &get_servers($dom,'library');
4659: }
1.841 albertel 4660: foreach my $tryserver (keys(%servers)) {
1.1172.2.82 raeburn 4661: if (&reply('domroleput:'.$dom.':'.
4662: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4663: last;
4664: } else {
1.841 albertel 4665: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4666: }
1.662 raeburn 4667: }
4668: }
1.186 www 4669: $dumpcount++;
1.157 www 4670: }
4671:
4672: sub courselog {
4673: my $what=shift;
1.158 www 4674: $what=time.':'.$what;
1.620 albertel 4675: unless ($env{'request.course.id'}) { return ''; }
4676: $coursedombuf{$env{'request.course.id'}}=
4677: $env{'course.'.$env{'request.course.id'}.'.domain'};
4678: $coursenumbuf{$env{'request.course.id'}}=
4679: $env{'course.'.$env{'request.course.id'}.'.num'};
4680: $coursehombuf{$env{'request.course.id'}}=
4681: $env{'course.'.$env{'request.course.id'}.'.home'};
4682: $coursedescrbuf{$env{'request.course.id'}}=
4683: $env{'course.'.$env{'request.course.id'}.'.description'};
4684: $courseinstcodebuf{$env{'request.course.id'}}=
4685: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4686: $courseownerbuf{$env{'request.course.id'}}=
4687: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4688: $coursetypebuf{$env{'request.course.id'}}=
4689: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4690: if (defined $courselogs{$env{'request.course.id'}}) {
4691: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4692: } else {
1.620 albertel 4693: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4694: }
1.620 albertel 4695: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4696: &flushcourselogs();
4697: }
1.158 www 4698: }
4699:
4700: sub courseacclog {
4701: my $fnsymb=shift;
1.620 albertel 4702: unless ($env{'request.course.id'}) { return ''; }
4703: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4704: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4705: $what.=':POST';
1.583 matthew 4706: # FIXME: Probably ought to escape things....
1.800 albertel 4707: foreach my $key (keys(%env)) {
4708: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4709: my $formitem = $1;
4710: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4711: $what.=':'.$formitem.'='.$env{$key};
4712: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131 raeburn 4713: if ($formitem eq 'proctorpassword') {
1.1172.2.132 raeburn 4714: $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131 raeburn 4715: } else {
4716: $what.=':'.$formitem.'='.$env{$key};
4717: }
1.975 raeburn 4718: }
1.158 www 4719: }
1.191 harris41 4720: }
1.583 matthew 4721: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4722: # FIXME: We should not be depending on a form parameter that someone
4723: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4724: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4725: $what.= ':POST';
4726: # FIXME: Probably ought to escape things....
4727: foreach my $element ('courseexp','crsfulltext','crsrelated',
4728: 'crsdiscuss') {
1.620 albertel 4729: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4730: }
4731: }
1.158 www 4732: }
4733: &courselog($what);
1.149 www 4734: }
4735:
1.185 www 4736: sub countacc {
4737: my $url=&declutter(shift);
1.458 matthew 4738: return if (! defined($url) || $url eq '');
1.620 albertel 4739: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4740: #
4741: # Mark that this url was used in this course
4742: #
1.620 albertel 4743: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4744: #
4745: # Increase the access count for this resource in this child process
4746: #
1.281 www 4747: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4748: $accesshash{$key}++;
1.185 www 4749: }
1.349 www 4750:
1.361 www 4751: sub linklog {
4752: my ($from,$to)=@_;
4753: $from=&declutter($from);
4754: $to=&declutter($to);
4755: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4756: $accesshash{$to.'___'.$from.'___goto'}=1;
4757: }
1.1160 www 4758:
4759: sub statslog {
4760: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4761: if ($users<2) { return; }
4762: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4763: 'course' => $env{'request.course.id'},
4764: 'sections' => '"all"',
4765: 'num_students' => $users,
4766: 'part' => $part,
4767: 'symb' => $symb,
4768: 'mean_tries' => $av_attempts,
4769: 'deg_of_diff' => $degdiff});
4770: foreach my $key (keys(%dynstore)) {
4771: $accesshash{$key}=$dynstore{$key};
4772: }
4773: }
1.361 www 4774:
1.349 www 4775: sub userrolelog {
4776: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4777: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4778: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4779: $userrolehash
4780: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4781: =$tend.':'.$tstart;
1.662 raeburn 4782: }
1.1169 droeschl 4783: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4784: $userrolehash
4785: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4786: =$tend.':'.$tstart;
4787: }
1.1172.2.90 raeburn 4788: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4789: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4790: $domainrolehash
4791: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4792: = $tend.':'.$tstart;
4793: }
1.351 www 4794: }
4795:
1.957 raeburn 4796: sub courserolelog {
4797: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9 raeburn 4798: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4799: my $cdom = $1;
4800: my $cnum = $2;
4801: my $sec = $3;
4802: my $namespace = 'rolelog';
4803: my %storehash = (
4804: role => $trole,
4805: start => $tstart,
4806: end => $tend,
4807: selfenroll => $selfenroll,
4808: context => $context,
4809: );
4810: if ($trole eq 'gr') {
4811: $namespace = 'groupslog';
4812: $storehash{'group'} = $sec;
4813: } else {
4814: $storehash{'section'} = $sec;
4815: }
4816: &write_log('course',$namespace,\%storehash,$delflag,$username,
4817: $domain,$cnum,$cdom);
4818: if (($trole ne 'st') || ($sec ne '')) {
4819: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4820: }
4821: }
4822: return;
4823: }
4824:
1.1172.2.9 raeburn 4825: sub domainrolelog {
4826: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4827: if ($area =~ m{^/($match_domain)/$}) {
4828: my $cdom = $1;
4829: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4830: my $namespace = 'rolelog';
4831: my %storehash = (
4832: role => $trole,
4833: start => $tstart,
4834: end => $tend,
4835: context => $context,
4836: );
4837: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4838: $domain,$domconfiguser,$cdom);
4839: }
4840: return;
4841:
4842: }
4843:
4844: sub coauthorrolelog {
4845: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4846: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4847: my $audom = $1;
4848: my $auname = $2;
4849: my $namespace = 'rolelog';
4850: my %storehash = (
4851: role => $trole,
4852: start => $tstart,
4853: end => $tend,
4854: context => $context,
4855: );
4856: &write_log('author',$namespace,\%storehash,$delflag,$username,
4857: $domain,$auname,$audom);
4858: }
4859: return;
4860: }
4861:
1.351 www 4862: sub get_course_adv_roles {
1.948 raeburn 4863: my ($cid,$codes) = @_;
1.620 albertel 4864: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4865: my %coursehash=&coursedescription($cid);
1.988 raeburn 4866: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4867: my %nothide=();
1.800 albertel 4868: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4869: if ($user !~ /:/) {
4870: $nothide{join(':',split(/[\@]/,$user))}=1;
4871: } else {
4872: $nothide{$user}=1;
4873: }
1.470 www 4874: }
1.1172.2.23 raeburn 4875: my @possdoms = ($coursehash{'domain'});
4876: if ($coursehash{'checkforpriv'}) {
4877: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4878: }
1.351 www 4879: my %returnhash=();
4880: my %dumphash=
4881: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4882: my $now=time;
1.997 raeburn 4883: my %privileged;
1.1000 raeburn 4884: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4885: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4886: if (($tstart) && ($tstart<0)) { next; }
4887: if (($tend) && ($tend<$now)) { next; }
4888: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4889: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4890: if ($username eq '' || $domain eq '') { next; }
1.1172.2.23 raeburn 4891: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4892: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4893: if ($role eq 'cr') { next; }
1.948 raeburn 4894: if ($codes) {
4895: if ($section) { $role .= ':'.$section; }
4896: if ($returnhash{$role}) {
4897: $returnhash{$role}.=','.$username.':'.$domain;
4898: } else {
4899: $returnhash{$role}=$username.':'.$domain;
4900: }
1.351 www 4901: } else {
1.988 raeburn 4902: my $key=&plaintext($role,$crstype);
1.973 bisitz 4903: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4904: if ($returnhash{$key}) {
4905: $returnhash{$key}.=','.$username.':'.$domain;
4906: } else {
4907: $returnhash{$key}=$username.':'.$domain;
4908: }
1.351 www 4909: }
1.948 raeburn 4910: }
1.400 www 4911: return %returnhash;
4912: }
4913:
4914: sub get_my_roles {
1.937 raeburn 4915: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4916: unless (defined($uname)) { $uname=$env{'user.name'}; }
4917: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4918: my (%dumphash,%nothide);
1.1086 raeburn 4919: if ($context eq 'userroles') {
1.1166 raeburn 4920: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4921: } else {
1.1172.2.23 raeburn 4922: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4923: if ($hidepriv) {
4924: my %coursehash=&coursedescription($udom.'_'.$uname);
4925: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4926: if ($user !~ /:/) {
4927: $nothide{join(':',split(/[\@]/,$user))} = 1;
4928: } else {
4929: $nothide{$user} = 1;
4930: }
4931: }
4932: }
1.858 raeburn 4933: }
1.400 www 4934: my %returnhash=();
4935: my $now=time;
1.999 raeburn 4936: my %privileged;
1.800 albertel 4937: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4938: my ($role,$tend,$tstart);
4939: if ($context eq 'userroles') {
1.1149 raeburn 4940: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4941: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4942: } else {
4943: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4944: }
1.400 www 4945: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4946: my $status = 'active';
1.939 raeburn 4947: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4948: $status = 'previous';
4949: }
4950: if (($tstart) && ($now<$tstart)) {
4951: $status = 'future';
4952: }
4953: if (ref($types) eq 'ARRAY') {
4954: if (!grep(/^\Q$status\E$/,@{$types})) {
4955: next;
4956: }
4957: } else {
4958: if ($status ne 'active') {
4959: next;
4960: }
4961: }
1.867 raeburn 4962: my ($rolecode,$username,$domain,$section,$area);
4963: if ($context eq 'userroles') {
1.1172.2.9 raeburn 4964: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4965: (undef,$domain,$username,$section) = split(/\//,$area);
4966: } else {
4967: ($role,$username,$domain,$section) = split(/\:/,$entry);
4968: }
1.832 raeburn 4969: if (ref($roledoms) eq 'ARRAY') {
4970: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4971: next;
4972: }
4973: }
4974: if (ref($roles) eq 'ARRAY') {
4975: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4976: if ($role =~ /^cr\//) {
4977: if (!grep(/^cr$/,@{$roles})) {
4978: next;
4979: }
1.1104 raeburn 4980: } elsif ($role =~ /^gr\//) {
4981: if (!grep(/^gr$/,@{$roles})) {
4982: next;
4983: }
1.922 raeburn 4984: } else {
4985: next;
4986: }
1.832 raeburn 4987: }
1.867 raeburn 4988: }
1.937 raeburn 4989: if ($hidepriv) {
1.1172.2.23 raeburn 4990: my @privroles = ('dc','su');
1.999 raeburn 4991: if ($context eq 'userroles') {
1.1172.2.23 raeburn 4992: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4993: } else {
1.1172.2.23 raeburn 4994: my $possdoms = [$domain];
4995: if (ref($roledoms) eq 'ARRAY') {
4996: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4997: }
1.1172.2.23 raeburn 4998: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4999: if (!$nothide{$username.':'.$domain}) {
5000: next;
5001: }
5002: }
1.937 raeburn 5003: }
5004: }
1.933 raeburn 5005: if ($withsec) {
5006: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5007: $tstart.':'.$tend;
5008: } else {
5009: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5010: }
1.832 raeburn 5011: }
1.373 www 5012: return %returnhash;
1.399 www 5013: }
5014:
1.1172.2.89 raeburn 5015: sub get_all_adhocroles {
5016: my ($dom) = @_;
5017: my @roles_by_num = ();
5018: my %domdefaults = &get_domain_defaults($dom);
5019: my (%description,%access_in_dom,%access_info);
5020: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5021: my $count = 0;
5022: my %domcurrent = %{$domdefaults{'adhocroles'}};
5023: my %ordered;
5024: foreach my $role (sort(keys(%domcurrent))) {
5025: my ($order,$desc,$access_in_dom);
5026: if (ref($domcurrent{$role}) eq 'HASH') {
5027: $order = $domcurrent{$role}{'order'};
5028: $desc = $domcurrent{$role}{'desc'};
5029: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5030: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5031: }
5032: if ($order eq '') {
5033: $order = $count;
5034: }
5035: $ordered{$order} = $role;
5036: if ($desc ne '') {
5037: $description{$role} = $desc;
5038: } else {
5039: $description{$role}= $role;
5040: }
5041: $count++;
5042: }
5043: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5044: push(@roles_by_num,$ordered{$item});
5045: }
5046: }
5047: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5048: }
5049:
5050: sub get_my_adhocroles {
5051: my ($cid,$checkreg) = @_;
5052: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5053: if ($env{'request.course.id'} eq $cid) {
5054: $cdom = $env{'course.'.$cid.'.domain'};
5055: $cnum = $env{'course.'.$cid.'.num'};
5056: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5057: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5058: $cdom = $1;
5059: $cnum = $2;
5060: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5061: $cdom,$cnum);
5062: }
5063: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5064: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5065: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5066: if ($rosterhash{$user} ne '') {
5067: my $type = (split(/:/,$rosterhash{$user}))[5];
5068: return ([],{}) if ($type eq 'auto');
5069: }
5070: }
5071: if (($cdom ne '') && ($cnum ne '')) {
1.1172.2.90 raeburn 5072: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89 raeburn 5073: my $then=$env{'user.login.time'};
5074: my $update=$env{'user.update.time'};
1.1172.2.90 raeburn 5075: if (!$update) {
5076: $update = $then;
5077: }
5078: my @liveroles;
5079: foreach my $role ('dh','da') {
5080: if ($env{"user.role.$role./$cdom/"}) {
5081: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
5082: my $limit = $update;
5083: if ($env{'request.role'} eq "$role./$cdom/") {
5084: $limit = $then;
5085: }
5086: my $activerole = 1;
5087: if ($tstart && $tstart>$limit) { $activerole = 0; }
5088: if ($tend && $tend <$limit) { $activerole = 0; }
5089: if ($activerole) {
5090: push(@liveroles,$role);
5091: }
5092: }
5093: }
5094: if (@liveroles) {
1.1172.2.89 raeburn 5095: if (&homeserver($cnum,$cdom) ne 'no_host') {
5096: my ($accessref,$accessinfo,%access_in_dom);
5097: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5098: if (ref($roles_by_num) eq 'ARRAY') {
5099: if (@{$roles_by_num}) {
5100: my %settings;
5101: if ($env{'request.course.id'} eq $cid) {
5102: foreach my $envkey (keys(%env)) {
5103: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5104: $settings{$1} = $env{$envkey};
5105: }
5106: }
5107: } else {
5108: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5109: }
5110: my %setincrs;
5111: if ($settings{'internal.adhocaccess'}) {
5112: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5113: }
5114: my @statuses;
5115: if ($env{'environment.inststatus'}) {
5116: @statuses = split(/,/,$env{'environment.inststatus'});
5117: }
5118: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5119: if (ref($accessref) eq 'HASH') {
5120: %access_in_dom = %{$accessref};
5121: }
5122: foreach my $role (@{$roles_by_num}) {
5123: my ($curraccess,@okstatus,@personnel);
5124: if ($setincrs{$role}) {
5125: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5126: if ($curraccess eq 'status') {
5127: @okstatus = split(/\&/,$rest);
5128: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5129: @personnel = split(/\&/,$rest);
5130: }
5131: } else {
5132: $curraccess = $access_in_dom{$role};
5133: if (ref($accessinfo) eq 'HASH') {
5134: if ($curraccess eq 'status') {
5135: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5136: @okstatus = @{$accessinfo->{$role}};
5137: }
5138: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5139: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5140: @personnel = @{$accessinfo->{$role}};
5141: }
5142: }
5143: }
5144: }
5145: if ($curraccess eq 'none') {
5146: next;
5147: } elsif ($curraccess eq 'all') {
5148: push(@possroles,$role);
1.1172.2.90 raeburn 5149: } elsif ($curraccess eq 'dh') {
5150: if (grep(/^dh$/,@liveroles)) {
5151: push(@possroles,$role);
5152: } else {
5153: next;
5154: }
5155: } elsif ($curraccess eq 'da') {
5156: if (grep(/^da$/,@liveroles)) {
5157: push(@possroles,$role);
5158: } else {
5159: next;
5160: }
1.1172.2.89 raeburn 5161: } elsif ($curraccess eq 'status') {
5162: if (@okstatus) {
5163: if (!@statuses) {
5164: if (grep(/^default$/,@okstatus)) {
5165: push(@possroles,$role);
5166: }
5167: } else {
5168: foreach my $status (@okstatus) {
5169: if (grep(/^\Q$status\E$/,@statuses)) {
5170: push(@possroles,$role);
5171: last;
5172: }
5173: }
5174: }
5175: }
5176: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5177: if (grep(/^\Q$user\E$/,@personnel)) {
5178: if ($curraccess eq 'exc') {
5179: push(@possroles,$role);
5180: }
5181: } elsif ($curraccess eq 'inc') {
5182: push(@possroles,$role);
5183: }
5184: }
5185: }
5186: }
5187: }
5188: }
5189: }
5190: }
5191: }
5192: unless (ref($description) eq 'HASH') {
5193: if (ref($roles_by_num) eq 'ARRAY') {
5194: my %desc;
5195: map { $desc{$_} = $_; } (@{$roles_by_num});
5196: $description = \%desc;
5197: } else {
5198: $description = {};
5199: }
5200: }
5201: return (\@possroles,$description);
5202: }
5203:
1.399 www 5204: # ----------------------------------------------------- Frontpage Announcements
5205: #
5206: #
5207:
5208: sub postannounce {
5209: my ($server,$text)=@_;
1.844 albertel 5210: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 5211: unless ($text=~/\w/) { $text=''; }
5212: return &reply('setannounce:'.&escape($text),$server);
5213: }
5214:
5215: sub getannounce {
1.448 albertel 5216:
1.1172.2.96 raeburn 5217: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 5218: my $announcement='';
1.800 albertel 5219: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 5220: close($fh);
1.399 www 5221: if ($announcement=~/\w/) {
5222: return
5223: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 5224: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 5225: } else {
5226: return '';
5227: }
5228: } else {
5229: return '';
5230: }
1.351 www 5231: }
1.353 www 5232:
5233: # ---------------------------------------------------------- Course ID routines
5234: # Deal with domain's nohist_courseid.db files
5235: #
5236:
5237: sub courseidput {
1.921 raeburn 5238: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 5239: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 5240: my $outcome;
5241: if ($caller eq 'timeonly') {
5242: my $cids = '';
5243: foreach my $item (keys(%$storehash)) {
5244: $cids.=&escape($item).'&';
5245: }
5246: $cids=~s/\&$//;
5247: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5248: $coursehome);
5249: } else {
5250: my $items = '';
5251: foreach my $item (keys(%$storehash)) {
5252: $items.= &escape($item).'='.
5253: &freeze_escape($$storehash{$item}).'&';
5254: }
5255: $items=~s/\&$//;
5256: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5257: $coursehome);
1.918 raeburn 5258: }
5259: if ($outcome eq 'unknown_cmd') {
5260: my $what;
5261: foreach my $cid (keys(%$storehash)) {
5262: $what .= &escape($cid).'=';
1.921 raeburn 5263: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 5264: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 5265: }
5266: $what =~ s/\:$/&/;
5267: }
5268: $what =~ s/\&$//;
5269: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5270: } else {
5271: return $outcome;
5272: }
1.353 www 5273: }
5274:
5275: sub courseiddump {
1.921 raeburn 5276: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 5277: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 5278: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38 raeburn 5279: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68 raeburn 5280: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 5281: my $as_hash = 1;
5282: my %returnhash;
5283: if (!$domfilter) { $domfilter=''; }
1.845 albertel 5284: my %libserv = &all_library();
5285: foreach my $tryserver (keys(%libserv)) {
5286: if ( ( $hostidflag == 1
5287: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5288: || (!defined($hostidflag)) ) {
5289:
1.918 raeburn 5290: if (($domfilter eq '') ||
5291: (&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22 raeburn 5292: my $rep;
5293: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
5294: $rep = &LONCAPA::Lond::dump_course_id_handler(
5295: join(":", (&host_domain($tryserver), $sincefilter,
5296: &escape($descfilter), &escape($instcodefilter),
5297: &escape($ownerfilter), &escape($coursefilter),
5298: &escape($typefilter), &escape($regexp_ok),
5299: $as_hash, &escape($selfenrollonly),
5300: &escape($catfilter), $showhidden, $caller,
5301: &escape($cloner), &escape($cc_clone), $cloneonly,
5302: &escape($createdbefore), &escape($createdafter),
1.1172.2.68 raeburn 5303: &escape($creationcontext),$domcloner,$hasuniquecode,
5304: $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22 raeburn 5305: } else {
5306: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5307: $sincefilter.':'.&escape($descfilter).':'.
5308: &escape($instcodefilter).':'.&escape($ownerfilter).
5309: ':'.&escape($coursefilter).':'.&escape($typefilter).
5310: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5311: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5312: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5313: &escape($cc_clone).':'.$cloneonly.':'.
5314: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68 raeburn 5315: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5316: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22 raeburn 5317: }
5318:
1.918 raeburn 5319: my @pairs=split(/\&/,$rep);
5320: foreach my $item (@pairs) {
5321: my ($key,$value)=split(/\=/,$item,2);
5322: $key = &unescape($key);
5323: next if ($key =~ /^error: 2 /);
5324: my $result = &thaw_unescape($value);
5325: if (ref($result) eq 'HASH') {
5326: $returnhash{$key}=$result;
5327: } else {
1.921 raeburn 5328: my @responses = split(/:/,$value);
5329: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5330: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5331: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5332: }
1.1008 raeburn 5333: }
1.353 www 5334: }
5335: }
5336: }
5337: }
5338: return %returnhash;
5339: }
5340:
1.1055 raeburn 5341: sub courselastaccess {
5342: my ($cdom,$cnum,$hostidref) = @_;
5343: my %returnhash;
5344: if ($cdom && $cnum) {
5345: my $chome = &homeserver($cnum,$cdom);
5346: if ($chome ne 'no_host') {
5347: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5348: &extract_lastaccess(\%returnhash,$rep);
5349: }
5350: } else {
5351: if (!$cdom) { $cdom=''; }
5352: my %libserv = &all_library();
5353: foreach my $tryserver (keys(%libserv)) {
5354: if (ref($hostidref) eq 'ARRAY') {
5355: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5356: }
5357: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5358: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5359: &extract_lastaccess(\%returnhash,$rep);
5360: }
5361: }
5362: }
5363: return %returnhash;
5364: }
5365:
5366: sub extract_lastaccess {
5367: my ($returnhash,$rep) = @_;
5368: if (ref($returnhash) eq 'HASH') {
5369: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5370: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5371: $rep eq '') {
5372: my @pairs=split(/\&/,$rep);
5373: foreach my $item (@pairs) {
5374: my ($key,$value)=split(/\=/,$item,2);
5375: $key = &unescape($key);
5376: next if ($key =~ /^error: 2 /);
5377: $returnhash->{$key} = &thaw_unescape($value);
5378: }
5379: }
5380: }
5381: return;
5382: }
5383:
1.658 raeburn 5384: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5385:
5386: sub dcmailput {
1.685 raeburn 5387: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 5388: my $status = &Apache::lonnet::critical(
1.740 www 5389: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5390: &escape($message),$server);
1.662 raeburn 5391: return $status;
5392: }
5393:
1.658 raeburn 5394: sub dcmaildump {
5395: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5396: my %returnhash=();
1.846 albertel 5397:
5398: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5399: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5400: &escape($enddate).':';
5401: my @esc_senders=map { &escape($_)} @$senders;
5402: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5403: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5404: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5405: if (($key) && ($value)) {
5406: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5407: }
5408: }
5409: }
5410: return %returnhash;
5411: }
1.662 raeburn 5412: # ---------------------------------------------------------- Domain roles
5413:
5414: sub get_domain_roles {
5415: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5416: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5417: $startdate = '.';
5418: }
1.1018 raeburn 5419: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5420: $enddate = '.';
5421: }
1.922 raeburn 5422: my $rolelist;
5423: if (ref($roles) eq 'ARRAY') {
1.1172.2.23 raeburn 5424: $rolelist = join('&',@{$roles});
1.922 raeburn 5425: }
1.662 raeburn 5426: my %personnel = ();
1.841 albertel 5427:
5428: my %servers = &get_servers($dom,'library');
5429: foreach my $tryserver (keys(%servers)) {
5430: %{$personnel{$tryserver}}=();
5431: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5432: &escape($startdate).':'.
5433: &escape($enddate).':'.
5434: &escape($rolelist), $tryserver))) {
5435: my ($key,$value) = split(/\=/,$line,2);
5436: if (($key) && ($value)) {
5437: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5438: }
5439: }
1.662 raeburn 5440: }
5441: return %personnel;
5442: }
1.658 raeburn 5443:
1.1172.2.89 raeburn 5444: sub get_active_domroles {
5445: my ($dom,$roles) = @_;
5446: return () unless (ref($roles) eq 'ARRAY');
5447: my $now = time;
5448: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5449: my %domroles;
5450: foreach my $server (keys(%dompersonnel)) {
5451: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5452: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5453: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5454: }
5455: }
5456: return %domroles;
5457: }
5458:
1.1057 www 5459: # ----------------------------------------------------------- Interval timing
1.149 www 5460:
1.1153 www 5461: {
5462: # Caches needed for speedup of navmaps
5463: # We don't want to cache this for very long at all (5 seconds at most)
5464: #
5465: # The user for whom we cache
5466: my $cachedkey='';
5467: # The cached times for this user
5468: my %cachedtimes=();
5469: # When this was last done
1.1172.2.66 raeburn 5470: my $cachedtime='';
1.1153 www 5471:
5472: sub load_all_first_access {
1.1154 raeburn 5473: my ($uname,$udom)=@_;
1.1156 www 5474: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 5475: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 5476: return;
5477: }
5478: $cachedtime=time;
5479: $cachedkey=$uname.':'.$udom;
5480: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5481: }
5482:
1.504 albertel 5483: sub get_first_access {
1.1162 raeburn 5484: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 5485: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5486: if ($argsymb) { $symb=$argsymb; }
5487: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5488: if ($argmap) { $map = $argmap; }
1.926 albertel 5489: if ($type eq 'course') {
5490: $res='course';
5491: } elsif ($type eq 'map') {
1.588 albertel 5492: $res=&symbread($map);
5493: } else {
5494: $res=$symb;
5495: }
1.1153 www 5496: &load_all_first_access($uname,$udom);
5497: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5498: }
5499:
5500: sub set_first_access {
1.1162 raeburn 5501: my ($type,$interval)=@_;
1.790 albertel 5502: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5503: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5504: if ($type eq 'course') {
5505: $res='course';
5506: } elsif ($type eq 'map') {
1.588 albertel 5507: $res=&symbread($map);
5508: } else {
5509: $res=$symb;
5510: }
1.1153 www 5511: $cachedkey='';
1.1162 raeburn 5512: my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102 raeburn 5513: if ($firstaccess) {
5514: &logthis("First access time already set ($firstaccess) when attempting ".
5515: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5516: "in $courseid");
5517: return 'already_set';
5518: } else {
1.1162 raeburn 5519: my $start = time;
5520: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5521: $udom,$uname);
5522: if ($putres eq 'ok') {
5523: &put('timerinterval',{"$courseid\0$res"=>$interval},
5524: $udom,$uname);
5525: &appenv(
5526: {
5527: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5528: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5529: }
5530: );
1.1172.2.97 raeburn 5531: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5532: $cachedtimes{"$courseid\0$res"} = $start;
5533: }
1.1172.2.102 raeburn 5534: } elsif ($putres ne 'refused') {
5535: &logthis("Result: $putres when attempting to set first access time ".
5536: "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162 raeburn 5537: }
5538: return $putres;
1.505 albertel 5539: }
5540: return 'already_set';
1.504 albertel 5541: }
1.1153 www 5542: }
1.1172.2.32 raeburn 5543:
5544: sub checkout {
5545: my ($symb,$tuname,$tudom,$tcrsid)=@_;
5546: my $now=time;
5547: my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134 raeburn 5548: my $ip = &get_requestor_ip();
1.1172.2.32 raeburn 5549: my $infostr=&escape(
5550: 'CHECKOUTTOKEN&'.
5551: $tuname.'&'.
5552: $tudom.'&'.
5553: $tcrsid.'&'.
5554: $symb.'&'.
1.1172.2.134 raeburn 5555: $now.'&'.$ip);
1.1172.2.32 raeburn 5556: my $token=&reply('tmpput:'.$infostr,$lonhost);
5557: if ($token=~/^error\:/) {
5558: &logthis("<font color=\"blue\">WARNING: ".
5559: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
5560: "</font>");
5561: return '';
5562: }
5563:
5564: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
5565: $token=~tr/a-z/A-Z/;
5566:
5567: my %infohash=('resource.0.outtoken' => $token,
5568: 'resource.0.checkouttime' => $now,
1.1172.2.134 raeburn 5569: 'resource.0.outremote' => $ip);
1.1172.2.32 raeburn 5570:
5571: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5572: return '';
5573: } else {
5574: &logthis("<font color=\"blue\">WARNING: ".
5575: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
5576: "</font>");
5577: }
5578:
5579: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5580: &escape('Checkout '.$infostr.' - '.
5581: $token)) ne 'ok') {
5582: return '';
5583: } else {
5584: &logthis("<font color=\"blue\">WARNING: ".
5585: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
5586: "</font>");
5587: }
5588: return $token;
5589: }
5590:
5591: # ------------------------------------------------------------ Check in an item
5592:
5593: sub checkin {
5594: my $token=shift;
5595: my $now=time;
5596: my ($ta,$tb,$lonhost)=split(/\*/,$token);
5597: $lonhost=~tr/A-Z/a-z/;
5598: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
5599: $dtoken=~s/\W/\_/g;
1.1172.2.134 raeburn 5600: my $ip = &get_requestor_ip();
1.1172.2.32 raeburn 5601: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
5602: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
5603:
5604: unless (($tuname) && ($tudom)) {
5605: &logthis('Check in '.$token.' ('.$dtoken.') failed');
5606: return '';
5607: }
5608:
5609: unless (&allowed('mgr',$tcrsid)) {
5610: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
5611: $env{'user.name'}.' - '.$env{'user.domain'});
5612: return '';
5613: }
5614:
5615: my %infohash=('resource.0.intoken' => $token,
5616: 'resource.0.checkintime' => $now,
1.1172.2.134 raeburn 5617: 'resource.0.inremote' => $ip);
1.1172.2.32 raeburn 5618:
5619: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5620: return '';
5621: }
5622:
5623: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5624: &escape('Checkin - '.$token)) ne 'ok') {
5625: return '';
5626: }
5627:
5628: return ($symb,$tuname,$tudom,$tcrsid);
5629: }
5630:
1.110 www 5631: # --------------------------------------------- Set Expire Date for Spreadsheet
5632:
5633: sub expirespread {
5634: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5635: my $cid=$env{'request.course.id'};
1.110 www 5636: if ($cid) {
5637: my $now=time;
5638: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5639: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5640: $env{'course.'.$cid.'.num'}.
1.110 www 5641: ':nohist_expirationdates:'.
5642: &escape($key).'='.$now,
1.620 albertel 5643: $env{'course.'.$cid.'.home'})
1.110 www 5644: }
5645: return 'ok';
1.14 www 5646: }
5647:
1.109 www 5648: # ----------------------------------------------------- Devalidate Spreadsheets
5649:
5650: sub devalidate {
1.325 www 5651: my ($symb,$uname,$udom)=@_;
1.620 albertel 5652: my $cid=$env{'request.course.id'};
1.109 www 5653: if ($cid) {
1.391 matthew 5654: # delete the stored spreadsheets for
5655: # - the student level sheet of this user in course's homespace
5656: # - the assessment level sheet for this resource
5657: # for this user in user's homespace
1.553 albertel 5658: # - current conditional state info
1.325 www 5659: my $key=$uname.':'.$udom.':';
1.109 www 5660: my $status=
1.299 matthew 5661: &del('nohist_calculatedsheets',
1.391 matthew 5662: [$key.'studentcalc:'],
1.620 albertel 5663: $env{'course.'.$cid.'.domain'},
5664: $env{'course.'.$cid.'.num'})
1.133 albertel 5665: .' '.
5666: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5667: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5668: unless ($status eq 'ok ok') {
5669: &logthis('Could not devalidate spreadsheet '.
1.325 www 5670: $uname.' at '.$udom.' for '.
1.109 www 5671: $symb.': '.$status);
1.133 albertel 5672: }
1.553 albertel 5673: &delenv('user.state.'.$cid);
1.109 www 5674: }
5675: }
5676:
1.265 albertel 5677: sub get_scalar {
5678: my ($string,$end) = @_;
5679: my $value;
5680: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5681: $value = $1;
5682: } elsif ($$string =~ s/^([^&]*?)&//) {
5683: $value = $1;
5684: }
5685: return &unescape($value);
5686: }
5687:
5688: sub array2str {
5689: my (@array) = @_;
5690: my $result=&arrayref2str(\@array);
5691: $result=~s/^__ARRAY_REF__//;
5692: $result=~s/__END_ARRAY_REF__$//;
5693: return $result;
5694: }
5695:
1.204 albertel 5696: sub arrayref2str {
5697: my ($arrayref) = @_;
1.265 albertel 5698: my $result='__ARRAY_REF__';
1.204 albertel 5699: foreach my $elem (@$arrayref) {
1.265 albertel 5700: if(ref($elem) eq 'ARRAY') {
5701: $result.=&arrayref2str($elem).'&';
5702: } elsif(ref($elem) eq 'HASH') {
5703: $result.=&hashref2str($elem).'&';
5704: } elsif(ref($elem)) {
5705: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5706: } else {
5707: $result.=&escape($elem).'&';
5708: }
5709: }
5710: $result=~s/\&$//;
1.265 albertel 5711: $result .= '__END_ARRAY_REF__';
1.204 albertel 5712: return $result;
5713: }
5714:
1.168 albertel 5715: sub hash2str {
1.204 albertel 5716: my (%hash) = @_;
5717: my $result=&hashref2str(\%hash);
1.265 albertel 5718: $result=~s/^__HASH_REF__//;
5719: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5720: return $result;
5721: }
5722:
5723: sub hashref2str {
5724: my ($hashref)=@_;
1.265 albertel 5725: my $result='__HASH_REF__';
1.800 albertel 5726: foreach my $key (sort(keys(%$hashref))) {
5727: if (ref($key) eq 'ARRAY') {
5728: $result.=&arrayref2str($key).'=';
5729: } elsif (ref($key) eq 'HASH') {
5730: $result.=&hashref2str($key).'=';
5731: } elsif (ref($key)) {
1.265 albertel 5732: $result.='=';
1.800 albertel 5733: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5734: } else {
1.1132 raeburn 5735: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5736: }
5737:
1.800 albertel 5738: if(ref($hashref->{$key}) eq 'ARRAY') {
5739: $result.=&arrayref2str($hashref->{$key}).'&';
5740: } elsif(ref($hashref->{$key}) eq 'HASH') {
5741: $result.=&hashref2str($hashref->{$key}).'&';
5742: } elsif(ref($hashref->{$key})) {
1.265 albertel 5743: $result.='&';
1.800 albertel 5744: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5745: } else {
1.800 albertel 5746: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5747: }
5748: }
1.168 albertel 5749: $result=~s/\&$//;
1.265 albertel 5750: $result .= '__END_HASH_REF__';
1.168 albertel 5751: return $result;
5752: }
5753:
5754: sub str2hash {
1.265 albertel 5755: my ($string)=@_;
5756: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5757: return %$hash;
5758: }
5759:
5760: sub str2hashref {
1.168 albertel 5761: my ($string) = @_;
1.265 albertel 5762:
5763: my %hash;
5764:
5765: if($string !~ /^__HASH_REF__/) {
5766: if (! ($string eq '' || !defined($string))) {
5767: $hash{'error'}='Not hash reference';
5768: }
5769: return (\%hash, $string);
5770: }
5771:
5772: $string =~ s/^__HASH_REF__//;
5773:
5774: while($string !~ /^__END_HASH_REF__/) {
5775: #key
5776: my $key='';
5777: if($string =~ /^__HASH_REF__/) {
5778: ($key, $string)=&str2hashref($string);
5779: if(defined($key->{'error'})) {
5780: $hash{'error'}='Bad data';
5781: return (\%hash, $string);
5782: }
5783: } elsif($string =~ /^__ARRAY_REF__/) {
5784: ($key, $string)=&str2arrayref($string);
5785: if($key->[0] eq 'Array reference error') {
5786: $hash{'error'}='Bad data';
5787: return (\%hash, $string);
5788: }
5789: } else {
5790: $string =~ s/^(.*?)=//;
1.267 albertel 5791: $key=&unescape($1);
1.265 albertel 5792: }
5793: $string =~ s/^=//;
5794:
5795: #value
5796: my $value='';
5797: if($string =~ /^__HASH_REF__/) {
5798: ($value, $string)=&str2hashref($string);
5799: if(defined($value->{'error'})) {
5800: $hash{'error'}='Bad data';
5801: return (\%hash, $string);
5802: }
5803: } elsif($string =~ /^__ARRAY_REF__/) {
5804: ($value, $string)=&str2arrayref($string);
5805: if($value->[0] eq 'Array reference error') {
5806: $hash{'error'}='Bad data';
5807: return (\%hash, $string);
5808: }
5809: } else {
5810: $value=&get_scalar(\$string,'__END_HASH_REF__');
5811: }
5812: $string =~ s/^&//;
5813:
5814: $hash{$key}=$value;
1.204 albertel 5815: }
1.265 albertel 5816:
5817: $string =~ s/^__END_HASH_REF__//;
5818:
5819: return (\%hash, $string);
1.204 albertel 5820: }
5821:
5822: sub str2array {
1.265 albertel 5823: my ($string)=@_;
5824: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5825: return @$array;
5826: }
5827:
5828: sub str2arrayref {
1.204 albertel 5829: my ($string) = @_;
1.265 albertel 5830: my @array;
5831:
5832: if($string !~ /^__ARRAY_REF__/) {
5833: if (! ($string eq '' || !defined($string))) {
5834: $array[0]='Array reference error';
5835: }
5836: return (\@array, $string);
5837: }
5838:
5839: $string =~ s/^__ARRAY_REF__//;
5840:
5841: while($string !~ /^__END_ARRAY_REF__/) {
5842: my $value='';
5843: if($string =~ /^__HASH_REF__/) {
5844: ($value, $string)=&str2hashref($string);
5845: if(defined($value->{'error'})) {
5846: $array[0] ='Array reference error';
5847: return (\@array, $string);
5848: }
5849: } elsif($string =~ /^__ARRAY_REF__/) {
5850: ($value, $string)=&str2arrayref($string);
5851: if($value->[0] eq 'Array reference error') {
5852: $array[0] ='Array reference error';
5853: return (\@array, $string);
5854: }
5855: } else {
5856: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5857: }
5858: $string =~ s/^&//;
5859:
5860: push(@array, $value);
1.191 harris41 5861: }
1.265 albertel 5862:
5863: $string =~ s/^__END_ARRAY_REF__//;
5864:
5865: return (\@array, $string);
1.168 albertel 5866: }
5867:
1.167 albertel 5868: # -------------------------------------------------------------------Temp Store
5869:
1.168 albertel 5870: sub tmpreset {
5871: my ($symb,$namespace,$domain,$stuname) = @_;
5872: if (!$symb) {
5873: $symb=&symbread();
1.620 albertel 5874: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5875: }
5876: $symb=escape($symb);
5877:
1.620 albertel 5878: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5879: $namespace=~s/\//\_/g;
5880: $namespace=~s/\W//g;
5881:
1.620 albertel 5882: if (!$domain) { $domain=$env{'user.domain'}; }
5883: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5884: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 5885: $stuname=&get_requestor_ip();
1.591 albertel 5886: }
1.1117 foxr 5887: my $path=LONCAPA::tempdir();
1.168 albertel 5888: my %hash;
5889: if (tie(%hash,'GDBM_File',
5890: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5891: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5892: foreach my $key (keys(%hash)) {
1.180 albertel 5893: if ($key=~ /:$symb/) {
1.168 albertel 5894: delete($hash{$key});
5895: }
5896: }
5897: }
5898: }
5899:
1.167 albertel 5900: sub tmpstore {
1.168 albertel 5901: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5902:
5903: if (!$symb) {
5904: $symb=&symbread();
1.620 albertel 5905: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5906: }
5907: $symb=escape($symb);
5908:
5909: if (!$namespace) {
5910: # I don't think we would ever want to store this for a course.
5911: # it seems this will only be used if we don't have a course.
1.620 albertel 5912: #$namespace=$env{'request.course.id'};
1.168 albertel 5913: #if (!$namespace) {
1.620 albertel 5914: $namespace=$env{'request.state'};
1.168 albertel 5915: #}
5916: }
5917: $namespace=~s/\//\_/g;
5918: $namespace=~s/\W//g;
1.620 albertel 5919: if (!$domain) { $domain=$env{'user.domain'}; }
5920: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5921: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 5922: $stuname=&get_requestor_ip();
1.591 albertel 5923: }
1.168 albertel 5924: my $now=time;
5925: my %hash;
1.1117 foxr 5926: my $path=LONCAPA::tempdir();
1.168 albertel 5927: if (tie(%hash,'GDBM_File',
5928: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5929: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5930: $hash{"version:$symb"}++;
5931: my $version=$hash{"version:$symb"};
5932: my $allkeys='';
5933: foreach my $key (keys(%$storehash)) {
5934: $allkeys.=$key.':';
1.591 albertel 5935: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5936: }
5937: $hash{"$version:$symb:timestamp"}=$now;
5938: $allkeys.='timestamp';
5939: $hash{"$version:keys:$symb"}=$allkeys;
5940: if (untie(%hash)) {
5941: return 'ok';
5942: } else {
5943: return "error:$!";
5944: }
5945: } else {
5946: return "error:$!";
5947: }
5948: }
1.167 albertel 5949:
1.168 albertel 5950: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5951:
1.168 albertel 5952: sub tmprestore {
5953: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5954:
1.168 albertel 5955: if (!$symb) {
5956: $symb=&symbread();
1.620 albertel 5957: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5958: }
5959: $symb=escape($symb);
5960:
1.620 albertel 5961: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5962:
1.620 albertel 5963: if (!$domain) { $domain=$env{'user.domain'}; }
5964: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5965: if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138 raeburn 5966: $stuname=&get_requestor_ip();
1.591 albertel 5967: }
1.168 albertel 5968: my %returnhash;
5969: $namespace=~s/\//\_/g;
5970: $namespace=~s/\W//g;
5971: my %hash;
1.1117 foxr 5972: my $path=LONCAPA::tempdir();
1.168 albertel 5973: if (tie(%hash,'GDBM_File',
5974: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5975: &GDBM_READER(),0640)) {
1.168 albertel 5976: my $version=$hash{"version:$symb"};
5977: $returnhash{'version'}=$version;
5978: my $scope;
5979: for ($scope=1;$scope<=$version;$scope++) {
5980: my $vkeys=$hash{"$scope:keys:$symb"};
5981: my @keys=split(/:/,$vkeys);
5982: my $key;
5983: $returnhash{"$scope:keys"}=$vkeys;
5984: foreach $key (@keys) {
1.591 albertel 5985: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5986: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5987: }
5988: }
1.168 albertel 5989: if (!(untie(%hash))) {
5990: return "error:$!";
5991: }
5992: } else {
5993: return "error:$!";
5994: }
5995: return %returnhash;
1.167 albertel 5996: }
5997:
1.9 www 5998: # ----------------------------------------------------------------------- Store
5999:
6000: sub store {
1.1172.2.64 raeburn 6001: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6002: my $home='';
6003:
1.168 albertel 6004: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6005:
1.213 www 6006: $symb=&symbclean($symb);
1.122 albertel 6007: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6008:
1.620 albertel 6009: if (!$domain) { $domain=$env{'user.domain'}; }
6010: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6011:
6012: &devalidate($symb,$stuname,$domain);
1.109 www 6013:
6014: $symb=escape($symb);
1.187 www 6015: if (!$namespace) {
1.620 albertel 6016: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6017: return '';
6018: }
6019: }
1.620 albertel 6020: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6021:
1.1172.2.138 raeburn 6022: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6023: $$storehash{'host'}=$perlvar{'lonHostID'};
6024:
1.12 www 6025: my $namevalue='';
1.800 albertel 6026: foreach my $key (keys(%$storehash)) {
6027: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6028: }
1.12 www 6029: $namevalue=~s/\&$//;
1.187 www 6030: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64 raeburn 6031: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 6032: }
6033:
1.47 www 6034: # -------------------------------------------------------------- Critical Store
6035:
6036: sub cstore {
1.1172.2.64 raeburn 6037: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 6038: my $home='';
6039:
1.168 albertel 6040: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6041:
1.213 www 6042: $symb=&symbclean($symb);
1.122 albertel 6043: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 6044:
1.620 albertel 6045: if (!$domain) { $domain=$env{'user.domain'}; }
6046: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 6047:
6048: &devalidate($symb,$stuname,$domain);
1.109 www 6049:
6050: $symb=escape($symb);
1.187 www 6051: if (!$namespace) {
1.620 albertel 6052: unless ($namespace=$env{'request.course.id'}) {
1.187 www 6053: return '';
6054: }
6055: }
1.620 albertel 6056: if (!$home) { $home=$env{'user.home'}; }
1.447 www 6057:
1.1172.2.138 raeburn 6058: $$storehash{'ip'}=&get_requestor_ip();
1.447 www 6059: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 6060:
1.47 www 6061: my $namevalue='';
1.800 albertel 6062: foreach my $key (keys(%$storehash)) {
6063: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 6064: }
1.47 www 6065: $namevalue=~s/\&$//;
1.187 www 6066: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 6067: return critical
1.1172.2.64 raeburn 6068: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 6069: }
6070:
1.9 www 6071: # --------------------------------------------------------------------- Restore
6072:
6073: sub restore {
1.124 www 6074: my ($symb,$namespace,$domain,$stuname) = @_;
6075: my $home='';
6076:
1.168 albertel 6077: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 6078:
1.122 albertel 6079: if (!$symb) {
1.1172.2.26 raeburn 6080: return if ($namespace eq 'courserequests');
6081: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 6082: } else {
1.1172.2.26 raeburn 6083: unless ($namespace eq 'courserequests') {
6084: $symb=&escape(&symbclean($symb));
6085: }
1.122 albertel 6086: }
1.188 www 6087: if (!$namespace) {
1.620 albertel 6088: unless ($namespace=$env{'request.course.id'}) {
1.188 www 6089: return '';
6090: }
6091: }
1.620 albertel 6092: if (!$domain) { $domain=$env{'user.domain'}; }
6093: if (!$stuname) { $stuname=$env{'user.name'}; }
6094: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 6095: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6096:
1.12 www 6097: my %returnhash=();
1.800 albertel 6098: foreach my $line (split(/\&/,$answer)) {
6099: my ($name,$value)=split(/\=/,$line);
1.591 albertel 6100: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 6101: }
1.75 www 6102: my $version;
6103: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 6104: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6105: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 6106: }
1.75 www 6107: }
1.13 www 6108: return %returnhash;
1.34 www 6109: }
6110:
6111: # ---------------------------------------------------------- Course Description
1.1118 foxr 6112: #
6113: #
1.34 www 6114:
6115: sub coursedescription {
1.731 albertel 6116: my ($courseid,$args)=@_;
1.34 www 6117: $courseid=~s/^\///;
1.49 www 6118: $courseid=~s/\_/\//g;
1.34 www 6119: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 6120: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 6121: my $normalid=$cdomain.'_'.$cnum;
6122: # need to always cache even if we get errors otherwise we keep
6123: # trying and trying and trying to get the course description.
6124: my %envhash=();
6125: my %returnhash=();
1.731 albertel 6126:
6127: my $expiretime=600;
6128: if ($env{'request.course.id'} eq $normalid) {
6129: $expiretime=120;
6130: }
6131:
6132: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6133: if (!$args->{'freshen_cache'}
6134: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6135: foreach my $key (keys(%env)) {
6136: next if ($key !~ /^\Q$prefix\E(.*)/);
6137: my ($setting) = $1;
6138: $returnhash{$setting} = $env{$key};
6139: }
6140: return %returnhash;
6141: }
6142:
1.1118 foxr 6143: # get the data again
6144:
1.731 albertel 6145: if (!$args->{'one_time'}) {
6146: $envhash{'course.'.$normalid.'.last_cache'}=time;
6147: }
1.811 albertel 6148:
1.34 www 6149: if ($chome ne 'no_host') {
1.302 albertel 6150: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 6151: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 6152: my $username = $env{'user.name'}; # Defult username
6153: if(defined $args->{'user'}) {
6154: $username = $args->{'user'};
6155: }
1.129 albertel 6156: $returnhash{'home'}= $chome;
6157: $returnhash{'domain'} = $cdomain;
6158: $returnhash{'num'} = $cnum;
1.741 raeburn 6159: if (!defined($returnhash{'type'})) {
6160: $returnhash{'type'} = 'Course';
6161: }
1.130 albertel 6162: while (my ($name,$value) = each %returnhash) {
1.53 www 6163: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 6164: }
1.270 www 6165: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 6166: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 6167: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 6168: $envhash{'course.'.$normalid.'.home'}=$chome;
6169: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6170: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 6171: }
6172: }
1.731 albertel 6173: if (!$args->{'one_time'}) {
1.949 raeburn 6174: &appenv(\%envhash);
1.731 albertel 6175: }
1.302 albertel 6176: return %returnhash;
1.461 www 6177: }
6178:
1.1080 raeburn 6179: sub update_released_required {
6180: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6181: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6182: $cid = $env{'request.course.id'};
6183: $cdom = $env{'course.'.$cid.'.domain'};
6184: $cnum = $env{'course.'.$cid.'.num'};
6185: $chome = $env{'course.'.$cid.'.home'};
6186: }
6187: if ($needsrelease) {
6188: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6189: my $needsupdate;
6190: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6191: $needsupdate = 1;
6192: } else {
6193: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6194: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6195: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6196: $needsupdate = 1;
6197: }
6198: }
6199: if ($needsupdate) {
6200: my %needshash = (
6201: 'internal.releaserequired' => $needsrelease,
6202: );
6203: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6204: if ($putresult eq 'ok') {
6205: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6206: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6207: if (ref($crsinfo{$cid}) eq 'HASH') {
6208: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6209: &courseidput($cdom,\%crsinfo,$chome,'notime');
6210: }
6211: }
6212: }
6213: }
6214: return;
6215: }
6216:
1.461 www 6217: # -------------------------------------------------See if a user is privileged
6218:
6219: sub privileged {
1.1172.2.23 raeburn 6220: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 6221: my $now = time;
1.1172.2.23 raeburn 6222: my $roles;
6223: if (ref($possroles) eq 'ARRAY') {
6224: $roles = $possroles;
6225: } else {
6226: $roles = ['dc','su'];
6227: }
6228: if (ref($possdomains) eq 'ARRAY') {
6229: my %privileged = &privileged_by_domain($possdomains,$roles);
6230: foreach my $dom (@{$possdomains}) {
6231: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6232: (ref($privileged{$dom}) eq 'HASH')) {
6233: foreach my $role (@{$roles}) {
6234: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6235: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6236: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6237: return 1 unless (($end && $end < $now) ||
6238: ($start && $start > $now));
6239: }
6240: }
6241: }
6242: }
6243: }
6244: } else {
6245: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6246: my $now = time;
1.1170 droeschl 6247:
1.1172.2.58 raeburn 6248: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 6249: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23 raeburn 6250: if (grep(/^\Q$trole\E$/,@{$roles})) {
6251: return 1 unless ($tend && $tend < $now)
6252: or ($tstart && $tstart > $now);
1.1170 droeschl 6253: }
1.1172.2.23 raeburn 6254: }
6255: }
1.461 www 6256: return 0;
1.9 www 6257: }
1.1 albertel 6258:
1.1172.2.23 raeburn 6259: sub privileged_by_domain {
6260: my ($domains,$roles) = @_;
6261: my %privileged = ();
6262: my $cachetime = 60*60*24;
6263: my $now = time;
6264: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6265: return %privileged;
6266: }
6267: foreach my $dom (@{$domains}) {
6268: next if (ref($privileged{$dom}) eq 'HASH');
6269: my $needroles;
6270: foreach my $role (@{$roles}) {
6271: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6272: if (defined($cached)) {
6273: if (ref($result) eq 'HASH') {
6274: $privileged{$dom}{$role} = $result;
6275: }
6276: } else {
6277: $needroles = 1;
6278: }
6279: }
6280: if ($needroles) {
6281: my %dompersonnel = &get_domain_roles($dom,$roles);
6282: $privileged{$dom} = {};
6283: foreach my $server (keys(%dompersonnel)) {
6284: if (ref($dompersonnel{$server}) eq 'HASH') {
6285: foreach my $item (keys(%{$dompersonnel{$server}})) {
6286: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6287: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6288: next if ($end && $end < $now);
6289: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6290: $dompersonnel{$server}{$item};
6291: }
6292: }
6293: }
6294: if (ref($privileged{$dom}) eq 'HASH') {
6295: foreach my $role (@{$roles}) {
6296: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6297: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6298: } else {
6299: my %hash = ();
6300: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6301: }
6302: }
6303: }
6304: }
6305: }
6306: return %privileged;
6307: }
6308:
1.103 harris41 6309: # -------------------------------------------------------- Get user privileges
1.11 www 6310:
6311: sub rolesinit {
1.1169 droeschl 6312: my ($domain, $username) = @_;
6313: my %userroles = ('user.login.time' => time);
6314: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6315:
6316: # firstaccess and timerinterval are related to timed maps/resources.
6317: # also, blocking can be triggered by an activating timer
6318: # it's saved in the user's %env.
6319: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6320: my %timerinterval = &dump('timerinterval', $domain, $username);
6321: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6322: %timerintchk, %timerintenv);
6323:
1.1162 raeburn 6324: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 6325: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 6326: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6327: }
1.1169 droeschl 6328:
1.1162 raeburn 6329: foreach my $key (keys(%timerinterval)) {
6330: my ($cid,$rest) = split(/\0/,$key);
6331: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6332: }
1.1169 droeschl 6333:
1.11 www 6334: my %allroles=();
1.1162 raeburn 6335: my %allgroups=();
1.11 www 6336:
1.1172.2.58 raeburn 6337: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 6338: my $role = $rolesdump{$area};
6339: $area =~ s/\_\w\w$//;
6340:
6341: my ($trole, $tend, $tstart, $group_privs);
6342:
6343: if ($role =~ /^cr/) {
6344: # Custom role, defined by a user
6345: # e.g., user.role.cr/msu/smith/mynewrole
6346: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6347: $trole = $1;
6348: ($tend, $tstart) = split('_', $2);
6349: } else {
6350: $trole = $role;
6351: }
6352: } elsif ($role =~ m|^gr/|) {
6353: # Role of member in a group, defined within a course/community
6354: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6355: ($trole, $tend, $tstart) = split(/_/, $role);
6356: next if $tstart eq '-1';
6357: ($trole, $group_privs) = split(/\//, $trole);
6358: $group_privs = &unescape($group_privs);
6359: } else {
6360: # Just a normal role, defined in roles.tab
6361: ($trole, $tend, $tstart) = split(/_/,$role);
6362: }
6363:
6364: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6365: $username);
6366: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6367:
6368: # role expired or not available yet?
6369: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6370: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6371:
6372: next if $area eq '' or $trole eq '';
6373:
6374: my $spec = "$trole.$area";
6375: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6376:
6377: if ($trole =~ /^cr\//) {
6378: # Custom role, defined by a user
6379: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6380: } elsif ($trole eq 'gr') {
6381: # Role of a member in a group, defined within a course/community
6382: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6383: next;
6384: } else {
6385: # Normal role, defined in roles.tab
6386: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6387: }
6388:
6389: my $cid = $tdomain.'_'.$trest;
6390: unless ($firstaccchk{$cid}) {
6391: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6392: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6393: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6394: $coursetimerstarts{$cid}{$item};
6395: }
6396: }
6397: $firstaccchk{$cid} = 1;
6398: }
6399: unless ($timerintchk{$cid}) {
6400: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6401: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6402: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6403: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 6404: }
1.12 www 6405: }
1.1169 droeschl 6406: $timerintchk{$cid} = 1;
1.191 harris41 6407: }
1.11 www 6408: }
1.1169 droeschl 6409:
1.1172.2.91 raeburn 6410: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6411: \%allroles, \%allgroups);
1.1169 droeschl 6412: $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91 raeburn 6413: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 6414:
1.1162 raeburn 6415: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6416: }
6417:
1.567 raeburn 6418: sub set_arearole {
1.1172.2.19 raeburn 6419: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6420: unless ($nolog) {
1.567 raeburn 6421: # log the associated role with the area
1.1172.2.19 raeburn 6422: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6423: }
1.743 albertel 6424: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6425: }
6426:
6427: sub custom_roleprivs {
6428: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6429: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40 raeburn 6430: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6431: if (&hostname($homsvr) ne '') {
1.567 raeburn 6432: my ($rdummy,$roledef)=
6433: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6434: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6435: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6436: if (defined($syspriv)) {
1.1043 raeburn 6437: if ($trest =~ /^$match_community$/) {
6438: $syspriv =~ s/bre\&S//;
6439: }
1.567 raeburn 6440: $$allroles{'cm./'}.=':'.$syspriv;
6441: $$allroles{$spec.'./'}.=':'.$syspriv;
6442: }
6443: if ($tdomain ne '') {
6444: if (defined($dompriv)) {
6445: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6446: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6447: }
6448: if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89 raeburn 6449: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6450: my $rolename = $1;
6451: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6452: }
1.567 raeburn 6453: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6454: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6455: }
6456: }
6457: }
6458: }
6459: }
6460:
1.1172.2.89 raeburn 6461: sub course_adhocrole_privs {
6462: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6463: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6464: if ($overrides{"internal.adhocpriv.$rolename"}) {
6465: my (%currprivs,%storeprivs);
6466: foreach my $item (split(/:/,$coursepriv)) {
6467: my ($priv,$restrict) = split(/\&/,$item);
6468: $currprivs{$priv} = $restrict;
6469: }
6470: my (%possadd,%possremove,%full);
6471: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6472: my ($priv,$restrict)=split(/\&/,$item);
6473: $full{$priv} = $restrict;
6474: }
6475: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6476: next if ($item eq '');
6477: my ($rule,$rest) = split(/=/,$item);
6478: next unless (($rule eq 'off') || ($rule eq 'on'));
6479: foreach my $priv (split(/:/,$rest)) {
6480: if ($priv ne '') {
6481: if ($rule eq 'off') {
6482: $possremove{$priv} = 1;
6483: } else {
6484: $possadd{$priv} = 1;
6485: }
6486: }
6487: }
6488: }
6489: foreach my $priv (sort(keys(%full))) {
6490: if (exists($currprivs{$priv})) {
6491: unless (exists($possremove{$priv})) {
6492: $storeprivs{$priv} = $currprivs{$priv};
6493: }
6494: } elsif (exists($possadd{$priv})) {
6495: $storeprivs{$priv} = $full{$priv};
6496: }
6497: }
6498: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6499: }
6500: return $coursepriv;
6501: }
6502:
1.678 raeburn 6503: sub group_roleprivs {
6504: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6505: my $access = 1;
6506: my $now = time;
6507: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6508: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6509: if ($access) {
1.811 albertel 6510: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6511: $$allgroups{$course}{$group} .=':'.$group_privs;
6512: }
6513: }
1.567 raeburn 6514:
6515: sub standard_roleprivs {
6516: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6517: if (defined($pr{$trole.':s'})) {
6518: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6519: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6520: }
6521: if ($tdomain ne '') {
6522: if (defined($pr{$trole.':d'})) {
6523: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6524: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6525: }
6526: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6527: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6528: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6529: }
6530: }
6531: }
6532:
6533: sub set_userprivs {
1.1064 raeburn 6534: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6535: my $author=0;
6536: my $adv=0;
1.1172.2.91 raeburn 6537: my $rar=0;
1.678 raeburn 6538: my %grouproles = ();
6539: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6540: my @groupkeys;
1.1000 raeburn 6541: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6542: push(@groupkeys,$role);
6543: }
6544: if (ref($groups_roles) eq 'HASH') {
6545: foreach my $key (keys(%{$groups_roles})) {
6546: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6547: push(@groupkeys,$key);
6548: }
6549: }
6550: }
6551: if (@groupkeys > 0) {
6552: foreach my $role (@groupkeys) {
6553: my ($trole,$area,$sec,$extendedarea);
6554: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6555: $trole = $1;
6556: $area = $2;
6557: $sec = $3;
6558: $extendedarea = $area.$sec;
6559: if (exists($$allgroups{$area})) {
6560: foreach my $group (keys(%{$$allgroups{$area}})) {
6561: my $spec = $trole.'.'.$extendedarea;
6562: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6563: $$allgroups{$area}{$group};
1.1064 raeburn 6564: }
1.678 raeburn 6565: }
6566: }
6567: }
6568: }
6569: }
1.800 albertel 6570: foreach my $group (keys(%grouproles)) {
6571: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6572: }
1.800 albertel 6573: foreach my $role (keys(%{$allroles})) {
6574: my %thesepriv;
1.941 raeburn 6575: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6576: foreach my $item (split(/:/,$$allroles{$role})) {
6577: if ($item ne '') {
6578: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 6579: if ($restrictions eq '') {
6580: $thesepriv{$privilege}='F';
6581: } elsif ($thesepriv{$privilege} ne 'F') {
6582: $thesepriv{$privilege}.=$restrictions;
6583: }
6584: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91 raeburn 6585: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 6586: }
6587: }
6588: my $thesestr='';
1.1104 raeburn 6589: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 6590: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6591: }
6592: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 6593: }
1.1172.2.91 raeburn 6594: return ($author,$adv,$rar);
1.567 raeburn 6595: }
6596:
1.994 raeburn 6597: sub role_status {
1.1104 raeburn 6598: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 6599: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40 raeburn 6600: my ($one,$two) = split(m{\./},$rolekey,2);
6601: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 6602: unless (!defined($$role) || $$role eq '') {
1.1172.2.40 raeburn 6603: $$where = '/'.$two;
1.994 raeburn 6604: $$trolecode=$$role.'.'.$$where;
6605: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6606: $$tstatus='is';
1.1104 raeburn 6607: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6608: $$tstatus='future';
1.1034 raeburn 6609: if ($$tstart<$now) {
6610: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6611: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6612: my (%allroles,%allgroups,$group_privs,
6613: %groups_roles,@rolecodes);
1.1002 raeburn 6614: my %userroles = (
6615: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6616: );
1.1064 raeburn 6617: @rolecodes = ('cm');
1.1002 raeburn 6618: my $spec=$$role.'.'.$$where;
6619: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6620: if ($$role =~ /^cr\//) {
6621: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6622: push(@rolecodes,'cr');
1.1002 raeburn 6623: } elsif ($$role eq 'gr') {
1.1064 raeburn 6624: push(@rolecodes,$$role);
1.1002 raeburn 6625: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6626: $env{'user.name'});
1.1064 raeburn 6627: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6628: (undef,my $group_privs) = split(/\//,$trole);
6629: $group_privs = &unescape($group_privs);
6630: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6631: 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 6632: &get_groups_roles($tdomain,$trest,
6633: \%course_roles,\@rolecodes,
6634: \%groups_roles);
1.1002 raeburn 6635: } else {
1.1064 raeburn 6636: push(@rolecodes,$$role);
1.1002 raeburn 6637: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6638: }
1.1172.2.91 raeburn 6639: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6640: \%groups_roles);
1.1064 raeburn 6641: &appenv(\%userroles,\@rolecodes);
1.1172.2.92 raeburn 6642: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 6643: }
6644: }
1.1034 raeburn 6645: $$tstatus = 'is';
1.1002 raeburn 6646: }
1.994 raeburn 6647: }
6648: if ($$tend) {
1.1104 raeburn 6649: if ($$tend<$update) {
1.994 raeburn 6650: $$tstatus='expired';
6651: } elsif ($$tend<$now) {
6652: $$tstatus='will_not';
6653: }
6654: }
6655: }
6656: }
6657: }
6658:
1.1104 raeburn 6659: sub get_groups_roles {
6660: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6661: return unless((ref($cdom_courseroles) eq 'HASH') &&
6662: (ref($rolecodes) eq 'ARRAY') &&
6663: (ref($groups_roles) eq 'HASH'));
6664: if (keys(%{$cdom_courseroles}) > 0) {
6665: my ($cnum) = ($rest =~ /^($match_courseid)/);
6666: if ($cdom ne '' && $cnum ne '') {
6667: foreach my $key (keys(%{$cdom_courseroles})) {
6668: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6669: my $crsrole = $1;
6670: my $crssec = $2;
6671: if ($crsrole =~ /^cr/) {
6672: unless (grep(/^cr$/,@{$rolecodes})) {
6673: push(@{$rolecodes},'cr');
6674: }
6675: } else {
6676: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6677: push(@{$rolecodes},$crsrole);
6678: }
6679: }
6680: my $rolekey = "$crsrole./$cdom/$cnum";
6681: if ($crssec ne '') {
6682: $rolekey .= "/$crssec";
6683: }
6684: $rolekey .= './';
6685: $groups_roles->{$rolekey} = $rolecodes;
6686: }
6687: }
6688: }
6689: }
6690: return;
6691: }
6692:
6693: sub delete_env_groupprivs {
6694: my ($where,$courseroles,$possroles) = @_;
6695: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6696: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6697: unless (ref($courseroles->{$udom}) eq 'HASH') {
6698: %{$courseroles->{$udom}} =
6699: &get_my_roles('','','userroles',['active'],
6700: $possroles,[$udom],1);
6701: }
6702: if (ref($courseroles->{$udom}) eq 'HASH') {
6703: foreach my $item (keys(%{$courseroles->{$udom}})) {
6704: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6705: my $area = '/'.$cdom.'/'.$cnum;
6706: my $privkey = "user.priv.$crsrole.$area";
6707: if ($crssec ne '') {
6708: $privkey .= '/'.$crssec;
6709: }
6710: $privkey .= ".$area/$group";
6711: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6712: }
6713: }
6714: return;
6715: }
6716:
1.994 raeburn 6717: sub check_adhoc_privs {
1.1172.2.86 raeburn 6718: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6719: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86 raeburn 6720: if ($sec) {
6721: $cckey .= '/'.$sec;
6722: }
1.1172.2.9 raeburn 6723: my $setprivs;
1.994 raeburn 6724: if ($env{$cckey}) {
6725: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6726: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6727: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86 raeburn 6728: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6729: $setprivs = 1;
1.994 raeburn 6730: }
6731: } else {
1.1172.2.87 raeburn 6732: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9 raeburn 6733: $setprivs = 1;
1.994 raeburn 6734: }
1.1172.2.9 raeburn 6735: return $setprivs;
1.994 raeburn 6736: }
6737:
6738: sub set_adhoc_privileges {
1.1172.2.84 raeburn 6739: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86 raeburn 6740: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6741: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86 raeburn 6742: if ($sec ne '') {
6743: $area .= '/'.$sec;
6744: }
1.994 raeburn 6745: my $spec = $role.'.'.$area;
6746: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19 raeburn 6747: $env{'user.name'},1);
1.1172.2.84 raeburn 6748: my %rolehash = ();
1.1172.2.89 raeburn 6749: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6750: my $rolename = $1;
1.1172.2.84 raeburn 6751: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89 raeburn 6752: my %domdef = &get_domain_defaults($dcdom);
6753: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6754: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6755: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6756: }
6757: }
1.1172.2.84 raeburn 6758: } else {
6759: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6760: }
1.1172.2.91 raeburn 6761: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6762: &appenv(\%userroles,[$role,'cm']);
1.1172.2.92 raeburn 6763: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088 raeburn 6764: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6765: &appenv( {'request.role' => $spec,
6766: 'request.role.domain' => $dcdom,
1.1172.2.89 raeburn 6767: 'request.course.sec' => $sec,
1.1088 raeburn 6768: }
6769: );
6770: my $tadv=0;
6771: if (&allowed('adv') eq 'F') { $tadv=1; }
6772: &appenv({'request.role.adv' => $tadv});
6773: }
1.994 raeburn 6774: }
6775:
1.12 www 6776: # --------------------------------------------------------------- get interface
6777:
6778: sub get {
1.131 albertel 6779: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6780: my $items='';
1.800 albertel 6781: foreach my $item (@$storearr) {
6782: $items.=&escape($item).'&';
1.191 harris41 6783: }
1.12 www 6784: $items=~s/\&$//;
1.620 albertel 6785: if (!$udomain) { $udomain=$env{'user.domain'}; }
6786: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6787: my $uhome=&homeserver($uname,$udomain);
6788:
1.133 albertel 6789: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6790: my @pairs=split(/\&/,$rep);
1.273 albertel 6791: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6792: return @pairs;
6793: }
1.15 www 6794: my %returnhash=();
1.42 www 6795: my $i=0;
1.800 albertel 6796: foreach my $item (@$storearr) {
6797: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6798: $i++;
1.191 harris41 6799: }
1.15 www 6800: return %returnhash;
1.27 www 6801: }
6802:
6803: # --------------------------------------------------------------- del interface
6804:
6805: sub del {
1.133 albertel 6806: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6807: my $items='';
1.800 albertel 6808: foreach my $item (@$storearr) {
6809: $items.=&escape($item).'&';
1.191 harris41 6810: }
1.984 neumanie 6811:
1.27 www 6812: $items=~s/\&$//;
1.620 albertel 6813: if (!$udomain) { $udomain=$env{'user.domain'}; }
6814: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6815: my $uhome=&homeserver($uname,$udomain);
6816: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6817: }
6818:
6819: # -------------------------------------------------------------- dump interface
6820:
1.1172.2.22 raeburn 6821: sub unserialize {
6822: my ($rep, $escapedkeys) = @_;
6823:
6824: return {} if $rep =~ /^error/;
6825:
6826: my %returnhash=();
6827: foreach my $item (split(/\&/,$rep)) {
6828: my ($key, $value) = split(/=/, $item, 2);
6829: $key = unescape($key) unless $escapedkeys;
6830: next if $key =~ /^error: 2 /;
6831: $returnhash{$key} = &thaw_unescape($value);
6832: }
6833: return \%returnhash;
6834: }
6835:
6836: # see Lond::dump_with_regexp
6837: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6838: sub dump {
1.1172.2.22 raeburn 6839: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6840: if (!$udomain) { $udomain=$env{'user.domain'}; }
6841: if (!$uname) { $uname=$env{'user.name'}; }
6842: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6843:
1.1172.2.55 raeburn 6844: if ($regexp) {
6845: $regexp=&escape($regexp);
6846: } else {
6847: $regexp='.';
6848: }
1.1172.2.22 raeburn 6849: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
6850: # user is hosted on this machine
1.1172.2.55 raeburn 6851: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27 raeburn 6852: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22 raeburn 6853: return %{&unserialize($reply, $escapedkeys)};
6854: }
1.1166 raeburn 6855: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6856: my @pairs=split(/\&/,$rep);
6857: my %returnhash=();
1.1098 foxr 6858: if (!($rep =~ /^error/ )) {
6859: foreach my $item (@pairs) {
6860: my ($key,$value)=split(/=/,$item,2);
1.1172.2.22 raeburn 6861: $key = &unescape($key) unless ($escapedkeys);
1.1098 foxr 6862: next if ($key =~ /^error: 2 /);
6863: $returnhash{$key}=&thaw_unescape($value);
6864: }
1.755 albertel 6865: }
6866: return %returnhash;
1.407 www 6867: }
6868:
1.1098 foxr 6869:
1.717 albertel 6870: # --------------------------------------------------------- dumpstore interface
6871:
6872: sub dumpstore {
6873: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22 raeburn 6874: # same as dump but keys must be escaped. They may contain colon separated
6875: # lists of values that may themself contain colons (e.g. symbs).
6876: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6877: }
6878:
1.407 www 6879: # -------------------------------------------------------------- keys interface
6880:
6881: sub getkeys {
6882: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6883: if (!$udomain) { $udomain=$env{'user.domain'}; }
6884: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6885: my $uhome=&homeserver($uname,$udomain);
6886: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6887: my @keyarray=();
1.800 albertel 6888: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6889: next if ($key =~ /^error: 2 /);
1.800 albertel 6890: push(@keyarray,&unescape($key));
1.407 www 6891: }
6892: return @keyarray;
1.318 matthew 6893: }
6894:
1.319 matthew 6895: # --------------------------------------------------------------- currentdump
6896: sub currentdump {
1.328 matthew 6897: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6898: $courseid = $env{'request.course.id'} if (! defined($courseid));
6899: $sdom = $env{'user.domain'} if (! defined($sdom));
6900: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6901: my $uhome = &homeserver($sname,$sdom);
1.1172.2.50 raeburn 6902: my $rep;
6903:
6904: if (grep { $_ eq $uhome } current_machine_ids()) {
6905: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6906: $courseid)));
6907: } else {
6908: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6909: }
6910:
1.318 matthew 6911: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6912: #
1.318 matthew 6913: my %returnhash=();
1.319 matthew 6914: #
6915: if ($rep eq "unknown_cmd") {
6916: # an old lond will not know currentdump
6917: # Do a dump and make it look like a currentdump
1.822 albertel 6918: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6919: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6920: my %hash = @tmp;
6921: @tmp=();
1.424 matthew 6922: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6923: } else {
6924: my @pairs=split(/\&/,$rep);
1.800 albertel 6925: foreach my $pair (@pairs) {
6926: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6927: my ($symb,$param) = split(/:/,$key);
6928: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6929: &thaw_unescape($value);
1.319 matthew 6930: }
1.191 harris41 6931: }
1.12 www 6932: return %returnhash;
1.424 matthew 6933: }
6934:
6935: sub convert_dump_to_currentdump{
6936: my %hash = %{shift()};
6937: my %returnhash;
6938: # Code ripped from lond, essentially. The only difference
6939: # here is the unescaping done by lonnet::dump(). Conceivably
6940: # we might run in to problems with parameter names =~ /^v\./
6941: while (my ($key,$value) = each(%hash)) {
6942: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 6943: $symb = &unescape($symb);
6944: $param = &unescape($param);
1.424 matthew 6945: next if ($v eq 'version' || $symb eq 'keys');
6946: next if (exists($returnhash{$symb}) &&
6947: exists($returnhash{$symb}->{$param}) &&
6948: $returnhash{$symb}->{'v.'.$param} > $v);
6949: $returnhash{$symb}->{$param}=$value;
6950: $returnhash{$symb}->{'v.'.$param}=$v;
6951: }
6952: #
6953: # Remove all of the keys in the hashes which keep track of
6954: # the version of the parameter.
6955: while (my ($symb,$param_hash) = each(%returnhash)) {
6956: # use a foreach because we are going to delete from the hash.
6957: foreach my $key (keys(%$param_hash)) {
6958: delete($param_hash->{$key}) if ($key =~ /^v\./);
6959: }
6960: }
6961: return \%returnhash;
1.12 www 6962: }
6963:
1.627 albertel 6964: # ------------------------------------------------------ critical inc interface
6965:
6966: sub cinc {
6967: return &inc(@_,'critical');
6968: }
6969:
1.449 matthew 6970: # --------------------------------------------------------------- inc interface
6971:
6972: sub inc {
1.627 albertel 6973: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 6974: if (!$udomain) { $udomain=$env{'user.domain'}; }
6975: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 6976: my $uhome=&homeserver($uname,$udomain);
6977: my $items='';
6978: if (! ref($store)) {
6979: # got a single value, so use that instead
6980: $items = &escape($store).'=&';
6981: } elsif (ref($store) eq 'SCALAR') {
6982: $items = &escape($$store).'=&';
6983: } elsif (ref($store) eq 'ARRAY') {
6984: $items = join('=&',map {&escape($_);} @{$store});
6985: } elsif (ref($store) eq 'HASH') {
6986: while (my($key,$value) = each(%{$store})) {
6987: $items.= &escape($key).'='.&escape($value).'&';
6988: }
6989: }
6990: $items=~s/\&$//;
1.627 albertel 6991: if ($critical) {
6992: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6993: } else {
6994: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6995: }
1.449 matthew 6996: }
6997:
1.12 www 6998: # --------------------------------------------------------------- put interface
6999:
7000: sub put {
1.134 albertel 7001: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7002: if (!$udomain) { $udomain=$env{'user.domain'}; }
7003: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7004: my $uhome=&homeserver($uname,$udomain);
1.12 www 7005: my $items='';
1.800 albertel 7006: foreach my $item (keys(%$storehash)) {
7007: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7008: }
1.12 www 7009: $items=~s/\&$//;
1.134 albertel 7010: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 7011: }
7012:
1.631 albertel 7013: # ------------------------------------------------------------ newput interface
7014:
7015: sub newput {
7016: my ($namespace,$storehash,$udomain,$uname)=@_;
7017: if (!$udomain) { $udomain=$env{'user.domain'}; }
7018: if (!$uname) { $uname=$env{'user.name'}; }
7019: my $uhome=&homeserver($uname,$udomain);
7020: my $items='';
7021: foreach my $key (keys(%$storehash)) {
7022: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7023: }
7024: $items=~s/\&$//;
7025: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7026: }
7027:
7028: # --------------------------------------------------------- putstore interface
7029:
1.524 raeburn 7030: sub putstore {
1.1172.2.59 raeburn 7031: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 7032: if (!$udomain) { $udomain=$env{'user.domain'}; }
7033: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 7034: my $uhome=&homeserver($uname,$udomain);
7035: my $items='';
1.715 albertel 7036: foreach my $key (keys(%$storehash)) {
7037: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 7038: }
1.715 albertel 7039: $items=~s/\&$//;
1.716 albertel 7040: my $esc_symb=&escape($symb);
7041: my $esc_v=&escape($version);
1.715 albertel 7042: my $reply =
1.716 albertel 7043: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 7044: $uhome);
1.1172.2.59 raeburn 7045: if (($tolog) && ($reply eq 'ok')) {
7046: my $namevalue='';
7047: foreach my $key (keys(%{$storehash})) {
7048: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7049: }
1.1172.2.134 raeburn 7050: my $ip = &get_requestor_ip();
1.1172.2.135 raeburn 7051: $namevalue .= 'ip='.&escape($ip).
1.1172.2.59 raeburn 7052: '&host='.&escape($perlvar{'lonHostID'}).
7053: '&version='.$esc_v.
7054: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7055: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7056: }
1.715 albertel 7057: if ($reply eq 'unknown_cmd') {
1.716 albertel 7058: # gfall back to way things use to be done
1.715 albertel 7059: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7060: $uname);
1.524 raeburn 7061: }
1.715 albertel 7062: return $reply;
7063: }
7064:
7065: sub old_putstore {
1.716 albertel 7066: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7067: if (!$udomain) { $udomain=$env{'user.domain'}; }
7068: if (!$uname) { $uname=$env{'user.name'}; }
7069: my $uhome=&homeserver($uname,$udomain);
7070: my %newstorehash;
1.800 albertel 7071: foreach my $item (keys(%$storehash)) {
7072: my $key = $version.':'.&escape($symb).':'.$item;
7073: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 7074: }
7075: my $items='';
7076: my %allitems = ();
1.800 albertel 7077: foreach my $item (keys(%newstorehash)) {
7078: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 7079: my $key = $1.':keys:'.$2;
7080: $allitems{$key} .= $3.':';
7081: }
1.800 albertel 7082: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 7083: }
1.800 albertel 7084: foreach my $item (keys(%allitems)) {
7085: $allitems{$item} =~ s/\:$//;
7086: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 7087: }
7088: $items=~s/\&$//;
7089: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 7090: }
7091:
1.47 www 7092: # ------------------------------------------------------ critical put interface
7093:
7094: sub cput {
1.134 albertel 7095: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 7096: if (!$udomain) { $udomain=$env{'user.domain'}; }
7097: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 7098: my $uhome=&homeserver($uname,$udomain);
1.47 www 7099: my $items='';
1.800 albertel 7100: foreach my $item (keys(%$storehash)) {
7101: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 7102: }
1.47 www 7103: $items=~s/\&$//;
1.134 albertel 7104: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7105: }
7106:
7107: # -------------------------------------------------------------- eget interface
7108:
7109: sub eget {
1.133 albertel 7110: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 7111: my $items='';
1.800 albertel 7112: foreach my $item (@$storearr) {
7113: $items.=&escape($item).'&';
1.191 harris41 7114: }
1.12 www 7115: $items=~s/\&$//;
1.620 albertel 7116: if (!$udomain) { $udomain=$env{'user.domain'}; }
7117: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 7118: my $uhome=&homeserver($uname,$udomain);
7119: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 7120: my @pairs=split(/\&/,$rep);
7121: my %returnhash=();
1.42 www 7122: my $i=0;
1.800 albertel 7123: foreach my $item (@$storearr) {
7124: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 7125: $i++;
1.191 harris41 7126: }
1.12 www 7127: return %returnhash;
7128: }
7129:
1.667 albertel 7130: # ------------------------------------------------------------ tmpput interface
7131: sub tmpput {
1.802 raeburn 7132: my ($storehash,$server,$context)=@_;
1.667 albertel 7133: my $items='';
1.800 albertel 7134: foreach my $item (keys(%$storehash)) {
7135: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 7136: }
7137: $items=~s/\&$//;
1.802 raeburn 7138: if (defined($context)) {
7139: $items .= ':'.&escape($context);
7140: }
1.667 albertel 7141: return &reply("tmpput:$items",$server);
7142: }
7143:
7144: # ------------------------------------------------------------ tmpget interface
7145: sub tmpget {
1.688 albertel 7146: my ($token,$server)=@_;
7147: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7148: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 7149: my %returnhash;
1.1172.2.85 raeburn 7150: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7151: return %returnhash;
7152: }
1.667 albertel 7153: foreach my $item (split(/\&/,$rep)) {
7154: my ($key,$value)=split(/=/,$item);
7155: $returnhash{&unescape($key)}=&thaw_unescape($value);
7156: }
7157: return %returnhash;
7158: }
7159:
1.1113 raeburn 7160: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 7161: sub tmpdel {
7162: my ($token,$server)=@_;
7163: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7164: return &reply("tmpdel:$token",$server);
7165: }
7166:
1.1172.2.13 raeburn 7167: # ------------------------------------------------------------ get_timebased_id
7168:
7169: sub get_timebased_id {
7170: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7171: $maxtries) = @_;
7172: my ($newid,$error,$dellock);
7173: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7174: return ('','ok','invalid call to get suffix');
7175: }
7176:
7177: # set defaults for any optional args for which values were not supplied
7178: if ($who eq '') {
7179: $who = $env{'user.name'}.':'.$env{'user.domain'};
7180: }
7181: if (!$locktries) {
7182: $locktries = 3;
7183: }
7184: if (!$maxtries) {
7185: $maxtries = 10;
7186: }
7187:
7188: if (($cdom eq '') || ($cnum eq '')) {
7189: if ($env{'request.course.id'}) {
7190: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7191: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7192: }
7193: if (($cdom eq '') || ($cnum eq '')) {
7194: return ('','ok','call to get suffix not in course context');
7195: }
7196: }
7197:
7198: # construct locking item
7199: my $lockhash = {
7200: $prefix."\0".'locked_'.$keyid => $who,
7201: };
7202: my $tries = 0;
7203:
7204: # attempt to get lock on nohist_$namespace file
7205: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7206: while (($gotlock ne 'ok') && $tries <$locktries) {
7207: $tries ++;
7208: sleep 1;
7209: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7210: }
7211:
7212: # attempt to get unique identifier, based on current timestamp
7213: if ($gotlock eq 'ok') {
7214: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7215: my $id = time;
7216: $newid = $id;
1.1172.2.56 raeburn 7217: if ($idtype eq 'addcode') {
7218: $newid .= &sixnum_code();
7219: }
1.1172.2.13 raeburn 7220: my $idtries = 0;
7221: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7222: if ($idtype eq 'concat') {
7223: $newid = $id.$idtries;
1.1172.2.56 raeburn 7224: } elsif ($idtype eq 'addcode') {
7225: $newid = $newid.&sixnum_code();
1.1172.2.13 raeburn 7226: } else {
7227: $newid ++;
7228: }
7229: $idtries ++;
7230: }
7231: if (!exists($inuse{$prefix."\0".$newid})) {
7232: my %new_item = (
7233: $prefix."\0".$newid => $who,
7234: );
7235: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7236: $cdom,$cnum);
7237: if ($putresult ne 'ok') {
7238: undef($newid);
7239: $error = 'error saving new item: '.$putresult;
7240: }
7241: } else {
1.1172.2.56 raeburn 7242: undef($newid);
1.1172.2.13 raeburn 7243: $error = ('error: no unique suffix available for the new item ');
7244: }
7245: # remove lock
7246: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7247: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7248: } else {
7249: $error = "error: could not obtain lockfile\n";
7250: $dellock = 'ok';
1.1172.2.58 raeburn 7251: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7252: $dellock = 'nolock';
7253: }
1.1172.2.13 raeburn 7254: }
7255: return ($newid,$dellock,$error);
7256: }
7257:
1.1172.2.56 raeburn 7258: sub sixnum_code {
7259: my $code;
7260: for (0..6) {
7261: $code .= int( rand(9) );
7262: }
7263: return $code;
7264: }
7265:
1.765 albertel 7266: # -------------------------------------------------- portfolio access checking
7267:
7268: sub portfolio_access {
1.1172.2.77 raeburn 7269: my ($requrl,$clientip) = @_;
1.765 albertel 7270: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77 raeburn 7271: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 7272: if ($result) {
7273: my %setters;
7274: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7275: my ($startblock,$endblock) =
7276: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
7277: if ($startblock && $endblock) {
7278: return 'B';
7279: }
7280: } else {
7281: my ($startblock,$endblock) =
7282: &Apache::loncommon::blockcheck(\%setters,'port');
7283: if ($startblock && $endblock) {
7284: return 'B';
7285: }
7286: }
7287: }
1.765 albertel 7288: if ($result eq 'ok') {
1.766 albertel 7289: return 'F';
1.765 albertel 7290: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 7291: return 'A';
1.765 albertel 7292: }
1.766 albertel 7293: return '';
1.765 albertel 7294: }
7295:
7296: sub get_portfolio_access {
1.1172.2.77 raeburn 7297: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 7298:
7299: if (!ref($access_hash)) {
7300: my $current_perms = &get_portfile_permissions($udom,$unum);
7301: my %access_controls = &get_access_controls($current_perms,$group,
7302: $file_name);
7303: $access_hash = $access_controls{$file_name};
7304: }
7305:
1.1172.2.77 raeburn 7306: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 7307: my $now = time;
7308: if (ref($access_hash) eq 'HASH') {
7309: foreach my $key (keys(%{$access_hash})) {
7310: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7311: if ($start > $now) {
7312: next;
7313: }
7314: if ($end && $end<$now) {
7315: next;
7316: }
7317: if ($scope eq 'public') {
7318: $public = $key;
7319: last;
7320: } elsif ($scope eq 'guest') {
7321: $guest = $key;
7322: } elsif ($scope eq 'domains') {
7323: push(@domains,$key);
7324: } elsif ($scope eq 'users') {
7325: push(@users,$key);
7326: } elsif ($scope eq 'course') {
7327: push(@courses,$key);
7328: } elsif ($scope eq 'group') {
7329: push(@groups,$key);
1.1172.2.77 raeburn 7330: } elsif ($scope eq 'ip') {
7331: push(@ips,$key);
1.765 albertel 7332: }
7333: }
7334: if ($public) {
7335: return 'ok';
1.1172.2.77 raeburn 7336: } elsif (@ips > 0) {
7337: my $allowed;
7338: foreach my $ipkey (@ips) {
7339: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7340: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7341: $allowed = 1;
7342: last;
7343: }
7344: }
7345: }
7346: if ($allowed) {
7347: return 'ok';
7348: }
1.765 albertel 7349: }
7350: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7351: if ($guest) {
7352: return $guest;
7353: }
7354: } else {
7355: if (@domains > 0) {
7356: foreach my $domkey (@domains) {
7357: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7358: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7359: return 'ok';
7360: }
7361: }
7362: }
7363: }
7364: if (@users > 0) {
7365: foreach my $userkey (@users) {
1.865 raeburn 7366: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7367: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7368: if (ref($item) eq 'HASH') {
7369: if (($item->{'uname'} eq $env{'user.name'}) &&
7370: ($item->{'udom'} eq $env{'user.domain'})) {
7371: return 'ok';
7372: }
7373: }
7374: }
7375: }
1.765 albertel 7376: }
7377: }
7378: my %roleshash;
7379: my @courses_and_groups = @courses;
7380: push(@courses_and_groups,@groups);
7381: if (@courses_and_groups > 0) {
7382: my (%allgroups,%allroles);
7383: my ($start,$end,$role,$sec,$group);
7384: foreach my $envkey (%env) {
1.1060 raeburn 7385: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7386: my $cid = $2.'_'.$3;
7387: if ($1 eq 'gr') {
7388: $group = $4;
7389: $allgroups{$cid}{$group} = $env{$envkey};
7390: } else {
7391: if ($4 eq '') {
7392: $sec = 'none';
7393: } else {
7394: $sec = $4;
7395: }
7396: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7397: }
1.811 albertel 7398: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 7399: my $cid = $2.'_'.$3;
7400: if ($4 eq '') {
7401: $sec = 'none';
7402: } else {
7403: $sec = $4;
7404: }
7405: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7406: }
7407: }
7408: if (keys(%allroles) == 0) {
7409: return;
7410: }
7411: foreach my $key (@courses_and_groups) {
7412: my %content = %{$$access_hash{$key}};
7413: my $cnum = $content{'number'};
7414: my $cdom = $content{'domain'};
7415: my $cid = $cdom.'_'.$cnum;
7416: if (!exists($allroles{$cid})) {
7417: next;
7418: }
7419: foreach my $role_id (keys(%{$content{'roles'}})) {
7420: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7421: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7422: my @status = @{$content{'roles'}{$role_id}{'access'}};
7423: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7424: foreach my $role (keys(%{$allroles{$cid}})) {
7425: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7426: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7427: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7428: if (grep/^all$/,@sections) {
7429: return 'ok';
7430: } else {
7431: if (grep/^$sec$/,@sections) {
7432: return 'ok';
7433: }
7434: }
7435: }
7436: }
7437: if (keys(%{$allgroups{$cid}}) == 0) {
7438: if (grep/^none$/,@groups) {
7439: return 'ok';
7440: }
7441: } else {
7442: if (grep/^all$/,@groups) {
7443: return 'ok';
7444: }
7445: foreach my $group (keys(%{$allgroups{$cid}})) {
7446: if (grep/^$group$/,@groups) {
7447: return 'ok';
7448: }
7449: }
7450: }
7451: }
7452: }
7453: }
7454: }
7455: }
7456: if ($guest) {
7457: return $guest;
7458: }
7459: }
7460: }
7461: return;
7462: }
7463:
7464: sub course_group_datechecker {
7465: my ($dates,$now,$status) = @_;
7466: my ($start,$end) = split(/\./,$dates);
7467: if (!$start && !$end) {
7468: return 'ok';
7469: }
7470: if (grep/^active$/,@{$status}) {
7471: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7472: return 'ok';
7473: }
7474: }
7475: if (grep/^previous$/,@{$status}) {
7476: if ($end > $now ) {
7477: return 'ok';
7478: }
7479: }
7480: if (grep/^future$/,@{$status}) {
7481: if ($start > $now) {
7482: return 'ok';
7483: }
7484: }
7485: return;
7486: }
7487:
7488: sub parse_portfolio_url {
7489: my ($url) = @_;
7490:
7491: my ($type,$udom,$unum,$group,$file_name);
7492:
1.823 albertel 7493: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7494: $type = 1;
7495: $udom = $1;
7496: $unum = $2;
7497: $file_name = $3;
1.823 albertel 7498: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7499: $type = 2;
7500: $udom = $1;
7501: $unum = $2;
7502: $group = $3;
7503: $file_name = $3.'/'.$4;
7504: }
7505: if (wantarray) {
7506: return ($type,$udom,$unum,$file_name,$group);
7507: }
7508: return $type;
7509: }
7510:
7511: sub is_portfolio_url {
7512: my ($url) = @_;
7513: return scalar(&parse_portfolio_url($url));
7514: }
7515:
1.798 raeburn 7516: sub is_portfolio_file {
7517: my ($file) = @_;
1.820 raeburn 7518: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7519: return 1;
7520: }
7521: return;
7522: }
7523:
1.976 raeburn 7524: sub usertools_access {
1.1084 raeburn 7525: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7526: my ($access,%tools);
7527: if ($context eq '') {
7528: $context = 'tools';
7529: }
7530: if ($context eq 'requestcourses') {
7531: %tools = (
7532: official => 1,
7533: unofficial => 1,
1.1006 raeburn 7534: community => 1,
1.1172.2.37 raeburn 7535: textbook => 1,
1.985 raeburn 7536: );
1.1172.2.9 raeburn 7537: } elsif ($context eq 'requestauthor') {
7538: %tools = (
7539: requestauthor => 1,
7540: );
1.985 raeburn 7541: } else {
7542: %tools = (
7543: aboutme => 1,
7544: blog => 1,
1.1172.2.6 raeburn 7545: webdav => 1,
1.985 raeburn 7546: portfolio => 1,
7547: );
7548: }
1.976 raeburn 7549: return if (!defined($tools{$tool}));
7550:
1.1172.2.35 raeburn 7551: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7552: $udom = $env{'user.domain'};
7553: $uname = $env{'user.name'};
7554: }
7555:
1.978 raeburn 7556: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7557: if ($action ne 'reload') {
1.985 raeburn 7558: if ($context eq 'requestcourses') {
7559: return $env{'environment.canrequest.'.$tool};
1.1172.2.9 raeburn 7560: } elsif ($context eq 'requestauthor') {
7561: return $env{'environment.canrequest.author'};
1.985 raeburn 7562: } else {
7563: return $env{'environment.availabletools.'.$tool};
7564: }
7565: }
1.976 raeburn 7566: }
7567:
1.1172.2.9 raeburn 7568: my ($toolstatus,$inststatus,$envkey);
7569: if ($context eq 'requestauthor') {
7570: $envkey = $context;
7571: } else {
7572: $envkey = $context.'.'.$tool;
7573: }
1.976 raeburn 7574:
1.985 raeburn 7575: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7576: ($action ne 'reload')) {
1.1172.2.9 raeburn 7577: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 7578: $inststatus = $env{'environment.inststatus'};
7579: } else {
1.1084 raeburn 7580: if (ref($userenvref) eq 'HASH') {
1.1172.2.9 raeburn 7581: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 7582: $inststatus = $userenvref->{'inststatus'};
7583: } else {
1.1172.2.9 raeburn 7584: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7585: $toolstatus = $userenv{$envkey};
1.1084 raeburn 7586: $inststatus = $userenv{'inststatus'};
7587: }
1.976 raeburn 7588: }
7589:
7590: if ($toolstatus ne '') {
7591: if ($toolstatus) {
7592: $access = 1;
7593: } else {
7594: $access = 0;
7595: }
7596: return $access;
7597: }
7598:
1.1084 raeburn 7599: my ($is_adv,%domdef);
7600: if (ref($is_advref) eq 'HASH') {
7601: $is_adv = $is_advref->{'is_adv'};
7602: } else {
7603: $is_adv = &is_advanced_user($udom,$uname);
7604: }
7605: if (ref($domdefref) eq 'HASH') {
7606: %domdef = %{$domdefref};
7607: } else {
7608: %domdef = &get_domain_defaults($udom);
7609: }
1.976 raeburn 7610: if (ref($domdef{$tool}) eq 'HASH') {
7611: if ($is_adv) {
7612: if ($domdef{$tool}{'_LC_adv'} ne '') {
7613: if ($domdef{$tool}{'_LC_adv'}) {
7614: $access = 1;
7615: } else {
7616: $access = 0;
7617: }
7618: return $access;
7619: }
7620: }
7621: if ($inststatus ne '') {
7622: my ($hasaccess,$hasnoaccess);
7623: foreach my $affiliation (split(/:/,$inststatus)) {
7624: if ($domdef{$tool}{$affiliation} ne '') {
7625: if ($domdef{$tool}{$affiliation}) {
7626: $hasaccess = 1;
7627: } else {
7628: $hasnoaccess = 1;
7629: }
7630: }
7631: }
7632: if ($hasaccess || $hasnoaccess) {
7633: if ($hasaccess) {
7634: $access = 1;
7635: } elsif ($hasnoaccess) {
7636: $access = 0;
7637: }
7638: return $access;
7639: }
7640: } else {
7641: if ($domdef{$tool}{'default'} ne '') {
7642: if ($domdef{$tool}{'default'}) {
7643: $access = 1;
7644: } elsif ($domdef{$tool}{'default'} == 0) {
7645: $access = 0;
7646: }
7647: return $access;
7648: }
7649: }
7650: } else {
1.1172.2.6 raeburn 7651: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7652: $access = 1;
7653: } else {
7654: $access = 0;
7655: }
1.976 raeburn 7656: return $access;
7657: }
7658: }
7659:
1.1050 raeburn 7660: sub is_course_owner {
7661: my ($cdom,$cnum,$udom,$uname) = @_;
7662: if (($udom eq '') || ($uname eq '')) {
7663: $udom = $env{'user.domain'};
7664: $uname = $env{'user.name'};
7665: }
7666: unless (($udom eq '') || ($uname eq '')) {
7667: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7668: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7669: return 1;
7670: } else {
7671: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7672: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7673: return 1;
7674: }
7675: }
7676: }
7677: }
7678: return;
7679: }
7680:
1.976 raeburn 7681: sub is_advanced_user {
7682: my ($udom,$uname) = @_;
1.1085 raeburn 7683: if ($udom ne '' && $uname ne '') {
7684: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7685: if (wantarray) {
7686: return ($env{'user.adv'},$env{'user.author'});
7687: } else {
7688: return $env{'user.adv'};
7689: }
1.1085 raeburn 7690: }
7691: }
1.976 raeburn 7692: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7693: my %allroles;
1.1128 raeburn 7694: my ($is_adv,$is_author);
1.976 raeburn 7695: foreach my $role (keys(%roleshash)) {
7696: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7697: my $area = '/'.$tdomain.'/'.$trest;
7698: if ($sec ne '') {
7699: $area .= '/'.$sec;
7700: }
7701: if (($area ne '') && ($trole ne '')) {
7702: my $spec=$trole.'.'.$area;
7703: if ($trole =~ /^cr\//) {
7704: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7705: } elsif ($trole ne 'gr') {
7706: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7707: }
1.1128 raeburn 7708: if ($trole eq 'au') {
7709: $is_author = 1;
7710: }
1.976 raeburn 7711: }
7712: }
7713: foreach my $role (keys(%allroles)) {
7714: last if ($is_adv);
7715: foreach my $item (split(/:/,$allroles{$role})) {
7716: if ($item ne '') {
7717: my ($privilege,$restrictions)=split(/&/,$item);
7718: if ($privilege eq 'adv') {
7719: $is_adv = 1;
7720: last;
7721: }
7722: }
7723: }
7724: }
1.1128 raeburn 7725: if (wantarray) {
7726: return ($is_adv,$is_author);
7727: }
1.976 raeburn 7728: return $is_adv;
7729: }
1.798 raeburn 7730:
1.1035 raeburn 7731: sub check_can_request {
1.1036 raeburn 7732: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7733: my $canreq = 0;
7734: my ($types,$typename) = &Apache::loncommon::course_types();
7735: my @options = ('approval','validate','autolimit');
7736: my $optregex = join('|',@options);
7737: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7738: foreach my $type (@{$types}) {
7739: if (&usertools_access($env{'user.name'},
7740: $env{'user.domain'},
7741: $type,undef,'requestcourses')) {
7742: $canreq ++;
1.1036 raeburn 7743: if (ref($request_domains) eq 'HASH') {
7744: push(@{$request_domains->{$type}},$env{'user.domain'});
7745: }
1.1035 raeburn 7746: if ($dom eq $env{'user.domain'}) {
7747: $can_request->{$type} = 1;
7748: }
7749: }
7750: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7751: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7752: if (@curr > 0) {
1.1036 raeburn 7753: foreach my $item (@curr) {
7754: if (ref($request_domains) eq 'HASH') {
7755: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7756: if ($otherdom ne '') {
7757: if (ref($request_domains->{$type}) eq 'ARRAY') {
7758: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7759: push(@{$request_domains->{$type}},$otherdom);
7760: }
7761: } else {
7762: push(@{$request_domains->{$type}},$otherdom);
7763: }
7764: }
7765: }
7766: }
7767: unless($dom eq $env{'user.domain'}) {
7768: $canreq ++;
1.1035 raeburn 7769: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7770: $can_request->{$type} = 1;
7771: }
7772: }
7773: }
7774: }
7775: }
7776: }
7777: return $canreq;
7778: }
7779:
1.341 www 7780: # ---------------------------------------------- Custom access rule evaluation
7781:
7782: sub customaccess {
7783: my ($priv,$uri)=@_;
1.807 albertel 7784: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7785: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7786: $udom = &LONCAPA::clean_domain($udom);
7787: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7788: my $access=0;
1.800 albertel 7789: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7790: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7791: if ($type eq 'user') {
7792: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7793: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7794: if ($tdom) {
7795: if ($tdom ne $env{'user.domain'}) { next; }
7796: }
1.896 albertel 7797: if ($tuname) {
7798: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7799: }
7800: $access=($effect eq 'allow');
7801: last;
7802: }
7803: } else {
7804: if ($role) {
7805: if ($role ne $urole) { next; }
7806: }
7807: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7808: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7809: if ($tdom) {
7810: if ($tdom ne $udom) { next; }
7811: }
7812: if ($tcrs) {
7813: if ($tcrs ne $ucrs) { next; }
7814: }
7815: if ($tsec) {
7816: if ($tsec ne $usec) { next; }
7817: }
7818: $access=($effect eq 'allow');
7819: last;
7820: }
7821: if ($realm eq '' && $role eq '') {
7822: $access=($effect eq 'allow');
7823: }
1.402 bowersj2 7824: }
1.341 www 7825: }
7826: return $access;
7827: }
7828:
1.103 harris41 7829: # ------------------------------------------------- Check for a user privilege
1.12 www 7830:
7831: sub allowed {
1.1172.2.126 raeburn 7832: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705 albertel 7833: my $ver_orguri=$uri;
1.439 www 7834: $uri=&deversion($uri);
1.152 www 7835: my $orguri=$uri;
1.52 www 7836: $uri=&declutter($uri);
1.809 raeburn 7837:
1.810 raeburn 7838: if ($priv eq 'evb') {
7839: # Evade communication block restrictions for specified role in a course
7840: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7841: return $1;
7842: } else {
7843: return;
7844: }
7845: }
7846:
1.620 albertel 7847: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7848: # Free bre access to adm and meta resources
1.1172.2.133 raeburn 7849: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme)$}))
1.769 albertel 7850: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7851: && ($priv eq 'bre')) {
1.14 www 7852: return 'F';
1.159 www 7853: }
7854:
1.545 banghart 7855: # Free bre access to user's own portfolio contents
1.714 raeburn 7856: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7857: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7858: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7859: my %setters;
7860: my ($startblock,$endblock) =
7861: &Apache::loncommon::blockcheck(\%setters,'port');
7862: if ($startblock && $endblock) {
7863: return 'B';
7864: } else {
7865: return 'F';
7866: }
1.545 banghart 7867: }
7868:
1.762 raeburn 7869: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7870: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7871: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7872: if (exists($env{'request.course.id'})) {
7873: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7874: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7875: if (($domain eq $cdom) && ($name eq $cnum)) {
7876: my $courseprivid=$env{'request.course.id'};
7877: $courseprivid=~s/\_/\//;
7878: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7879: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7880: return $1;
1.762 raeburn 7881: } else {
7882: if ($env{'request.course.sec'}) {
7883: $courseprivid.='/'.$env{'request.course.sec'};
7884: }
7885: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7886: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7887: return $2;
7888: }
1.714 raeburn 7889: }
7890: }
7891: }
7892: }
7893:
1.159 www 7894: # Free bre to public access
7895:
7896: if ($priv eq 'bre') {
1.238 www 7897: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7898: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7899: return 'F';
7900: }
1.238 www 7901: if ($copyright eq 'priv') {
7902: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7903: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7904: return '';
7905: }
7906: }
7907: if ($copyright eq 'domain') {
7908: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7909: unless (($env{'user.domain'} eq $1) ||
7910: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7911: return '';
7912: }
1.262 matthew 7913: }
1.620 albertel 7914: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7915: # Library role, so allow browsing of resources in this domain.
7916: return 'F';
1.238 www 7917: }
1.341 www 7918: if ($copyright eq 'custom') {
7919: unless (&customaccess($priv,$uri)) { return ''; }
7920: }
1.14 www 7921: }
1.264 matthew 7922: # Domain coordinator is trying to create a course
1.620 albertel 7923: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7924: # uri is the requested domain in this case.
7925: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7926: # a role of dc for the domain in question.
1.620 albertel 7927: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7928: }
1.29 www 7929:
1.52 www 7930: my $thisallowed='';
7931: my $statecond=0;
7932: my $courseprivid='';
7933:
1.1039 raeburn 7934: my $ownaccess;
1.1043 raeburn 7935: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7936: if (($priv eq 'bro') && ($env{'user.author'})) {
7937: if ($uri eq '') {
7938: $ownaccess = 1;
7939: } else {
7940: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7941: my $udom = $env{'user.domain'};
7942: my $uname = $env{'user.name'};
7943: if ($uri =~ m{^\Q$udom\E/?$}) {
7944: $ownaccess = 1;
1.1040 raeburn 7945: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 7946: unless ($uri =~ m{\.\./}) {
7947: $ownaccess = 1;
7948: }
7949: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7950: my $now = time;
7951: if ($uri =~ m{^([^/]+)/?$}) {
7952: my $adom = $1;
7953: foreach my $key (keys(%env)) {
1.1042 raeburn 7954: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 7955: my ($start,$end) = split('.',$env{$key});
7956: if (($now >= $start) && (!$end || $end < $now)) {
7957: $ownaccess = 1;
7958: last;
7959: }
7960: }
7961: }
7962: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7963: my $adom = $1;
7964: my $aname = $2;
1.1042 raeburn 7965: foreach my $role ('ca','aa') {
7966: if ($env{"user.role.$role./$adom/$aname"}) {
7967: my ($start,$end) =
7968: split('.',$env{"user.role.$role./$adom/$aname"});
7969: if (($now >= $start) && (!$end || $end < $now)) {
7970: $ownaccess = 1;
7971: last;
7972: }
1.1039 raeburn 7973: }
7974: }
7975: }
7976: }
7977: }
7978: }
7979: }
7980:
1.52 www 7981: # Course
7982:
1.620 albertel 7983: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7984: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7985: $thisallowed.=$1;
7986: }
1.52 www 7987: }
1.29 www 7988:
1.52 www 7989: # Domain
7990:
1.620 albertel 7991: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7992: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7993: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7994: $thisallowed.=$1;
7995: }
1.12 www 7996: }
1.52 www 7997:
1.1141 raeburn 7998: # User who is not author or co-author might still be able to edit
7999: # resource of an author in the domain (e.g., if Domain Coordinator).
8000: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8001: (&allowed('mdc',$env{'request.course.id'}))) {
8002: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8003: $thisallowed.=$1;
8004: }
8005: }
8006:
1.52 www 8007: # Course: uri itself is a course
1.66 www 8008: my $courseuri=$uri;
8009: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 8010: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 8011:
1.620 albertel 8012: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 8013: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115 raeburn 8014: if ($priv eq 'mip') {
8015: my $rem = $1;
8016: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8017: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8018: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8019: if ($cdom ne '') {
8020: my %passwdconf = &get_passwdconf($cdom);
8021: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8022: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8023: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8024: my @inststatuses = split(':',$env{'environment.inststatus'});
8025: unless (@inststatuses) {
8026: @inststatuses = ('default');
8027: }
8028: foreach my $status (@inststatuses) {
8029: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8030: $thisallowed.=$rem;
8031: }
8032: }
8033: }
8034: }
8035: }
8036: }
8037: }
8038: } else {
8039: unless (($priv eq 'bro') && (!$ownaccess)) {
8040: $thisallowed.=$1;
8041: }
1.1039 raeburn 8042: }
1.12 www 8043: }
1.29 www 8044:
1.665 albertel 8045: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 8046: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 8047: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 8048: $thisallowed='';
1.671 raeburn 8049: my ($match)=&is_on_map($uri);
8050: if ($match) {
8051: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8052: =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65 raeburn 8053: my $value = $1;
8054: if ($noblockcheck) {
8055: $thisallowed.=$value;
1.1162 raeburn 8056: } else {
1.1172.2.126 raeburn 8057: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8058: if (@blockers > 0) {
8059: $thisallowed = 'B';
8060: } else {
8061: $thisallowed.=$value;
8062: }
1.1162 raeburn 8063: }
1.671 raeburn 8064: }
8065: } else {
1.705 albertel 8066: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 8067: if ($refuri) {
8068: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 8069: $thisallowed='F';
1.671 raeburn 8070: } else {
8071: $refuri=&declutter($refuri);
8072: my ($match) = &is_on_map($refuri);
8073: if ($match) {
1.1172.2.65 raeburn 8074: if ($noblockcheck) {
1.1162 raeburn 8075: $thisallowed='F';
1.1172.2.65 raeburn 8076: } else {
1.1172.2.127 raeburn 8077: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8078: if (@blockers > 0) {
8079: $thisallowed = 'B';
8080: } else {
8081: $thisallowed='F';
8082: }
1.1162 raeburn 8083: }
1.671 raeburn 8084: }
1.669 raeburn 8085: }
1.671 raeburn 8086: }
8087: }
1.314 www 8088: }
1.492 albertel 8089:
1.766 albertel 8090: if ($priv eq 'bre'
8091: && $thisallowed ne 'F'
8092: && $thisallowed ne '2'
8093: && &is_portfolio_url($uri)) {
1.1172.2.77 raeburn 8094: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 8095: }
8096:
1.52 www 8097: # Full access at system, domain or course-wide level? Exit.
1.29 www 8098: if ($thisallowed=~/F/) {
8099: return 'F';
8100: }
8101:
1.52 www 8102: # If this is generating or modifying users, exit with special codes
1.29 www 8103:
1.643 www 8104: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8105: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 8106: my ($audom,$auname)=split('/',$uri);
1.643 www 8107: # no author name given, so this just checks on the general right to make a co-author in this domain
8108: unless ($auname) { return $thisallowed; }
8109: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 8110: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8111: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8112: ($audom ne $env{'request.role.domain'}))) { return ''; }
8113: }
1.52 www 8114: return $thisallowed;
8115: }
8116: #
1.103 harris41 8117: # Gathered so far: system, domain and course wide privileges
1.52 www 8118: #
8119: # Course: See if uri or referer is an individual resource that is part of
8120: # the course
8121:
1.620 albertel 8122: if ($env{'request.course.id'}) {
1.232 www 8123:
1.1172.2.115 raeburn 8124: # If this is modifying password (internal auth) domains must match for user and user's role.
8125:
8126: if ($priv eq 'mip') {
8127: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8128: return $thisallowed;
8129: } else {
8130: return '';
8131: }
8132: }
8133:
1.620 albertel 8134: $courseprivid=$env{'request.course.id'};
8135: if ($env{'request.course.sec'}) {
8136: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 8137: }
8138: $courseprivid=~s/\_/\//;
8139: my $checkreferer=1;
1.232 www 8140: my ($match,$cond)=&is_on_map($uri);
8141: if ($match) {
8142: $statecond=$cond;
1.620 albertel 8143: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8144: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8145: my $value = $1;
8146: if ($priv eq 'bre') {
1.1172.2.65 raeburn 8147: if ($noblockcheck) {
1.1162 raeburn 8148: $thisallowed.=$value;
1.1172.2.65 raeburn 8149: } else {
1.1172.2.126 raeburn 8150: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65 raeburn 8151: if (@blockers > 0) {
8152: $thisallowed = 'B';
8153: } else {
8154: $thisallowed.=$value;
8155: }
1.1162 raeburn 8156: }
8157: } else {
8158: $thisallowed.=$value;
8159: }
1.52 www 8160: $checkreferer=0;
8161: }
1.29 www 8162: }
1.1172.2.126 raeburn 8163:
1.148 www 8164: if ($checkreferer) {
1.620 albertel 8165: my $refuri=$env{'httpref.'.$orguri};
1.148 www 8166: unless ($refuri) {
1.800 albertel 8167: foreach my $key (keys(%env)) {
8168: if ($key=~/^httpref\..*\*/) {
8169: my $pattern=$key;
1.156 www 8170: $pattern=~s/^httpref\.\/res\///;
1.148 www 8171: $pattern=~s/\*/\[\^\/\]\+/g;
8172: $pattern=~s/\//\\\//g;
1.152 www 8173: if ($orguri=~/$pattern/) {
1.800 albertel 8174: $refuri=$env{$key};
1.148 www 8175: }
8176: }
1.191 harris41 8177: }
1.148 www 8178: }
1.232 www 8179:
1.148 www 8180: if ($refuri) {
1.152 www 8181: $refuri=&declutter($refuri);
1.232 www 8182: my ($match,$cond)=&is_on_map($refuri);
8183: if ($match) {
8184: my $refstatecond=$cond;
1.620 albertel 8185: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 8186: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 8187: my $value = $1;
8188: if ($priv eq 'bre') {
1.1172.2.65 raeburn 8189: if ($noblockcheck) {
1.1162 raeburn 8190: $thisallowed.=$value;
1.1172.2.65 raeburn 8191: } else {
1.1172.2.127 raeburn 8192: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65 raeburn 8193: if (@blockers > 0) {
8194: $thisallowed = 'B';
8195: } else {
8196: $thisallowed.=$value;
8197: }
1.1162 raeburn 8198: }
8199: } else {
8200: $thisallowed.=$value;
8201: }
1.53 www 8202: $uri=$refuri;
8203: $statecond=$refstatecond;
1.52 www 8204: }
8205: }
1.148 www 8206: }
1.29 www 8207: }
1.52 www 8208: }
1.29 www 8209:
1.52 www 8210: #
1.103 harris41 8211: # Gathered now: all privileges that could apply, and condition number
1.52 www 8212: #
8213: #
8214: # Full or no access?
8215: #
1.29 www 8216:
1.52 www 8217: if ($thisallowed=~/F/) {
8218: return 'F';
8219: }
1.29 www 8220:
1.52 www 8221: unless ($thisallowed) {
8222: return '';
8223: }
1.29 www 8224:
1.52 www 8225: # Restrictions exist, deal with them
8226: #
8227: # C:according to course preferences
8228: # R:according to resource settings
8229: # L:unless locked
8230: # X:according to user session state
8231: #
8232:
8233: # Possibly locked functionality, check all courses
1.54 www 8234: # Locks might take effect only after 10 minutes cache expiration for other
8235: # courses, and 2 minutes for current course
1.52 www 8236:
8237: my $envkey;
8238: if ($thisallowed=~/L/) {
1.1000 raeburn 8239: foreach $envkey (keys(%env)) {
1.54 www 8240: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8241: my $courseid=$2;
8242: my $roleid=$1.'.'.$2;
1.92 www 8243: $courseid=~s/^\///;
1.54 www 8244: my $expiretime=600;
1.620 albertel 8245: if ($env{'request.role'} eq $roleid) {
1.54 www 8246: $expiretime=120;
8247: }
8248: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8249: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 8250: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 8251: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 8252: }
1.620 albertel 8253: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8254: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8255: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8256: &log($env{'user.domain'},$env{'user.name'},
8257: $env{'user.home'},
1.57 www 8258: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 8259: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8260: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8261: return '';
8262: }
8263: }
1.620 albertel 8264: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8265: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
8266: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
8267: &log($env{'user.domain'},$env{'user.name'},
8268: $env{'user.home'},
1.57 www 8269: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 8270: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 8271: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 8272: return '';
8273: }
8274: }
8275: }
1.29 www 8276: }
1.52 www 8277: }
1.1172.2.126 raeburn 8278:
1.52 www 8279: #
8280: # Rest of the restrictions depend on selected course
8281: #
8282:
1.620 albertel 8283: unless ($env{'request.course.id'}) {
1.766 albertel 8284: if ($thisallowed eq 'A') {
8285: return 'A';
1.814 raeburn 8286: } elsif ($thisallowed eq 'B') {
8287: return 'B';
1.766 albertel 8288: } else {
8289: return '1';
8290: }
1.52 www 8291: }
1.29 www 8292:
1.52 www 8293: #
8294: # Now user is definitely in a course
8295: #
1.53 www 8296:
8297:
8298: # Course preferences
8299:
8300: if ($thisallowed=~/C/) {
1.620 albertel 8301: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8302: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8303: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 8304: =~/\Q$rolecode\E/) {
1.1103 raeburn 8305: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8306: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8307: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8308: $env{'request.course.id'});
8309: }
1.237 www 8310: return '';
8311: }
8312:
1.620 albertel 8313: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 8314: =~/\Q$unamedom\E/) {
1.1103 raeburn 8315: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8316: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8317: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8318: $env{'request.course.id'});
8319: }
1.54 www 8320: return '';
8321: }
1.53 www 8322: }
8323:
8324: # Resource preferences
8325:
8326: if ($thisallowed=~/R/) {
1.620 albertel 8327: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 8328: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 8329: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 8330: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8331: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8332: }
8333: return '';
1.54 www 8334: }
1.53 www 8335: }
1.30 www 8336:
1.246 www 8337: # Restricted by state or randomout?
1.30 www 8338:
1.52 www 8339: if ($thisallowed=~/X/) {
1.620 albertel 8340: if ($env{'acc.randomout'}) {
1.579 albertel 8341: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 8342: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 8343: return '';
8344: }
1.247 www 8345: }
8346: if (&condval($statecond)) {
1.52 www 8347: return '2';
8348: } else {
8349: return '';
8350: }
8351: }
1.30 www 8352:
1.766 albertel 8353: if ($thisallowed eq 'A') {
8354: return 'A';
1.814 raeburn 8355: } elsif ($thisallowed eq 'B') {
8356: return 'B';
1.766 albertel 8357: }
1.52 www 8358: return 'F';
1.232 www 8359: }
1.1162 raeburn 8360:
1.1172.2.13 raeburn 8361: # ------------------------------------------- Check construction space access
8362:
8363: sub constructaccess {
8364: my ($url,$setpriv)=@_;
8365:
8366: # We do not allow editing of previous versions of files
8367: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8368:
8369: # Get username and domain from URL
8370: my ($ownername,$ownerdomain,$ownerhome);
8371:
8372: ($ownerdomain,$ownername) =
1.1172.2.83 raeburn 8373: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13 raeburn 8374:
8375: # The URL does not really point to any authorspace, forget it
8376: unless (($ownername) && ($ownerdomain)) { return ''; }
8377:
8378: # Now we need to see if the user has access to the authorspace of
8379: # $ownername at $ownerdomain
8380:
8381: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8382: # Real author for this?
8383: $ownerhome = $env{'user.home'};
8384: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8385: return ($ownername,$ownerdomain,$ownerhome);
8386: }
8387: } else {
8388: # Co-author for this?
8389: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8390: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8391: $ownerhome = &homeserver($ownername,$ownerdomain);
8392: return ($ownername,$ownerdomain,$ownerhome);
8393: }
8394: }
8395:
8396: # We don't have any access right now. If we are not possibly going to do anything about this,
8397: # we might as well leave
8398: unless ($setpriv) { return ''; }
8399:
8400: # Backdoor access?
8401: my $allowed=&allowed('eco',$ownerdomain);
8402: # Nope
8403: unless ($allowed) { return ''; }
8404: # Looks like we may have access, but could be locked by the owner of the construction space
8405: if ($allowed eq 'U') {
8406: my %blocked=&get('environment',['domcoord.author'],
8407: $ownerdomain,$ownername);
8408: # Is blocked by owner
8409: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8410: }
8411: if (($allowed eq 'F') || ($allowed eq 'U')) {
8412: # Grant temporary access
8413: my $then=$env{'user.login.time'};
1.1172.2.16 raeburn 8414: my $update=$env{'user.update.time'};
1.1172.2.13 raeburn 8415: if (!$update) { $update = $then; }
8416: my $refresh=$env{'user.refresh.time'};
8417: if (!$refresh) { $refresh = $update; }
8418: my $now = time;
8419: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8420: $now,'ca','constructaccess');
8421: $ownerhome = &homeserver($ownername,$ownerdomain);
8422: return($ownername,$ownerdomain,$ownerhome);
8423: }
8424: # No business here
8425: return '';
8426: }
8427:
1.1172.2.66 raeburn 8428: # ----------------------------------------------------------- Content Blocking
8429:
8430: {
8431: # Caches for faster Course Contents display where content blocking
8432: # is in operation (i.e., interval param set) for timed quiz.
8433: #
8434: # User for whom data are being temporarily cached.
8435: my $cacheduser='';
1.1172.2.126 raeburn 8436: # Course for which data are being temporarily cached.
8437: my $cachedcid='';
1.1172.2.66 raeburn 8438: # Cached blockers for this user (a hash of blocking items).
8439: my %cachedblockers=();
8440: # When the data were last cached.
8441: my $cachedlast='';
8442:
8443: sub load_all_blockers {
1.1172.2.128 raeburn 8444: my ($uname,$udom)=@_;
1.1172.2.66 raeburn 8445: if (($uname ne '') && ($udom ne '')) {
8446: if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126 raeburn 8447: ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128 raeburn 8448: (abs($cachedlast-time)<5)) {
1.1172.2.66 raeburn 8449: return;
8450: }
8451: }
8452: $cachedlast=time;
8453: $cacheduser=$uname.':'.$udom;
1.1172.2.126 raeburn 8454: $cachedcid=$env{'request.course.id'};
1.1172.2.128 raeburn 8455: %cachedblockers = &get_commblock_resources();
1.1172.2.126 raeburn 8456: return;
1.1172.2.66 raeburn 8457: }
8458:
1.1162 raeburn 8459: sub get_comm_blocks {
8460: my ($cdom,$cnum) = @_;
8461: if ($cdom eq '' || $cnum eq '') {
8462: return unless ($env{'request.course.id'});
8463: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8464: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8465: }
8466: my %commblocks;
8467: my $hashid=$cdom.'_'.$cnum;
8468: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8469: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8470: %commblocks = %{$blocksref};
8471: } else {
8472: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8473: my $cachetime = 600;
8474: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8475: }
8476: return %commblocks;
8477: }
8478:
1.1172.2.66 raeburn 8479: sub get_commblock_resources {
8480: my ($blocks) = @_;
8481: my %blockers = ();
8482: return %blockers unless ($env{'request.course.id'});
8483: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 8484: my %commblocks;
8485: if (ref($blocks) eq 'HASH') {
8486: %commblocks = %{$blocks};
8487: } else {
8488: %commblocks = &get_comm_blocks();
8489: }
1.1172.2.66 raeburn 8490: return %blockers unless (keys(%commblocks) > 0);
1.1163 raeburn 8491: my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66 raeburn 8492: return %blockers unless (ref($navmap));
8493: my $now = time;
1.1162 raeburn 8494: foreach my $block (keys(%commblocks)) {
8495: if ($block =~ /^(\d+)____(\d+)$/) {
8496: my ($start,$end) = ($1,$2);
8497: if ($start <= $now && $end >= $now) {
8498: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8499: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8500: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66 raeburn 8501: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8502: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 8503: }
8504: }
8505: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66 raeburn 8506: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8507: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 8508: }
8509: }
8510: }
8511: }
8512: }
8513: } elsif ($block =~ /^firstaccess____(.+)$/) {
8514: my $item = $1;
1.1163 raeburn 8515: my @to_test;
1.1162 raeburn 8516: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8517: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66 raeburn 8518: my @interval;
8519: my $type = 'map';
8520: if ($item eq 'course') {
8521: $type = 'course';
8522: @interval=&EXT("resource.0.interval");
8523: } else {
8524: if ($item =~ /___\d+___/) {
8525: $type = 'resource';
8526: @interval=&EXT("resource.0.interval",$item);
8527: if (ref($navmap)) {
8528: my $res = $navmap->getBySymb($item);
8529: push(@to_test,$res);
8530: }
1.1162 raeburn 8531: } else {
1.1172.2.66 raeburn 8532: my $mapsymb = &symbread($item,1);
8533: if ($mapsymb) {
8534: if (ref($navmap)) {
8535: my $mapres = $navmap->getBySymb($mapsymb);
1.1172.2.129 raeburn 8536: if (ref($mapres)) {
8537: my $first = $mapres->map_start();
8538: my $finish = $mapres->map_finish();
8539: my $it = $navmap->getIterator($first,$finish,undef,0,0);
8540: if (ref($it)) {
8541: my $res;
8542: while ($res = $it->next(undef,1)) {
8543: next unless (ref($res));
8544: my $symb = $res->symb();
8545: next if (($symb eq $mapsymb) || ($symb eq ''));
8546: @interval=&EXT("resource.0.interval",$symb);
8547: if ($interval[1] eq 'map') {
8548: if ($res->answerable()) {
8549: push(@to_test,$res);
8550: last;
8551: }
8552: }
1.1162 raeburn 8553: }
8554: }
8555: }
8556: }
8557: }
8558: }
1.1172.2.66 raeburn 8559: }
8560: if ($interval[0] =~ /^\d+$/) {
8561: my $first_access;
8562: if ($type eq 'resource') {
8563: $first_access=&get_first_access($interval[1],$item);
8564: } elsif ($type eq 'map') {
8565: $first_access=&get_first_access($interval[1],undef,$item);
8566: } else {
8567: $first_access=&get_first_access($interval[1]);
8568: }
8569: if ($first_access) {
8570: my $timesup = $first_access+$interval[0];
8571: if ($timesup > $now) {
8572: my $activeblock;
8573: foreach my $res (@to_test) {
8574: if ($res->answerable()) {
8575: $activeblock = 1;
8576: last;
8577: }
8578: }
8579: if ($activeblock) {
8580: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8581: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8582: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8583: }
8584: }
8585: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8586: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8587: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 8588: }
1.1162 raeburn 8589: }
8590: }
8591: }
8592: }
8593: }
8594: }
8595: }
8596: }
8597: }
1.1172.2.66 raeburn 8598: return %blockers;
1.1162 raeburn 8599: }
8600:
1.1172.2.66 raeburn 8601: sub has_comm_blocking {
1.1172.2.128 raeburn 8602: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66 raeburn 8603: my @blockers;
8604: return unless ($env{'request.course.id'});
8605: return unless ($priv eq 'bre');
8606: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8607: return if ($env{'request.state'} eq 'construct');
1.1172.2.128 raeburn 8608: my %blockinfo;
8609: if (ref($blocks) eq 'HASH') {
8610: %blockinfo = &get_commblock_resources($blocks);
8611: } else {
8612: &load_all_blockers($env{'user.name'},$env{'user.domain'});
8613: %blockinfo = %cachedblockers;
8614: }
8615: return unless (keys(%blockinfo) > 0);
1.1172.2.66 raeburn 8616: my (%possibles,@symbs);
8617: if (!$symb) {
1.1172.2.128 raeburn 8618: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162 raeburn 8619: }
1.1172.2.66 raeburn 8620: if ($symb) {
8621: @symbs = ($symb);
8622: } elsif (keys(%possibles)) {
8623: @symbs = keys(%possibles);
8624: }
8625: my $noblock;
8626: foreach my $symb (@symbs) {
8627: last if ($noblock);
8628: my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128 raeburn 8629: foreach my $block (keys(%blockinfo)) {
1.1172.2.66 raeburn 8630: if ($block =~ /^firstaccess____(.+)$/) {
8631: my $item = $1;
1.1172.2.126 raeburn 8632: unless ($blocked) {
8633: if (($item eq $map) || ($item eq $symb)) {
8634: $noblock = 1;
8635: last;
8636: }
1.1172.2.66 raeburn 8637: }
1.1162 raeburn 8638: }
1.1172.2.128 raeburn 8639: if (ref($blockinfo{$block}) eq 'HASH') {
8640: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
8641: if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66 raeburn 8642: unless (grep(/^\Q$block\E$/,@blockers)) {
8643: push(@blockers,$block);
8644: }
8645: }
8646: }
1.1172.2.128 raeburn 8647: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
8648: if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126 raeburn 8649: unless (grep(/^\Q$block\E$/,@blockers)) {
8650: push(@blockers,$block);
8651: }
1.1172.2.66 raeburn 8652: }
8653: }
1.1162 raeburn 8654: }
8655: }
8656: }
1.1172.2.126 raeburn 8657: unless ($noblock) {
8658: return @blockers;
8659: }
8660: return;
1.1172.2.66 raeburn 8661: }
1.1162 raeburn 8662: }
8663:
1.1172.2.66 raeburn 8664: # -------------------------------- Deversion and split uri into path an filename
8665:
1.1133 foxr 8666: #
1.1172.2.66 raeburn 8667: # Removes the version from a URI and
1.1133 foxr 8668: # splits it in to its filename and path to the filename.
8669: # Seems like File::Basename could have done this more clearly.
8670: # Parameters:
8671: # $uri - input URI
8672: # Returns:
8673: # Two element list consisting of
8674: # $pathname - the URI up to and excluding the trailing /
8675: # $filename - The part of the URI following the last /
8676: # NOTE:
8677: # Another realization of this is simply:
8678: # use File::Basename;
8679: # ...
8680: # $uri = shift;
8681: # $filename = basename($uri);
8682: # $path = dirname($uri);
8683: # return ($filename, $path);
8684: #
8685: # The implementation below is probably faster however.
8686: #
1.710 albertel 8687: sub split_uri_for_cond {
8688: my $uri=&deversion(&declutter(shift));
8689: my @uriparts=split(/\//,$uri);
8690: my $filename=pop(@uriparts);
8691: my $pathname=join('/',@uriparts);
8692: return ($pathname,$filename);
8693: }
1.232 www 8694: # --------------------------------------------------- Is a resource on the map?
8695:
8696: sub is_on_map {
1.710 albertel 8697: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8698: #Trying to find the conditional for the file
1.620 albertel 8699: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8700: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8701: if ($match) {
1.289 bowersj2 8702: return (1,$1);
8703: } else {
1.434 www 8704: return (0,0);
1.289 bowersj2 8705: }
1.12 www 8706: }
8707:
1.427 www 8708: # --------------------------------------------------------- Get symb from alias
8709:
8710: sub get_symb_from_alias {
8711: my $symb=shift;
8712: my ($map,$resid,$url)=&decode_symb($symb);
8713: # Already is a symb
8714: if ($url) { return $symb; }
8715: # Must be an alias
8716: my $aliassymb='';
8717: my %bighash;
1.620 albertel 8718: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8719: &GDBM_READER(),0640)) {
8720: my $rid=$bighash{'mapalias_'.$symb};
8721: if ($rid) {
8722: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8723: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8724: $resid,$bighash{'src_'.$rid});
1.427 www 8725: }
8726: untie %bighash;
8727: }
8728: return $aliassymb;
8729: }
8730:
1.12 www 8731: # ----------------------------------------------------------------- Define Role
8732:
8733: sub definerole {
8734: if (allowed('mcr','/')) {
1.1172.2.84 raeburn 8735: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8736: foreach my $role (split(':',$sysrole)) {
8737: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8738: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8739: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8740: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8741: return "refused:s:$crole&$cqual";
8742: }
8743: }
1.191 harris41 8744: }
1.800 albertel 8745: foreach my $role (split(':',$domrole)) {
8746: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8747: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8748: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8749: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8750: return "refused:d:$crole&$cqual";
8751: }
8752: }
1.191 harris41 8753: }
1.800 albertel 8754: foreach my $role (split(':',$courole)) {
8755: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8756: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8757: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8758: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8759: return "refused:c:$crole&$cqual";
8760: }
8761: }
1.191 harris41 8762: }
1.1172.2.84 raeburn 8763: my $uhome;
8764: if (($uname ne '') && ($udom ne '')) {
8765: $uhome = &homeserver($uname,$udom);
8766: return $uhome if ($uhome eq 'no_host');
8767: } else {
8768: $uname = $env{'user.name'};
8769: $udom = $env{'user.domain'};
8770: $uhome = $env{'user.home'};
8771: }
1.620 albertel 8772: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84 raeburn 8773: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8774: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84 raeburn 8775: return reply($command,$uhome);
1.12 www 8776: } else {
8777: return 'refused';
8778: }
1.105 harris41 8779: }
8780:
8781: # ---------------- Make a metadata query against the network of library servers
8782:
8783: sub metadata_query {
1.1172.2.33 raeburn 8784: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8785: my %rhash;
1.845 albertel 8786: my %libserv = &all_library();
1.244 matthew 8787: my @server_list = (defined($server_array) ? @$server_array
8788: : keys(%libserv) );
8789: for my $server (@server_list) {
1.1172.2.33 raeburn 8790: my $domains = '';
8791: if (ref($domains_hash) eq 'HASH') {
8792: $domains = $domains_hash->{$server};
8793: }
1.118 harris41 8794: unless ($custom or $customshow) {
1.1172.2.33 raeburn 8795: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8796: $rhash{$server}=$reply;
8797: }
8798: else {
8799: my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33 raeburn 8800: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8801: $server);
8802: $rhash{$server}=$reply;
8803: }
1.112 harris41 8804: }
1.118 harris41 8805: return \%rhash;
1.240 www 8806: }
8807:
8808: # ----------------------------------------- Send log queries and wait for reply
8809:
8810: sub log_query {
8811: my ($uname,$udom,$query,%filters)=@_;
8812: my $uhome=&homeserver($uname,$udom);
8813: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8814: my $uhost=&hostname($uhome);
1.800 albertel 8815: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8816: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8817: $uhome);
1.479 albertel 8818: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8819: return get_query_reply($queryid);
8820: }
8821:
1.818 raeburn 8822: # -------------------------- Update MySQL table for portfolio file
8823:
8824: sub update_portfolio_table {
1.821 raeburn 8825: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8826: if ($group ne '') {
8827: $file_name =~s /^\Q$group\E//;
8828: }
1.818 raeburn 8829: my $homeserver = &homeserver($uname,$udom);
8830: my $queryid=
1.821 raeburn 8831: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8832: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8833: my $reply = &get_query_reply($queryid);
8834: return $reply;
8835: }
8836:
1.899 raeburn 8837: # -------------------------- Update MySQL allusers table
8838:
8839: sub update_allusers_table {
8840: my ($uname,$udom,$names) = @_;
8841: my $homeserver = &homeserver($uname,$udom);
8842: my $queryid=
8843: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8844: 'lastname='.&escape($names->{'lastname'}).'%%'.
8845: 'firstname='.&escape($names->{'firstname'}).'%%'.
8846: 'middlename='.&escape($names->{'middlename'}).'%%'.
8847: 'generation='.&escape($names->{'generation'}).'%%'.
8848: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8849: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8850: return;
1.899 raeburn 8851: }
8852:
1.508 raeburn 8853: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8854:
8855: sub fetch_enrollment_query {
1.511 raeburn 8856: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79 raeburn 8857: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8858: my $maxtries = 1;
1.508 raeburn 8859: if ($context eq 'automated') {
8860: $homeserver = $perlvar{'lonHostID'};
1.1172.2.79 raeburn 8861: $sleep = 2;
8862: $loopmax = 100;
1.547 raeburn 8863: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8864: } else {
8865: $homeserver = &homeserver($cnum,$dom);
8866: }
1.838 albertel 8867: my $host=&hostname($homeserver);
1.506 raeburn 8868: my $cmd = '';
1.1000 raeburn 8869: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8870: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8871: }
8872: $cmd =~ s/%%$//;
8873: $cmd = &escape($cmd);
8874: my $query = 'fetchenrollment';
1.620 albertel 8875: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8876: unless ($queryid=~/^\Q$host\E\_/) {
8877: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8878: return 'error: '.$queryid;
8879: }
1.1172.2.93 raeburn 8880: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8881: my $tries = 1;
8882: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79 raeburn 8883: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8884: $tries ++;
8885: }
1.526 raeburn 8886: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 8887: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 8888: } else {
1.901 albertel 8889: my @responses = split(/:/,$reply);
1.1172.2.82 raeburn 8890: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 8891: foreach my $line (@responses) {
8892: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 8893: $$replyref{$key} = $value;
8894: }
8895: } else {
1.1117 foxr 8896: my $pathname = LONCAPA::tempdir();
1.800 albertel 8897: foreach my $line (@responses) {
8898: my ($key,$value) = split(/=/,$line);
1.506 raeburn 8899: $$replyref{$key} = $value;
8900: if ($value > 0) {
1.800 albertel 8901: foreach my $item (@{$$affiliatesref{$key}}) {
8902: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 8903: my $destname = $pathname.'/'.$filename;
8904: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 8905: if ($xml_classlist =~ /^error/) {
8906: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8907: } else {
1.1172.2.96 raeburn 8908: if ( open(FILE,">",$destname) ) {
1.506 raeburn 8909: print FILE &unescape($xml_classlist);
8910: close(FILE);
1.526 raeburn 8911: } else {
8912: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 8913: }
8914: }
8915: }
8916: }
8917: }
8918: }
8919: return 'ok';
8920: }
8921: return 'error';
8922: }
8923:
1.242 www 8924: sub get_query_reply {
1.1172.2.79 raeburn 8925: my ($queryid,$sleep,$loopmax) = @_;
8926: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8927: $sleep = 0.2;
8928: }
8929: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8930: $loopmax = 100;
8931: }
1.1117 foxr 8932: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 8933: my $reply='';
1.1172.2.79 raeburn 8934: for (1..$loopmax) {
8935: sleep($sleep);
1.240 www 8936: if (-e $replyfile.'.end') {
1.1172.2.96 raeburn 8937: if (open(my $fh,"<",$replyfile)) {
1.904 albertel 8938: $reply = join('',<$fh>);
8939: close($fh);
1.240 www 8940: } else { return 'error: reply_file_error'; }
1.242 www 8941: return &unescape($reply);
8942: }
1.240 www 8943: }
1.242 www 8944: return 'timeout:'.$queryid;
1.240 www 8945: }
8946:
8947: sub courselog_query {
1.241 www 8948: #
8949: # possible filters:
8950: # url: url or symb
8951: # username
8952: # domain
8953: # action: view, submit, grade
8954: # start: timestamp
8955: # end: timestamp
8956: #
1.240 www 8957: my (%filters)=@_;
1.620 albertel 8958: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 8959: if ($filters{'url'}) {
8960: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8961: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8962: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8963: }
1.620 albertel 8964: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8965: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 8966: return &log_query($cname,$cdom,'courselog',%filters);
8967: }
8968:
8969: sub userlog_query {
1.858 raeburn 8970: #
8971: # possible filters:
8972: # action: log check role
8973: # start: timestamp
8974: # end: timestamp
8975: #
1.240 www 8976: my ($uname,$udom,%filters)=@_;
8977: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 8978: }
8979:
1.506 raeburn 8980: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8981:
8982: sub auto_run {
1.508 raeburn 8983: my ($cnum,$cdom) = @_;
1.876 raeburn 8984: my $response = 0;
8985: my $settings;
8986: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8987: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8988: $settings = $domconfig{'autoenroll'};
8989: if ($settings->{'run'} eq '1') {
8990: $response = 1;
8991: }
8992: } else {
1.934 raeburn 8993: my $homeserver;
8994: if (&is_course($cdom,$cnum)) {
8995: $homeserver = &homeserver($cnum,$cdom);
8996: } else {
8997: $homeserver = &domain($cdom,'primary');
8998: }
8999: if ($homeserver ne 'no_host') {
9000: $response = &reply('autorun:'.$cdom,$homeserver);
9001: }
1.876 raeburn 9002: }
1.506 raeburn 9003: return $response;
9004: }
1.776 albertel 9005:
1.506 raeburn 9006: sub auto_get_sections {
1.508 raeburn 9007: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 9008: my $homeserver;
9009: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9010: $homeserver = &homeserver($cnum,$cdom);
9011: }
9012: if (!defined($homeserver)) {
9013: if ($cdom =~ /^$match_domain$/) {
9014: $homeserver = &domain($cdom,'primary');
9015: }
9016: }
9017: my @secs;
9018: if (defined($homeserver)) {
9019: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9020: unless ($response eq 'refused') {
9021: @secs = split(/:/,$response);
9022: }
1.506 raeburn 9023: }
9024: return @secs;
9025: }
1.776 albertel 9026:
1.506 raeburn 9027: sub auto_new_course {
1.1099 raeburn 9028: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 9029: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 9030: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 9031: return $response;
9032: }
1.776 albertel 9033:
1.506 raeburn 9034: sub auto_validate_courseID {
1.508 raeburn 9035: my ($cnum,$cdom,$inst_course_id) = @_;
9036: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 9037: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 9038: return $response;
9039: }
1.776 albertel 9040:
1.1007 raeburn 9041: sub auto_validate_instcode {
1.1020 raeburn 9042: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 9043: my ($homeserver,$response);
9044: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9045: $homeserver = &homeserver($cnum,$cdom);
9046: }
9047: if (!defined($homeserver)) {
9048: if ($cdom =~ /^$match_domain$/) {
9049: $homeserver = &domain($cdom,'primary');
9050: }
9051: }
1.1065 raeburn 9052: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9053: &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19 raeburn 9054: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9055: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 9056: }
9057:
1.1172.2.141! raeburn 9058: sub auto_validate_inst_crosslist {
! 9059: my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
! 9060: my ($homeserver,$response);
! 9061: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
! 9062: $homeserver = &homeserver($cnum,$cdom);
! 9063: }
! 9064: if (!defined($homeserver)) {
! 9065: if ($cdom =~ /^$match_domain$/) {
! 9066: $homeserver = &domain($cdom,'primary');
! 9067: }
! 9068: }
! 9069: unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
! 9070: $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
! 9071: &escape($instcode).':'.&escape($inst_xlist).':'.
! 9072: &escape($coowner),$homeserver);
! 9073: }
! 9074: return $response;
! 9075: }
! 9076:
1.506 raeburn 9077: sub auto_create_password {
1.873 raeburn 9078: my ($cnum,$cdom,$authparam,$udom) = @_;
9079: my ($homeserver,$response);
1.506 raeburn 9080: my $create_passwd = 0;
9081: my $authchk = '';
1.873 raeburn 9082: if ($udom =~ /^$match_domain$/) {
9083: $homeserver = &domain($udom,'primary');
9084: }
9085: if ($homeserver eq '') {
9086: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9087: $homeserver = &homeserver($cnum,$cdom);
9088: }
9089: }
9090: if ($homeserver eq '') {
9091: $authchk = 'nodomain';
1.506 raeburn 9092: } else {
1.873 raeburn 9093: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9094: if ($response eq 'refused') {
9095: $authchk = 'refused';
9096: } else {
1.901 albertel 9097: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 9098: }
1.506 raeburn 9099: }
9100: return ($authparam,$create_passwd,$authchk);
9101: }
9102:
1.706 raeburn 9103: sub auto_photo_permission {
9104: my ($cnum,$cdom,$students) = @_;
9105: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 9106: my ($outcome,$perm_reqd,$conditions) =
9107: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 9108: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9109: return (undef,undef);
9110: }
1.706 raeburn 9111: return ($outcome,$perm_reqd,$conditions);
9112: }
9113:
9114: sub auto_checkphotos {
9115: my ($uname,$udom,$pid) = @_;
9116: my $homeserver = &homeserver($uname,$udom);
9117: my ($result,$resulttype);
9118: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 9119: &escape($uname).':'.&escape($pid),
9120: $homeserver));
1.709 albertel 9121: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9122: return (undef,undef);
9123: }
1.706 raeburn 9124: if ($outcome) {
9125: ($result,$resulttype) = split(/:/,$outcome);
9126: }
9127: return ($result,$resulttype);
9128: }
9129:
9130: sub auto_photochoice {
9131: my ($cnum,$cdom) = @_;
9132: my $homeserver = &homeserver($cnum,$cdom);
9133: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 9134: &escape($cdom),
9135: $homeserver)));
1.709 albertel 9136: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9137: return (undef,undef);
9138: }
1.706 raeburn 9139: return ($update,$comment);
9140: }
9141:
9142: sub auto_photoupdate {
9143: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9144: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 9145: my $host=&hostname($homeserver);
1.706 raeburn 9146: my $cmd = '';
9147: my $maxtries = 1;
1.800 albertel 9148: foreach my $affiliate (keys(%{$affiliatesref})) {
9149: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 9150: }
9151: $cmd =~ s/%%$//;
9152: $cmd = &escape($cmd);
9153: my $query = 'institutionalphotos';
9154: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9155: unless ($queryid=~/^\Q$host\E\_/) {
9156: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9157: return 'error: '.$queryid;
9158: }
9159: my $reply = &get_query_reply($queryid);
9160: my $tries = 1;
9161: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9162: $reply = &get_query_reply($queryid);
9163: $tries ++;
9164: }
9165: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9166: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9167: } else {
9168: my @responses = split(/:/,$reply);
9169: my $outcome = shift(@responses);
9170: foreach my $item (@responses) {
9171: my ($key,$value) = split(/=/,$item);
9172: $$photo{$key} = $value;
9173: }
9174: return $outcome;
9175: }
9176: return 'error';
9177: }
9178:
1.521 raeburn 9179: sub auto_instcode_format {
1.793 albertel 9180: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9181: $cat_order) = @_;
1.521 raeburn 9182: my $courses = '';
1.772 raeburn 9183: my @homeservers;
1.521 raeburn 9184: if ($caller eq 'global') {
1.841 albertel 9185: my %servers = &get_servers($codedom,'library');
9186: foreach my $tryserver (keys(%servers)) {
9187: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9188: push(@homeservers,$tryserver);
9189: }
1.584 raeburn 9190: }
1.1022 raeburn 9191: } elsif ($caller eq 'requests') {
9192: if ($codedom =~ /^$match_domain$/) {
9193: my $chome = &domain($codedom,'primary');
9194: unless ($chome eq 'no_host') {
9195: push(@homeservers,$chome);
9196: }
9197: }
1.521 raeburn 9198: } else {
1.772 raeburn 9199: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 9200: }
1.793 albertel 9201: foreach my $code (keys(%{$instcodes})) {
9202: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 9203: }
9204: chop($courses);
1.772 raeburn 9205: my $ok_response = 0;
9206: my $response;
9207: while (@homeservers > 0 && $ok_response == 0) {
9208: my $server = shift(@homeservers);
9209: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9210: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9211: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 9212: split(/:/,$response);
1.772 raeburn 9213: %{$codes} = (%{$codes},&str2hash($codes_str));
9214: push(@{$codetitles},&str2array($codetitles_str));
9215: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9216: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9217: $ok_response = 1;
9218: }
9219: }
9220: if ($ok_response) {
1.521 raeburn 9221: return 'ok';
1.772 raeburn 9222: } else {
9223: return $response;
1.521 raeburn 9224: }
9225: }
9226:
1.792 raeburn 9227: sub auto_instcode_defaults {
9228: my ($domain,$returnhash,$code_order) = @_;
9229: my @homeservers;
1.841 albertel 9230:
9231: my %servers = &get_servers($domain,'library');
9232: foreach my $tryserver (keys(%servers)) {
9233: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9234: push(@homeservers,$tryserver);
9235: }
1.792 raeburn 9236: }
1.841 albertel 9237:
1.792 raeburn 9238: my $response;
1.841 albertel 9239: foreach my $server (@homeservers) {
1.792 raeburn 9240: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 9241: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9242:
9243: foreach my $pair (split(/\&/,$response)) {
9244: my ($name,$value)=split(/\=/,$pair);
9245: if ($name eq 'code_order') {
9246: @{$code_order} = split(/\&/,&unescape($value));
9247: } else {
9248: $returnhash->{&unescape($name)}=&unescape($value);
9249: }
9250: }
9251: return 'ok';
1.792 raeburn 9252: }
1.841 albertel 9253:
9254: return $response;
1.1003 raeburn 9255: }
9256:
9257: sub auto_possible_instcodes {
1.1007 raeburn 9258: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9259: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9260: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9261: return;
9262: }
1.1003 raeburn 9263: my (@homeservers,$uhome);
9264: if (defined(&domain($domain,'primary'))) {
9265: $uhome=&domain($domain,'primary');
9266: push(@homeservers,&domain($domain,'primary'));
9267: } else {
9268: my %servers = &get_servers($domain,'library');
9269: foreach my $tryserver (keys(%servers)) {
9270: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9271: push(@homeservers,$tryserver);
9272: }
9273: }
9274: }
9275: my $response;
9276: foreach my $server (@homeservers) {
9277: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9278: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 9279: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9280: split(':',$response);
9281: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9282: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 9283: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 9284: my ($name,$value)=split('=',$item);
9285: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9286: }
9287: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 9288: my ($name,$value)=split('=',$item);
9289: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 9290: }
9291: return 'ok';
9292: }
9293: return $response;
9294: }
1.792 raeburn 9295:
1.1010 raeburn 9296: sub auto_courserequest_checks {
9297: my ($dom) = @_;
1.1020 raeburn 9298: my ($homeserver,%validations);
9299: if ($dom =~ /^$match_domain$/) {
9300: $homeserver = &domain($dom,'primary');
9301: }
9302: unless ($homeserver eq 'no_host') {
9303: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9304: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9305: my @items = split(/&/,$response);
9306: foreach my $item (@items) {
9307: my ($key,$value) = split('=',$item);
9308: $validations{&unescape($key)} = &thaw_unescape($value);
9309: }
9310: }
9311: }
1.1010 raeburn 9312: return %validations;
9313: }
9314:
1.1020 raeburn 9315: sub auto_courserequest_validation {
1.1172.2.43 raeburn 9316: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 9317: my ($homeserver,$response);
9318: if ($dom =~ /^$match_domain$/) {
9319: $homeserver = &domain($dom,'primary');
9320: }
1.1172.2.43 raeburn 9321: unless ($homeserver eq 'no_host') {
9322: my $customdata;
9323: if (ref($custominfo) eq 'HASH') {
9324: $customdata = &freeze_escape($custominfo);
9325: }
1.1020 raeburn 9326: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 9327: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43 raeburn 9328: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9329: $customdata,$homeserver));
1.1020 raeburn 9330: }
9331: return $response;
9332: }
9333:
1.777 albertel 9334: sub auto_validate_class_sec {
1.918 raeburn 9335: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 9336: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 9337: my $ownerlist;
9338: if (ref($owners) eq 'ARRAY') {
9339: $ownerlist = join(',',@{$owners});
9340: } else {
9341: $ownerlist = $owners;
9342: }
1.773 raeburn 9343: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 9344: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 9345: return $response;
9346: }
9347:
1.1172.2.141! raeburn 9348: sub auto_instsec_reformat {
! 9349: my ($cdom,$action,$instsecref) = @_;
! 9350: return unless(($action eq 'clutter') || ($action eq 'declutter'));
! 9351: my @homeservers;
! 9352: if (defined(&domain($cdom,'primary'))) {
! 9353: push(@homeservers,&domain($cdom,'primary'));
! 9354: } else {
! 9355: my %servers = &get_servers($cdom,'library');
! 9356: foreach my $tryserver (keys(%servers)) {
! 9357: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
! 9358: push(@homeservers,$tryserver);
! 9359: }
! 9360: }
! 9361: }
! 9362: my $response;
! 9363: my %reformatted = %{$instsecref};
! 9364: foreach my $server (@homeservers) {
! 9365: if (ref($instsecref) eq 'HASH') {
! 9366: my $info = &freeze_escape($instsecref);
! 9367: my $response=&reply('autoinstsecreformat:'.$cdom.':'.
! 9368: $action.':'.$info,$server);
! 9369: next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
! 9370: my @items = split(/&/,$response);
! 9371: foreach my $item (@items) {
! 9372: my ($key,$value) = split(/=/,$item);
! 9373: $reformatted{&unescape($key)} = &thaw_unescape($value);
! 9374: }
! 9375: }
! 9376: }
! 9377: return %reformatted;
! 9378: }
! 9379:
1.1172.2.94 raeburn 9380: sub auto_validate_instclasses {
9381: my ($cdom,$cnum,$owners,$classesref) = @_;
9382: my ($homeserver,%validations);
9383: $homeserver = &homeserver($cnum,$cdom);
9384: unless ($homeserver eq 'no_host') {
9385: my $ownerlist;
9386: if (ref($owners) eq 'ARRAY') {
9387: $ownerlist = join(',',@{$owners});
9388: } else {
9389: $ownerlist = $owners;
9390: }
9391: if (ref($classesref) eq 'HASH') {
9392: my $classes = &freeze_escape($classesref);
9393: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9394: ':'.$cdom.':'.$classes,$homeserver);
9395: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9396: my @items = split(/&/,$response);
9397: foreach my $item (@items) {
9398: my ($key,$value) = split('=',$item);
9399: $validations{&unescape($key)} = &thaw_unescape($value);
9400: }
9401: }
9402: }
9403: }
9404: return %validations;
9405: }
9406:
1.1172.2.38 raeburn 9407: sub auto_crsreq_update {
9408: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45 raeburn 9409: $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38 raeburn 9410: my ($homeserver,%crsreqresponse);
9411: if ($cdom =~ /^$match_domain$/) {
9412: $homeserver = &domain($cdom,'primary');
9413: }
9414: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9415: my $info;
9416: if (ref($inbound) eq 'HASH') {
9417: $info = &freeze_escape($inbound);
9418: }
9419: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9420: ':'.&escape($action).':'.&escape($ownername).':'.
9421: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45 raeburn 9422: &escape($title).':'.&escape($code).':'.
9423: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38 raeburn 9424: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9425: my @items = split(/&/,$response);
9426: foreach my $item (@items) {
9427: my ($key,$value) = split('=',$item);
9428: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9429: }
9430: }
9431: }
9432: return \%crsreqresponse;
9433: }
9434:
1.1172.2.78 raeburn 9435: sub auto_export_grades {
9436: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9437: my ($homeserver,%exportresponse);
9438: if ($cdom =~ /^$match_domain$/) {
9439: $homeserver = &domain($cdom,'primary');
9440: }
9441: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9442: my $info;
9443: if (ref($inforef) eq 'HASH') {
9444: $info = &freeze_escape($inforef);
9445: }
9446: if (ref($gradesref) eq 'HASH') {
9447: my $grades = &freeze_escape($gradesref);
9448: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9449: $info.':'.$grades,$homeserver);
9450: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9451: my @items = split(/&/,$response);
9452: foreach my $item (@items) {
9453: my ($key,$value) = split('=',$item);
9454: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9455: }
9456: }
9457: }
9458: }
9459: return \%exportresponse;
9460: }
9461:
1.1172.2.68 raeburn 9462: sub check_instcode_cloning {
9463: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9464: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9465: return;
9466: }
9467: my $canclone;
9468: if (@{$code_order} > 0) {
9469: my $instcoderegexp ='^';
9470: my @clonecodes = split(/\&/,$cloner);
9471: foreach my $item (@{$code_order}) {
9472: if (grep(/^\Q$item\E=/,@clonecodes)) {
9473: foreach my $pair (@clonecodes) {
9474: my ($key,$val) = split(/\=/,$pair,2);
9475: $val = &unescape($val);
9476: if ($key eq $item) {
9477: $instcoderegexp .= '('.$val.')';
9478: last;
9479: }
9480: }
9481: } else {
9482: $instcoderegexp .= $codedefaults->{$item};
9483: }
9484: }
9485: $instcoderegexp .= '$';
9486: my (@from,@to);
9487: eval {
9488: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9489: (@to) = ($clonetocode =~ /$instcoderegexp/);
9490: };
9491: if ((@from > 0) && (@to > 0)) {
9492: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9493: if (!@diffs) {
9494: $canclone = 1;
9495: }
9496: }
9497: }
9498: return $canclone;
9499: }
9500:
9501: sub default_instcode_cloning {
9502: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9503: my (%codedefaults,@code_order,$canclone);
9504: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9505: %codedefaults = %{$codedefaultsref};
9506: @code_order = @{$codeorderref};
9507: } elsif ($clonedom) {
9508: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9509: }
9510: if (($domdefclone) && (@code_order)) {
9511: my @clonecodes = split(/\+/,$domdefclone);
9512: my $instcoderegexp ='^';
9513: foreach my $item (@code_order) {
9514: if (grep(/^\Q$item\E$/,@clonecodes)) {
9515: $instcoderegexp .= '('.$codedefaults{$item}.')';
9516: } else {
9517: $instcoderegexp .= $codedefaults{$item};
9518: }
9519: }
9520: $instcoderegexp .= '$';
9521: my (@from,@to);
9522: eval {
9523: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9524: (@to) = ($clonetocode =~ /$instcoderegexp/);
9525: };
9526: if ((@from > 0) && (@to > 0)) {
9527: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9528: if (!@diffs) {
9529: $canclone = 1;
9530: }
9531: }
9532: }
9533: return $canclone;
9534: }
9535:
1.679 raeburn 9536: # ------------------------------------------------------- Course Group routines
9537:
9538: sub get_coursegroups {
1.809 raeburn 9539: my ($cdom,$cnum,$group,$namespace) = @_;
9540: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 9541: }
9542:
1.679 raeburn 9543: sub modify_coursegroup {
9544: my ($cdom,$cnum,$groupsettings) = @_;
9545: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9546: }
9547:
1.809 raeburn 9548: sub toggle_coursegroup_status {
9549: my ($cdom,$cnum,$group,$action) = @_;
9550: my ($from_namespace,$to_namespace);
9551: if ($action eq 'delete') {
9552: $from_namespace = 'coursegroups';
9553: $to_namespace = 'deleted_groups';
9554: } else {
9555: $from_namespace = 'deleted_groups';
9556: $to_namespace = 'coursegroups';
9557: }
9558: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 9559: if (my $tmp = &error(%curr_group)) {
9560: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9561: return ('read error',$tmp);
9562: } else {
9563: my %savedsettings = %curr_group;
1.809 raeburn 9564: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 9565: my $deloutcome;
9566: if ($result eq 'ok') {
1.809 raeburn 9567: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 9568: } else {
9569: return ('write error',$result);
9570: }
9571: if ($deloutcome eq 'ok') {
9572: return 'ok';
9573: } else {
9574: return ('delete error',$deloutcome);
9575: }
9576: }
9577: }
9578:
1.679 raeburn 9579: sub modify_group_roles {
1.957 raeburn 9580: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 9581: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9582: my $role = 'gr/'.&escape($userprivs);
9583: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 9584: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 9585: if ($result eq 'ok') {
9586: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9587: }
1.679 raeburn 9588: return $result;
9589: }
9590:
9591: sub modify_coursegroup_membership {
9592: my ($cdom,$cnum,$membership) = @_;
9593: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9594: return $result;
9595: }
9596:
1.682 raeburn 9597: sub get_active_groups {
9598: my ($udom,$uname,$cdom,$cnum) = @_;
9599: my $now = time;
9600: my %groups = ();
9601: foreach my $key (keys(%env)) {
1.811 albertel 9602: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 9603: my ($start,$end) = split(/\./,$env{$key});
9604: if (($end!=0) && ($end<$now)) { next; }
9605: if (($start!=0) && ($start>$now)) { next; }
9606: if ($1 eq $cdom && $2 eq $cnum) {
9607: $groups{$3} = $env{$key} ;
9608: }
9609: }
9610: }
9611: return %groups;
9612: }
9613:
1.683 raeburn 9614: sub get_group_membership {
9615: my ($cdom,$cnum,$group) = @_;
9616: return(&dump('groupmembership',$cdom,$cnum,$group));
9617: }
9618:
9619: sub get_users_groups {
9620: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 9621: my @usersgroups;
1.683 raeburn 9622: my $cachetime=1800;
9623:
9624: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 9625: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9626: if (defined($cached)) {
1.734 albertel 9627: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 9628: } else {
9629: $grouplist = '';
1.816 raeburn 9630: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 9631: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 9632: my $access_end = $env{'course.'.$courseid.
9633: '.default_enrollment_end_date'};
9634: my $now = time;
9635: foreach my $key (keys(%roleshash)) {
9636: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9637: my $group = $1;
9638: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9639: my $start = $2;
9640: my $end = $1;
9641: if ($start == -1) { next; } # deleted from group
9642: if (($start!=0) && ($start>$now)) { next; }
9643: if (($end!=0) && ($end<$now)) {
9644: if ($access_end && $access_end < $now) {
9645: if ($access_end - $end < 86400) {
9646: push(@usersgroups,$group);
1.733 raeburn 9647: }
9648: }
1.817 raeburn 9649: next;
1.733 raeburn 9650: }
1.817 raeburn 9651: push(@usersgroups,$group);
1.683 raeburn 9652: }
9653: }
9654: }
1.817 raeburn 9655: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9656: $grouplist = join(':',@usersgroups);
9657: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 9658: }
1.733 raeburn 9659: return @usersgroups;
1.683 raeburn 9660: }
9661:
9662: sub devalidate_getgroups_cache {
9663: my ($udom,$uname,$cdom,$cnum)=@_;
9664: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 9665:
1.683 raeburn 9666: my $hashid="$udom:$uname:$courseid";
9667: &devalidate_cache_new('getgroups',$hashid);
9668: }
9669:
1.12 www 9670: # ------------------------------------------------------------------ Plain Text
9671:
9672: sub plaintext {
1.988 raeburn 9673: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 9674: if ($short =~ m{^cr/}) {
1.758 albertel 9675: return (split('/',$short))[-1];
9676: }
1.742 raeburn 9677: if (!defined($cid)) {
9678: $cid = $env{'request.course.id'};
9679: }
9680: my %rolenames = (
1.1008 raeburn 9681: Course => 'std',
9682: Community => 'alt1',
1.742 raeburn 9683: );
1.1037 raeburn 9684: if ($cid ne '') {
9685: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9686: unless ($forcedefault) {
9687: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9688: &Apache::lonlocal::mt_escape(\$roletext);
9689: return &Apache::lonlocal::mt($roletext);
9690: }
9691: }
9692: }
9693: if ((defined($type)) && (defined($rolenames{$type})) &&
9694: (defined($rolenames{$type})) &&
9695: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 9696: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 9697: } elsif ($cid ne '') {
9698: my $crstype = $env{'course.'.$cid.'.type'};
9699: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9700: (defined($prp{$short}{$rolenames{$crstype}}))) {
9701: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9702: }
1.742 raeburn 9703: }
1.1037 raeburn 9704: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 9705: }
9706:
9707: # ----------------------------------------------------------------- Assign Role
9708:
9709: sub assignrole {
1.957 raeburn 9710: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9711: $context)=@_;
1.21 www 9712: my $mrole;
9713: if ($role =~ /^cr\//) {
1.393 www 9714: my $cwosec=$url;
1.811 albertel 9715: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 9716: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 9717: my $refused = 1;
9718: if ($context eq 'requestcourses') {
9719: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9720: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9721: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9722: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9723: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9724: if ($crsenv{'internal.courseowner'} eq
9725: $env{'user.name'}.':'.$env{'user.domain'}) {
9726: $refused = '';
9727: }
9728: }
9729: }
9730: }
9731: }
9732: if ($refused) {
9733: &logthis('Refused custom assignrole: '.
9734: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9735: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9736: return 'refused';
9737: }
1.104 www 9738: }
1.21 www 9739: $mrole='cr';
1.678 raeburn 9740: } elsif ($role =~ /^gr\//) {
9741: my $cwogrp=$url;
1.811 albertel 9742: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 9743: unless (&allowed('mdg',$cwogrp)) {
9744: &logthis('Refused group assignrole: '.
9745: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9746: $env{'user.name'}.' at '.$env{'user.domain'});
9747: return 'refused';
9748: }
9749: $mrole='gr';
1.21 www 9750: } else {
1.82 www 9751: my $cwosec=$url;
1.811 albertel 9752: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9753: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9754: my $refused;
9755: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9756: if (!(&allowed('c'.$role,$url))) {
9757: $refused = 1;
9758: }
9759: } else {
9760: $refused = 1;
9761: }
1.947 raeburn 9762: if ($refused) {
1.1045 raeburn 9763: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9764: if (!$selfenroll && $context eq 'course') {
9765: my %crsenv;
9766: if ($role eq 'cc' || $role eq 'co') {
9767: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9768: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9769: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9770: if ($crsenv{'internal.courseowner'} eq
9771: $env{'user.name'}.':'.$env{'user.domain'}) {
9772: $refused = '';
9773: }
9774: }
9775: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9776: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9777: if ($crsenv{'internal.courseowner'} eq
9778: $env{'user.name'}.':'.$env{'user.domain'}) {
9779: $refused = '';
9780: }
9781: }
9782: }
9783: }
9784: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 9785: $refused = '';
1.1017 raeburn 9786: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9787: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9788: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9789: my $wrongcc;
9790: if ($cnum =~ /^$match_community$/) {
9791: $wrongcc = 1 if ($role eq 'cc');
9792: } else {
9793: $wrongcc = 1 if ($role eq 'co');
9794: }
9795: unless ($wrongcc) {
9796: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9797: if ($crsenv{'internal.courseowner'} eq
9798: $env{'user.name'}.':'.$env{'user.domain'}) {
9799: $refused = '';
9800: }
1.1017 raeburn 9801: }
9802: }
1.1172.2.9 raeburn 9803: } elsif ($context eq 'requestauthor') {
9804: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9805: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9806: if ($env{'environment.requestauthor'} eq 'automatic') {
9807: $refused = '';
9808: } else {
9809: my %domdefaults = &get_domain_defaults($udom);
9810: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9811: my $checkbystatus;
9812: if ($env{'user.adv'}) {
9813: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9814: if ($disposition eq 'automatic') {
9815: $refused = '';
9816: } elsif ($disposition eq '') {
9817: $checkbystatus = 1;
9818: }
9819: } else {
9820: $checkbystatus = 1;
9821: }
9822: if ($checkbystatus) {
9823: if ($env{'environment.inststatus'}) {
9824: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9825: foreach my $type (@inststatuses) {
9826: if (($type ne '') &&
9827: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9828: $refused = '';
9829: }
9830: }
9831: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9832: $refused = '';
9833: }
9834: }
9835: }
9836: }
9837: }
1.1017 raeburn 9838: }
9839: if ($refused) {
1.947 raeburn 9840: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9841: ' '.$role.' '.$end.' '.$start.' by '.
9842: $env{'user.name'}.' at '.$env{'user.domain'});
9843: return 'refused';
9844: }
1.932 raeburn 9845: }
1.1131 raeburn 9846: } elsif ($role eq 'au') {
9847: if ($url ne '/'.$udom.'/') {
9848: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9849: ' to assign author role for '.$uname.':'.$udom.
9850: ' in domain: '.$url.' refused (wrong domain).');
9851: return 'refused';
9852: }
1.104 www 9853: }
1.21 www 9854: $mrole=$role;
9855: }
1.620 albertel 9856: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9857: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9858: if ($end) { $command.='_'.$end; }
1.21 www 9859: if ($start) {
9860: if ($end) {
1.81 www 9861: $command.='_'.$start;
1.21 www 9862: } else {
1.81 www 9863: $command.='_0_'.$start;
1.21 www 9864: }
9865: }
1.739 raeburn 9866: my $origstart = $start;
9867: my $origend = $end;
1.957 raeburn 9868: my $delflag;
1.357 www 9869: # actually delete
9870: if ($deleteflag) {
1.373 www 9871: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9872: # modify command to delete the role
1.620 albertel 9873: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9874: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9875: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9876: # set start and finish to negative values for userrolelog
9877: $start=-1;
9878: $end=-1;
1.957 raeburn 9879: $delflag = 1;
1.357 www 9880: }
9881: }
9882: # send command
1.349 www 9883: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9884: # log new user role if status is ok
1.349 www 9885: if ($answer eq 'ok') {
1.663 raeburn 9886: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9 raeburn 9887: if (($role eq 'cc') || ($role eq 'in') ||
9888: ($role eq 'ep') || ($role eq 'ad') ||
9889: ($role eq 'ta') || ($role eq 'st') ||
9890: ($role=~/^cr/) || ($role eq 'gr') ||
9891: ($role eq 'co')) {
1.1172.2.13 raeburn 9892: # for course roles, perform group memberships changes triggered by role change.
9893: unless ($role =~ /^gr/) {
9894: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9895: $origstart,$selfenroll,$context);
9896: }
1.1172.2.9 raeburn 9897: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9898: $selfenroll,$context);
9899: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90 raeburn 9900: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9901: ($role eq 'da')) {
1.1172.2.9 raeburn 9902: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9903: $context);
9904: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9905: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9906: $context);
9907: }
1.1053 raeburn 9908: if ($role eq 'cc') {
9909: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9910: }
1.349 www 9911: }
9912: return $answer;
1.169 harris41 9913: }
9914:
1.1053 raeburn 9915: sub autoupdate_coowners {
9916: my ($url,$end,$start,$uname,$udom) = @_;
9917: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9918: if (($cdom ne '') && ($cnum ne '')) {
9919: my $now = time;
9920: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9921: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9922: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9923: my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141! raeburn 9924: my $xlists = $coursehash{'internal.crosslistings'};
1.1053 raeburn 9925: if ($instcode ne '') {
1.1056 raeburn 9926: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9927: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 9928: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 9929: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141! raeburn 9930: unless ($result eq 'valid') {
! 9931: if ($xlists ne '') {
! 9932: foreach my $xlist (split(',',$xlists)) {
! 9933: my ($inst_crosslist,$lcsec) = split(':',$xlist);
! 9934: $result =
! 9935: &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
! 9936: $inst_crosslist,$uname.':'.$udom);
! 9937: last if ($result eq 'valid');
! 9938: }
! 9939: }
! 9940: }
1.1056 raeburn 9941: if ($result eq 'valid') {
9942: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 9943: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9944: push(@newcoowners,$coowner);
9945: }
9946: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9947: push(@newcoowners,$uname.':'.$udom);
9948: }
9949: @newcoowners = sort(@newcoowners);
9950: } else {
9951: push(@newcoowners,$uname.':'.$udom);
9952: }
1.1172.2.141! raeburn 9953: } elsif ($coursehash{'internal.co-owners'}) {
! 9954: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
! 9955: unless ($coowner eq $uname.':'.$udom) {
! 9956: push(@newcoowners,$coowner);
1.1053 raeburn 9957: }
9958: }
1.1172.2.141! raeburn 9959: unless (@newcoowners > 0) {
! 9960: $delcoowners = 1;
! 9961: $coowners = '';
! 9962: }
1.1053 raeburn 9963: }
9964: if (@newcoowners || $delcoowners) {
9965: &store_coowners($cdom,$cnum,$coursehash{'home'},
9966: $delcoowners,@newcoowners);
9967: }
9968: }
9969: }
9970: }
9971: }
9972: }
9973: }
9974:
9975: sub store_coowners {
9976: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9977: my $cid = $cdom.'_'.$cnum;
9978: my ($coowners,$delresult,$putresult);
9979: if (@newcoowners) {
9980: $coowners = join(',',@newcoowners);
9981: my %coownershash = (
9982: 'internal.co-owners' => $coowners,
9983: );
9984: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9985: if ($putresult eq 'ok') {
9986: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9987: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9988: }
9989: }
9990: }
9991: if ($delcoowners) {
9992: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9993: if ($delresult eq 'ok') {
9994: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9995: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9996: }
9997: }
9998: }
9999: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10000: my %crsinfo =
10001: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10002: if (ref($crsinfo{$cid}) eq 'HASH') {
10003: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10004: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
10005: }
10006: }
10007: }
10008:
1.169 harris41 10009: # -------------------------------------------------- Modify user authentication
1.197 www 10010: # Overrides without validation
10011:
1.169 harris41 10012: sub modifyuserauth {
10013: my ($udom,$uname,$umode,$upass)=@_;
10014: my $uhome=&homeserver($uname,$udom);
1.1172.2.115 raeburn 10015: my $allowed;
10016: if (&allowed('mau',$udom)) {
10017: $allowed = 1;
10018: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10019: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10020: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10021: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10022: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10023: if (($cdom ne '') && ($cnum ne '')) {
10024: my $is_owner = &is_course_owner($cdom,$cnum);
10025: if ($is_owner) {
10026: $allowed = 1;
10027: }
10028: }
10029: }
10030: unless ($allowed) { return 'refused'; }
1.197 www 10031: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 10032: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10033: ' in domain '.$env{'request.role.domain'});
1.169 harris41 10034: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10035: &escape($upass),$uhome);
1.1172.2.134 raeburn 10036: my $ip = &get_requestor_ip();
1.620 albertel 10037: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 10038: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134 raeburn 10039: '(Remote '.$ip.'): '.$reply);
1.197 www 10040: &log($udom,,$uname,$uhome,
1.620 albertel 10041: 'Authentication changed by '.$env{'user.domain'}.', '.
10042: $env{'user.name'}.', '.$umode.
1.1172.2.134 raeburn 10043: '(Remote '.$ip.'): '.$reply);
1.169 harris41 10044: unless ($reply eq 'ok') {
1.197 www 10045: &logthis('Authentication mode error: '.$reply);
1.169 harris41 10046: return 'error: '.$reply;
10047: }
1.170 harris41 10048: return 'ok';
1.80 www 10049: }
10050:
1.81 www 10051: # --------------------------------------------------------------- Modify a user
1.80 www 10052:
1.81 www 10053: sub modifyuser {
1.206 matthew 10054: my ($udom, $uname, $uid,
10055: $umode, $upass, $first,
10056: $middle, $last, $gene,
1.1058 raeburn 10057: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 10058: $udom= &LONCAPA::clean_domain($udom);
10059: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 10060: my $showcandelete = 'none';
10061: if (ref($candelete) eq 'ARRAY') {
10062: if (@{$candelete} > 0) {
10063: $showcandelete = join(', ',@{$candelete});
10064: }
10065: }
1.81 www 10066: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 10067: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 10068: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 10069: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10070: ' desiredhome not specified').
1.620 albertel 10071: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10072: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 10073: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 10074: my $newuser;
10075: if ($uhome eq 'no_host') {
10076: $newuser = 1;
10077: }
1.80 www 10078: # ----------------------------------------------------------------- Create User
1.406 albertel 10079: if (($uhome eq 'no_host') &&
10080: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 10081: my $unhome='';
1.844 albertel 10082: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 10083: $unhome = $desiredhome;
1.620 albertel 10084: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10085: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 10086: } else { # load balancing routine for determining $unhome
1.81 www 10087: my $loadm=10000000;
1.841 albertel 10088: my %servers = &get_servers($udom,'library');
10089: foreach my $tryserver (keys(%servers)) {
10090: my $answer=reply('load',$tryserver);
10091: if (($answer=~/\d+/) && ($answer<$loadm)) {
10092: $loadm=$answer;
10093: $unhome=$tryserver;
10094: }
1.80 www 10095: }
10096: }
10097: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 10098: return 'error: unable to find a home server for '.$uname.
10099: ' in domain '.$udom;
1.80 www 10100: }
10101: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10102: &escape($upass),$unhome);
10103: unless ($reply eq 'ok') {
10104: return 'error: '.$reply;
10105: }
1.230 stredwic 10106: $uhome=&homeserver($uname,$udom,'true');
1.80 www 10107: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 10108: return 'error: unable verify users home machine.';
1.80 www 10109: }
1.209 matthew 10110: } # End of creation of new user
1.80 www 10111: # ---------------------------------------------------------------------- Add ID
10112: if ($uid) {
10113: $uid=~tr/A-Z/a-z/;
10114: my %uidhash=&idrget($udom,$uname);
1.196 www 10115: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10116: && (!$forceid)) {
1.80 www 10117: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 10118: return 'error: user id "'.$uid.'" does not match '.
10119: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 10120: }
10121: } else {
10122: &idput($udom,($uname => $uid));
10123: }
10124: }
10125: # -------------------------------------------------------------- Add names, etc
1.313 matthew 10126: my @tmp=&get('environment',
1.899 raeburn 10127: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 10128: 'permanentemail','inststatus'],
1.134 albertel 10129: $udom,$uname);
1.1075 raeburn 10130: my (%names,%oldnames);
1.313 matthew 10131: if ($tmp[0] =~ m/^error:.*/) {
10132: %names=();
10133: } else {
10134: %names = @tmp;
1.1075 raeburn 10135: %oldnames = %names;
1.313 matthew 10136: }
1.388 www 10137: #
1.1058 raeburn 10138: # If name, email and/or uid are blank (e.g., because an uploaded file
10139: # of users did not contain them), do not overwrite existing values
10140: # unless field is in $candelete array ref.
10141: #
10142:
10143: my @fields = ('firstname','middlename','lastname','generation',
10144: 'permanentemail','id');
10145: my %newvalues;
10146: if (ref($candelete) eq 'ARRAY') {
10147: foreach my $field (@fields) {
10148: if (grep(/^\Q$field\E$/,@{$candelete})) {
10149: if ($field eq 'firstname') {
10150: $names{$field} = $first;
10151: } elsif ($field eq 'middlename') {
10152: $names{$field} = $middle;
10153: } elsif ($field eq 'lastname') {
10154: $names{$field} = $last;
10155: } elsif ($field eq 'generation') {
10156: $names{$field} = $gene;
10157: } elsif ($field eq 'permanentemail') {
10158: $names{$field} = $email;
10159: } elsif ($field eq 'id') {
10160: $names{$field} = $uid;
10161: }
10162: }
10163: }
10164: }
1.388 www 10165: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 10166: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 10167: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 10168: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 10169: if ($email) {
10170: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 10171: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 10172: }
1.899 raeburn 10173: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 10174: if (defined($inststatus)) {
10175: $names{'inststatus'} = '';
10176: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10177: if (ref($usertypes) eq 'HASH') {
10178: my @okstatuses;
10179: foreach my $item (split(/:/,$inststatus)) {
10180: if (defined($usertypes->{$item})) {
10181: push(@okstatuses,$item);
10182: }
10183: }
10184: if (@okstatuses) {
10185: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10186: }
10187: }
10188: }
1.1075 raeburn 10189: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 10190: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 10191: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 10192: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10193: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10194: } else {
10195: $logmsg .= ' during self creation';
10196: }
1.1075 raeburn 10197: my $changed;
10198: if ($newuser) {
10199: $changed = 1;
10200: } else {
10201: foreach my $field (@fields) {
10202: if ($names{$field} ne $oldnames{$field}) {
10203: $changed = 1;
10204: last;
10205: }
10206: }
10207: }
10208: unless ($changed) {
10209: $logmsg = 'No changes in user information needed for: '.$logmsg;
10210: &logthis($logmsg);
10211: return 'ok';
10212: }
10213: my $reply = &put('environment', \%names, $udom,$uname);
10214: if ($reply ne 'ok') {
10215: return 'error: '.$reply;
10216: }
1.1087 raeburn 10217: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10218: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10219: }
1.1075 raeburn 10220: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10221: &devalidate_cache_new('namescache',$uname.':'.$udom);
10222: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 10223: &logthis($logmsg);
1.134 albertel 10224: return 'ok';
1.80 www 10225: }
10226:
1.81 www 10227: # -------------------------------------------------------------- Modify student
1.80 www 10228:
1.81 www 10229: sub modifystudent {
10230: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 10231: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76 raeburn 10232: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 10233: if (!$cid) {
1.620 albertel 10234: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10235: return 'not_in_class';
10236: }
1.80 www 10237: }
10238: # --------------------------------------------------------------- Make the user
1.81 www 10239: my $reply=&modifyuser
1.209 matthew 10240: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 10241: $desiredhome,$email,$inststatus);
1.80 www 10242: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 10243: # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31 raeburn 10244: # student's environment
1.297 matthew 10245: $uid = undef if (!$forceid);
1.455 albertel 10246: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19 raeburn 10247: $gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76 raeburn 10248: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 10249: return $reply;
10250: }
10251:
10252: sub modify_student_enrollment {
1.1172.2.23 raeburn 10253: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76 raeburn 10254: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 10255: my ($cdom,$cnum,$chome);
10256: if (!$cid) {
1.620 albertel 10257: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 10258: return 'not_in_class';
10259: }
1.620 albertel 10260: $cdom=$env{'course.'.$cid.'.domain'};
10261: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 10262: } else {
10263: ($cdom,$cnum)=split(/_/,$cid);
10264: }
1.620 albertel 10265: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 10266: if (!$chome) {
1.457 raeburn 10267: $chome=&homeserver($cnum,$cdom);
1.297 matthew 10268: }
1.455 albertel 10269: if (!$chome) { return 'unknown_course'; }
1.297 matthew 10270: # Make sure the user exists
1.81 www 10271: my $uhome=&homeserver($uname,$udom);
10272: if (($uhome eq '') || ($uhome eq 'no_host')) {
10273: return 'error: no such user';
10274: }
1.297 matthew 10275: # Get student data if we were not given enough information
10276: if (!defined($first) || $first eq '' ||
10277: !defined($last) || $last eq '' ||
10278: !defined($uid) || $uid eq '' ||
10279: !defined($middle) || $middle eq '' ||
10280: !defined($gene) || $gene eq '') {
1.294 matthew 10281: # They did not supply us with enough data to enroll the student, so
10282: # we need to pick up more information.
1.297 matthew 10283: my %tmp = &get('environment',
1.294 matthew 10284: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 10285: ,$udom,$uname);
10286:
1.800 albertel 10287: #foreach my $key (keys(%tmp)) {
10288: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 10289: #}
1.294 matthew 10290: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10291: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10292: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 10293: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 10294: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10295: }
1.556 albertel 10296: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 10297: my $user = "$uname:$udom";
10298: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 10299: my $reply=cput('classlist',
1.1148 raeburn 10300: {$user =>
1.1172.2.76 raeburn 10301: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 10302: $cdom,$cnum);
1.1148 raeburn 10303: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10304: &devalidate_getsection_cache($udom,$uname,$cid);
10305: } else {
1.81 www 10306: return 'error: '.$reply;
10307: }
1.297 matthew 10308: # Add student role to user
1.83 www 10309: my $uurl='/'.$cid;
1.81 www 10310: $uurl=~s/\_/\//g;
10311: if ($usec) {
10312: $uurl.='/'.$usec;
10313: }
1.1148 raeburn 10314: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10315: $selfenroll,$context);
10316: if ($result ne 'ok') {
10317: if ($old_entry{$user} ne '') {
10318: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10319: } else {
10320: $reply = &del('classlist',[$user],$cdom,$cnum);
10321: }
10322: }
10323: return $result;
1.21 www 10324: }
10325:
1.556 albertel 10326: sub format_name {
10327: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10328: my $name;
10329: if ($first ne 'lastname') {
10330: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10331: } else {
10332: if ($lastname=~/\S/) {
10333: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10334: $name=~s/\s+,/,/;
10335: } else {
10336: $name.= $firstname.' '.$middlename.' '.$generation;
10337: }
10338: }
10339: $name=~s/^\s+//;
10340: $name=~s/\s+$//;
10341: $name=~s/\s+/ /g;
10342: return $name;
10343: }
10344:
1.84 www 10345: # ------------------------------------------------- Write to course preferences
10346:
10347: sub writecoursepref {
10348: my ($courseid,%prefs)=@_;
10349: $courseid=~s/^\///;
10350: $courseid=~s/\_/\//g;
10351: my ($cdomain,$cnum)=split(/\//,$courseid);
10352: my $chome=homeserver($cnum,$cdomain);
10353: if (($chome eq '') || ($chome eq 'no_host')) {
10354: return 'error: no such course';
10355: }
10356: my $cstring='';
1.800 albertel 10357: foreach my $pref (keys(%prefs)) {
10358: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 10359: }
1.84 www 10360: $cstring=~s/\&$//;
10361: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10362: }
10363:
10364: # ---------------------------------------------------------- Make/modify course
10365:
10366: sub createcourse {
1.741 raeburn 10367: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 10368: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 10369: $url=&declutter($url);
10370: my $cid='';
1.1028 raeburn 10371: if ($context eq 'requestcourses') {
10372: my $can_create = 0;
10373: my ($ownername,$ownerdom) = split(':',$course_owner);
10374: if ($udom eq $ownerdom) {
10375: if (&usertools_access($ownername,$ownerdom,$category,undef,
10376: $context)) {
10377: $can_create = 1;
10378: }
10379: } else {
10380: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10381: $category);
10382: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10383: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10384: if (@curr > 0) {
10385: my @options = qw(approval validate autolimit);
10386: my $optregex = join('|',@options);
10387: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10388: $can_create = 1;
10389: }
10390: }
10391: }
10392: }
10393: if ($can_create) {
10394: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10395: unless (&allowed('ccc',$udom)) {
10396: return 'refused';
10397: }
1.1017 raeburn 10398: }
10399: } else {
10400: return 'refused';
10401: }
1.1028 raeburn 10402: } elsif (!&allowed('ccc',$udom)) {
10403: return 'refused';
1.84 www 10404: }
1.1011 raeburn 10405: # --------------------------------------------------------------- Get Unique ID
10406: my $uname;
10407: if ($cnum =~ /^$match_courseid$/) {
10408: my $chome=&homeserver($cnum,$udom,'true');
10409: if (($chome eq '') || ($chome eq 'no_host')) {
10410: $uname = $cnum;
10411: } else {
1.1038 raeburn 10412: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10413: }
10414: } else {
1.1038 raeburn 10415: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 10416: }
10417: return $uname if ($uname =~ /^error/);
10418: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 10419: if (!defined($course_server)) {
10420: if (defined(&domain($udom,'primary'))) {
10421: $course_server = &domain($udom,'primary');
10422: } else {
10423: $course_server = $env{'user.home'};
10424: }
10425: }
10426: my %host_servers =
10427: &Apache::lonnet::get_servers($udom,'library');
10428: unless ($host_servers{$course_server}) {
10429: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 10430: }
1.84 www 10431: # ------------------------------------------------------------- Make the course
10432: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 10433: $course_server);
1.84 www 10434: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 10435: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 10436: if (($uhome eq '') || ($uhome eq 'no_host')) {
10437: return 'error: no such course';
10438: }
1.271 www 10439: # ----------------------------------------------------------------- Course made
1.516 raeburn 10440: # log existence
1.1029 raeburn 10441: my $now = time;
1.918 raeburn 10442: my $newcourse = {
10443: $udom.'_'.$uname => {
1.921 raeburn 10444: description => $description,
10445: inst_code => $inst_code,
10446: owner => $course_owner,
10447: type => $crstype,
1.1029 raeburn 10448: creator => $env{'user.name'}.':'.
10449: $env{'user.domain'},
10450: created => $now,
10451: context => $context,
1.918 raeburn 10452: },
10453: };
1.921 raeburn 10454: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 10455: # set toplevel url
1.271 www 10456: my $topurl=$url;
10457: unless ($nonstandard) {
10458: # ------------------------------------------ For standard courses, make top url
10459: my $mapurl=&clutter($url);
1.278 www 10460: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 10461: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 10462: <map>
10463: <resource id="1" type="start"></resource>
10464: <resource id="2" src="$mapurl"></resource>
10465: <resource id="3" type="finish"></resource>
10466: <link index="1" from="1" to="2"></link>
10467: <link index="2" from="2" to="3"></link>
10468: </map>
10469: ENDINITMAP
10470: $topurl=&declutter(
1.638 albertel 10471: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 10472: );
10473: }
10474: # ----------------------------------------------------------- Write preferences
1.84 www 10475: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 10476: ('description' => $description,
10477: 'url' => $topurl,
10478: 'internal.creator' => $env{'user.name'}.':'.
10479: $env{'user.domain'},
10480: 'internal.created' => $now,
10481: 'internal.creationcontext' => $context)
10482: );
1.84 www 10483: return '/'.$udom.'/'.$uname;
10484: }
10485:
1.1011 raeburn 10486: # ------------------------------------------------------------------- Create ID
10487: sub generate_coursenum {
1.1038 raeburn 10488: my ($udom,$crstype) = @_;
1.1011 raeburn 10489: my $domdesc = &domain($udom);
10490: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 10491: my $first;
10492: if ($crstype eq 'Community') {
10493: $first = '0';
10494: } else {
10495: $first = int(1+rand(9));
10496: }
10497: my $uname=$first.
1.1011 raeburn 10498: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10499: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10500: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10501: # ----------------------------------------------- Make sure that does not exist
10502: my $uhome=&homeserver($uname,$udom,'true');
10503: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 10504: if ($crstype eq 'Community') {
10505: $first = '0';
10506: } else {
10507: $first = int(1+rand(9));
10508: }
10509: $uname=$first.
1.1011 raeburn 10510: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10511: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10512: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10513: $uhome=&homeserver($uname,$udom,'true');
10514: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10515: return 'error: unable to generate unique course-ID';
10516: }
10517: }
10518: return $uname;
10519: }
10520:
1.813 albertel 10521: sub is_course {
1.1167 droeschl 10522: my ($cdom, $cnum) = scalar(@_) == 1 ?
10523: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
1.1172.2.95 raeburn 10524: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10525: my $uhome=&homeserver($cnum,$cdom);
10526: my $iscourse;
10527: if (grep { $_ eq $uhome } current_machine_ids()) {
10528: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10529: } else {
10530: my $hashid = $cdom.':'.$cnum;
10531: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10532: unless (defined($cached)) {
10533: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10534: $cnum,undef,undef,'.');
10535: $iscourse = 0;
10536: if (exists($courses{$cdom.'_'.$cnum})) {
10537: $iscourse = 1;
10538: }
10539: &do_cache_new('iscourse',$hashid,$iscourse,3600);
10540: }
10541: }
10542: return unless($iscourse);
1.1167 droeschl 10543: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 10544: }
10545:
1.1015 raeburn 10546: sub store_userdata {
10547: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 10548: my $result;
1.1016 raeburn 10549: if ($datakey ne '') {
1.1013 raeburn 10550: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 10551: if ($udom eq '' || $uname eq '') {
10552: $udom = $env{'user.domain'};
10553: $uname = $env{'user.name'};
10554: }
10555: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 10556: if (($uhome eq '') || ($uhome eq 'no_host')) {
10557: $result = 'error: no_host';
10558: } else {
1.1172.2.138 raeburn 10559: $storehash->{'ip'} = &get_requestor_ip();
1.1013 raeburn 10560: $storehash->{'host'} = $perlvar{'lonHostID'};
10561:
10562: my $namevalue='';
10563: foreach my $key (keys(%{$storehash})) {
10564: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10565: }
10566: $namevalue=~s/\&$//;
1.1172.2.26 raeburn 10567: unless ($namespace eq 'courserequests') {
10568: $datakey = &escape($datakey);
10569: }
1.1105 raeburn 10570: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10571: $namevalue,$uhome);
1.1013 raeburn 10572: }
10573: } else {
10574: $result = 'error: data to store was not a hash reference';
10575: }
10576: } else {
10577: $result= 'error: invalid requestkey';
10578: }
10579: return $result;
10580: }
10581:
1.21 www 10582: # ---------------------------------------------------------- Assign Custom Role
10583:
10584: sub assigncustomrole {
1.957 raeburn 10585: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10586: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 10587: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 10588: }
10589:
10590: # ----------------------------------------------------------------- Revoke Role
10591:
10592: sub revokerole {
1.957 raeburn 10593: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10594: my $now=time;
1.965 raeburn 10595: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 10596: }
10597:
10598: # ---------------------------------------------------------- Revoke Custom Role
10599:
10600: sub revokecustomrole {
1.957 raeburn 10601: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10602: my $now=time;
1.357 www 10603: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 10604: $deleteflag,$selfenroll,$context);
1.17 www 10605: }
10606:
1.533 banghart 10607: # ------------------------------------------------------------ Disk usage
1.535 albertel 10608: sub diskusage {
1.955 raeburn 10609: my ($udom,$uname,$directorypath,$getpropath)=@_;
10610: $directorypath =~ s/\/$//;
10611: my $listing=&reply('du2:'.&escape($directorypath).':'
10612: .&escape($getpropath).':'.&escape($uname).':'
10613: .&escape($udom),homeserver($uname,$udom));
10614: if ($listing eq 'unknown_cmd') {
10615: if ($getpropath) {
10616: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10617: }
10618: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10619: }
1.514 albertel 10620: return $listing;
1.512 banghart 10621: }
10622:
1.566 banghart 10623: sub is_locked {
1.1096 raeburn 10624: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 10625: my @check;
10626: my $is_locked;
1.1093 raeburn 10627: push (@check,$file_name);
1.613 albertel 10628: my %locked = &get('file_permissions',\@check,
1.620 albertel 10629: $env{'user.domain'},$env{'user.name'});
1.615 albertel 10630: my ($tmp)=keys(%locked);
10631: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 10632:
1.566 banghart 10633: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 10634: $is_locked = 'false';
10635: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 10636: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 10637: $is_locked = 'true';
1.1096 raeburn 10638: if (ref($which) eq 'ARRAY') {
10639: push(@{$which},$entry);
10640: } else {
10641: last;
10642: }
1.745 raeburn 10643: }
10644: }
1.566 banghart 10645: } else {
10646: $is_locked = 'false';
10647: }
1.1093 raeburn 10648: return $is_locked;
1.566 banghart 10649: }
10650:
1.759 albertel 10651: sub declutter_portfile {
10652: my ($file) = @_;
1.833 albertel 10653: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 10654: return $file;
10655: }
10656:
1.559 banghart 10657: # ------------------------------------------------------------- Mark as Read Only
10658:
10659: sub mark_as_readonly {
10660: my ($domain,$user,$files,$what) = @_;
1.613 albertel 10661: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10662: my ($tmp)=keys(%current_permissions);
10663: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 10664: foreach my $file (@{$files}) {
1.759 albertel 10665: $file = &declutter_portfile($file);
1.561 banghart 10666: push(@{$current_permissions{$file}},$what);
1.559 banghart 10667: }
1.613 albertel 10668: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10669: return;
10670: }
10671:
1.572 banghart 10672: # ------------------------------------------------------------Save Selected Files
10673:
10674: sub save_selected_files {
10675: my ($user, $path, @files) = @_;
10676: my $filename = $user."savedfiles";
1.573 banghart 10677: my @other_files = &files_not_in_path($user, $path);
1.1172.2.96 raeburn 10678: open (OUT,'>',LONCAPA::tempdir().$filename);
1.573 banghart 10679: foreach my $file (@files) {
1.620 albertel 10680: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 10681: }
10682: foreach my $file (@other_files) {
1.574 banghart 10683: print (OUT $file."\n");
1.572 banghart 10684: }
1.574 banghart 10685: close (OUT);
1.572 banghart 10686: return 'ok';
10687: }
10688:
1.574 banghart 10689: sub clear_selected_files {
10690: my ($user) = @_;
10691: my $filename = $user."savedfiles";
1.1172.2.96 raeburn 10692: open (OUT,'>',LONCAPA::tempdir().$filename);
1.574 banghart 10693: print (OUT undef);
10694: close (OUT);
10695: return ("ok");
10696: }
10697:
1.572 banghart 10698: sub files_in_path {
10699: my ($user, $path) = @_;
10700: my $filename = $user."savedfiles";
10701: my %return_files;
1.1172.2.96 raeburn 10702: open (IN,'<',LONCAPA::tempdir().$filename);
1.573 banghart 10703: while (my $line_in = <IN>) {
1.574 banghart 10704: chomp ($line_in);
10705: my @paths_and_file = split (m!/!, $line_in);
10706: my $file_part = pop (@paths_and_file);
10707: my $path_part = join ('/', @paths_and_file);
1.573 banghart 10708: $path_part.='/';
10709: my $path_and_file = $path_part.$file_part;
10710: if ($path_part eq $path) {
10711: $return_files{$file_part}= 'selected';
10712: }
10713: }
1.574 banghart 10714: close (IN);
10715: return (\%return_files);
1.572 banghart 10716: }
10717:
10718: # called in portfolio select mode, to show files selected NOT in current directory
10719: sub files_not_in_path {
10720: my ($user, $path) = @_;
10721: my $filename = $user."savedfiles";
10722: my @return_files;
10723: my $path_part;
1.1172.2.96 raeburn 10724: open(IN, '<',LONCAPA::tempdir().$filename);
1.800 albertel 10725: while (my $line = <IN>) {
1.572 banghart 10726: #ok, I know it's clunky, but I want it to work
1.800 albertel 10727: my @paths_and_file = split(m|/|, $line);
10728: my $file_part = pop(@paths_and_file);
10729: chomp($file_part);
10730: my $path_part = join('/', @paths_and_file);
1.572 banghart 10731: $path_part .= '/';
10732: my $path_and_file = $path_part.$file_part;
10733: if ($path_part ne $path) {
1.800 albertel 10734: push(@return_files, ($path_and_file));
1.572 banghart 10735: }
10736: }
1.800 albertel 10737: close(OUT);
1.574 banghart 10738: return (@return_files);
1.572 banghart 10739: }
10740:
1.745 raeburn 10741: #----------------------------------------------Get portfolio file permissions
1.629 banghart 10742:
1.745 raeburn 10743: sub get_portfile_permissions {
10744: my ($domain,$user) = @_;
1.613 albertel 10745: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10746: my ($tmp)=keys(%current_permissions);
10747: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10748: return \%current_permissions;
10749: }
10750:
10751: #---------------------------------------------Get portfolio file access controls
10752:
1.749 raeburn 10753: sub get_access_controls {
1.745 raeburn 10754: my ($current_permissions,$group,$file) = @_;
1.769 albertel 10755: my %access;
10756: my $real_file = $file;
10757: $file =~ s/\.meta$//;
1.745 raeburn 10758: if (defined($file)) {
1.749 raeburn 10759: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10760: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 10761: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 10762: }
10763: }
1.745 raeburn 10764: } else {
1.749 raeburn 10765: foreach my $key (keys(%{$current_permissions})) {
10766: if ($key =~ /\0accesscontrol$/) {
10767: if (defined($group)) {
10768: if ($key !~ m-^\Q$group\E/-) {
10769: next;
10770: }
10771: }
10772: my ($fullpath) = split(/\0/,$key);
10773: if (ref($$current_permissions{$key}) eq 'HASH') {
10774: foreach my $control (keys(%{$$current_permissions{$key}})) {
10775: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10776: }
10777: }
10778: }
10779: }
10780: }
10781: return %access;
10782: }
10783:
10784: sub modify_access_controls {
10785: my ($file_name,$changes,$domain,$user)=@_;
10786: my ($outcome,$deloutcome);
10787: my %store_permissions;
10788: my %new_values;
10789: my %new_control;
10790: my %translation;
10791: my @deletions = ();
10792: my $now = time;
10793: if (exists($$changes{'activate'})) {
10794: if (ref($$changes{'activate'}) eq 'HASH') {
10795: my @newitems = sort(keys(%{$$changes{'activate'}}));
10796: my $numnew = scalar(@newitems);
10797: for (my $i=0; $i<$numnew; $i++) {
10798: my $newkey = $newitems[$i];
10799: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10800: if ($newkey =~ /^\d+:/) {
10801: $newkey =~ s/^(\d+)/$newid/;
10802: $translation{$1} = $newid;
10803: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10804: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10805: $translation{$1} = $newid;
10806: }
1.749 raeburn 10807: $new_values{$file_name."\0".$newkey} =
10808: $$changes{'activate'}{$newitems[$i]};
10809: $new_control{$newkey} = $now;
10810: }
10811: }
10812: }
10813: my %todelete;
10814: my %changed_items;
10815: foreach my $action ('delete','update') {
10816: if (exists($$changes{$action})) {
10817: if (ref($$changes{$action}) eq 'HASH') {
10818: foreach my $key (keys(%{$$changes{$action}})) {
10819: my ($itemnum) = ($key =~ /^([^:]+):/);
10820: if ($action eq 'delete') {
10821: $todelete{$itemnum} = 1;
10822: } else {
10823: $changed_items{$itemnum} = $key;
10824: }
10825: }
1.745 raeburn 10826: }
10827: }
1.749 raeburn 10828: }
10829: # get lock on access controls for file.
10830: my $lockhash = {
10831: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10832: ':'.$env{'user.domain'},
10833: };
10834: my $tries = 0;
10835: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10836:
1.1172.2.79 raeburn 10837: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10838: $tries ++;
1.1172.2.79 raeburn 10839: sleep(0.1);
1.749 raeburn 10840: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10841: }
10842: if ($gotlock eq 'ok') {
10843: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10844: my ($tmp)=keys(%curr_permissions);
10845: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10846: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10847: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10848: if (ref($curr_controls) eq 'HASH') {
10849: foreach my $control_item (keys(%{$curr_controls})) {
10850: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10851: if (defined($todelete{$itemnum})) {
10852: push(@deletions,$file_name."\0".$control_item);
10853: } else {
10854: if (defined($changed_items{$itemnum})) {
10855: $new_control{$changed_items{$itemnum}} = $now;
10856: push(@deletions,$file_name."\0".$control_item);
10857: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10858: } else {
10859: $new_control{$control_item} = $$curr_controls{$control_item};
10860: }
10861: }
1.745 raeburn 10862: }
10863: }
10864: }
1.970 raeburn 10865: my ($group);
10866: if (&is_course($domain,$user)) {
10867: ($group,my $file) = split(/\//,$file_name,2);
10868: }
1.749 raeburn 10869: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10870: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10871: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10872: # remove lock
10873: my @del_lock = ($file_name."\0".'locked_access_records');
10874: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 10875: my $sqlresult =
1.970 raeburn 10876: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 10877: $group);
1.749 raeburn 10878: } else {
10879: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 10880: }
1.749 raeburn 10881: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 10882: }
10883:
1.827 raeburn 10884: sub make_public_indefinitely {
10885: my ($requrl) = @_;
10886: my $now = time;
10887: my $action = 'activate';
10888: my $aclnum = 0;
10889: if (&is_portfolio_url($requrl)) {
10890: my (undef,$udom,$unum,$file_name,$group) =
10891: &parse_portfolio_url($requrl);
10892: my $current_perms = &get_portfile_permissions($udom,$unum);
10893: my %access_controls = &get_access_controls($current_perms,
10894: $group,$file_name);
10895: foreach my $key (keys(%{$access_controls{$file_name}})) {
10896: my ($num,$scope,$end,$start) =
10897: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10898: if ($scope eq 'public') {
10899: if ($start <= $now && $end == 0) {
10900: $action = 'none';
10901: } else {
10902: $action = 'update';
10903: $aclnum = $num;
10904: }
10905: last;
10906: }
10907: }
10908: if ($action eq 'none') {
10909: return 'ok';
10910: } else {
10911: my %changes;
10912: my $newend = 0;
10913: my $newstart = $now;
10914: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
10915: $changes{$action}{$newkey} = {
10916: type => 'public',
10917: time => {
10918: start => $newstart,
10919: end => $newend,
10920: },
10921: };
10922: my ($outcome,$deloutcome,$new_values,$translation) =
10923: &modify_access_controls($file_name,\%changes,$udom,$unum);
10924: return $outcome;
10925: }
10926: } else {
10927: return 'invalid';
10928: }
10929: }
10930:
1.745 raeburn 10931: #------------------------------------------------------Get Marked as Read Only
10932:
10933: sub get_marked_as_readonly {
10934: my ($domain,$user,$what,$group) = @_;
10935: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 10936: my @readonly_files;
1.629 banghart 10937: my $cmp1=$what;
10938: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10939: while (my ($file_name,$value) = each(%{$current_permissions})) {
10940: if (defined($group)) {
10941: if ($file_name !~ m-^\Q$group\E/-) {
10942: next;
10943: }
10944: }
1.561 banghart 10945: if (ref($value) eq "ARRAY"){
10946: foreach my $stored_what (@{$value}) {
1.629 banghart 10947: my $cmp2=$stored_what;
1.759 albertel 10948: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 10949: $cmp2=join('',@{$stored_what});
1.745 raeburn 10950: }
1.629 banghart 10951: if ($cmp1 eq $cmp2) {
1.561 banghart 10952: push(@readonly_files, $file_name);
1.745 raeburn 10953: last;
1.563 banghart 10954: } elsif (!defined($what)) {
10955: push(@readonly_files, $file_name);
1.745 raeburn 10956: last;
1.561 banghart 10957: }
10958: }
1.745 raeburn 10959: }
1.561 banghart 10960: }
10961: return @readonly_files;
10962: }
1.577 banghart 10963: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 10964:
1.577 banghart 10965: sub get_marked_as_readonly_hash {
1.745 raeburn 10966: my ($current_permissions,$group,$what) = @_;
1.577 banghart 10967: my %readonly_files;
1.745 raeburn 10968: while (my ($file_name,$value) = each(%{$current_permissions})) {
10969: if (defined($group)) {
10970: if ($file_name !~ m-^\Q$group\E/-) {
10971: next;
10972: }
10973: }
1.577 banghart 10974: if (ref($value) eq "ARRAY"){
10975: foreach my $stored_what (@{$value}) {
1.745 raeburn 10976: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 10977: foreach my $lock_descriptor(@{$stored_what}) {
10978: if ($lock_descriptor eq 'graded') {
10979: $readonly_files{$file_name} = 'graded';
10980: } elsif ($lock_descriptor eq 'handback') {
10981: $readonly_files{$file_name} = 'handback';
10982: } else {
10983: if (!exists($readonly_files{$file_name})) {
10984: $readonly_files{$file_name} = 'locked';
10985: }
10986: }
1.745 raeburn 10987: }
1.750 banghart 10988: }
1.577 banghart 10989: }
10990: }
10991: }
10992: return %readonly_files;
10993: }
1.559 banghart 10994: # ------------------------------------------------------------ Unmark as Read Only
10995:
10996: sub unmark_as_readonly {
1.629 banghart 10997: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10998: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 10999: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 11000: $file_name = &declutter_portfile($file_name);
1.634 albertel 11001: my $symb_crs = $what;
11002: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 11003: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 11004: my ($tmp)=keys(%current_permissions);
11005: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 11006: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 11007: foreach my $file (@readonly_files) {
1.759 albertel 11008: my $clean_file = &declutter_portfile($file);
11009: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 11010: my $current_locks = $current_permissions{$file};
1.563 banghart 11011: my @new_locks;
11012: my @del_keys;
11013: if (ref($current_locks) eq "ARRAY"){
11014: foreach my $locker (@{$current_locks}) {
1.632 albertel 11015: my $compare=$locker;
1.749 raeburn 11016: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 11017: $compare=join('',@{$locker});
1.746 raeburn 11018: if ($compare ne $symb_crs) {
11019: push(@new_locks, $locker);
11020: }
1.563 banghart 11021: }
11022: }
1.650 albertel 11023: if (scalar(@new_locks) > 0) {
1.563 banghart 11024: $current_permissions{$file} = \@new_locks;
11025: } else {
11026: push(@del_keys, $file);
1.613 albertel 11027: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 11028: delete($current_permissions{$file});
1.563 banghart 11029: }
11030: }
1.561 banghart 11031: }
1.613 albertel 11032: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 11033: return;
11034: }
1.512 banghart 11035:
1.17 www 11036: # ------------------------------------------------------------ Directory lister
11037:
11038: sub dirlist {
1.955 raeburn 11039: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 11040: $uri=~s/^\///;
11041: $uri=~s/\/$//;
1.253 stredwic 11042: my ($udom, $uname);
1.955 raeburn 11043: if ($getuserdir) {
1.253 stredwic 11044: $udom = $userdomain;
11045: $uname = $username;
1.955 raeburn 11046: } else {
11047: (undef,$udom,$uname)=split(/\//,$uri);
11048: if(defined($userdomain)) {
11049: $udom = $userdomain;
11050: }
11051: if(defined($username)) {
11052: $uname = $username;
11053: }
1.253 stredwic 11054: }
1.955 raeburn 11055: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 11056:
1.955 raeburn 11057: $dirRoot = $perlvar{'lonDocRoot'};
11058: if (defined($getpropath)) {
11059: $dirRoot = &propath($udom,$uname);
1.253 stredwic 11060: $dirRoot =~ s/\/$//;
1.955 raeburn 11061: } elsif (defined($getuserdir)) {
11062: my $subdir=$uname.'__';
11063: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11064: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11065: ."/$udom/$subdir/$uname";
11066: } elsif (defined($alternateRoot)) {
11067: $dirRoot = $alternateRoot;
1.751 banghart 11068: }
1.253 stredwic 11069:
11070: if($udom) {
11071: if($uname) {
1.1135 raeburn 11072: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 11073: if ($uhome eq 'no_host') {
11074: return ([],'no_host');
11075: }
1.955 raeburn 11076: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 11077: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 11078: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 11079: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11080: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 11081: } else {
11082: @listing_results = map { &unescape($_); } split(/:/,$listing);
11083: }
1.605 matthew 11084: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 11085: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 11086: @listing_results = split(/:/,$listing);
11087: } else {
11088: @listing_results = map { &unescape($_); } split(/:/,$listing);
11089: }
1.1135 raeburn 11090: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 11091: ($listing eq 'rejected') || ($listing eq 'refused') ||
11092: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11093: return ([],$listing);
11094: } else {
11095: return (\@listing_results);
1.1135 raeburn 11096: }
1.955 raeburn 11097: } elsif(!$alternateRoot) {
1.1136 raeburn 11098: my (%allusers,%listerror);
1.841 albertel 11099: my %servers = &get_servers($udom,'library');
1.955 raeburn 11100: foreach my $tryserver (keys(%servers)) {
11101: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11102: &escape($udom),$tryserver);
11103: if ($listing eq 'unknown_cmd') {
11104: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11105: $udom, $tryserver);
11106: } else {
11107: @listing_results = map { &unescape($_); } split(/:/,$listing);
11108: }
1.841 albertel 11109: if ($listing eq 'unknown_cmd') {
11110: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11111: $udom, $tryserver);
11112: @listing_results = split(/:/,$listing);
11113: } else {
11114: @listing_results =
11115: map { &unescape($_); } split(/:/,$listing);
11116: }
1.1136 raeburn 11117: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11118: ($listing eq 'rejected') || ($listing eq 'refused') ||
11119: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11120: $listerror{$tryserver} = $listing;
11121: } else {
1.841 albertel 11122: foreach my $line (@listing_results) {
11123: my ($entry) = split(/&/,$line,2);
11124: $allusers{$entry} = 1;
11125: }
11126: }
1.253 stredwic 11127: }
1.1136 raeburn 11128: my @alluserslist=();
1.800 albertel 11129: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 11130: push(@alluserslist,$user.'&user');
1.253 stredwic 11131: }
1.1172.2.80 raeburn 11132: if (!%listerror) {
11133: # no errors
11134: return (\@alluserslist);
11135: } elsif (scalar(keys(%servers)) == 1) {
11136: # one library server, one error
11137: my ($key) = keys(%listerror);
11138: return (\@alluserslist, $listerror{$key});
11139: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11140: # con_lost indicates that we might miss data from at least one
11141: # library server
11142: return (\@alluserslist, 'con_lost');
11143: } else {
11144: # multiple library servers and no con_lost -> data should be
11145: # complete.
11146: return (\@alluserslist);
11147: }
11148:
1.253 stredwic 11149: } else {
1.1136 raeburn 11150: return ([],'missing username');
1.253 stredwic 11151: }
1.955 raeburn 11152: } elsif(!defined($getpropath)) {
1.1136 raeburn 11153: my $path = $perlvar{'lonDocRoot'}.'/res/';
11154: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11155: return (\@all_domains);
1.955 raeburn 11156: } else {
1.1136 raeburn 11157: return ([],'missing domain');
1.275 stredwic 11158: }
11159: }
11160:
11161: # --------------------------------------------- GetFileTimestamp
11162: # This function utilizes dirlist and returns the date stamp for
11163: # when it was last modified. It will also return an error of -1
11164: # if an error occurs
11165:
11166: sub GetFileTimestamp {
1.955 raeburn 11167: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 11168: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11169: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 11170: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11171: undef,$getuserdir);
11172: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11173: return -1;
11174: }
11175: if (ref($fileref) eq 'ARRAY') {
11176: my @stats = split('&',$fileref->[0]);
1.375 matthew 11177: # @stats contains first the filename, then the stat output
11178: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 11179: } else {
11180: return -1;
1.253 stredwic 11181: }
1.26 www 11182: }
11183:
1.712 albertel 11184: sub stat_file {
11185: my ($uri) = @_;
1.787 albertel 11186: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 11187:
1.955 raeburn 11188: my ($udom,$uname,$file);
1.712 albertel 11189: if ($uri =~ m-^/(uploaded|editupload)/-) {
11190: ($udom,$uname,$file) =
1.811 albertel 11191: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 11192: $file = 'userfiles/'.$file;
11193: }
11194: if ($uri =~ m-^/res/-) {
11195: ($udom,$uname) =
1.807 albertel 11196: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 11197: $file = $uri;
11198: }
11199:
11200: if (!$udom || !$uname || !$file) {
11201: # unable to handle the uri
11202: return ();
11203: }
1.956 raeburn 11204: my $getpropath;
11205: if ($file =~ /^userfiles\//) {
11206: $getpropath = 1;
11207: }
1.1136 raeburn 11208: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11209: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11210: return ();
11211: } else {
11212: if (ref($listref) eq 'ARRAY') {
11213: my @stats = split('&',$listref->[0]);
11214: shift(@stats); #filename is first
11215: return @stats;
11216: }
1.712 albertel 11217: }
11218: return ();
11219: }
11220:
1.26 www 11221: # -------------------------------------------------------- Value of a Condition
11222:
1.713 albertel 11223: # gets the value of a specific preevaluated condition
11224: # stored in the string $env{user.state.<cid>}
11225: # or looks up a condition reference in the bighash and if if hasn't
11226: # already been evaluated recurses into docondval to get the value of
11227: # the condition, then memoizing it to
11228: # $env{user.state.<cid>.<condition>}
1.40 www 11229: sub directcondval {
11230: my $number=shift;
1.620 albertel 11231: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 11232: &Apache::lonuserstate::evalstate();
11233: }
1.713 albertel 11234: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11235: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11236: } elsif ($number =~ /^_/) {
11237: my $sub_condition;
11238: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11239: &GDBM_READER(),0640)) {
11240: $sub_condition=$bighash{'conditions'.$number};
11241: untie(%bighash);
11242: }
11243: my $value = &docondval($sub_condition);
1.949 raeburn 11244: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 11245: return $value;
11246: }
1.620 albertel 11247: if ($env{'user.state.'.$env{'request.course.id'}}) {
11248: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 11249: } else {
11250: return 2;
11251: }
11252: }
11253:
1.713 albertel 11254: # get the collection of conditions for this resource
1.26 www 11255: sub condval {
11256: my $condidx=shift;
1.54 www 11257: my $allpathcond='';
1.713 albertel 11258: foreach my $cond (split(/\|/,$condidx)) {
11259: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11260: $allpathcond.=
11261: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11262: }
1.191 harris41 11263: }
1.54 www 11264: $allpathcond=~s/\|$//;
1.713 albertel 11265: return &docondval($allpathcond);
11266: }
11267:
11268: #evaluates an expression of conditions
11269: sub docondval {
11270: my ($allpathcond) = @_;
11271: my $result=0;
11272: if ($env{'request.course.id'}
11273: && defined($allpathcond)) {
11274: my $operand='|';
11275: my @stack;
11276: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11277: if ($chunk eq '(') {
11278: push @stack,($operand,$result);
11279: } elsif ($chunk eq ')') {
11280: my $before=pop @stack;
11281: if (pop @stack eq '&') {
11282: $result=$result>$before?$before:$result;
11283: } else {
11284: $result=$result>$before?$result:$before;
11285: }
11286: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11287: $operand=$chunk;
11288: } else {
11289: my $new=directcondval($chunk);
11290: if ($operand eq '&') {
11291: $result=$result>$new?$new:$result;
11292: } else {
11293: $result=$result>$new?$result:$new;
11294: }
11295: }
11296: }
1.26 www 11297: }
11298: return $result;
1.421 albertel 11299: }
11300:
11301: # ---------------------------------------------------- Devalidate courseresdata
11302:
11303: sub devalidatecourseresdata {
11304: my ($coursenum,$coursedomain)=@_;
11305: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11306: &devalidate_cache_new('courseres',$hashid);
1.28 www 11307: }
11308:
1.763 www 11309:
1.200 www 11310: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 11311: #
11312: # Parameters:
11313: # $coursenum - Number of the course.
11314: # $coursedomain - Domain at which the course was created.
11315: # Returns:
11316: # A hash of the course parameters along (I think) with timestamps
11317: # and version info.
1.877 foxr 11318:
1.624 albertel 11319: sub get_courseresdata {
11320: my ($coursenum,$coursedomain)=@_;
1.200 www 11321: my $coursehom=&homeserver($coursenum,$coursedomain);
11322: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11323: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 11324: my %dumpreply;
1.417 albertel 11325: unless (defined($cached)) {
1.624 albertel 11326: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 11327: $result=\%dumpreply;
1.251 albertel 11328: my ($tmp) = keys(%dumpreply);
11329: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 11330: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 11331: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11332: return $tmp;
1.416 albertel 11333: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 11334: $result=undef;
1.599 albertel 11335: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 11336: }
11337: }
1.624 albertel 11338: return $result;
11339: }
11340:
1.633 albertel 11341: sub devalidateuserresdata {
11342: my ($uname,$udom)=@_;
11343: my $hashid="$udom:$uname";
11344: &devalidate_cache_new('userres',$hashid);
11345: }
11346:
1.624 albertel 11347: sub get_userresdata {
11348: my ($uname,$udom)=@_;
11349: #most student don\'t have any data set, check if there is some data
11350: if (&EXT_cache_status($udom,$uname)) { return undef; }
11351:
11352: my $hashid="$udom:$uname";
11353: my ($result,$cached)=&is_cached_new('userres',$hashid);
11354: if (!defined($cached)) {
11355: my %resourcedata=&dump('resourcedata',$udom,$uname);
11356: $result=\%resourcedata;
11357: &do_cache_new('userres',$hashid,$result,600);
11358: }
11359: my ($tmp)=keys(%$result);
11360: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11361: return $result;
11362: }
11363: #error 2 occurs when the .db doesn't exist
11364: if ($tmp!~/error: 2 /) {
1.1172.2.71 raeburn 11365: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11366: &logthis("<font color=\"blue\">WARNING:".
11367: " Trying to get resource data for ".
11368: $uname." at ".$udom.": ".
11369: $tmp."</font>");
11370: }
1.624 albertel 11371: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 11372: #&EXT_cache_set($udom,$uname);
11373: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 11374: undef($tmp); # not really an error so don't send it back
1.624 albertel 11375: }
11376: return $tmp;
11377: }
1.879 foxr 11378: #----------------------------------------------- resdata - return resource data
11379: # Purpose:
11380: # Return resource data for either users or for a course.
11381: # Parameters:
11382: # $name - Course/user name.
11383: # $domain - Name of the domain the user/course is registered on.
11384: # $type - Type of thing $name is (must be 'course' or 'user'
11385: # @which - Array of names of resources desired.
11386: # Returns:
11387: # The value of the first reasource in @which that is found in the
11388: # resource hash.
11389: # Exceptional Conditions:
11390: # If the $type passed in is not valid (not the string 'course' or
11391: # 'user', an undefined reference is returned.
11392: # If none of the resources are found, an undef is returned
1.624 albertel 11393: sub resdata {
11394: my ($name,$domain,$type,@which)=@_;
11395: my $result;
11396: if ($type eq 'course') {
11397: $result=&get_courseresdata($name,$domain);
11398: } elsif ($type eq 'user') {
11399: $result=&get_userresdata($name,$domain);
11400: }
11401: if (!ref($result)) { return $result; }
1.251 albertel 11402: foreach my $item (@which) {
1.927 albertel 11403: if (defined($result->{$item->[0]})) {
11404: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 11405: }
1.250 albertel 11406: }
1.291 albertel 11407: return undef;
1.200 www 11408: }
11409:
1.1172.2.31 raeburn 11410: sub get_numsuppfiles {
11411: my ($cnum,$cdom,$ignorecache)=@_;
11412: my $hashid=$cnum.':'.$cdom;
11413: my ($suppcount,$cached);
11414: unless ($ignorecache) {
11415: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11416: }
11417: unless (defined($cached)) {
11418: my $chome=&homeserver($cnum,$cdom);
11419: unless ($chome eq 'no_host') {
11420: ($suppcount,my $errors) = (0,0);
11421: my $suppmap = 'supplemental.sequence';
11422: ($suppcount,$errors) =
11423: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11424: }
11425: &do_cache_new('suppcount',$hashid,$suppcount,600);
11426: }
11427: return $suppcount;
11428: }
11429:
1.379 matthew 11430: #
11431: # EXT resource caching routines
11432: #
11433:
11434: sub clear_EXT_cache_status {
1.383 albertel 11435: &delenv('cache.EXT.');
1.379 matthew 11436: }
11437:
11438: sub EXT_cache_status {
11439: my ($target_domain,$target_user) = @_;
1.383 albertel 11440: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 11441: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 11442: # We know already the user has no data
11443: return 1;
11444: } else {
11445: return 0;
11446: }
11447: }
11448:
11449: sub EXT_cache_set {
11450: my ($target_domain,$target_user) = @_;
1.383 albertel 11451: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 11452: #&appenv({$cachename => time});
1.379 matthew 11453: }
11454:
1.28 www 11455: # --------------------------------------------------------- Value of a Variable
1.58 www 11456: sub EXT {
1.715 albertel 11457:
1.1172.2.28 raeburn 11458: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 11459: unless ($varname) { return ''; }
1.218 albertel 11460: #get real user name/domain, courseid and symb
11461: my $courseid;
1.359 albertel 11462: my $publicuser;
1.427 www 11463: if ($symbparm) {
11464: $symbparm=&get_symb_from_alias($symbparm);
11465: }
1.218 albertel 11466: if (!($uname && $udom)) {
1.790 albertel 11467: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 11468: if (!$symbparm) { $symbparm=$cursymb; }
11469: } else {
1.620 albertel 11470: $courseid=$env{'request.course.id'};
1.218 albertel 11471: }
1.48 www 11472: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11473: my $rest;
1.320 albertel 11474: if (defined($therest[0])) {
1.48 www 11475: $rest=join('.',@therest);
11476: } else {
11477: $rest='';
11478: }
1.320 albertel 11479:
1.57 www 11480: my $qualifierrest=$qualifier;
11481: if ($rest) { $qualifierrest.='.'.$rest; }
11482: my $spacequalifierrest=$space;
11483: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 11484: if ($realm eq 'user') {
1.48 www 11485: # --------------------------------------------------------------- user.resource
11486: if ($space eq 'resource') {
1.651 albertel 11487: if ( (defined($Apache::lonhomework::parsing_a_problem)
11488: || defined($Apache::lonhomework::parsing_a_task))
11489: &&
1.744 albertel 11490: ($symbparm eq &symbread()) ) {
11491: # if we are in the middle of processing the resource the
11492: # get the value we are planning on committing
11493: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11494: return $Apache::lonhomework::results{$qualifierrest};
11495: } else {
11496: return $Apache::lonhomework::history{$qualifierrest};
11497: }
1.335 albertel 11498: } else {
1.359 albertel 11499: my %restored;
1.620 albertel 11500: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 11501: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11502: } else {
11503: %restored=&restore($symbparm,$courseid,$udom,$uname);
11504: }
1.335 albertel 11505: return $restored{$qualifierrest};
11506: }
1.48 www 11507: # ----------------------------------------------------------------- user.access
11508: } elsif ($space eq 'access') {
1.218 albertel 11509: # FIXME - not supporting calls for a specific user
1.48 www 11510: return &allowed($qualifier,$rest);
11511: # ------------------------------------------ user.preferences, user.environment
11512: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 11513: if (($uname eq $env{'user.name'}) &&
11514: ($udom eq $env{'user.domain'})) {
11515: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 11516: } else {
1.359 albertel 11517: my %returnhash;
11518: if (!$publicuser) {
11519: %returnhash=&userenvironment($udom,$uname,
11520: $qualifierrest);
11521: }
1.218 albertel 11522: return $returnhash{$qualifierrest};
11523: }
1.48 www 11524: # ----------------------------------------------------------------- user.course
11525: } elsif ($space eq 'course') {
1.218 albertel 11526: # FIXME - not supporting calls for a specific user
1.620 albertel 11527: return $env{join('.',('request.course',$qualifier))};
1.48 www 11528: # ------------------------------------------------------------------- user.role
11529: } elsif ($space eq 'role') {
1.218 albertel 11530: # FIXME - not supporting calls for a specific user
1.620 albertel 11531: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 11532: if ($qualifier eq 'value') {
11533: return $role;
11534: } elsif ($qualifier eq 'extent') {
11535: return $where;
11536: }
11537: # ----------------------------------------------------------------- user.domain
11538: } elsif ($space eq 'domain') {
1.218 albertel 11539: return $udom;
1.48 www 11540: # ------------------------------------------------------------------- user.name
11541: } elsif ($space eq 'name') {
1.218 albertel 11542: return $uname;
1.48 www 11543: # ---------------------------------------------------- Any other user namespace
1.29 www 11544: } else {
1.359 albertel 11545: my %reply;
11546: if (!$publicuser) {
11547: %reply=&get($space,[$qualifierrest],$udom,$uname);
11548: }
11549: return $reply{$qualifierrest};
1.48 www 11550: }
1.236 www 11551: } elsif ($realm eq 'query') {
11552: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 11553: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11554: [$spacequalifierrest]);
1.620 albertel 11555: return $env{'form.'.$spacequalifierrest};
1.236 www 11556: } elsif ($realm eq 'request') {
1.48 www 11557: # ------------------------------------------------------------- request.browser
11558: if ($space eq 'browser') {
1.1145 bisitz 11559: return $env{'browser.'.$qualifier};
1.57 www 11560: # ------------------------------------------------------------ request.filename
11561: } else {
1.620 albertel 11562: return $env{'request.'.$spacequalifierrest};
1.29 www 11563: }
1.28 www 11564: } elsif ($realm eq 'course') {
1.48 www 11565: # ---------------------------------------------------------- course.description
1.620 albertel 11566: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 11567: } elsif ($realm eq 'resource') {
1.165 www 11568:
1.620 albertel 11569: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 11570: if (!$symbparm) { $symbparm=&symbread(); }
11571: }
1.693 albertel 11572:
1.1172.2.30 raeburn 11573: if ($qualifier eq '') {
11574: if ($space eq 'title') {
11575: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11576: return &gettitle($symbparm);
11577: }
1.693 albertel 11578:
1.1172.2.30 raeburn 11579: if ($space eq 'map') {
11580: my ($map) = &decode_symb($symbparm);
11581: return &symbread($map);
11582: }
11583: if ($space eq 'maptitle') {
11584: my ($map) = &decode_symb($symbparm);
11585: return &gettitle($map);
11586: }
11587: if ($space eq 'filename') {
11588: if ($symbparm) {
11589: return &clutter((&decode_symb($symbparm))[2]);
11590: }
11591: return &hreflocation('',$env{'request.filename'});
1.905 albertel 11592: }
1.1172.2.30 raeburn 11593:
11594: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11595: if ($space eq 'visibleparts') {
11596: my $navmap = Apache::lonnavmaps::navmap->new();
11597: my $item;
11598: if (ref($navmap)) {
11599: my $res = $navmap->getBySymb($symbparm);
11600: my $parts = $res->parts();
11601: if (ref($parts) eq 'ARRAY') {
11602: $item = join(',',@{$parts});
11603: }
11604: undef($navmap);
11605: }
11606: return $item;
11607: }
11608: }
11609: }
1.693 albertel 11610:
11611: my ($section, $group, @groups);
1.593 albertel 11612: my ($courselevelm,$courselevel);
1.1172.2.28 raeburn 11613: if (($courseid eq '') && ($cid)) {
11614: $courseid = $cid;
11615: }
11616: if (($symbparm && $courseid) &&
11617: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 11618:
1.218 albertel 11619: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 11620:
1.60 www 11621: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 11622: my $symbp=$symbparm;
1.735 albertel 11623: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 11624:
11625: my $symbparm=$symbp.'.'.$spacequalifierrest;
11626: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11627:
1.620 albertel 11628: if (($env{'user.name'} eq $uname) &&
11629: ($env{'user.domain'} eq $udom)) {
11630: $section=$env{'request.course.sec'};
1.733 raeburn 11631: @groups = split(/:/,$env{'request.course.groups'});
11632: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 11633: } else {
1.539 albertel 11634: if (! defined($usection)) {
1.551 albertel 11635: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 11636: } else {
11637: $section = $usection;
11638: }
1.733 raeburn 11639: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 11640: }
11641:
11642: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11643: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11644: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11645:
1.593 albertel 11646: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 11647: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 11648: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 11649:
1.60 www 11650: # ----------------------------------------------------------- first, check user
1.624 albertel 11651:
11652: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 11653: ([$courselevelr,'resource'],
11654: [$courselevelm,'map' ],
11655: [$courselevel, 'course' ]));
1.931 albertel 11656: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 11657:
1.594 albertel 11658: # ------------------------------------------------ second, check some of course
1.684 raeburn 11659: my $coursereply;
1.691 raeburn 11660: if (@groups > 0) {
11661: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11662: $mapparm,$spacequalifierrest);
1.927 albertel 11663: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 11664: }
1.96 www 11665:
1.684 raeburn 11666: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 11667: $env{'course.'.$courseid.'.domain'},
11668: 'course',
11669: ([$seclevelr, 'resource'],
11670: [$seclevelm, 'map' ],
11671: [$seclevel, 'course' ],
11672: [$courselevelr,'resource']));
11673: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 11674:
1.60 www 11675: # ------------------------------------------------------ third, check map parms
1.218 albertel 11676: my %parmhash=();
11677: my $thisparm='';
11678: if (tie(%parmhash,'GDBM_File',
1.620 albertel 11679: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 11680: &GDBM_READER(),0640)) {
1.218 albertel 11681: $thisparm=$parmhash{$symbparm};
11682: untie(%parmhash);
11683: }
1.927 albertel 11684: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 11685: }
1.594 albertel 11686: # ------------------------------------------ fourth, look in resource metadata
1.71 www 11687:
1.218 albertel 11688: $spacequalifierrest=~s/\./\_/;
1.282 albertel 11689: my $filename;
11690: if (!$symbparm) { $symbparm=&symbread(); }
11691: if ($symbparm) {
1.409 www 11692: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 11693: } else {
1.620 albertel 11694: $filename=$env{'request.filename'};
1.282 albertel 11695: }
11696: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 11697: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 11698: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 11699: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 11700:
1.927 albertel 11701: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 11702: if ($symbparm && defined($courseid) &&
1.620 albertel 11703: $courseid eq $env{'request.course.id'}) {
1.624 albertel 11704: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11705: $env{'course.'.$courseid.'.domain'},
11706: 'course',
1.927 albertel 11707: ([$courselevelm,'map' ],
11708: [$courselevel, 'course']));
11709: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 11710: }
1.145 www 11711: # ------------------------------------------------------------------ Cascade up
1.218 albertel 11712: unless ($space eq '0') {
1.336 albertel 11713: my @parts=split(/_/,$space);
11714: my $id=pop(@parts);
11715: my $part=join('_',@parts);
11716: if ($part eq '') { $part='0'; }
1.927 albertel 11717: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 11718: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 11719: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 11720: }
1.395 albertel 11721: if ($recurse) { return undef; }
11722: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 11723: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 11724: # ---------------------------------------------------- Any other user namespace
11725: } elsif ($realm eq 'environment') {
11726: # ----------------------------------------------------------------- environment
1.620 albertel 11727: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11728: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 11729: } else {
1.770 albertel 11730: if ($uname eq 'anonymous' && $udom eq '') {
11731: return '';
11732: }
1.219 albertel 11733: my %returnhash=&userenvironment($udom,$uname,
11734: $spacequalifierrest);
11735: return $returnhash{$spacequalifierrest};
11736: }
1.28 www 11737: } elsif ($realm eq 'system') {
1.48 www 11738: # ----------------------------------------------------------------- system.time
11739: if ($space eq 'time') {
11740: return time;
11741: }
1.696 albertel 11742: } elsif ($realm eq 'server') {
11743: # ----------------------------------------------------------------- system.time
11744: if ($space eq 'name') {
11745: return $ENV{'SERVER_NAME'};
11746: }
1.28 www 11747: }
1.48 www 11748: return '';
1.61 www 11749: }
11750:
1.927 albertel 11751: sub get_reply {
11752: my ($reply_value) = @_;
1.940 raeburn 11753: if (ref($reply_value) eq 'ARRAY') {
11754: if (wantarray) {
11755: return @$reply_value;
11756: }
11757: return $reply_value->[0];
11758: } else {
11759: return $reply_value;
1.927 albertel 11760: }
11761: }
11762:
1.691 raeburn 11763: sub check_group_parms {
11764: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
11765: my @groupitems = ();
11766: my $resultitem;
1.927 albertel 11767: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 11768: foreach my $group (@{$groups}) {
11769: foreach my $level (@levels) {
1.927 albertel 11770: my $item = $courseid.'.['.$group.'].'.$level->[0];
11771: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11772: }
11773: }
11774: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11775: $env{'course.'.$courseid.'.domain'},
11776: 'course',@groupitems);
11777: return $coursereply;
11778: }
11779:
11780: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11781: my ($courseid,@groups) = @_;
11782: @groups = sort(@groups);
1.691 raeburn 11783: return @groups;
11784: }
11785:
1.395 albertel 11786: sub packages_tab_default {
11787: my ($uri,$varname)=@_;
11788: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11789:
11790: my (@extension,@specifics,$do_default);
11791: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11792: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11793: if ($pack_type eq 'default') {
11794: $do_default=1;
11795: } elsif ($pack_type eq 'extension') {
11796: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11797: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11798: # only look at packages defaults for packages that this id is
1.738 albertel 11799: push(@specifics,[$package,$pack_type,$pack_part]);
11800: }
11801: }
11802: # first look for a package that matches the requested part id
11803: foreach my $package (@specifics) {
11804: my (undef,$pack_type,$pack_part)=@{$package};
11805: next if ($pack_part ne $part);
11806: if (defined($packagetab{"$pack_type&$name&default"})) {
11807: return $packagetab{"$pack_type&$name&default"};
11808: }
11809: }
11810: # look for any possible matching non extension_ package
11811: foreach my $package (@specifics) {
11812: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11813: if (defined($packagetab{"$pack_type&$name&default"})) {
11814: return $packagetab{"$pack_type&$name&default"};
11815: }
1.585 albertel 11816: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11817: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11818: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11819: }
11820: }
1.738 albertel 11821: # look for any posible extension_ match
11822: foreach my $package (@extension) {
11823: my ($package,$pack_type)=@{$package};
11824: if (defined($packagetab{"$pack_type&$name&default"})) {
11825: return $packagetab{"$pack_type&$name&default"};
11826: }
11827: if (defined($packagetab{$package."&$name&default"})) {
11828: return $packagetab{$package."&$name&default"};
11829: }
11830: }
11831: # look for a global default setting
11832: if ($do_default && defined($packagetab{"default&$name&default"})) {
11833: return $packagetab{"default&$name&default"};
11834: }
1.395 albertel 11835: return undef;
11836: }
11837:
1.334 albertel 11838: sub add_prefix_and_part {
11839: my ($prefix,$part)=@_;
11840: my $keyroot;
11841: if (defined($prefix) && $prefix !~ /^__/) {
11842: # prefix that has a part already
11843: $keyroot=$prefix;
11844: } elsif (defined($prefix)) {
11845: # prefix that is missing a part
11846: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11847: } else {
11848: # no prefix at all
11849: if (defined($part)) { $keyroot='_'.$part; }
11850: }
11851: return $keyroot;
11852: }
11853:
1.71 www 11854: # ---------------------------------------------------------------- Get metadata
11855:
1.599 albertel 11856: my %metaentry;
1.1070 www 11857: my %importedpartids;
1.1172.2.99 raeburn 11858: my %importedrespids;
1.71 www 11859: sub metadata {
1.176 www 11860: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11861: $uri=&declutter($uri);
1.288 albertel 11862: # if it is a non metadata possible uri return quickly
1.529 albertel 11863: if (($uri eq '') ||
11864: (($uri =~ m|^/*adm/|) &&
1.1172.2.20 raeburn 11865: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 11866: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11867: return undef;
11868: }
1.1172.2.49 raeburn 11869: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11870: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11871: return undef;
1.288 albertel 11872: }
1.73 www 11873: my $filename=$uri;
11874: $uri=~s/\.meta$//;
1.172 www 11875: #
11876: # Is the metadata already cached?
1.177 www 11877: # Look at timestamp of caching
1.172 www 11878: # Everything is cached by the main uri, libraries are never directly cached
11879: #
1.428 albertel 11880: if (!defined($liburi)) {
1.599 albertel 11881: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11882: if (defined($cached)) { return $result->{':'.$what}; }
11883: }
11884: {
1.1069 www 11885: # Imported parts would go here
1.1172.2.99 raeburn 11886: my @origfiletagids=();
1.1069 www 11887: my $importedparts=0;
1.1172.2.99 raeburn 11888:
11889: # Imported responseids would go here
11890: my $importedresponses=0;
1.172 www 11891: #
11892: # Is this a recursive call for a library?
11893: #
1.599 albertel 11894: # if (! exists($metacache{$uri})) {
11895: # $metacache{$uri}={};
11896: # }
1.924 albertel 11897: my $cachetime = 60*60;
1.171 www 11898: if ($liburi) {
11899: $liburi=&declutter($liburi);
11900: $filename=$liburi;
1.401 bowersj2 11901: } else {
1.599 albertel 11902: &devalidate_cache_new('meta',$uri);
11903: undef(%metaentry);
1.401 bowersj2 11904: }
1.140 www 11905: my %metathesekeys=();
1.73 www 11906: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 11907: my $metastring;
1.1140 www 11908: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 11909: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 11910: $metastring =
1.929 albertel 11911: &Apache::lonnet::ssi_body($which,
1.924 albertel 11912: ('grade_target' => 'meta'));
11913: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 11914: } elsif (($uri !~ m -^(editupload)/-) &&
11915: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 11916: my $file=&filelocation('',&clutter($filename));
1.599 albertel 11917: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 11918: $metastring=&getfile($file);
1.489 albertel 11919: }
1.208 albertel 11920: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 11921: my $token;
1.140 www 11922: undef %metathesekeys;
1.71 www 11923: while ($token=$parser->get_token) {
1.339 albertel 11924: if ($token->[0] eq 'S') {
11925: if (defined($token->[2]->{'package'})) {
1.172 www 11926: #
11927: # This is a package - get package info
11928: #
1.339 albertel 11929: my $package=$token->[2]->{'package'};
11930: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11931: if (defined($token->[2]->{'id'})) {
11932: $keyroot.='_'.$token->[2]->{'id'};
11933: }
1.599 albertel 11934: if ($metaentry{':packages'}) {
11935: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 11936: } else {
1.599 albertel 11937: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 11938: }
1.736 albertel 11939: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 11940: my $part=$keyroot;
11941: $part=~s/^\_//;
1.736 albertel 11942: if ($pack_entry=~/^\Q$package\E\&/ ||
11943: $pack_entry=~/^\Q$package\E_0\&/) {
11944: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11945: # ignore package.tab specified default values
11946: # here &package_tab_default() will fetch those
11947: if ($subp eq 'default') { next; }
1.736 albertel 11948: my $value=$packagetab{$pack_entry};
1.432 albertel 11949: my $unikey;
11950: if ($pack =~ /_0$/) {
11951: $unikey='parameter_0_'.$name;
11952: $part=0;
11953: } else {
11954: $unikey='parameter'.$keyroot.'_'.$name;
11955: }
1.339 albertel 11956: if ($subp eq 'display') {
11957: $value.=' [Part: '.$part.']';
11958: }
1.599 albertel 11959: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11960: $metathesekeys{$unikey}=1;
1.599 albertel 11961: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11962: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11963: }
1.599 albertel 11964: if (defined($metaentry{':'.$unikey.'.default'})) {
11965: $metaentry{':'.$unikey}=
11966: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11967: }
1.339 albertel 11968: }
11969: }
11970: } else {
1.172 www 11971: #
11972: # This is not a package - some other kind of start tag
1.339 albertel 11973: #
11974: my $entry=$token->[1];
1.1068 www 11975: my $unikey='';
1.175 www 11976:
1.339 albertel 11977: if ($entry eq 'import') {
1.175 www 11978: #
11979: # Importing a library here
1.339 albertel 11980: #
1.1067 www 11981: my $location=$parser->get_text('/import');
11982: my $dir=$filename;
11983: $dir=~s|[^/]*$||;
11984: $location=&filelocation($dir,$location);
1.1172.2.99 raeburn 11985:
11986: my $importid=$token->[2]->{'id'};
1.1068 www 11987: my $importmode=$token->[2]->{'importmode'};
1.1172.2.99 raeburn 11988: #
11989: # Check metadata for imported file to
11990: # see if it contained response items
11991: #
11992: my %currmetaentry = %metaentry;
11993: my $libresponseorder = &metadata($location,'responseorder');
11994: my $origfile;
11995: if ($libresponseorder ne '') {
11996: if ($#origfiletagids<0) {
11997: undef(%importedrespids);
11998: undef(%importedpartids);
11999: }
12000: @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
12001: if (@{$importedrespids{$importid}} > 0) {
12002: $importedresponses = 1;
12003: # We need to get the original file and the imported file to get the response order correct
12004: # Load and inspect original file
12005: if ($#origfiletagids<0) {
12006: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12007: $origfile=&getfile($origfilelocation);
12008: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12009: }
12010: }
12011: }
12012: # Do not overwrite contents of %metaentry hash for resource itself with
12013: # hash populated for imported library file
12014: %metaentry = %currmetaentry;
12015: undef(%currmetaentry);
1.1068 www 12016: if ($importmode eq 'problem') {
1.1069 www 12017: # Import as problem/response
1.1068 www 12018: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12019: } elsif ($importmode eq 'part') {
12020: # Import as part(s)
1.1069 www 12021: $importedparts=1;
12022: # We need to get the original file and the imported file to get the part order correct
12023: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99 raeburn 12024: # Load and inspect original file if we didn't do that already
12025: if ($#origfiletagids<0) {
12026: undef(%importedrespids);
12027: undef(%importedpartids);
12028: if ($origfile eq '') {
12029: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
12030: $origfile=&getfile($origfilelocation);
12031: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12032: }
1.1070 www 12033: }
12034:
1.1069 www 12035: # Load and inspect imported file
12036: my $impfile=&getfile($location);
12037: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
12038: if ($#impfilepartids>=0) {
12039: # This problem had parts
1.1070 www 12040: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 12041: } else {
12042: # Importing by turning a single problem into a problem part
12043: # It gets the import-tags ID as part-ID
12044: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 12045: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 12046: }
1.1068 www 12047: } else {
12048: # Normal import
12049: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12050: if (defined($token->[2]->{'id'})) {
12051: $unikey.='_'.$token->[2]->{'id'};
12052: }
1.1067 www 12053: }
12054:
1.339 albertel 12055: if ($depthcount<20) {
1.736 albertel 12056: my $metadata =
12057: &metadata($uri,'keys', $location,$unikey,
12058: $depthcount+1);
12059: foreach my $meta (split(',',$metadata)) {
12060: $metaentry{':'.$meta}=$metaentry{':'.$meta};
12061: $metathesekeys{$meta}=1;
1.339 albertel 12062: }
1.1068 www 12063:
12064: }
1.1067 www 12065: } else {
12066: #
12067: # Not importing, some other kind of non-package, non-library start tag
12068: #
12069: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12070: if (defined($token->[2]->{'id'})) {
12071: $unikey.='_'.$token->[2]->{'id'};
12072: }
1.339 albertel 12073: if (defined($token->[2]->{'name'})) {
12074: $unikey.='_'.$token->[2]->{'name'};
12075: }
12076: $metathesekeys{$unikey}=1;
1.736 albertel 12077: foreach my $param (@{$token->[3]}) {
12078: $metaentry{':'.$unikey.'.'.$param} =
12079: $token->[2]->{$param};
1.339 albertel 12080: }
12081: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 12082: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 12083: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12084: # only ws inside the tag, and not in default, so use default
12085: # as value
1.599 albertel 12086: $metaentry{':'.$unikey}=$default;
1.908 albertel 12087: } elsif ( $internaltext =~ /\S/ ) {
12088: # something interesting inside the tag
12089: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 12090: } else {
1.908 albertel 12091: # no interesting values, don't set a default
1.339 albertel 12092: }
1.172 www 12093: # end of not-a-package not-a-library import
1.339 albertel 12094: }
1.172 www 12095: # end of not-a-package start tag
1.339 albertel 12096: }
1.172 www 12097: # the next is the end of "start tag"
1.339 albertel 12098: }
12099: }
1.483 albertel 12100: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 12101: $extension = lc($extension);
12102: if ($extension eq 'htm') { $extension='html'; }
12103:
1.737 albertel 12104: foreach my $key (keys(%packagetab)) {
1.483 albertel 12105: #no specific packages #how's our extension
12106: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 12107: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 12108: \%metathesekeys);
12109: }
1.883 albertel 12110:
12111: if (!exists($metaentry{':packages'})
12112: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 12113: foreach my $key (keys(%packagetab)) {
1.483 albertel 12114: #no specific packages well let's get default then
12115: if ($key!~/^default&/) { next; }
1.488 albertel 12116: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 12117: \%metathesekeys);
12118: }
12119: }
1.338 www 12120: # are there custom rights to evaluate
1.599 albertel 12121: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 12122:
1.338 www 12123: #
12124: # Importing a rights file here
1.339 albertel 12125: #
12126: unless ($depthcount) {
1.599 albertel 12127: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 12128: my $dir=$filename;
12129: $dir=~s|[^/]*$||;
12130: $location=&filelocation($dir,$location);
1.736 albertel 12131: my $rights_metadata =
12132: &metadata($uri,'keys',$location,'_rights',
12133: $depthcount+1);
12134: foreach my $rights (split(',',$rights_metadata)) {
12135: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12136: $metathesekeys{$rights}=1;
1.339 albertel 12137: }
12138: }
12139: }
1.737 albertel 12140: # uniqifiy package listing
12141: my %seen;
12142: my @uniq_packages =
12143: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12144: $metaentry{':packages'} = join(',',@uniq_packages);
12145:
1.1172.2.99 raeburn 12146: if (($importedresponses) || ($importedparts)) {
12147: if ($importedparts) {
1.1070 www 12148: # We had imported parts and need to rebuild partorder
1.1172.2.99 raeburn 12149: $metaentry{':partorder'}='';
12150: $metathesekeys{'partorder'}=1;
12151: }
12152: if ($importedresponses) {
12153: # We had imported responses and need to rebuild responseorder
12154: $metaentry{':responseorder'}='';
12155: $metathesekeys{'responseorder'}=1;
12156: }
12157: for (my $index=0;$index<$#origfiletagids;$index+=2) {
12158: my $origid = $origfiletagids[$index+1];
12159: if ($origfiletagids[$index] eq 'part') {
12160: # Original part, part of the problem
12161: if ($importedparts) {
12162: $metaentry{':partorder'}.=','.$origid;
12163: }
12164: } elsif ($origfiletagids[$index] eq 'import') {
12165: if ($importedparts) {
12166: # We have imported parts at this position
12167: $metaentry{':partorder'}.=','.$importedpartids{$origid};
12168: }
12169: if ($importedresponses) {
12170: # We have imported responses at this position
12171: if (ref($importedrespids{$origid}) eq 'ARRAY') {
12172: $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
12173: }
12174: }
12175: } else {
12176: # Original response item, part of the problem
12177: if ($importedresponses) {
12178: $metaentry{':responseorder'}.=','.$origid;
12179: }
12180: }
12181: }
12182: if ($importedparts) {
12183: $metaentry{':partorder'}=~s/^\,//;
12184: }
12185: if ($importedresponses) {
12186: $metaentry{':responseorder'}=~s/^\,//;
12187: }
1.1070 www 12188: }
12189:
1.737 albertel 12190: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 12191: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58 raeburn 12192: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 12193: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 12194: # this is the end of "was not already recently cached
1.71 www 12195: }
1.599 albertel 12196: return $metaentry{':'.$what};
1.261 albertel 12197: }
12198:
1.488 albertel 12199: sub metadata_create_package_def {
1.483 albertel 12200: my ($uri,$key,$package,$metathesekeys)=@_;
12201: my ($pack,$name,$subp)=split(/\&/,$key);
12202: if ($subp eq 'default') { next; }
12203:
1.599 albertel 12204: if (defined($metaentry{':packages'})) {
12205: $metaentry{':packages'}.=','.$package;
1.483 albertel 12206: } else {
1.599 albertel 12207: $metaentry{':packages'}=$package;
1.483 albertel 12208: }
12209: my $value=$packagetab{$key};
12210: my $unikey;
12211: $unikey='parameter_0_'.$name;
1.599 albertel 12212: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 12213: $$metathesekeys{$unikey}=1;
1.599 albertel 12214: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12215: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 12216: }
1.599 albertel 12217: if (defined($metaentry{':'.$unikey.'.default'})) {
12218: $metaentry{':'.$unikey}=
12219: $metaentry{':'.$unikey.'.default'};
1.483 albertel 12220: }
12221: }
12222:
1.261 albertel 12223: sub metadata_generate_part0 {
12224: my ($metadata,$metacache,$uri) = @_;
12225: my %allnames;
1.737 albertel 12226: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 12227: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 12228: my $part=$$metacache{':'.$metakey.'.part'};
12229: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 12230: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 12231: $allnames{$name}=$part;
12232: }
12233: }
12234: }
12235: foreach my $name (keys(%allnames)) {
12236: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 12237: my $key=":parameter_0_$name";
1.261 albertel 12238: $$metacache{"$key.part"}='0';
12239: $$metacache{"$key.name"}=$name;
1.428 albertel 12240: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 12241: $allnames{$name}.'_'.$name.
12242: '.type'};
1.428 albertel 12243: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 12244: '.display'};
1.644 www 12245: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 12246: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 12247: $$metacache{"$key.display"}=$olddis;
12248: }
1.71 www 12249: }
12250:
1.764 albertel 12251: # ------------------------------------------------------ Devalidate title cache
12252:
12253: sub devalidate_title_cache {
12254: my ($url)=@_;
12255: if (!$env{'request.course.id'}) { return; }
12256: my $symb=&symbread($url);
12257: if (!$symb) { return; }
12258: my $key=$env{'request.course.id'}."\0".$symb;
12259: &devalidate_cache_new('title',$key);
12260: }
12261:
1.1014 droeschl 12262: # ------------------------------------------------- Get the title of a course
12263:
12264: sub current_course_title {
12265: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12266: }
1.301 www 12267: # ------------------------------------------------- Get the title of a resource
12268:
12269: sub gettitle {
12270: my $urlsymb=shift;
12271: my $symb=&symbread($urlsymb);
1.534 albertel 12272: if ($symb) {
1.620 albertel 12273: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 12274: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 12275: if (defined($cached)) {
12276: return $result;
12277: }
1.534 albertel 12278: my ($map,$resid,$url)=&decode_symb($symb);
12279: my $title='';
1.907 albertel 12280: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12281: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12282: } else {
12283: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12284: &GDBM_READER(),0640)) {
12285: my $mapid=$bighash{'map_pc_'.&clutter($map)};
12286: $title=$bighash{'title_'.$mapid.'.'.$resid};
12287: untie(%bighash);
12288: }
1.534 albertel 12289: }
12290: $title=~s/\&colon\;/\:/gs;
12291: if ($title) {
1.1159 www 12292: # Remember both $symb and $title for dynamic metadata
12293: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 12294: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 12295: # Cache this title and then return it
1.599 albertel 12296: return &do_cache_new('title',$key,$title,600);
1.534 albertel 12297: }
12298: $urlsymb=$url;
12299: }
12300: my $title=&metadata($urlsymb,'title');
12301: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
12302: return $title;
1.301 www 12303: }
1.613 albertel 12304:
1.614 albertel 12305: sub get_slot {
12306: my ($which,$cnum,$cdom)=@_;
12307: if (!$cnum || !$cdom) {
1.790 albertel 12308: (undef,my $courseid)=&whichuser();
1.620 albertel 12309: $cdom=$env{'course.'.$courseid.'.domain'};
12310: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 12311: }
1.703 albertel 12312: my $key=join("\0",'slots',$cdom,$cnum,$which);
12313: my %slotinfo;
12314: if (exists($remembered{$key})) {
12315: $slotinfo{$which} = $remembered{$key};
12316: } else {
12317: %slotinfo=&get('slots',[$which],$cdom,$cnum);
12318: &Apache::lonhomework::showhash(%slotinfo);
12319: my ($tmp)=keys(%slotinfo);
12320: if ($tmp=~/^error:/) { return (); }
12321: $remembered{$key} = $slotinfo{$which};
12322: }
1.616 albertel 12323: if (ref($slotinfo{$which}) eq 'HASH') {
12324: return %{$slotinfo{$which}};
12325: }
12326: return $slotinfo{$which};
1.614 albertel 12327: }
1.1150 raeburn 12328:
12329: sub get_reservable_slots {
12330: my ($cnum,$cdom,$uname,$udom) = @_;
12331: my $now = time;
12332: my $reservable_info;
12333: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12334: if (exists($remembered{$key})) {
12335: $reservable_info = $remembered{$key};
12336: } else {
12337: my %resv;
12338: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12339: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12340: $reservable_info = \%resv;
12341: $remembered{$key} = $reservable_info;
12342: }
12343: return $reservable_info;
12344: }
12345:
12346: sub get_course_slots {
12347: my ($cnum,$cdom) = @_;
12348: my $hashid=$cnum.':'.$cdom;
12349: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12350: if (defined($cached)) {
12351: if (ref($result) eq 'HASH') {
12352: return %{$result};
12353: }
12354: } else {
12355: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12356: my ($tmp) = keys(%slots);
12357: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23 raeburn 12358: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 12359: return %slots;
12360: }
12361: }
12362: return;
12363: }
12364:
12365: sub devalidate_slots_cache {
12366: my ($cnum,$cdom)=@_;
12367: my $hashid=$cnum.':'.$cdom;
12368: &devalidate_cache_new('allslots',$hashid);
12369: }
12370:
1.1172.2.8 raeburn 12371: sub get_coursechange {
12372: my ($cdom,$cnum) = @_;
12373: if ($cdom eq '' || $cnum eq '') {
12374: return unless ($env{'request.course.id'});
12375: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12376: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12377: }
12378: my $hashid=$cdom.'_'.$cnum;
12379: my ($change,$cached)=&is_cached_new('crschange',$hashid);
12380: if ((defined($cached)) && ($change ne '')) {
12381: return $change;
12382: } else {
12383: my %crshash;
12384: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12385: if ($crshash{'internal.contentchange'} eq '') {
12386: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12387: if ($change eq '') {
12388: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12389: $change = $crshash{'internal.created'};
12390: }
12391: } else {
12392: $change = $crshash{'internal.contentchange'};
12393: }
12394: my $cachetime = 600;
12395: &do_cache_new('crschange',$hashid,$change,$cachetime);
12396: }
12397: return $change;
12398: }
12399:
12400: sub devalidate_coursechange_cache {
12401: my ($cnum,$cdom)=@_;
12402: my $hashid=$cnum.':'.$cdom;
12403: &devalidate_cache_new('crschange',$hashid);
12404: }
12405:
1.31 www 12406: # ------------------------------------------------- Update symbolic store links
12407:
12408: sub symblist {
12409: my ($mapname,%newhash)=@_;
1.438 www 12410: $mapname=&deversion(&declutter($mapname));
1.31 www 12411: my %hash;
1.620 albertel 12412: if (($env{'request.course.fn'}) && (%newhash)) {
12413: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12414: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 12415: foreach my $url (keys(%newhash)) {
1.711 albertel 12416: next if ($url eq 'last_known'
12417: && $env{'form.no_update_last_known'});
12418: $hash{declutter($url)}=&encode_symb($mapname,
12419: $newhash{$url}->[1],
12420: $newhash{$url}->[0]);
1.191 harris41 12421: }
1.31 www 12422: if (untie(%hash)) {
12423: return 'ok';
12424: }
12425: }
12426: }
12427: return 'error';
1.212 www 12428: }
12429:
12430: # --------------------------------------------------------------- Verify a symb
12431:
12432: sub symbverify {
1.1172.2.11 raeburn 12433: my ($symb,$thisurl,$encstate)=@_;
1.510 www 12434: my $thisfn=$thisurl;
1.439 www 12435: $thisfn=&declutter($thisfn);
1.215 www 12436: # direct jump to resource in page or to a sequence - will construct own symbs
12437: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12438: # check URL part
1.409 www 12439: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 12440:
1.431 www 12441: unless ($url eq $thisfn) { return 0; }
1.213 www 12442:
1.216 www 12443: $symb=&symbclean($symb);
1.510 www 12444: $thisurl=&deversion($thisurl);
1.439 www 12445: $thisfn=&deversion($thisfn);
1.213 www 12446:
12447: my %bighash;
12448: my $okay=0;
1.431 www 12449:
1.620 albertel 12450: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12451: &GDBM_READER(),0640)) {
1.1032 raeburn 12452: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12453: $thisurl =~ s/\?.+$//;
1.1172.2.13 raeburn 12454: if ($map =~ m{^uploaded/.+\.page$}) {
12455: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12456: $thisurl =~ s{^\Qhttp://https://\E}{https://};
12457: }
12458: }
12459: my $ids;
1.1172.2.122 raeburn 12460: if ($map =~ m{^uploaded/.+\.page$}) {
12461: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13 raeburn 12462: } else {
12463: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 12464: }
1.1102 raeburn 12465: unless ($ids) {
1.1172.2.13 raeburn 12466: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102 raeburn 12467: $ids=$bighash{$idkey};
1.216 www 12468: }
12469: if ($ids) {
12470: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13 raeburn 12471: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12472: $symb =~ s/\?.+$//;
12473: }
1.800 albertel 12474: foreach my $id (split(/\,/,$ids)) {
12475: my ($mapid,$resid)=split(/\./,$id);
1.216 www 12476: if (
12477: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13 raeburn 12478: eq $symb) {
1.1172.2.11 raeburn 12479: if (ref($encstate)) {
12480: $$encstate = $bighash{'encrypted_'.$id};
12481: }
1.1172.2.13 raeburn 12482: if (($env{'request.role.adv'}) ||
12483: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101 raeburn 12484: ($thisurl eq '/adm/navmaps')) {
1.1172.2.13 raeburn 12485: $okay=1;
12486: last;
12487: }
12488: }
12489: }
1.216 www 12490: }
1.213 www 12491: untie(%bighash);
12492: }
12493: return $okay;
1.31 www 12494: }
12495:
1.210 www 12496: # --------------------------------------------------------------- Clean-up symb
12497:
12498: sub symbclean {
12499: my $symb=shift;
1.568 albertel 12500: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 12501: # remove version from map
12502: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 12503:
1.210 www 12504: # remove version from URL
12505: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 12506:
1.507 www 12507: # remove wrapper
12508:
1.510 www 12509: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 12510: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 12511: return $symb;
1.409 www 12512: }
12513:
12514: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 12515:
12516: sub encode_symb {
12517: my ($map,$resid,$url)=@_;
12518: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12519: }
1.409 www 12520:
12521: sub decode_symb {
1.568 albertel 12522: my $symb=shift;
12523: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12524: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 12525: return (&fixversion($map),$resid,&fixversion($url));
12526: }
12527:
12528: sub fixversion {
12529: my $fn=shift;
1.609 banghart 12530: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 12531: my %bighash;
12532: my $uri=&clutter($fn);
1.620 albertel 12533: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 12534: # is this cached?
1.599 albertel 12535: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 12536: if (defined($cached)) { return $result; }
12537: # unfortunately not cached, or expired
1.620 albertel 12538: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 12539: &GDBM_READER(),0640)) {
12540: if ($bighash{'version_'.$uri}) {
12541: my $version=$bighash{'version_'.$uri};
1.444 www 12542: unless (($version eq 'mostrecent') ||
12543: ($version==&getversion($uri))) {
1.440 www 12544: $uri=~s/\.(\w+)$/\.$version\.$1/;
12545: }
12546: }
12547: untie %bighash;
1.413 www 12548: }
1.599 albertel 12549: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 12550: }
12551:
12552: sub deversion {
12553: my $url=shift;
12554: $url=~s/\.\d+\.(\w+)$/\.$1/;
12555: return $url;
1.210 www 12556: }
12557:
1.31 www 12558: # ------------------------------------------------------ Return symb list entry
12559:
12560: sub symbread {
1.1172.2.126 raeburn 12561: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128 raeburn 12562: $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54 raeburn 12563: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128 raeburn 12564: if (defined($env{$cache_str})) {
1.1172.2.126 raeburn 12565: unless (ref($possibles) eq 'HASH') {
12566: if ($ignorecachednull) {
12567: return $env{$cache_str} unless ($env{$cache_str} eq '');
12568: } else {
12569: return $env{$cache_str};
12570: }
1.1172.2.66 raeburn 12571: }
12572: }
1.242 www 12573: # no filename provided? try from environment
1.1172.2.54 raeburn 12574: unless ($thisfn) {
1.620 albertel 12575: if ($env{'request.symb'}) {
1.1172.2.128 raeburn 12576: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13 raeburn 12577: }
12578: $thisfn=$env{'request.filename'};
1.44 www 12579: }
1.569 albertel 12580: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 12581: # is that filename actually a symb? Verify, clean, and return
12582: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 12583: if (&symbverify($thisfn,$1)) {
1.1172.2.128 raeburn 12584: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 12585: }
1.242 www 12586: }
1.44 www 12587: $thisfn=declutter($thisfn);
1.31 www 12588: my %hash;
1.37 www 12589: my %bighash;
12590: my $syval='';
1.620 albertel 12591: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 12592: my $targetfn = $thisfn;
1.609 banghart 12593: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 12594: $targetfn = 'adm/wrapper/'.$thisfn;
12595: }
1.687 albertel 12596: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12597: $targetfn=$1;
12598: }
1.1172.2.128 raeburn 12599: unless ($ignoresymbdb) {
1.1172.2.126 raeburn 12600: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12601: &GDBM_READER(),0640)) {
12602: $syval=$hash{$targetfn};
12603: untie(%hash);
12604: }
1.1172.2.128 raeburn 12605: if ($syval && $checkforblock) {
12606: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126 raeburn 12607: if (@blockers) {
12608: $syval='';
12609: }
12610: }
1.37 www 12611: }
12612: # ---------------------------------------------------------- There was an entry
12613: if ($syval) {
1.601 albertel 12614: #unless ($syval=~/\_\d+$/) {
1.620 albertel 12615: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 12616: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12617: #return $env{$cache_str}='';
1.601 albertel 12618: #}
12619: #$syval.=$1;
12620: #}
1.37 www 12621: } else {
12622: # ------------------------------------------------------- Was not in symb table
1.620 albertel 12623: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12624: &GDBM_READER(),0640)) {
1.37 www 12625: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 12626: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 12627: unless ($ids) {
12628: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 12629: }
12630: unless ($ids) {
12631: # alias?
12632: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 12633: }
1.37 www 12634: if ($ids) {
12635: # ------------------------------------------------------------------- Has ID(s)
12636: my @possibilities=split(/\,/,$ids);
1.39 www 12637: if ($#possibilities==0) {
12638: # ----------------------------------------------- There is only one possibility
1.37 www 12639: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 12640: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12641: $resid,$thisfn);
1.1172.2.66 raeburn 12642: if (ref($possibles) eq 'HASH') {
1.1172.2.126 raeburn 12643: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12644: $possibles->{$syval} = 1;
12645: }
1.1172.2.66 raeburn 12646: }
12647: if ($checkforblock) {
1.1172.2.126 raeburn 12648: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127 raeburn 12649: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126 raeburn 12650: if (@blockers) {
12651: $syval = '';
12652: untie(%bighash);
12653: return $env{$cache_str}='';
12654: }
1.1172.2.66 raeburn 12655: }
12656: }
12657: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 12658: # ------------------------------------------ There is more than one possibility
12659: my $realpossible=0;
1.800 albertel 12660: foreach my $id (@possibilities) {
12661: my $file=$bighash{'src_'.$id};
1.1172.2.66 raeburn 12662: my $canaccess;
12663: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12664: $canaccess = 1;
12665: } else {
12666: $canaccess = &allowed('bre',$file);
12667: }
12668: if ($canaccess) {
12669: my ($mapid,$resid)=split(/\./,$id);
12670: if ($bighash{'map_type_'.$mapid} ne 'page') {
12671: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12672: $resid,$thisfn);
1.1172.2.126 raeburn 12673: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127 raeburn 12674: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66 raeburn 12675: if ($checkforblock) {
1.1172.2.127 raeburn 12676: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126 raeburn 12677: if (@blockers > 0) {
12678: $syval = '';
12679: } else {
1.1172.2.66 raeburn 12680: $syval = $poss_syval;
12681: $realpossible++;
12682: }
12683: } else {
12684: $syval = $poss_syval;
12685: $realpossible++;
12686: }
1.1172.2.126 raeburn 12687: if ($syval) {
12688: if (ref($possibles) eq 'HASH') {
12689: $possibles->{$syval} = 1;
12690: }
12691: }
1.1172.2.66 raeburn 12692: }
1.39 www 12693: }
1.191 harris41 12694: }
1.39 www 12695: if ($realpossible!=1) { $syval=''; }
1.249 www 12696: } else {
12697: $syval='';
1.37 www 12698: }
12699: }
1.1172.2.66 raeburn 12700: untie(%bighash);
1.481 raeburn 12701: }
1.31 www 12702: }
1.62 www 12703: if ($syval) {
1.1172.2.128 raeburn 12704: return $env{$cache_str}=$syval;
1.62 www 12705: }
1.31 www 12706: }
1.949 raeburn 12707: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12708: return $env{$cache_str}='';
1.31 www 12709: }
12710:
12711: # ---------------------------------------------------------- Return random seed
12712:
1.32 www 12713: sub numval {
12714: my $txt=shift;
12715: $txt=~tr/A-J/0-9/;
12716: $txt=~tr/a-j/0-9/;
12717: $txt=~tr/K-T/0-9/;
12718: $txt=~tr/k-t/0-9/;
12719: $txt=~tr/U-Z/0-5/;
12720: $txt=~tr/u-z/0-5/;
12721: $txt=~s/\D//g;
1.564 albertel 12722: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 12723: return int($txt);
1.368 albertel 12724: }
12725:
1.484 albertel 12726: sub numval2 {
12727: my $txt=shift;
12728: $txt=~tr/A-J/0-9/;
12729: $txt=~tr/a-j/0-9/;
12730: $txt=~tr/K-T/0-9/;
12731: $txt=~tr/k-t/0-9/;
12732: $txt=~tr/U-Z/0-5/;
12733: $txt=~tr/u-z/0-5/;
12734: $txt=~s/\D//g;
12735: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12736: my $total;
12737: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 12738: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 12739: return int($total);
12740: }
12741:
1.575 albertel 12742: sub numval3 {
12743: use integer;
12744: my $txt=shift;
12745: $txt=~tr/A-J/0-9/;
12746: $txt=~tr/a-j/0-9/;
12747: $txt=~tr/K-T/0-9/;
12748: $txt=~tr/k-t/0-9/;
12749: $txt=~tr/U-Z/0-5/;
12750: $txt=~tr/u-z/0-5/;
12751: $txt=~s/\D//g;
12752: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12753: my $total;
12754: foreach my $val (@txts) { $total+=$val; }
12755: if ($_64bit) { $total=(($total<<32)>>32); }
12756: return $total;
12757: }
12758:
1.675 albertel 12759: sub digest {
12760: my ($data)=@_;
12761: my $digest=&Digest::MD5::md5($data);
12762: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12763: my ($e,$f);
12764: {
12765: use integer;
12766: $e=($a+$b);
12767: $f=($c+$d);
12768: if ($_64bit) {
12769: $e=(($e<<32)>>32);
12770: $f=(($f<<32)>>32);
12771: }
12772: }
12773: if (wantarray) {
12774: return ($e,$f);
12775: } else {
12776: my $g;
12777: {
12778: use integer;
12779: $g=($e+$f);
12780: if ($_64bit) {
12781: $g=(($g<<32)>>32);
12782: }
12783: }
12784: return $g;
12785: }
12786: }
12787:
1.368 albertel 12788: sub latest_rnd_algorithm_id {
1.675 albertel 12789: return '64bit5';
1.366 albertel 12790: }
1.32 www 12791:
1.503 albertel 12792: sub get_rand_alg {
12793: my ($courseid)=@_;
1.790 albertel 12794: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12795: if ($courseid) {
1.620 albertel 12796: return $env{"course.$courseid.rndseed"};
1.503 albertel 12797: }
12798: return &latest_rnd_algorithm_id();
12799: }
12800:
1.562 albertel 12801: sub validCODE {
12802: my ($CODE)=@_;
12803: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12804: return 0;
12805: }
12806:
1.491 albertel 12807: sub getCODE {
1.620 albertel 12808: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12809: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12810: defined($Apache::lonhomework::parsing_a_task) ) &&
12811: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12812: return $Apache::lonhomework::history{'resource.CODE'};
12813: }
12814: return undef;
12815: }
1.1133 foxr 12816: #
12817: # Determines the random seed for a specific context:
12818: #
12819: # parameters:
12820: # symb - in course context the symb for the seed.
12821: # course_id - The course id of the form domain_coursenum.
12822: # domain - Domain for the user.
12823: # course - Course for the user.
12824: # cenv - environment of the course.
12825: #
12826: # NOTE:
12827: # All parameters are picked out of the environment if missing
12828: # or not defined.
12829: # If a symb cannot be determined the current time is used instead.
12830: #
12831: # For a given well defined symb, courside, domain, username,
12832: # and course environment, the seed is reproducible.
12833: #
1.31 www 12834: sub rndseed {
1.1133 foxr 12835: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12836: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12837: if (!defined($symb)) {
1.366 albertel 12838: unless ($symb=$wsymb) { return time; }
12839: }
1.1146 foxr 12840: if (!defined $courseid) {
12841: $courseid=$wcourseid;
12842: }
12843: if (!defined $domain) { $domain=$wdomain; }
12844: if (!defined $username) { $username=$wusername }
1.1133 foxr 12845:
12846: my $which;
12847: if (defined($cenv->{'rndseed'})) {
12848: $which = $cenv->{'rndseed'};
12849: } else {
12850: $which =&get_rand_alg($courseid);
12851: }
1.491 albertel 12852: if (defined(&getCODE())) {
1.675 albertel 12853: if ($which eq '64bit5') {
12854: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12855: } elsif ($which eq '64bit4') {
1.575 albertel 12856: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12857: } else {
12858: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12859: }
1.675 albertel 12860: } elsif ($which eq '64bit5') {
12861: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12862: } elsif ($which eq '64bit4') {
12863: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12864: } elsif ($which eq '64bit3') {
12865: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12866: } elsif ($which eq '64bit2') {
12867: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12868: } elsif ($which eq '64bit') {
12869: return &rndseed_64bit($symb,$courseid,$domain,$username);
12870: }
12871: return &rndseed_32bit($symb,$courseid,$domain,$username);
12872: }
12873:
12874: sub rndseed_32bit {
12875: my ($symb,$courseid,$domain,$username)=@_;
12876: {
12877: use integer;
12878: my $symbchck=unpack("%32C*",$symb) << 27;
12879: my $symbseed=numval($symb) << 22;
12880: my $namechck=unpack("%32C*",$username) << 17;
12881: my $nameseed=numval($username) << 12;
12882: my $domainseed=unpack("%32C*",$domain) << 7;
12883: my $courseseed=unpack("%32C*",$courseid);
12884: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12885: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12886: #&logthis("rndseed :$num:$symb");
1.564 albertel 12887: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 12888: return $num;
12889: }
12890: }
12891:
12892: sub rndseed_64bit {
12893: my ($symb,$courseid,$domain,$username)=@_;
12894: {
12895: use integer;
12896: my $symbchck=unpack("%32S*",$symb) << 21;
12897: my $symbseed=numval($symb) << 10;
12898: my $namechck=unpack("%32S*",$username);
12899:
12900: my $nameseed=numval($username) << 21;
12901: my $domainseed=unpack("%32S*",$domain) << 10;
12902: my $courseseed=unpack("%32S*",$courseid);
12903:
12904: my $num1=$symbchck+$symbseed+$namechck;
12905: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12906: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12907: #&logthis("rndseed :$num:$symb");
1.564 albertel 12908: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 12909: return "$num1,$num2";
1.155 albertel 12910: }
1.366 albertel 12911: }
12912:
1.443 albertel 12913: sub rndseed_64bit2 {
12914: my ($symb,$courseid,$domain,$username)=@_;
12915: {
12916: use integer;
12917: # strings need to be an even # of cahracters long, it it is odd the
12918: # last characters gets thrown away
12919: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12920: my $symbseed=numval($symb) << 10;
12921: my $namechck=unpack("%32S*",$username.' ');
12922:
12923: my $nameseed=numval($username) << 21;
1.501 albertel 12924: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12925: my $courseseed=unpack("%32S*",$courseid.' ');
12926:
12927: my $num1=$symbchck+$symbseed+$namechck;
12928: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12929: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12930: #&logthis("rndseed :$num:$symb");
1.803 albertel 12931: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 12932: return "$num1,$num2";
12933: }
12934: }
12935:
12936: sub rndseed_64bit3 {
12937: my ($symb,$courseid,$domain,$username)=@_;
12938: {
12939: use integer;
12940: # strings need to be an even # of cahracters long, it it is odd the
12941: # last characters gets thrown away
12942: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12943: my $symbseed=numval2($symb) << 10;
12944: my $namechck=unpack("%32S*",$username.' ');
12945:
12946: my $nameseed=numval2($username) << 21;
1.443 albertel 12947: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12948: my $courseseed=unpack("%32S*",$courseid.' ');
12949:
12950: my $num1=$symbchck+$symbseed+$namechck;
12951: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12952: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12953: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 12954: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12955:
1.503 albertel 12956: return "$num1:$num2";
1.443 albertel 12957: }
12958: }
12959:
1.575 albertel 12960: sub rndseed_64bit4 {
12961: my ($symb,$courseid,$domain,$username)=@_;
12962: {
12963: use integer;
12964: # strings need to be an even # of cahracters long, it it is odd the
12965: # last characters gets thrown away
12966: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12967: my $symbseed=numval3($symb) << 10;
12968: my $namechck=unpack("%32S*",$username.' ');
12969:
12970: my $nameseed=numval3($username) << 21;
12971: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12972: my $courseseed=unpack("%32S*",$courseid.' ');
12973:
12974: my $num1=$symbchck+$symbseed+$namechck;
12975: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12976: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12977: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 12978: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12979:
1.575 albertel 12980: return "$num1:$num2";
12981: }
12982: }
12983:
1.675 albertel 12984: sub rndseed_64bit5 {
12985: my ($symb,$courseid,$domain,$username)=@_;
12986: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12987: return "$num1:$num2";
12988: }
12989:
1.366 albertel 12990: sub rndseed_CODE_64bit {
12991: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 12992: {
1.366 albertel 12993: use integer;
1.443 albertel 12994: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 12995: my $symbseed=numval2($symb);
1.491 albertel 12996: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12997: my $CODEseed=numval(&getCODE());
1.443 albertel 12998: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 12999: my $num1=$symbseed+$CODEchck;
13000: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13001: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13002: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 13003: if ($_64bit) { $num1=(($num1<<32)>>32); }
13004: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 13005: return "$num1:$num2";
1.366 albertel 13006: }
13007: }
13008:
1.575 albertel 13009: sub rndseed_CODE_64bit4 {
13010: my ($symb,$courseid,$domain,$username)=@_;
13011: {
13012: use integer;
13013: my $symbchck=unpack("%32S*",$symb.' ') << 16;
13014: my $symbseed=numval3($symb);
13015: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
13016: my $CODEseed=numval3(&getCODE());
13017: my $courseseed=unpack("%32S*",$courseid.' ');
13018: my $num1=$symbseed+$CODEchck;
13019: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 13020: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
13021: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 13022: if ($_64bit) { $num1=(($num1<<32)>>32); }
13023: if ($_64bit) { $num2=(($num2<<32)>>32); }
13024: return "$num1:$num2";
13025: }
13026: }
13027:
1.675 albertel 13028: sub rndseed_CODE_64bit5 {
13029: my ($symb,$courseid,$domain,$username)=@_;
13030: my $code = &getCODE();
13031: my ($num1,$num2)=&digest("$symb,$courseid,$code");
13032: return "$num1:$num2";
13033: }
13034:
1.366 albertel 13035: sub setup_random_from_rndseed {
13036: my ($rndseed)=@_;
1.503 albertel 13037: if ($rndseed =~/([,:])/) {
1.1172.2.51 raeburn 13038: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
13039: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
13040: &Math::Random::random_set_seed_from_phrase($rndseed);
13041: } else {
13042: &Math::Random::random_set_seed($num1,$num2);
13043: }
1.366 albertel 13044: } else {
13045: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 13046: }
1.36 albertel 13047: }
13048:
1.474 albertel 13049: sub latest_receipt_algorithm_id {
1.835 albertel 13050: return 'receipt3';
1.474 albertel 13051: }
13052:
1.480 www 13053: sub recunique {
13054: my $fucourseid=shift;
13055: my $unique;
1.835 albertel 13056: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
13057: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13058: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 13059: } else {
13060: $unique=$perlvar{'lonReceipt'};
13061: }
13062: return unpack("%32C*",$unique);
13063: }
13064:
13065: sub recprefix {
13066: my $fucourseid=shift;
13067: my $prefix;
1.835 albertel 13068: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13069: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 13070: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 13071: } else {
13072: $prefix=$perlvar{'lonHostID'};
13073: }
13074: return unpack("%32C*",$prefix);
13075: }
13076:
1.76 www 13077: sub ireceipt {
1.474 albertel 13078: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 13079:
13080: my $return =&recprefix($fucourseid).'-';
13081:
13082: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13083: $env{'request.state'} eq 'construct') {
13084: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13085: return $return;
13086: }
13087:
1.76 www 13088: my $cuname=unpack("%32C*",$funame);
13089: my $cudom=unpack("%32C*",$fudom);
13090: my $cucourseid=unpack("%32C*",$fucourseid);
13091: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 13092: my $cunique=&recunique($fucourseid);
1.474 albertel 13093: my $cpart=unpack("%32S*",$part);
1.835 albertel 13094: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13095:
1.790 albertel 13096: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 13097:
13098: $return.= ($cunique%$cuname+
13099: $cunique%$cudom+
13100: $cusymb%$cuname+
13101: $cusymb%$cudom+
13102: $cucourseid%$cuname+
13103: $cucourseid%$cudom+
13104: $cpart%$cuname+
13105: $cpart%$cudom);
13106: } else {
13107: $return.= ($cunique%$cuname+
13108: $cunique%$cudom+
13109: $cusymb%$cuname+
13110: $cusymb%$cudom+
13111: $cucourseid%$cuname+
13112: $cucourseid%$cudom);
13113: }
13114: return $return;
1.76 www 13115: }
13116:
13117: sub receipt {
1.474 albertel 13118: my ($part)=@_;
1.790 albertel 13119: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 13120: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 13121: }
1.260 ng 13122:
1.790 albertel 13123: sub whichuser {
13124: my ($passedsymb)=@_;
13125: my ($symb,$courseid,$domain,$name,$publicuser);
13126: if (defined($env{'form.grade_symb'})) {
13127: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13128: my $allowed=&allowed('vgr',$tmp_courseid);
13129: if (!$allowed &&
13130: exists($env{'request.course.sec'}) &&
13131: $env{'request.course.sec'} !~ /^\s*$/) {
13132: $allowed=&allowed('vgr',$tmp_courseid.
13133: '/'.$env{'request.course.sec'});
13134: }
13135: if ($allowed) {
13136: ($symb)=&get_env_multiple('form.grade_symb');
13137: $courseid=$tmp_courseid;
13138: ($domain)=&get_env_multiple('form.grade_domain');
13139: ($name)=&get_env_multiple('form.grade_username');
13140: return ($symb,$courseid,$domain,$name,$publicuser);
13141: }
13142: }
13143: if (!$passedsymb) {
13144: $symb=&symbread();
13145: } else {
13146: $symb=$passedsymb;
13147: }
13148: $courseid=$env{'request.course.id'};
13149: $domain=$env{'user.domain'};
13150: $name=$env{'user.name'};
13151: if ($name eq 'public' && $domain eq 'public') {
13152: if (!defined($env{'form.username'})) {
13153: $env{'form.username'}.=time.rand(10000000);
13154: }
13155: $name.=$env{'form.username'};
13156: }
13157: return ($symb,$courseid,$domain,$name,$publicuser);
13158:
13159: }
13160:
1.36 albertel 13161: # ------------------------------------------------------------ Serves up a file
1.472 albertel 13162: # returns either the contents of the file or
13163: # -1 if the file doesn't exist
1.481 raeburn 13164: #
13165: # if the target is a file that was uploaded via DOCS,
13166: # a check will be made to see if a current copy exists on the local server,
13167: # if it does this will be served, otherwise a copy will be retrieved from
13168: # the home server for the course and stored in /home/httpd/html/userfiles on
13169: # the local server.
1.472 albertel 13170:
1.36 albertel 13171: sub getfile {
1.538 albertel 13172: my ($file) = @_;
1.609 banghart 13173: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 13174: &repcopy($file);
13175: return &readfile($file);
13176: }
13177:
13178: sub repcopy_userfile {
13179: my ($file)=@_;
1.1142 raeburn 13180: my $londocroot = $perlvar{'lonDocRoot'};
13181: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 13182: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 13183: my ($cdom,$cnum,$filename) =
1.811 albertel 13184: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 13185: my $uri="/uploaded/$cdom/$cnum/$filename";
13186: if (-e "$file") {
1.828 www 13187: # we already have a local copy, check it out
1.538 albertel 13188: my @fileinfo = stat($file);
1.828 www 13189: my $rtncode;
13190: my $info;
1.538 albertel 13191: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 13192: if ($lwpresp ne 'ok') {
1.828 www 13193: # there is no such file anymore, even though we had a local copy
1.482 albertel 13194: if ($rtncode eq '404') {
1.538 albertel 13195: unlink($file);
1.482 albertel 13196: }
13197: return -1;
13198: }
13199: if ($info < $fileinfo[9]) {
1.828 www 13200: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 13201: return 'ok';
1.828 www 13202: } else {
13203: # the file is outdated, get rid of it
13204: unlink($file);
1.482 albertel 13205: }
1.828 www 13206: }
13207: # one way or the other, at this point, we don't have the file
13208: # construct the correct path for the file
13209: my @parts = ($cdom,$cnum);
13210: if ($filename =~ m|^(.+)/[^/]+$|) {
13211: push @parts, split(/\//,$1);
13212: }
13213: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13214: foreach my $part (@parts) {
13215: $path .= '/'.$part;
13216: if (!-e $path) {
13217: mkdir($path,0770);
1.482 albertel 13218: }
13219: }
1.828 www 13220: # now the path exists for sure
13221: # get a user agent
13222: my $ua=new LWP::UserAgent;
13223: my $transferfile=$file.'.in.transfer';
13224: # FIXME: this should flock
13225: if (-e $transferfile) { return 'ok'; }
13226: my $request;
13227: $uri=~s/^\///;
1.980 raeburn 13228: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 13229: my $hostname = &hostname($homeserver);
1.980 raeburn 13230: my $protocol = $protocol{$homeserver};
13231: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13232: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828 www 13233: my $response=$ua->request($request,$transferfile);
13234: # did it work?
13235: if ($response->is_error()) {
13236: unlink($transferfile);
13237: &logthis("Userfile repcopy failed for $uri");
13238: return -1;
13239: }
13240: # worked, rename the transfer file
13241: rename($transferfile,$file);
1.607 raeburn 13242: return 'ok';
1.481 raeburn 13243: }
13244:
1.517 albertel 13245: sub tokenwrapper {
13246: my $uri=shift;
1.980 raeburn 13247: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 13248: $uri=~s|^/||;
1.620 albertel 13249: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 13250: my $token=$1;
1.552 albertel 13251: my (undef,$udom,$uname,$file)=split('/',$uri,4);
13252: if ($udom && $uname && $file) {
13253: $file=~s|(\?\.*)*$||;
1.949 raeburn 13254: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 13255: my $homeserver = &homeserver($uname,$udom);
1.1172.2.120 raeburn 13256: my $hostname = &hostname($homeserver);
1.980 raeburn 13257: my $protocol = $protocol{$homeserver};
13258: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13259: return $protocol.'://'.$hostname.'/'.$uri.
1.517 albertel 13260: (($uri=~/\?/)?'&':'?').'token='.$token.
13261: '&tokenissued='.$perlvar{'lonHostID'};
13262: } else {
13263: return '/adm/notfound.html';
13264: }
13265: }
13266:
1.828 www 13267: # call with reqtype HEAD: get last modification time
13268: # call with reqtype GET: get the file contents
13269: # Do not call this with reqtype GET for large files! It loads everything into memory
13270: #
1.481 raeburn 13271: sub getuploaded {
13272: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13273: $uri=~s/^\///;
1.980 raeburn 13274: my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120 raeburn 13275: my $hostname = &hostname($homeserver);
1.980 raeburn 13276: my $protocol = $protocol{$homeserver};
13277: $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120 raeburn 13278: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481 raeburn 13279: my $ua=new LWP::UserAgent;
13280: my $request=new HTTP::Request($reqtype,$uri);
13281: my $response=$ua->request($request);
13282: $$rtncode = $response->code;
1.482 albertel 13283: if (! $response->is_success()) {
13284: return 'failed';
13285: }
13286: if ($reqtype eq 'HEAD') {
1.486 www 13287: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 13288: } elsif ($reqtype eq 'GET') {
13289: $$info = $response->content;
1.472 albertel 13290: }
1.482 albertel 13291: return 'ok';
1.36 albertel 13292: }
13293:
1.481 raeburn 13294: sub readfile {
13295: my $file = shift;
13296: if ( (! -e $file ) || ($file eq '') ) { return -1; };
13297: my $fh;
1.1172.2.96 raeburn 13298: open($fh,"<",$file);
1.481 raeburn 13299: my $a='';
1.800 albertel 13300: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 13301: return $a;
13302: }
13303:
1.36 albertel 13304: sub filelocation {
1.590 banghart 13305: my ($dir,$file) = @_;
13306: my $location;
13307: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 13308:
13309: if ($file =~ m-^/adm/-) {
13310: $file=~s-^/adm/wrapper/-/-;
13311: $file=~s-^/adm/coursedocs/showdoc/-/-;
13312: }
1.882 albertel 13313:
1.1139 www 13314: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 13315: $location = $file;
1.609 banghart 13316: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 13317: my ($udom,$uname,$filename)=
1.811 albertel 13318: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 13319: my $home=&homeserver($uname,$udom);
13320: my $is_me=0;
13321: my @ids=¤t_machine_ids();
13322: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13323: if ($is_me) {
1.1117 foxr 13324: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 13325: } else {
13326: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13327: $udom.'/'.$uname.'/'.$filename;
13328: }
1.882 albertel 13329: } elsif ($file =~ m-^/adm/-) {
13330: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 13331: } else {
13332: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 13333: $file=~s:^/(res|priv)/:/:;
13334: my $space=$1;
1.590 banghart 13335: if ( !( $file =~ m:^/:) ) {
13336: $location = $dir. '/'.$file;
13337: } else {
1.1142 raeburn 13338: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 13339: }
1.59 albertel 13340: }
1.590 banghart 13341: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 13342: while ($location=~m{/\.\./}) {
13343: if ($location =~ m{/[^/]+/\.\./}) {
13344: $location=~ s{/[^/]+/\.\./}{/}g;
13345: } else {
13346: $location=~ s{/\.\./}{/}g;
13347: }
13348: } #remove dir/..
1.590 banghart 13349: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13350: return $location;
1.46 www 13351: }
1.36 albertel 13352:
1.46 www 13353: sub hreflocation {
13354: my ($dir,$file)=@_;
1.980 raeburn 13355: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 13356: $file=filelocation($dir,$file);
1.700 albertel 13357: } elsif ($file=~m-^/adm/-) {
13358: $file=~s-^/adm/wrapper/-/-;
13359: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 13360: }
13361: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13362: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13363: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 13364: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13365: {/uploaded/$1/$2/}x;
1.46 www 13366: }
1.913 albertel 13367: if ($file=~ m{^/userfiles/}) {
13368: $file =~ s{^/userfiles/}{/uploaded/};
13369: }
1.462 albertel 13370: return $file;
1.465 albertel 13371: }
13372:
1.1139 www 13373:
13374:
13375:
13376:
1.465 albertel 13377: sub current_machine_domains {
1.853 albertel 13378: return &machine_domains(&hostname($perlvar{'lonHostID'}));
13379: }
13380:
13381: sub machine_domains {
13382: my ($hostname) = @_;
1.465 albertel 13383: my @domains;
1.838 albertel 13384: my %hostname = &all_hostnames();
1.465 albertel 13385: while( my($id, $name) = each(%hostname)) {
1.467 matthew 13386: # &logthis("-$id-$name-$hostname-");
1.465 albertel 13387: if ($hostname eq $name) {
1.844 albertel 13388: push(@domains,&host_domain($id));
1.465 albertel 13389: }
13390: }
13391: return @domains;
13392: }
13393:
13394: sub current_machine_ids {
1.853 albertel 13395: return &machine_ids(&hostname($perlvar{'lonHostID'}));
13396: }
13397:
13398: sub machine_ids {
13399: my ($hostname) = @_;
13400: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 13401: my @ids;
1.888 albertel 13402: my %name_to_host = &all_names();
1.889 albertel 13403: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13404: return @{ $name_to_host{$hostname} };
13405: }
13406: return;
1.31 www 13407: }
13408:
1.824 raeburn 13409: sub additional_machine_domains {
13410: my @domains;
1.1172.2.96 raeburn 13411: open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824 raeburn 13412: while( my $line = <$fh>) {
13413: $line =~ s/\s//g;
13414: push(@domains,$line);
13415: }
13416: return @domains;
13417: }
13418:
13419: sub default_login_domain {
13420: my $domain = $perlvar{'lonDefDomain'};
13421: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13422: foreach my $posdom (¤t_machine_domains(),
13423: &additional_machine_domains()) {
13424: if (lc($posdom) eq lc($testdomain)) {
13425: $domain=$posdom;
13426: last;
13427: }
13428: }
13429: return $domain;
13430: }
13431:
1.1172.2.106 raeburn 13432: sub shared_institution {
1.1172.2.136 raeburn 13433: my ($dom,$lonhost) = @_;
13434: if ($lonhost eq '') {
13435: $lonhost = $perlvar{'lonHostID'};
13436: }
1.1172.2.106 raeburn 13437: my $same_intdom;
1.1172.2.136 raeburn 13438: my $hostintdom = &internet_dom($lonhost);
1.1172.2.106 raeburn 13439: if ($hostintdom ne '') {
13440: my %iphost = &get_iphost();
13441: my $primary_id = &domain($dom,'primary');
13442: my $primary_ip = &get_host_ip($primary_id);
13443: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
13444: foreach my $id (@{$iphost{$primary_ip}}) {
13445: my $intdom = &internet_dom($id);
13446: if ($intdom eq $hostintdom) {
13447: $same_intdom = 1;
13448: last;
13449: }
13450: }
13451: }
13452: }
13453: return $same_intdom;
13454: }
13455:
1.1172.2.120 raeburn 13456: sub uses_sts {
13457: my ($ignore_cache) = @_;
13458: my $lonhost = $perlvar{'lonHostID'};
13459: my $hostname = &hostname($lonhost);
13460: my $sts_on;
13461: if ($protocol{$lonhost} eq 'https') {
13462: my $cachetime = 12*3600;
13463: if (!$ignore_cache) {
13464: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13465: if (defined($cached)) {
13466: return $sts_on;
13467: }
13468: }
1.1172.2.121 raeburn 13469: my $ua=new LWP::UserAgent;
1.1172.2.120 raeburn 13470: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13471: my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121 raeburn 13472: my $response=$ua->request($request);
1.1172.2.120 raeburn 13473: if ($response->is_success) {
13474: my $has_sts = $response->header('Strict-Transport-Security');
13475: if ($has_sts eq '') {
13476: $sts_on = 0;
13477: } else {
13478: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13479: my $maxage = $1;
13480: if ($maxage) {
13481: $sts_on = 1;
13482: } else {
13483: $sts_on = 0;
13484: }
13485: } else {
13486: $sts_on = 0;
13487: }
13488: }
13489: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13490: }
13491: }
13492: return;
13493: }
13494:
1.1172.2.134 raeburn 13495: sub get_requestor_ip {
13496: my ($r,$nolookup,$noproxy) = @_;
13497: my $from_ip;
13498: if (ref($r)) {
13499: $from_ip = $r->get_remote_host($nolookup);
13500: } else {
13501: $from_ip = $ENV{'REMOTE_ADDR'};
13502: }
13503: return $from_ip;
13504: }
13505:
1.31 www 13506: # ------------------------------------------------------------- Declutters URLs
13507:
13508: sub declutter {
13509: my $thisfn=shift;
1.569 albertel 13510: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49 raeburn 13511: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13512: $thisfn=~s{^/home/httpd/html}{};
13513: }
1.31 www 13514: $thisfn=~s/^\///;
1.697 albertel 13515: $thisfn=~s|^adm/wrapper/||;
13516: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 13517: $thisfn=~s/^res\///;
1.1172 bisitz 13518: $thisfn=~s/^priv\///;
1.1032 raeburn 13519: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13520: $thisfn=~s/\?.+$//;
13521: }
1.268 www 13522: return $thisfn;
13523: }
13524:
13525: # ------------------------------------------------------------- Clutter up URLs
13526:
13527: sub clutter {
13528: my $thisfn='/'.&declutter(shift);
1.887 albertel 13529: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 13530: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 13531: $thisfn='/res'.$thisfn;
13532: }
1.1031 raeburn 13533: if ($thisfn !~m|^/adm|) {
13534: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 13535: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 13536: } else {
13537: my ($ext) = ($thisfn =~ /\.(\w+)$/);
13538: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 13539: if ($embstyle eq 'ssi'
13540: || ($embstyle eq 'hdn')
13541: || ($embstyle eq 'rat')
13542: || ($embstyle eq 'prv')
13543: || ($embstyle eq 'ign')) {
13544: #do nothing with these
13545: } elsif (($embstyle eq 'img')
1.695 albertel 13546: || ($embstyle eq 'emb')
13547: || ($embstyle eq 'wrp')) {
13548: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 13549: } elsif ($embstyle eq 'unk'
13550: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 13551: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 13552: } else {
1.718 www 13553: # &logthis("Got a blank emb style");
1.695 albertel 13554: }
1.694 albertel 13555: }
13556: }
1.31 www 13557: return $thisfn;
1.12 www 13558: }
13559:
1.787 albertel 13560: sub clutter_with_no_wrapper {
13561: my $uri = &clutter(shift);
13562: if ($uri =~ m-^/adm/-) {
13563: $uri =~ s-^/adm/wrapper/-/-;
13564: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
13565: }
13566: return $uri;
13567: }
13568:
1.557 albertel 13569: sub freeze_escape {
13570: my ($value)=@_;
13571: if (ref($value)) {
13572: $value=&nfreeze($value);
13573: return '__FROZEN__'.&escape($value);
13574: }
13575: return &escape($value);
13576: }
13577:
1.11 www 13578:
1.557 albertel 13579: sub thaw_unescape {
13580: my ($value)=@_;
13581: if ($value =~ /^__FROZEN__/) {
13582: substr($value,0,10,undef);
13583: $value=&unescape($value);
13584: return &thaw($value);
13585: }
13586: return &unescape($value);
13587: }
13588:
1.436 albertel 13589: sub correct_line_ends {
13590: my ($result)=@_;
13591: $$result =~s/\r\n/\n/mg;
13592: $$result =~s/\r/\n/mg;
1.415 albertel 13593: }
1.1 albertel 13594: # ================================================================ Main Program
13595:
1.184 www 13596: sub goodbye {
1.204 albertel 13597: &logthis("Starting Shut down");
1.443 albertel 13598: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 13599: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 13600: #converted
1.599 albertel 13601: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 13602: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13603: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13604: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 13605: #1.1 only
1.870 albertel 13606: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13607: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13608: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13609: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13610: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 13611: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13612: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 13613: &flushcourselogs();
13614: &logthis("Shutting down");
13615: }
13616:
1.852 albertel 13617: sub get_dns {
1.1172.2.17 raeburn 13618: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 13619: if (!$ignore_cache) {
13620: my ($content,$cached)=
13621: &Apache::lonnet::is_cached_new('dns',$url);
13622: if ($cached) {
1.1172.2.17 raeburn 13623: &$func($content,$hashref);
1.869 albertel 13624: return;
13625: }
13626: }
13627:
13628: my %alldns;
1.1172.2.96 raeburn 13629: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13630: foreach my $dns (<$config>) {
13631: next if ($dns !~ /^\^(\S*)/x);
13632: my $line = $1;
13633: my ($host,$protocol) = split(/:/,$line);
13634: if ($protocol ne 'https') {
13635: $protocol = 'http';
13636: }
13637: $alldns{$host} = $protocol;
1.979 raeburn 13638: }
1.1172.2.96 raeburn 13639: close($config);
1.869 albertel 13640: }
13641: while (%alldns) {
1.1172.2.52 raeburn 13642: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 13643: my $ua=new LWP::UserAgent;
1.1134 raeburn 13644: $ua->timeout(30);
1.979 raeburn 13645: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 13646: my $response=$ua->request($request);
1.979 raeburn 13647: delete($alldns{$dns});
1.852 albertel 13648: next if ($response->is_error());
13649: my @content = split("\n",$response->content);
1.1172.2.17 raeburn 13650: unless ($nocache) {
1.1172.2.23 raeburn 13651: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17 raeburn 13652: }
13653: &$func(\@content,$hashref);
1.869 albertel 13654: return;
1.852 albertel 13655: }
1.871 albertel 13656: my $which = (split('/',$url))[3];
13657: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105 raeburn 13658: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13659: my @content = <$config>;
13660: &$func(\@content,$hashref);
13661: }
1.1172.2.17 raeburn 13662: return;
13663: }
13664:
13665: # ------------------------------------------------------Get DNS checksums file
13666: sub parse_dns_checksums_tab {
13667: my ($lines,$hashref) = @_;
1.1172.2.53 raeburn 13668: my $lonhost = $perlvar{'lonHostID'};
13669: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17 raeburn 13670: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53 raeburn 13671: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13672: my $webconfdir = '/etc/httpd/conf';
13673: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13674: $webconfdir = '/etc/apache2';
13675: } elsif ($distro =~ /^sles(\d+)$/) {
13676: if ($1 >= 10) {
13677: $webconfdir = '/etc/apache2';
13678: }
13679: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13680: if ($1 >= 10.0) {
13681: $webconfdir = '/etc/apache2';
13682: }
13683: }
1.1172.2.17 raeburn 13684: my ($release,$timestamp) = split(/\-/,$loncaparev);
13685: my (%chksum,%revnum);
13686: if (ref($lines) eq 'ARRAY') {
13687: chomp(@{$lines});
1.1172.2.34 raeburn 13688: my $version = shift(@{$lines});
13689: if ($version eq $release) {
1.1172.2.17 raeburn 13690: foreach my $line (@{$lines}) {
1.1172.2.34 raeburn 13691: my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53 raeburn 13692: if ($file =~ m{^/etc/httpd/conf}) {
13693: if ($webconfdir eq '/etc/apache2') {
13694: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13695: }
13696: }
1.1172.2.34 raeburn 13697: $chksum{$file} = $shasum;
13698: $revnum{$file} = $version;
1.1172.2.17 raeburn 13699: }
13700: if (ref($hashref) eq 'HASH') {
13701: %{$hashref} = (
13702: sums => \%chksum,
13703: versions => \%revnum,
13704: );
13705: }
13706: }
13707: }
1.869 albertel 13708: return;
1.852 albertel 13709: }
1.1172.2.17 raeburn 13710:
13711: sub fetch_dns_checksums {
13712: my %checksums;
1.1172.2.34 raeburn 13713: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48 raeburn 13714: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34 raeburn 13715: my ($release,$timestamp) = split(/\-/,$loncaparev);
13716: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17 raeburn 13717: \%checksums);
13718: return \%checksums;
13719: }
13720:
1.327 albertel 13721: # ------------------------------------------------------------ Read domain file
13722: {
1.852 albertel 13723: my $loaded;
1.846 albertel 13724: my %domain;
13725:
1.852 albertel 13726: sub parse_domain_tab {
13727: my ($lines) = @_;
13728: foreach my $line (@$lines) {
13729: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 13730:
1.846 albertel 13731: chomp($line);
1.852 albertel 13732: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 13733: my %this_domain;
13734: foreach my $field ('description', 'auth_def', 'auth_arg_def',
13735: 'lang_def', 'city', 'longi', 'lati',
13736: 'primary') {
13737: $this_domain{$field} = shift(@elements);
13738: }
13739: $domain{$name} = \%this_domain;
1.852 albertel 13740: }
13741: }
1.864 albertel 13742:
13743: sub reset_domain_info {
13744: undef($loaded);
13745: undef(%domain);
13746: }
13747:
1.852 albertel 13748: sub load_domain_tab {
1.1172.2.70 raeburn 13749: my ($ignore_cache,$nocache) = @_;
13750: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 13751: my $fh;
1.1172.2.96 raeburn 13752: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852 albertel 13753: my @lines = <$fh>;
13754: &parse_domain_tab(\@lines);
1.448 albertel 13755: }
1.852 albertel 13756: close($fh);
13757: $loaded = 1;
1.327 albertel 13758: }
1.846 albertel 13759:
13760: sub domain {
1.852 albertel 13761: &load_domain_tab() if (!$loaded);
13762:
1.846 albertel 13763: my ($name,$what) = @_;
13764: return if ( !exists($domain{$name}) );
13765:
13766: if (!$what) {
13767: return $domain{$name}{'description'};
13768: }
13769: return $domain{$name}{$what};
13770: }
1.974 raeburn 13771:
13772: sub domain_info {
13773: &load_domain_tab() if (!$loaded);
13774: return %domain;
13775: }
13776:
1.327 albertel 13777: }
13778:
13779:
1.1 albertel 13780: # ------------------------------------------------------------- Read hosts file
13781: {
1.838 albertel 13782: my %hostname;
1.844 albertel 13783: my %hostdom;
1.845 albertel 13784: my %libserv;
1.852 albertel 13785: my $loaded;
1.888 albertel 13786: my %name_to_host;
1.1074 raeburn 13787: my %internetdom;
1.1107 raeburn 13788: my %LC_dns_serv;
1.852 albertel 13789:
13790: sub parse_hosts_tab {
13791: my ($file) = @_;
13792: foreach my $configline (@$file) {
13793: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 13794: chomp($configline);
13795: if ($configline =~ /^\^/) {
13796: if ($configline =~ /^\^([\w.\-]+)/) {
13797: $LC_dns_serv{$1} = 1;
13798: }
13799: next;
13800: }
1.1074 raeburn 13801: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 13802: $name=~s/\s//g;
13803: if ($id && $domain && $role && $name) {
1.1172.2.96 raeburn 13804: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13805: my $curr = $hostname{$id};
13806: my $skip;
13807: if (ref($name_to_host{$curr}) eq 'ARRAY') {
13808: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13809: $skip = 1;
13810: } else {
13811: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13812: }
13813: }
13814: unless ($skip) {
13815: push(@{$name_to_host{$name}},$id);
13816: }
13817: } else {
13818: push(@{$name_to_host{$name}},$id);
13819: }
1.852 albertel 13820: $hostname{$id}=$name;
13821: $hostdom{$id}=$domain;
13822: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 13823: if (defined($protocol)) {
13824: if ($protocol eq 'https') {
13825: $protocol{$id} = $protocol;
13826: } else {
13827: $protocol{$id} = 'http';
13828: }
1.968 raeburn 13829: } else {
1.969 raeburn 13830: $protocol{$id} = 'http';
1.968 raeburn 13831: }
1.1074 raeburn 13832: if (defined($intdom)) {
13833: $internetdom{$id} = $intdom;
13834: }
1.852 albertel 13835: }
13836: }
13837: }
1.864 albertel 13838:
13839: sub reset_hosts_info {
1.897 albertel 13840: &purge_remembered();
1.864 albertel 13841: &reset_domain_info();
13842: &reset_hosts_ip_info();
1.892 albertel 13843: undef(%name_to_host);
1.864 albertel 13844: undef(%hostname);
13845: undef(%hostdom);
13846: undef(%libserv);
13847: undef($loaded);
13848: }
1.1 albertel 13849:
1.852 albertel 13850: sub load_hosts_tab {
1.1172.2.70 raeburn 13851: my ($ignore_cache,$nocache) = @_;
13852: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96 raeburn 13853: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852 albertel 13854: my @config = <$config>;
13855: &parse_hosts_tab(\@config);
13856: close($config);
13857: $loaded=1;
1.1 albertel 13858: }
1.852 albertel 13859:
1.838 albertel 13860: sub hostname {
1.852 albertel 13861: &load_hosts_tab() if (!$loaded);
13862:
1.838 albertel 13863: my ($lonid) = @_;
13864: return $hostname{$lonid};
13865: }
1.845 albertel 13866:
1.838 albertel 13867: sub all_hostnames {
1.852 albertel 13868: &load_hosts_tab() if (!$loaded);
13869:
1.838 albertel 13870: return %hostname;
13871: }
1.845 albertel 13872:
1.888 albertel 13873: sub all_names {
1.1172.2.70 raeburn 13874: my ($ignore_cache,$nocache) = @_;
13875: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 13876:
13877: return %name_to_host;
13878: }
13879:
1.974 raeburn 13880: sub all_host_domain {
13881: &load_hosts_tab() if (!$loaded);
13882: return %hostdom;
13883: }
13884:
1.845 albertel 13885: sub is_library {
1.852 albertel 13886: &load_hosts_tab() if (!$loaded);
13887:
1.845 albertel 13888: return exists($libserv{$_[0]});
13889: }
13890:
13891: sub all_library {
1.852 albertel 13892: &load_hosts_tab() if (!$loaded);
13893:
1.845 albertel 13894: return %libserv;
13895: }
13896:
1.1062 droeschl 13897: sub unique_library {
13898: #2x reverse removes all hostnames that appear more than once
13899: my %unique = reverse &all_library();
13900: return reverse %unique;
13901: }
13902:
1.841 albertel 13903: sub get_servers {
1.852 albertel 13904: &load_hosts_tab() if (!$loaded);
13905:
1.841 albertel 13906: my ($domain,$type) = @_;
13907: my %possible_hosts = ($type eq 'library') ? %libserv
13908: : %hostname;
13909: my %result;
1.842 albertel 13910: if (ref($domain) eq 'ARRAY') {
13911: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 13912: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 13913: $result{$host} = $hostname;
13914: }
13915: }
13916: } else {
13917: while ( my ($host,$hostname) = each(%possible_hosts)) {
13918: if ($hostdom{$host} eq $domain) {
13919: $result{$host} = $hostname;
13920: }
1.841 albertel 13921: }
13922: }
13923: return %result;
13924: }
1.845 albertel 13925:
1.1062 droeschl 13926: sub get_unique_servers {
13927: my %unique = reverse &get_servers(@_);
13928: return reverse %unique;
13929: }
13930:
1.844 albertel 13931: sub host_domain {
1.852 albertel 13932: &load_hosts_tab() if (!$loaded);
13933:
1.844 albertel 13934: my ($lonid) = @_;
13935: return $hostdom{$lonid};
13936: }
13937:
1.841 albertel 13938: sub all_domains {
1.852 albertel 13939: &load_hosts_tab() if (!$loaded);
13940:
1.841 albertel 13941: my %seen;
13942: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13943: return @uniq;
13944: }
1.1074 raeburn 13945:
13946: sub internet_dom {
13947: &load_hosts_tab() if (!$loaded);
13948:
13949: my ($lonid) = @_;
13950: return $internetdom{$lonid};
13951: }
1.1107 raeburn 13952:
13953: sub is_LC_dns {
13954: &load_hosts_tab() if (!$loaded);
13955:
13956: my ($hostname) = @_;
13957: return exists($LC_dns_serv{$hostname});
13958: }
13959:
1.1 albertel 13960: }
13961:
1.847 albertel 13962: {
13963: my %iphost;
1.856 albertel 13964: my %name_to_ip;
13965: my %lonid_to_ip;
1.869 albertel 13966:
1.847 albertel 13967: sub get_hosts_from_ip {
13968: my ($ip) = @_;
13969: my %iphosts = &get_iphost();
13970: if (ref($iphosts{$ip})) {
13971: return @{$iphosts{$ip}};
13972: }
13973: return;
1.839 albertel 13974: }
1.864 albertel 13975:
13976: sub reset_hosts_ip_info {
13977: undef(%iphost);
13978: undef(%name_to_ip);
13979: undef(%lonid_to_ip);
13980: }
1.856 albertel 13981:
13982: sub get_host_ip {
13983: my ($lonid) = @_;
13984: if (exists($lonid_to_ip{$lonid})) {
13985: return $lonid_to_ip{$lonid};
13986: }
13987: my $name=&hostname($lonid);
13988: my $ip = gethostbyname($name);
13989: return if (!$ip || length($ip) ne 4);
13990: $ip=inet_ntoa($ip);
13991: $name_to_ip{$name} = $ip;
13992: $lonid_to_ip{$lonid} = $ip;
13993: return $ip;
13994: }
1.847 albertel 13995:
13996: sub get_iphost {
1.1172.2.70 raeburn 13997: my ($ignore_cache,$nocache) = @_;
1.894 albertel 13998:
1.869 albertel 13999: if (!$ignore_cache) {
14000: if (%iphost) {
14001: return %iphost;
14002: }
14003: my ($ip_info,$cached)=
14004: &Apache::lonnet::is_cached_new('iphost','iphost');
14005: if ($cached) {
14006: %iphost = %{$ip_info->[0]};
14007: %name_to_ip = %{$ip_info->[1]};
14008: %lonid_to_ip = %{$ip_info->[2]};
14009: return %iphost;
14010: }
14011: }
1.894 albertel 14012:
14013: # get yesterday's info for fallback
14014: my %old_name_to_ip;
14015: my ($ip_info,$cached)=
14016: &Apache::lonnet::is_cached_new('iphost','iphost');
14017: if ($cached) {
14018: %old_name_to_ip = %{$ip_info->[1]};
14019: }
14020:
1.1172.2.70 raeburn 14021: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 14022: foreach my $name (keys(%name_to_host)) {
1.847 albertel 14023: my $ip;
14024: if (!exists($name_to_ip{$name})) {
14025: $ip = gethostbyname($name);
14026: if (!$ip || length($ip) ne 4) {
1.894 albertel 14027: if (defined($old_name_to_ip{$name})) {
14028: $ip = $old_name_to_ip{$name};
14029: &logthis("Can't find $name defaulting to old $ip");
14030: } else {
14031: &logthis("Name $name no IP found");
14032: next;
14033: }
14034: } else {
14035: $ip=inet_ntoa($ip);
1.847 albertel 14036: }
14037: $name_to_ip{$name} = $ip;
14038: } else {
14039: $ip = $name_to_ip{$name};
1.653 albertel 14040: }
1.888 albertel 14041: foreach my $id (@{ $name_to_host{$name} }) {
14042: $lonid_to_ip{$id} = $ip;
14043: }
14044: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 14045: }
1.1172.2.70 raeburn 14046: unless ($nocache) {
14047: &do_cache_new('iphost','iphost',
14048: [\%iphost,\%name_to_ip,\%lonid_to_ip],
14049: 48*60*60);
14050: }
1.869 albertel 14051:
1.847 albertel 14052: return %iphost;
1.598 albertel 14053: }
14054:
1.992 raeburn 14055: #
14056: # Given a DNS returns the loncapa host name for that DNS
14057: #
14058: sub host_from_dns {
14059: my ($dns) = @_;
14060: my @hosts;
14061: my $ip;
14062:
1.993 raeburn 14063: if (exists($name_to_ip{$dns})) {
1.992 raeburn 14064: $ip = $name_to_ip{$dns};
14065: }
14066: if (!$ip) {
14067: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14068: if (length($ip) == 4) {
14069: $ip = &IO::Socket::inet_ntoa($ip);
14070: }
14071: }
14072: if ($ip) {
14073: @hosts = get_hosts_from_ip($ip);
14074: return $hosts[0];
14075: }
14076: return undef;
1.986 foxr 14077: }
1.992 raeburn 14078:
1.1074 raeburn 14079: sub get_internet_names {
14080: my ($lonid) = @_;
14081: return if ($lonid eq '');
14082: my ($idnref,$cached)=
14083: &Apache::lonnet::is_cached_new('internetnames',$lonid);
14084: if ($cached) {
14085: return $idnref;
14086: }
14087: my $ip = &get_host_ip($lonid);
14088: my @hosts = &get_hosts_from_ip($ip);
14089: my %iphost = &get_iphost();
14090: my (@idns,%seen);
14091: foreach my $id (@hosts) {
14092: my $dom = &host_domain($id);
14093: my $prim_id = &domain($dom,'primary');
14094: my $prim_ip = &get_host_ip($prim_id);
14095: next if ($seen{$prim_ip});
14096: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14097: foreach my $id (@{$iphost{$prim_ip}}) {
14098: my $intdom = &internet_dom($id);
14099: unless (grep(/^\Q$intdom\E$/,@idns)) {
14100: push(@idns,$intdom);
14101: }
14102: }
14103: }
14104: $seen{$prim_ip} = 1;
14105: }
1.1172.2.23 raeburn 14106: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 14107: }
14108:
1.986 foxr 14109: }
14110:
1.1079 raeburn 14111: sub all_loncaparevs {
1.1172.2.39 raeburn 14112: 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 14113: }
14114:
1.1172.2.27 raeburn 14115: # ------------------------------------------------------- Read loncaparev table
14116: {
14117: sub load_loncaparevs {
14118: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96 raeburn 14119: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27 raeburn 14120: while (my $configline=<$config>) {
14121: chomp($configline);
14122: my ($hostid,$loncaparev)=split(/:/,$configline);
14123: $loncaparevs{$hostid}=$loncaparev;
14124: }
14125: close($config);
14126: }
14127: }
14128: }
14129: }
14130:
14131: # ----------------------------------------------------- Read serverhostID table
14132: {
14133: sub load_serverhomeIDs {
14134: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96 raeburn 14135: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27 raeburn 14136: while (my $configline=<$config>) {
14137: chomp($configline);
14138: my ($name,$id)=split(/:/,$configline);
14139: $serverhomeIDs{$name}=$id;
14140: }
14141: close($config);
14142: }
14143: }
14144: }
14145: }
14146:
14147:
1.862 albertel 14148: BEGIN {
14149:
14150: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14151: unless ($readit) {
14152: {
14153: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14154: %perlvar = (%perlvar,%{$configvars});
14155: }
14156:
14157:
1.1 albertel 14158: # ------------------------------------------------------ Read spare server file
14159: {
1.1172.2.96 raeburn 14160: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 14161:
14162: while (my $configline=<$config>) {
14163: chomp($configline);
1.284 matthew 14164: if ($configline) {
1.784 albertel 14165: my ($host,$type) = split(':',$configline,2);
1.785 albertel 14166: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 14167: push(@{ $spareid{$type} }, $host);
1.1 albertel 14168: }
14169: }
1.448 albertel 14170: close($config);
1.1 albertel 14171: }
1.11 www 14172: # ------------------------------------------------------------ Read permissions
14173: {
1.1172.2.96 raeburn 14174: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11 www 14175:
14176: while (my $configline=<$config>) {
1.448 albertel 14177: chomp($configline);
14178: if ($configline) {
14179: my ($role,$perm)=split(/ /,$configline);
14180: if ($perm ne '') { $pr{$role}=$perm; }
14181: }
1.11 www 14182: }
1.448 albertel 14183: close($config);
1.11 www 14184: }
14185:
14186: # -------------------------------------------- Read plain texts for permissions
14187: {
1.1172.2.96 raeburn 14188: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 14189:
14190: while (my $configline=<$config>) {
1.448 albertel 14191: chomp($configline);
14192: if ($configline) {
1.742 raeburn 14193: my ($short,@plain)=split(/:/,$configline);
14194: %{$prp{$short}} = ();
14195: if (@plain > 0) {
14196: $prp{$short}{'std'} = $plain[0];
14197: for (my $i=1; $i<@plain; $i++) {
14198: $prp{$short}{'alt'.$i} = $plain[$i];
14199: }
14200: }
1.448 albertel 14201: }
1.135 www 14202: }
1.448 albertel 14203: close($config);
1.135 www 14204: }
14205:
14206: # ---------------------------------------------------------- Read package table
14207: {
1.1172.2.96 raeburn 14208: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135 www 14209:
14210: while (my $configline=<$config>) {
1.483 albertel 14211: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 14212: chomp($configline);
14213: my ($short,$plain)=split(/:/,$configline);
14214: my ($pack,$name)=split(/\&/,$short);
14215: if ($plain ne '') {
14216: $packagetab{$pack.'&'.$name.'&name'}=$name;
14217: $packagetab{$short}=$plain;
14218: }
1.11 www 14219: }
1.448 albertel 14220: close($config);
1.329 matthew 14221: }
14222:
1.1172.2.27 raeburn 14223: # --------------------------------------------------------- Read loncaparev table
1.1073 raeburn 14224:
1.1172.2.27 raeburn 14225: &load_loncaparevs();
14226:
14227: # ------------------------------------------------------- Read serverhostID table
14228:
14229: &load_serverhomeIDs();
1.1074 raeburn 14230:
1.1172.2.27 raeburn 14231: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 14232: {
14233: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14234: if (-e $file) {
14235: my $parser = HTML::LCParser->new($file);
14236: while (my $token = $parser->get_token()) {
14237: if ($token->[0] eq 'S') {
14238: my $item = $token->[1];
14239: my $name = $token->[2]{'name'};
14240: my $value = $token->[2]{'value'};
14241: if ($item ne '' && $name ne '' && $value ne '') {
14242: my $release = $parser->get_text();
14243: $release =~ s/(^\s*|\s*$ )//gx;
14244: $needsrelease{$item.':'.$name.':'.$value} = $release;
14245: }
14246: }
14247: }
14248: }
1.1073 raeburn 14249: }
14250:
1.1138 raeburn 14251: # ---------------------------------------------------------- Read managers table
14252: {
14253: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96 raeburn 14254: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138 raeburn 14255: while (my $configline=<$config>) {
14256: chomp($configline);
14257: next if ($configline =~ /^\#/);
14258: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14259: $managerstab{$configline} = 1;
14260: }
14261: }
14262: close($config);
14263: }
14264: }
14265: }
14266:
1.329 matthew 14267: # ------------- set up temporary directory
14268: {
1.1117 foxr 14269: $tmpdir = LONCAPA::tempdir();
1.329 matthew 14270:
1.11 www 14271: }
14272:
1.1172.2.104 raeburn 14273: # ------------- set default texengine (domain default overrides this)
14274: {
14275: $deftex = LONCAPA::texengine();
14276: }
14277:
1.1172.2.114 raeburn 14278: # ------------- set default minimum length for passwords for internal auth users
14279: {
14280: $passwdmin = LONCAPA::passwd_min();
14281: }
14282:
1.794 albertel 14283: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
14284: 'compress_threshold'=> 20_000,
14285: });
1.185 www 14286:
1.281 www 14287: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 14288: $dumpcount=0;
1.958 www 14289: $locknum=0;
1.22 www 14290:
1.163 harris41 14291: &logtouch();
1.672 albertel 14292: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 14293: $readit=1;
1.564 albertel 14294: {
14295: use integer;
14296: my $test=(2**32)+1;
1.568 albertel 14297: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 14298: &logthis(" Detected 64bit platform ($_64bit)");
14299: }
1.195 www 14300: }
1.1 albertel 14301: }
1.179 www 14302:
1.1 albertel 14303: 1;
1.191 harris41 14304: __END__
14305:
1.243 albertel 14306: =pod
14307:
1.191 harris41 14308: =head1 NAME
14309:
1.243 albertel 14310: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 14311:
14312: =head1 SYNOPSIS
14313:
1.243 albertel 14314: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 14315:
14316: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14317:
1.243 albertel 14318: Common parameters:
14319:
14320: =over 4
14321:
14322: =item *
14323:
14324: $uname : an internal username (if $cname expecting a course Id specifically)
14325:
14326: =item *
14327:
14328: $udom : a domain (if $cdom expecting a course's domain specifically)
14329:
14330: =item *
14331:
14332: $symb : a resource instance identifier
14333:
14334: =item *
14335:
14336: $namespace : the name of a .db file that contains the data needed or
14337: being set.
14338:
14339: =back
14340:
1.394 bowersj2 14341: =head1 OVERVIEW
1.191 harris41 14342:
1.394 bowersj2 14343: lonnet provides subroutines which interact with the
14344: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14345: about classes, users, and resources.
1.243 albertel 14346:
14347: For many of these objects you can also use this to store data about
14348: them or modify them in various ways.
1.191 harris41 14349:
1.394 bowersj2 14350: =head2 Symbs
1.191 harris41 14351:
1.394 bowersj2 14352: To identify a specific instance of a resource, LON-CAPA uses symbols
14353: or "symbs"X<symb>. These identifiers are built from the URL of the
14354: map, the resource number of the resource in the map, and the URL of
14355: the resource itself. The latter is somewhat redundant, but might help
14356: if maps change.
14357:
14358: An example is
14359:
14360: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14361:
14362: The respective map entry is
14363:
14364: <resource id="19" src="/res/msu/korte/tests/part12.problem"
14365: title="Problem 2">
14366: </resource>
14367:
14368: Symbs are used by the random number generator, as well as to store and
14369: restore data specific to a certain instance of for example a problem.
14370:
14371: =head2 Storing And Retrieving Data
14372:
14373: X<store()>X<cstore()>X<restore()>Three of the most important functions
14374: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14375: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14376: is is the non-critical message twin of cstore. These functions are for
14377: handlers to store a perl hash to a user's permanent data space in an
14378: easy manner, and to retrieve it again on another call. It is expected
14379: that a handler would use this once at the beginning to retrieve data,
14380: and then again once at the end to send only the new data back.
14381:
14382: The data is stored in the user's data directory on the user's
14383: homeserver under the ID of the course.
14384:
14385: The hash that is returned by restore will have all of the previous
14386: value for all of the elements of the hash.
14387:
14388: Example:
14389:
14390: #creating a hash
14391: my %hash;
14392: $hash{'foo'}='bar';
14393:
14394: #storing it
14395: &Apache::lonnet::cstore(\%hash);
14396:
14397: #changing a value
14398: $hash{'foo'}='notbar';
14399:
14400: #adding a new value
14401: $hash{'bar'}='foo';
14402: &Apache::lonnet::cstore(\%hash);
14403:
14404: #retrieving the hash
14405: my %history=&Apache::lonnet::restore();
14406:
14407: #print the hash
14408: foreach my $key (sort(keys(%history))) {
14409: print("\%history{$key} = $history{$key}");
14410: }
14411:
14412: Will print out:
1.191 harris41 14413:
1.394 bowersj2 14414: %history{1:foo} = bar
14415: %history{1:keys} = foo:timestamp
14416: %history{1:timestamp} = 990455579
14417: %history{2:bar} = foo
14418: %history{2:foo} = notbar
14419: %history{2:keys} = foo:bar:timestamp
14420: %history{2:timestamp} = 990455580
14421: %history{bar} = foo
14422: %history{foo} = notbar
14423: %history{timestamp} = 990455580
14424: %history{version} = 2
14425:
14426: Note that the special hash entries C<keys>, C<version> and
14427: C<timestamp> were added to the hash. C<version> will be equal to the
14428: total number of versions of the data that have been stored. The
14429: C<timestamp> attribute will be the UNIX time the hash was
14430: stored. C<keys> is available in every historical section to list which
14431: keys were added or changed at a specific historical revision of a
14432: hash.
14433:
14434: B<Warning>: do not store the hash that restore returns directly. This
14435: will cause a mess since it will restore the historical keys as if the
14436: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 14437:
1.394 bowersj2 14438: Calling convention:
1.191 harris41 14439:
1.1172.2.27 raeburn 14440: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64 raeburn 14441: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 14442:
1.394 bowersj2 14443: For more detailed information, see lonnet specific documentation.
1.191 harris41 14444:
1.394 bowersj2 14445: =head1 RETURN MESSAGES
1.191 harris41 14446:
1.394 bowersj2 14447: =over 4
1.191 harris41 14448:
1.394 bowersj2 14449: =item * B<con_lost>: unable to contact remote host
1.191 harris41 14450:
1.394 bowersj2 14451: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14452: when the connection is brought back up
1.191 harris41 14453:
1.394 bowersj2 14454: =item * B<con_failed>: unable to contact remote host and unable to save message
14455: for later delivery
1.191 harris41 14456:
1.967 bisitz 14457: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 14458:
1.394 bowersj2 14459: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 14460: that was requested
1.191 harris41 14461:
1.243 albertel 14462: =back
1.191 harris41 14463:
1.243 albertel 14464: =head1 PUBLIC SUBROUTINES
1.191 harris41 14465:
1.243 albertel 14466: =head2 Session Environment Functions
1.191 harris41 14467:
1.243 albertel 14468: =over 4
1.191 harris41 14469:
1.394 bowersj2 14470: =item *
14471: X<appenv()>
1.949 raeburn 14472: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 14473: the user envirnoment file, and will be restored for each access this
1.620 albertel 14474: user makes during this session, also modifies the %env for the current
1.949 raeburn 14475: process. Optional rolesarrayref - if defined contains a reference to an array
14476: of roles which are exempt from the restriction on modifying user.role entries
14477: in the user's environment.db and in %env.
1.191 harris41 14478:
14479: =item *
1.394 bowersj2 14480: X<delenv()>
1.987 raeburn 14481: B<delenv($delthis,$regexp)>: removes all items from the session
14482: environment file that begin with $delthis. If the
14483: optional second arg - $regexp - is true, $delthis is treated as a
14484: regular expression, otherwise \Q$delthis\E is used.
14485: The values are also deleted from the current processes %env.
1.191 harris41 14486:
1.795 albertel 14487: =item * get_env_multiple($name)
14488:
14489: gets $name from the %env hash, it seemlessly handles the cases where multiple
14490: values may be defined and end up as an array ref.
14491:
14492: returns an array of values
14493:
1.243 albertel 14494: =back
14495:
14496: =head2 User Information
1.191 harris41 14497:
1.243 albertel 14498: =over 4
1.191 harris41 14499:
14500: =item *
1.394 bowersj2 14501: X<queryauthenticate()>
14502: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 14503: authentication scheme
14504:
14505: =item *
1.394 bowersj2 14506: X<authenticate()>
1.1073 raeburn 14507: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 14508: authenticate user from domain's lib servers (first use the current
14509: one). C<$upass> should be the users password.
1.1073 raeburn 14510: $checkdefauth is optional (value is 1 if a check should be made to
14511: authenticate user using default authentication method, and allow
14512: account creation if username does not have account in the domain).
14513: $clientcancheckhost is optional (value is 1 if checking whether the
14514: server can host will occur on the client side in lonauth.pm).
1.191 harris41 14515:
14516: =item *
1.394 bowersj2 14517: X<homeserver()>
14518: B<homeserver($uname,$udom)>: find the server which has
14519: the user's directory and files (there must be only one), this caches
14520: the answer, and also caches if there is a borken connection.
1.191 harris41 14521:
14522: =item *
1.394 bowersj2 14523: X<idget()>
14524: B<idget($udom,@ids)>: find the usernames behind a list of IDs
14525: (IDs are a unique resource in a domain, there must be only 1 ID per
14526: username, and only 1 username per ID in a specific domain) (returns
14527: hash: id=>name,id=>name)
1.191 harris41 14528:
14529: =item *
1.394 bowersj2 14530: X<idrget()>
14531: B<idrget($udom,@unames)>: find the IDs behind a list of
14532: usernames (returns hash: name=>id,name=>id)
1.191 harris41 14533:
14534: =item *
1.394 bowersj2 14535: X<idput()>
14536: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 14537:
14538: =item *
1.394 bowersj2 14539: X<rolesinit()>
1.1169 droeschl 14540: B<rolesinit($udom,$username)>: get user privileges.
14541: returns user role, first access and timer interval hashes
1.243 albertel 14542:
14543: =item *
1.1171 droeschl 14544: X<privileged()>
14545: B<privileged($username,$domain)>: returns a true if user has a
14546: privileged and active role (i.e. su or dc), false otherwise.
14547:
14548: =item *
1.551 albertel 14549: X<getsection()>
14550: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 14551: course $cname, return section name/number or '' for "not in course"
14552: and '-1' for "no section"
14553:
14554: =item *
1.394 bowersj2 14555: X<userenvironment()>
14556: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 14557: passed in @what from the requested user's environment, returns a hash
14558:
1.858 raeburn 14559: =item *
14560: X<userlog_query()>
1.859 albertel 14561: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14562: activity.log file. %filters defines filters applied when parsing the
14563: log file. These can be start or end timestamps, or the type of action
14564: - log to look for Login or Logout events, check for Checkin or
14565: Checkout, role for role selection. The response is in the form
14566: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
14567: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 14568:
1.243 albertel 14569: =back
14570:
14571: =head2 User Roles
14572:
14573: =over 4
14574:
14575: =item *
14576:
1.1172.2.65 raeburn 14577: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14578: returns codes for allowed actions.
14579:
14580: The first argument is required, all others are optional.
14581:
14582: $priv is the privilege being checked.
14583: $uri contains additional information about what is being checked for access (e.g.,
14584: URL, course ID etc.).
14585: $symb is the unique resource instance identifier in a course; if needed,
14586: but not provided, it will be retrieved via a call to &symbread().
14587: $role is the role for which a priv is being checked (only used if priv is evb).
14588: $clientip is the user's IP address (only used when checking for access to portfolio
14589: files).
14590: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14591: prevents recursive calls to &allowed.
14592:
1.243 albertel 14593: F: full access
14594: U,I,K: authentication modes (cxx only)
14595: '': forbidden
14596: 1: user needs to choose course
14597: 2: browse allowed
1.766 albertel 14598: A: passphrase authentication needed
1.1172.2.65 raeburn 14599: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 14600:
14601: =item *
14602:
1.1172.2.13 raeburn 14603: constructaccess($url,$setpriv) : check for access to construction space URL
14604:
14605: See if the owner domain and name in the URL match those in the
14606: expected environment. If so, return three element list
14607: ($ownername,$ownerdomain,$ownerhome).
14608:
14609: Otherwise return the null string.
14610:
14611: If second argument 'setpriv' is true, it assigns the privileges,
14612: and returns the same three element list, unless the owner has
14613: blocked "ad hoc" Domain Coordinator access to the Author Space,
14614: in which case the null string is returned.
14615:
14616: =item *
14617:
1.1172.2.84 raeburn 14618: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14619: define a custom role rolename set privileges in format of lonTabs/roles.tab
14620: for system, domain, and course level. $uname and $udom are optional (current
14621: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 14622:
14623: =item *
14624:
1.988 raeburn 14625: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
14626: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 14627: $type is Course (default) or Community.
1.988 raeburn 14628: If $forcedefault evaluates to true, text returned will be default
14629: text for $type. Otherwise, if this is a course, the text returned
14630: will be a custom name for the role (if defined in the course's
14631: environment). If no custom name is defined the default is returned.
14632:
1.832 raeburn 14633: =item *
14634:
1.1172.2.23 raeburn 14635: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 14636: All arguments are optional. Returns a hash of a roles, either for
14637: co-author/assistant author roles for a user's Construction Space
1.906 albertel 14638: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 14639: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14640: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14641: For each key, value is set to colon-separated start and end times for
14642: the role. If no username and domain are specified, will default to
1.934 raeburn 14643: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 14644: of role statuses (active, future or previous), roles
14645: (e.g., cc,in, st etc.) and domains of the roles which can be used
14646: to restrict the list of roles reported. If no array ref is
14647: provided for types, will default to return only active roles.
1.834 albertel 14648:
1.1172.2.13 raeburn 14649: =item *
14650:
14651: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14652: user: $uname:$udom has a role in the course: $cdom_$cnum.
14653:
14654: Additional optional arguments are: $type (if role checking is to be restricted
14655: to certain user status types -- previous (expired roles), active (currently
14656: available roles) or future (roles available in the future), and
14657: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23 raeburn 14658: have active Domain Coordinator role in course's domain or in additional
14659: domains (specified in 'Domains to check for privileged users' in course
14660: environment -- set via: Course Settings -> Classlists and staff listing).
14661:
14662: =item *
14663:
14664: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14665: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14666: $possdomains and $possroles are optional array refs -- to domains to check and
14667: roles to check. If $possdomains is not specified, a dump will be done of the
14668: users' roles.db to check for a dc or su role in any domain. This can be
14669: time consuming if &privileged is called repeatedly (e.g., when displaying a
14670: classlist), so in such cases, supplying a $possdomains array is preferred, as
14671: this then allows &privileged_by_domain() to be used, which caches the identity
14672: of privileged users, eliminating the need for repeated calls to &dump().
14673:
14674: =item *
14675:
14676: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14677: where the outer hash keys are domains specified in the $possdomains array ref,
14678: next inner hash keys are privileged roles specified in the $roles array ref,
14679: and the innermost hash contains key = value pairs for username:domain = end:start
14680: for active or future "privileged" users with that role in that domain. To avoid
14681: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14682: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13 raeburn 14683:
1.243 albertel 14684: =back
14685:
14686: =head2 User Modification
14687:
14688: =over 4
14689:
14690: =item *
14691:
1.957 raeburn 14692: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 14693: user for the level given by URL. Optional start and end dates (leave empty
14694: string or zero for "no date")
1.191 harris41 14695:
14696: =item *
14697:
1.243 albertel 14698: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14699: change a users, password, possible return values are: ok,
14700: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14701: refused
1.191 harris41 14702:
14703: =item *
14704:
1.243 albertel 14705: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 14706:
14707: =item *
14708:
1.1058 raeburn 14709: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14710: $forceid,$desiredhome,$email,$inststatus,$candelete) :
14711:
14712: will update user information (firstname,middlename,lastname,generation,
14713: permanentemail), and if forceid is true, student/employee ID also.
14714: A user's institutional affiliation(s) can also be updated.
14715: User information fields will not be overwritten with empty entries
14716: unless the field is included in the $candelete array reference.
14717: This array is included when a single user is modified via "Manage Users",
14718: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 14719:
14720: =item *
14721:
1.286 matthew 14722: modifystudent
14723:
1.957 raeburn 14724: modify a student's enrollment and identification information.
1.1172.2.31 raeburn 14725: The course id is resolved based on the current user's environment.
14726: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 14727: associated with a course.
14728:
1.297 matthew 14729: This call is essentially a wrapper for lonnet::modifyuser and
14730: lonnet::modify_student_enrollment
1.286 matthew 14731:
14732: Inputs:
14733:
14734: =over 4
14735:
1.957 raeburn 14736: =item B<$udom> Student's loncapa domain
1.286 matthew 14737:
1.957 raeburn 14738: =item B<$uname> Student's loncapa login name
1.286 matthew 14739:
1.964 bisitz 14740: =item B<$uid> Student/Employee ID
1.286 matthew 14741:
1.957 raeburn 14742: =item B<$umode> Student's authentication mode
1.286 matthew 14743:
1.957 raeburn 14744: =item B<$upass> Student's password
1.286 matthew 14745:
1.957 raeburn 14746: =item B<$first> Student's first name
1.286 matthew 14747:
1.957 raeburn 14748: =item B<$middle> Student's middle name
1.286 matthew 14749:
1.957 raeburn 14750: =item B<$last> Student's last name
1.286 matthew 14751:
1.957 raeburn 14752: =item B<$gene> Student's generation
1.286 matthew 14753:
1.957 raeburn 14754: =item B<$usec> Student's section in course
1.286 matthew 14755:
14756: =item B<$end> Unix time of the roles expiration
14757:
14758: =item B<$start> Unix time of the roles start date
14759:
14760: =item B<$forceid> If defined, allow $uid to be changed
14761:
14762: =item B<$desiredhome> server to use as home server for student
14763:
1.957 raeburn 14764: =item B<$email> Student's permanent e-mail address
14765:
14766: =item B<$type> Type of enrollment (auto or manual)
14767:
1.963 raeburn 14768: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
14769:
14770: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 14771:
1.963 raeburn 14772: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 14773:
1.963 raeburn 14774: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 14775:
1.1172.2.19 raeburn 14776: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14777:
14778: =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 14779:
1.286 matthew 14780: =back
1.297 matthew 14781:
14782: =item *
14783:
14784: modify_student_enrollment
14785:
1.1172.2.31 raeburn 14786: Change a student's enrollment status in a class. The environment variable
1.297 matthew 14787: 'role.request.course' must be defined for this function to proceed.
14788:
14789: Inputs:
14790:
14791: =over 4
14792:
1.1172.2.31 raeburn 14793: =item $udom, student's domain
1.297 matthew 14794:
1.1172.2.31 raeburn 14795: =item $uname, student's name
1.297 matthew 14796:
1.1172.2.31 raeburn 14797: =item $uid, student's user id
1.297 matthew 14798:
1.1172.2.31 raeburn 14799: =item $first, student's first name
1.297 matthew 14800:
14801: =item $middle
14802:
14803: =item $last
14804:
14805: =item $gene
14806:
14807: =item $usec
14808:
14809: =item $end
14810:
14811: =item $start
14812:
1.957 raeburn 14813: =item $type
14814:
14815: =item $locktype
14816:
14817: =item $cid
14818:
14819: =item $selfenroll
14820:
14821: =item $context
14822:
1.1172.2.19 raeburn 14823: =item $credits, number of credits student will earn from this class
14824:
1.1172.2.76 raeburn 14825: =item $instsec, institutional course section code for student
14826:
1.297 matthew 14827: =back
14828:
1.191 harris41 14829:
14830: =item *
14831:
1.243 albertel 14832: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14833: custom role; give a custom role to a user for the level given by URL. Specify
14834: name and domain of role author, and role name
1.191 harris41 14835:
14836: =item *
14837:
1.243 albertel 14838: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 14839:
14840: =item *
14841:
1.243 albertel 14842: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14843:
14844: =back
14845:
14846: =head2 Course Infomation
14847:
14848: =over 4
1.191 harris41 14849:
14850: =item *
14851:
1.1118 foxr 14852: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 14853: specified course id, including all environment settings for the
14854: course, the description of the course will be in the hash under the
14855: key 'description'
1.191 harris41 14856:
1.1118 foxr 14857: $options is an optional parameter that if supplied is a hash reference that controls
14858: what how this function works. It has the following key/values:
14859:
14860: =over 4
14861:
14862: =item freshen_cache
14863:
14864: If defined, and the environment cache for the course is valid, it is
14865: returned in the returned hash.
14866:
14867: =item one_time
14868:
14869: If defined, the last cache time is set to _now_
14870:
14871: =item user
14872:
14873: If defined, the supplied username is used instead of the current user.
14874:
14875:
14876: =back
14877:
1.191 harris41 14878: =item *
14879:
1.624 albertel 14880: resdata($name,$domain,$type,@which) : request for current parameter
14881: setting for a specific $type, where $type is either 'course' or 'user',
14882: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31 raeburn 14883: answers for 10 minutes.
1.243 albertel 14884:
1.877 foxr 14885: =item *
14886:
14887: get_courseresdata($courseid, $domain) : dump the entire course resource
14888: data base, returning a hash that is keyed by the resource name and has
14889: values that are the resource value. I believe that the timestamps and
14890: versions are also returned.
14891:
1.1172.2.31 raeburn 14892: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14893: supplemental content area. This routine caches the number of files for
14894: 10 minutes.
14895:
1.243 albertel 14896: =back
14897:
14898: =head2 Course Modification
14899:
14900: =over 4
1.191 harris41 14901:
14902: =item *
14903:
1.243 albertel 14904: writecoursepref($courseid,%prefs) : write preferences (environment
14905: database) for a course
1.191 harris41 14906:
14907: =item *
14908:
1.1011 raeburn 14909: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14910:
14911: =item *
14912:
1.1038 raeburn 14913: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 14914:
1.1167 droeschl 14915: =item *
14916:
14917: is_course($courseid), is_course($cdom, $cnum)
14918:
14919: Accepts either a combined $courseid (in the form of domain_courseid) or the
14920: two component version $cdom, $cnum. It checks if the specified course exists.
14921:
14922: Returns:
14923: undef if the course doesn't exist, otherwise
14924: in scalar context the combined courseid.
14925: in list context the two components of the course identifier, domain and
14926: courseid.
14927:
1.243 albertel 14928: =back
14929:
1.1172.2.109 raeburn 14930: =head2 Bubblesheet Configuration
14931:
14932: =over 4
14933:
14934: =item *
14935:
14936: get_scantron_config($which)
14937:
14938: $which - the name of the configuration to parse from the file.
14939:
14940: Parses and returns the bubblesheet configuration line selected as a
14941: hash of configuration file fields.
14942:
14943:
14944: Returns:
14945: If the named configuration is not in the file, an empty
14946: hash is returned.
14947:
14948: a hash with the fields
14949: name - internal name for the this configuration setup
14950: description - text to display to operator that describes this config
14951: CODElocation - if 0 or the string 'none'
14952: - no CODE exists for this config
14953: if -1 || the string 'letter'
14954: - a CODE exists for this config and is
14955: a string of letters
14956: Unsupported value (but planned for future support)
14957: if a positive integer
14958: - The CODE exists as the first n items from
14959: the question section of the form
14960: if the string 'number'
14961: - The CODE exists for this config and is
14962: a string of numbers
14963: CODEstart - (only matter if a CODE exists) column in the line where
14964: the CODE starts
14965: CODElength - length of the CODE
14966: IDstart - column where the student/employee ID starts
14967: IDlength - length of the student/employee ID info
14968: Qstart - column where the information from the bubbled
14969: 'questions' start
14970: Qlength - number of columns comprising a single bubble line from
14971: the sheet. (usually either 1 or 10)
14972: Qon - either a single character representing the character used
14973: to signal a bubble was chosen in the positional setup, or
14974: the string 'letter' if the letter of the chosen bubble is
14975: in the final, or 'number' if a number representing the
14976: chosen bubble is in the file (1->A 0->J)
14977: Qoff - the character used to represent that a bubble was
14978: left blank
14979: PaperID - if the scanning process generates a unique number for each
14980: sheet scanned the column that this ID number starts in
14981: PaperIDlength - number of columns that comprise the unique ID number
14982: for the sheet of paper
14983: FirstName - column that the first name starts in
14984: FirstNameLength - number of columns that the first name spans
14985: LastName - column that the last name starts in
14986: LastNameLength - number of columns that the last name spans
14987: BubblesPerRow - number of bubbles available in each row used to
14988: bubble an answer. (If not specified, 10 assumed).
14989:
14990:
14991: =item *
14992:
14993: get_scantronformat_file($cdom)
14994:
14995: $cdom - the course's domain (optional); if not supplied, uses
14996: domain for current $env{'request.course.id'}.
14997:
14998: Returns an array containing lines from the scantron format file for
14999: the domain of the course.
15000:
15001: If a url for a custom.tab file is listed in domain's configuration.db,
15002: lines are from this file.
15003:
15004: Otherwise, if a default.tab has been published in RES space by the
15005: domainconfig user, lines are from this file.
15006:
15007: Otherwise, fall back to getting lines from the legacy file on the
15008: local server: /home/httpd/lonTabs/default_scantronformat.tab
15009:
15010: =back
15011:
1.243 albertel 15012: =head2 Resource Subroutines
15013:
15014: =over 4
1.191 harris41 15015:
15016: =item *
15017:
1.243 albertel 15018: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 15019:
15020: =item *
15021:
1.243 albertel 15022: repcopy($filename) : subscribes to the requested file, and attempts to
15023: replicate from the owning library server, Might return
1.607 raeburn 15024: 'unavailable', 'not_found', 'forbidden', 'ok', or
15025: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 15026: resource. Expects the local filesystem pathname
15027: (/home/httpd/html/res/....)
15028:
15029: =back
15030:
15031: =head2 Resource Information
15032:
15033: =over 4
1.191 harris41 15034:
15035: =item *
15036:
1.1172.2.28 raeburn 15037: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
15038: and returns the value of a variety of different possible values,
15039: $varname should be a request string, and the other parameters can be
15040: used to specify who and what one is asking about. Ordinarily, $cid
15041: does not need to be specified, as it is retrived from
15042: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
15043: within lonuserstate::loadmap() when initializing a course, before
15044: $env{'request.course.id'} has been set, so it needs to be provided
15045: in that one case.
1.243 albertel 15046:
15047: Possible values for $varname are environment.lastname (or other item
15048: from the envirnment hash), user.name (or someother aspect about the
15049: user), resource.0.maxtries (or some other part and parameter of a
15050: resource)
1.204 albertel 15051:
15052: =item *
15053:
1.243 albertel 15054: directcondval($number) : get current value of a condition; reads from a state
15055: string
1.204 albertel 15056:
15057: =item *
15058:
1.243 albertel 15059: condval($condidx) : value of condition index based on state
1.204 albertel 15060:
15061: =item *
15062:
1.243 albertel 15063: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
15064: resource's metadata, $what should be either a specific key, or either
15065: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15066: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
15067:
15068: this function automatically caches all requests
1.191 harris41 15069:
15070: =item *
15071:
1.243 albertel 15072: metadata_query($query,$custom,$customshow) : make a metadata query against the
15073: network of library servers; returns file handle of where SQL and regex results
15074: will be stored for query
1.191 harris41 15075:
15076: =item *
15077:
1.1172.2.66 raeburn 15078: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
15079: return symbolic list entry (all arguments optional).
15080:
15081: Args: filename is the filename (including path) for the file for which a symb
15082: is required; donotrecurse, if true will prevent calls to allowed() being made
15083: to check access status if more than one resource was found in the bighash
15084: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15085: a randompick); ignorecachednull, if true will prevent a symb of '' being
15086: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15087: cause possible symbs to be checked to determine if they are subject to content
15088: blocking, if so they will not be included as possible symbs; possibles is a
15089: ref to a hash, which, as a side effect, will be populated with all possible
15090: symbs (content blocking not tested).
15091:
1.243 albertel 15092: returns the data handle
1.191 harris41 15093:
15094: =item *
15095:
1.1172.2.17 raeburn 15096: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11 raeburn 15097: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 15098: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11 raeburn 15099: on failure, user must be in a course, as it assumes the existence of
15100: the course initial hash, and uses $env('request.course.id'}. The third
15101: arg is an optional reference to a scalar. If this arg is passed in the
15102: call to symbverify, it will be set to 1 if the symb has been set to be
15103: encrypted; otherwise it will be null.
1.243 albertel 15104:
1.191 harris41 15105: =item *
15106:
1.243 albertel 15107: symbclean($symb) : removes versions numbers from a symb, returns the
15108: cleaned symb
1.191 harris41 15109:
15110: =item *
15111:
1.243 albertel 15112: is_on_map($uri) : checks if the $uri is somewhere on the current
15113: course map, user must be in a course for it to work.
1.191 harris41 15114:
15115: =item *
15116:
1.243 albertel 15117: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 15118:
15119: =item *
15120:
1.243 albertel 15121: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15122: a random seed, all arguments are optional, if they aren't sent it uses the
15123: environment to derive them. Note: if symb isn't sent and it can't get one
15124: from &symbread it will use the current time as its return value
1.191 harris41 15125:
15126: =item *
15127:
1.243 albertel 15128: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15129: unfakeable, receipt
1.191 harris41 15130:
15131: =item *
15132:
1.620 albertel 15133: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 15134:
15135: =item *
15136:
1.243 albertel 15137: countacc($url) : count the number of accesses to a given URL
1.191 harris41 15138:
15139: =item *
15140:
1.243 albertel 15141: 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 15142:
15143: =item *
15144:
1.243 albertel 15145: 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 15146:
15147: =item *
15148:
1.243 albertel 15149: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 15150:
15151: =item *
15152:
1.243 albertel 15153: devalidate($symb) : devalidate temporary spreadsheet calculations,
15154: forcing spreadsheet to reevaluate the resource scores next time.
15155:
1.1172.2.13 raeburn 15156: =item *
15157:
15158: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15159: when viewing in course context.
15160:
15161: input: six args -- filename (decluttered), course number, course domain,
15162: url, symb (if registered) and group (if this is a
15163: group item -- e.g., bulletin board, group page etc.).
15164:
15165: output: array of five scalars --
15166: $cfile -- url for file editing if editable on current server
15167: $home -- homeserver of resource (i.e., for author if published,
15168: or course if uploaded.).
15169: $switchserver -- 1 if server switch will be needed.
15170: $forceedit -- 1 if icon/link should be to go to edit mode
15171: $forceview -- 1 if icon/link should be to go to view mode
15172:
15173: =item *
15174:
15175: is_course_upload($file,$cnum,$cdom)
15176:
15177: Used in course context to determine if current file was uploaded to
15178: the course (i.e., would be found in /userfiles/docs on the course's
15179: homeserver.
15180:
15181: input: 3 args -- filename (decluttered), course number and course domain.
15182: output: boolean -- 1 if file was uploaded.
15183:
1.243 albertel 15184: =back
15185:
15186: =head2 Storing/Retreiving Data
15187:
15188: =over 4
1.191 harris41 15189:
15190: =item *
15191:
1.1172.2.64 raeburn 15192: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15193: permanently for this url; hashref needs to be given and should be a \%hashname;
15194: the remaining args aren't required and if they aren't passed or are '' they will
15195: be derived from the env (with the exception of $laststore, which is an
15196: optional arg used when a user's submission is stored in grading).
15197: $laststore is $version=$timestamp, where $version is the most recent version
15198: number retrieved for the corresponding $symb in the $namespace db file, and
15199: $timestamp is the timestamp for that transaction (UNIX time).
15200: $laststore is currently only passed when cstore() is called by
15201: structuretags::finalize_storage().
1.191 harris41 15202:
15203: =item *
15204:
1.1172.2.64 raeburn 15205: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15206: but uses critical subroutine
1.191 harris41 15207:
15208: =item *
15209:
1.243 albertel 15210: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15211: all args are optional
1.191 harris41 15212:
15213: =item *
15214:
1.717 albertel 15215: dumpstore($namespace,$udom,$uname,$regexp,$range) :
15216: dumps the complete (or key matching regexp) namespace into a hash
15217: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15218: normally &store()ed into
15219:
15220: $range should be either an integer '100' (give me the first 100
15221: matching records)
15222: or be two integers sperated by a - with no spaces
15223: '30-50' (give me the 30th through the 50th matching
15224: records)
15225:
15226:
15227: =item *
15228:
1.1172.2.59 raeburn 15229: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 15230: replaces a &store() version of data with a replacement set of data
15231: for a particular resource in a namespace passed in the $storehash hash
1.1172.2.59 raeburn 15232: reference. If $tolog is true, the transaction is logged in the courselog
15233: with an action=PUTSTORE.
1.717 albertel 15234:
15235: =item *
15236:
1.243 albertel 15237: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15238: works very similar to store/cstore, but all data is stored in a
15239: temporary location and can be reset using tmpreset, $storehash should
15240: be a hash reference, returns nothing on success
1.191 harris41 15241:
15242: =item *
15243:
1.243 albertel 15244: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15245: similar to restore, but all data is stored in a temporary location and
15246: can be reset using tmpreset. Returns a hash of values on success,
15247: error string otherwise.
1.191 harris41 15248:
15249: =item *
15250:
1.243 albertel 15251: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15252: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 15253:
15254: =item *
15255:
1.243 albertel 15256: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15257: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 15258:
15259: =item *
15260:
1.243 albertel 15261: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15262: namesp ($udom and $uname are optional)
1.191 harris41 15263:
15264: =item *
15265:
1.702 albertel 15266: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 15267: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 15268: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 15269:
1.702 albertel 15270: $range should be either an integer '100' (give me the first 100
15271: matching records)
15272: or be two integers sperated by a - with no spaces
15273: '30-50' (give me the 30th through the 50th matching
15274: records)
1.449 matthew 15275: =item *
15276:
15277: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15278: $store can be a scalar, an array reference, or if the amount to be
15279: incremented is > 1, a hash reference.
15280:
15281: ($udom and $uname are optional)
1.191 harris41 15282:
15283: =item *
15284:
1.243 albertel 15285: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15286: ($udom and $uname are optional)
1.191 harris41 15287:
15288: =item *
15289:
1.243 albertel 15290: cput($namespace,$storehash,$udom,$uname) : critical put
15291: ($udom and $uname are optional)
1.191 harris41 15292:
15293: =item *
15294:
1.748 albertel 15295: newput($namespace,$storehash,$udom,$uname) :
15296:
15297: Attempts to store the items in the $storehash, but only if they don't
15298: currently exist, if this succeeds you can be certain that you have
15299: successfully created a new key value pair in the $namespace db.
15300:
15301:
15302: Args:
15303: $namespace: name of database to store values to
15304: $storehash: hashref to store to the db
15305: $udom: (optional) domain of user containing the db
15306: $uname: (optional) name of user caontaining the db
15307:
15308: Returns:
15309: 'ok' -> succeeded in storing all keys of $storehash
15310: 'key_exists: <key>' -> failed to anything out of $storehash, as at
15311: least <key> already existed in the db (other
15312: requested keys may also already exist)
1.967 bisitz 15313: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 15314: 'con_lost' -> unable to contact request server
15315: 'refused' -> action was not allowed by remote machine
15316:
15317:
15318: =item *
15319:
1.243 albertel 15320: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15321: reference filled in from namesp (encrypts the return communication)
15322: ($udom and $uname are optional)
1.191 harris41 15323:
15324: =item *
15325:
1.243 albertel 15326: log($udom,$name,$home,$message) : write to permanent log for user; use
15327: critical subroutine
15328:
1.806 raeburn 15329: =item *
15330:
1.860 raeburn 15331: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15332: array reference filled in from namespace found in domain level on either
15333: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 15334:
15335: =item *
15336:
1.860 raeburn 15337: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
15338: domain level either on specified domain server ($uhome) or primary domain
15339: server ($udom and $uhome are optional)
1.806 raeburn 15340:
1.943 raeburn 15341: =item *
15342:
1.1172.2.35 raeburn 15343: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15344: for: authentication, language, quotas, timezone, date locale, and portal URL in
15345: the target domain.
15346:
15347: May also include additional key => value pairs for the following groups:
15348:
15349: =over
15350:
15351: =item
15352: disk quotas (MB allocated by default to portfolios and authoring spaces).
15353:
15354: =over
15355:
15356: =item defaultquota, authorquota
15357:
15358: =back
15359:
15360: =item
15361: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15362: portfolio for users).
15363:
15364: =over
15365:
15366: =item
15367: aboutme, blog, webdav, portfolio
15368:
15369: =back
15370:
15371: =item
15372: requestcourses: ability to request courses, and how requests are processed.
15373:
15374: =over
15375:
15376: =item
1.1172.2.37 raeburn 15377: official, unofficial, community, textbook
1.1172.2.35 raeburn 15378:
15379: =back
15380:
15381: =item
15382: inststatus: types of institutional affiliation, and order in which they are displayed.
15383:
15384: =over
15385:
15386: =item
1.1172.2.44 raeburn 15387: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35 raeburn 15388:
15389: =back
15390:
15391: =item
15392: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15393: for course's uploaded content.
15394:
15395: =over
15396:
15397: =item
1.1172.2.68 raeburn 15398: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
15399: communityquota, textbookquota
1.1172.2.35 raeburn 15400:
15401: =back
15402:
15403: =item
15404: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15405: on your servers.
15406:
15407: =over
15408:
15409: =item
15410: remotesessions, hostedsessions
15411:
15412: =back
15413:
15414: =back
15415:
15416: In cases where a domain coordinator has never used the "Set Domain Configuration"
15417: utility to create a configuration.db file on a domain's primary library server
15418: only the following domain defaults: auth_def, auth_arg_def, lang_def
15419: -- corresponding values are authentication type (internal, krb4, krb5,
15420: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
15421: will be available. Values are retrieved from cache (if current), unless the
15422: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15423: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15424:
15425: Typical usage:
1.943 raeburn 15426:
1.1172.2.35 raeburn 15427: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 15428:
1.243 albertel 15429: =back
15430:
15431: =head2 Network Status Functions
15432:
15433: =over 4
1.191 harris41 15434:
15435: =item *
15436:
1.1137 raeburn 15437: dirlist() : return directory list based on URI (first arg).
15438:
15439: Inputs: 1 required, 5 optional.
15440:
15441: =over
15442:
15443: =item
15444: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15445:
15446: =item
15447: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
15448:
15449: =item
15450: $username - username of user/course to be listed. Extracted from $uri if absent.
15451:
15452: =item
15453: $getpropath - boolean: 1 if prepend path using &propath().
15454:
15455: =item
15456: $getuserdir - boolean: 1 if prepend path for "userfiles".
15457:
15458: =item
15459: $alternateRoot - path to prepend in place of path from $uri.
15460:
15461: =back
15462:
15463: Returns: Array of up to two items.
15464:
15465: =over
15466:
15467: a reference to an array of files/subdirectories
15468:
15469: =over
15470:
15471: Each element in the array of files/subdirectories is a & separated list of
15472: item name and the result of running stat on the item. If dirlist was requested
15473: for a file instead of a directory, the item name will be ''. For a directory
15474: listing, if the item is a metadata file, the element will end &N&M
15475: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15476: default copyright set (1).
15477:
15478: =back
15479:
15480: a scalar containing error condition (if encountered).
15481:
15482: =over
15483:
15484: =item
15485: no_host (no homeserver identified for $username:$domain).
15486:
15487: =item
15488: no_such_host (server contacted for listing not identified as valid host).
15489:
15490: =item
15491: con_lost (connection to remote server failed).
15492:
15493: =item
15494: refused (invalid $username:$domain received on lond side).
15495:
15496: =item
15497: no_such_dir (directory at specified path on lond side does not exist).
15498:
15499: =item
15500: empty (directory at specified path on lond side is empty).
15501:
15502: =over
15503:
15504: This is currently not encountered because the &ls3, &ls2,
15505: &ls (_handler) routines on the lond side do not filter out
15506: . and .. from a directory listing.
15507:
15508: =back
15509:
15510: =back
15511:
15512: =back
1.191 harris41 15513:
15514: =item *
15515:
1.243 albertel 15516: spareserver() : find server with least workload from spare.tab
15517:
1.986 foxr 15518:
15519: =item *
15520:
15521: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15522: if there is no corresponding loncapa host.
15523:
1.243 albertel 15524: =back
15525:
1.986 foxr 15526:
1.243 albertel 15527: =head2 Apache Request
15528:
15529: =over 4
1.191 harris41 15530:
15531: =item *
15532:
1.243 albertel 15533: ssi($url,%hash) : server side include, does a complete request cycle on url to
15534: localhost, posts hash
15535:
15536: =back
15537:
15538: =head2 Data to String to Data
15539:
15540: =over 4
1.191 harris41 15541:
15542: =item *
15543:
1.243 albertel 15544: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15545: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 15546:
15547: =item *
15548:
1.243 albertel 15549: hashref2str($hashref) : convert a hashref into a string complete with
15550: escaping and '=' and '&' separators, supports elements that are
15551: arrayrefs and hashrefs
1.191 harris41 15552:
15553: =item *
15554:
1.243 albertel 15555: arrayref2str($arrayref) : convert an arrayref into a string complete
15556: with escaping and '&' separators, supports elements that are arrayrefs
15557: and hashrefs
1.191 harris41 15558:
15559: =item *
15560:
1.243 albertel 15561: str2hash($string) : convert string to hash using unescaping and
15562: splitting on '=' and '&', supports elements that are arrayrefs and
15563: hashrefs
1.191 harris41 15564:
15565: =item *
15566:
1.243 albertel 15567: str2array($string) : convert string to hash using unescaping and
15568: splitting on '&', supports elements that are arrayrefs and hashrefs
15569:
15570: =back
15571:
15572: =head2 Logging Routines
15573:
15574:
15575: These routines allow one to make log messages in the lonnet.log and
15576: lonnet.perm logfiles.
1.191 harris41 15577:
1.1119 foxr 15578: =over 4
15579:
1.191 harris41 15580: =item *
15581:
1.243 albertel 15582: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 15583:
15584: =item *
15585:
1.243 albertel 15586: logthis() : append message to the normal lonnet.log file, it gets
15587: preiodically rolled over and deleted.
1.191 harris41 15588:
15589: =item *
15590:
1.243 albertel 15591: logperm() : append a permanent message to lonnet.perm.log, this log
15592: file never gets deleted by any automated portion of the system, only
15593: messages of critical importance should go in here.
15594:
1.1119 foxr 15595:
1.243 albertel 15596: =back
15597:
15598: =head2 General File Helper Routines
15599:
15600: =over 4
1.191 harris41 15601:
15602: =item *
15603:
1.481 raeburn 15604: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15605: (a) files in /uploaded
15606: (i) If a local copy of the file exists -
15607: compares modification date of local copy with last-modified date for
15608: definitive version stored on home server for course. If local copy is
15609: stale, requests a new version from the home server and stores it.
15610: If the original has been removed from the home server, then local copy
15611: is unlinked.
15612: (ii) If local copy does not exist -
15613: requests the file from the home server and stores it.
15614:
15615: If $caller is 'uploadrep':
15616: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15617: for request for files originally uploaded via DOCS.
15618: - returns 'ok' if fresh local copy now available, -1 otherwise.
15619:
15620: Otherwise:
15621: This indicates a call from the content generation phase of the request.
15622: - returns the entire contents of the file or -1.
15623:
15624: (b) files in /res
15625: - returns the entire contents of a file or -1;
15626: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 15627:
1.712 albertel 15628:
15629: =item *
15630:
15631: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15632: reference
15633:
15634: returns either a stat() list of data about the file or an empty list
15635: if the file doesn't exist or couldn't find out about it (connection
15636: problems or user unknown)
15637:
1.191 harris41 15638: =item *
15639:
1.243 albertel 15640: filelocation($dir,$file) : returns file system location of a file
15641: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15642: directory that relative $file lookups are to looked in ($dir of /a/dir
15643: and a file of ../bob will become /a/bob)
1.191 harris41 15644:
15645: =item *
15646:
15647: hreflocation($dir,$file) : returns file system location or a URL; same as
15648: filelocation except for hrefs
15649:
15650: =item *
15651:
1.1172.2.49 raeburn 15652: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15653: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 15654:
1.243 albertel 15655: =back
15656:
1.608 albertel 15657: =head2 Usererfile file routines (/uploaded*)
15658:
15659: =over 4
15660:
15661: =item *
15662:
15663: userfileupload(): main rotine for putting a file in a user or course's
15664: filespace, arguments are,
15665:
1.620 albertel 15666: formname - required - this is the name of the element in $env where the
1.608 albertel 15667: filename, and the contents of the file to create/modifed exist
1.620 albertel 15668: the filename is in $env{'form.'.$formname.'.filename'} and the
15669: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 15670: context - if coursedoc, store the file in the course of the active role
15671: of the current user;
15672: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15673: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 15674: subdir - required - subdirectory to put the file in under ../userfiles/
15675: if undefined, it will be placed in "unknown"
15676:
15677: (This routine calls clean_filename() to remove any dangerous
15678: characters from the filename, and then calls finuserfileupload() to
15679: complete the transaction)
15680:
15681: returns either the url of the uploaded file (/uploaded/....) if successful
15682: and /adm/notfound.html if unsuccessful
15683:
15684: =item *
15685:
15686: clean_filename(): routine for cleaing a filename up for storage in
15687: userfile space, argument is:
15688:
15689: filename - proposed filename
15690:
15691: returns: the new clean filename
15692:
15693: =item *
15694:
1.1090 raeburn 15695: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 15696: userspace, probably shouldn't be called directly
15697:
15698: docuname: username or courseid of destination for the file
15699: docudom: domain of user/course of destination for the file
15700: formname: same as for userfileupload()
1.1090 raeburn 15701: fname: filename (including subdirectories) for the file
15702: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109 raeburn 15703: if hashref, and context is scantron, will convert csv format to standard format
1.1090 raeburn 15704: allfiles: reference to hash used to store objects found by parser
15705: codebase: reference to hash used for codebases of java objects found by parser
15706: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15707: thumbheight: height (pixels) of thumbnail to be created for uploaded image
15708: resizewidth: width to be used to resize image using resizeImage from ImageMagick
15709: resizeheight: height to be used to resize image using resizeImage from ImageMagick
15710: context: if 'overwrite', will move the uploaded file from its temporary location to
15711: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 15712: mimetype: reference to scalar to accommodate mime type determined
15713: from File::MMagic if $parser = parse.
1.608 albertel 15714:
15715: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 15716: and /adm/notfound.html if unsuccessful (or an error message if context
15717: was 'overwrite').
15718:
1.608 albertel 15719:
15720: =item *
15721:
15722: renameuserfile(): renames an existing userfile to a new name
15723:
15724: Args:
15725: docuname: username or courseid of destination for the file
15726: docudom: domain of user/course of destination for the file
15727: old: current file name (including any subdirs under userfiles)
15728: new: desired file name (including any subdirs under userfiles)
15729:
15730: =item *
15731:
15732: mkdiruserfile(): creates a directory is a userfiles dir
15733:
15734: Args:
15735: docuname: username or courseid of destination for the file
15736: docudom: domain of user/course of destination for the file
15737: dir: dir to create (including any subdirs under userfiles)
15738:
15739: =item *
15740:
15741: removeuserfile(): removes a file that exists in userfiles
15742:
15743: Args:
15744: docuname: username or courseid of destination for the file
15745: docudom: domain of user/course of destination for the file
15746: fname: filname to delete (including any subdirs under userfiles)
15747:
15748: =item *
15749:
15750: removeuploadedurl(): convience function for removeuserfile()
15751:
15752: Args:
15753: url: a full /uploaded/... url to delete
15754:
1.747 albertel 15755: =item *
15756:
15757: get_portfile_permissions():
15758: Args:
15759: domain: domain of user or course contain the portfolio files
15760: user: name of user or num of course contain the portfolio files
15761: Returns:
15762: hashref of a dump of the proper file_permissions.db
15763:
15764:
15765: =item *
15766:
15767: get_access_controls():
15768:
15769: Args:
15770: current_permissions: the hash ref returned from get_portfile_permissions()
15771: group: (optional) the group you want the files associated with
15772: file: (optional) the file you want access info on
15773:
15774: Returns:
1.749 raeburn 15775: a hash (keys are file names) of hashes containing
15776: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15777: values are XML containing access control settings (see below)
1.747 albertel 15778:
15779: Internal notes:
15780:
1.749 raeburn 15781: access controls are stored in file_permissions.db as key=value pairs.
15782: key -> path to file/file_name\0uniqueID:scope_end_start
15783: where scope -> public,guest,course,group,domains or users.
15784: end -> UNIX time for end of access (0 -> no end date)
15785: start -> UNIX time for start of access
15786:
15787: value -> XML description of access control
15788: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15789: <start></start>
15790: <end></end>
15791:
15792: <password></password> for scope type = guest
15793:
15794: <domain></domain> for scope type = course or group
15795: <number></number>
15796: <roles id="">
15797: <role></role>
15798: <access></access>
15799: <section></section>
15800: <group></group>
15801: </roles>
15802:
15803: <dom></dom> for scope type = domains
15804:
15805: <users> for scope type = users
15806: <user>
15807: <uname></uname>
15808: <udom></udom>
15809: </user>
15810: </users>
15811: </scope>
15812:
15813: Access data is also aggregated for each file in an additional key=value pair:
15814: key -> path to file/file_name\0accesscontrol
15815: value -> reference to hash
15816: hash contains key = value pairs
15817: where key = uniqueID:scope_end_start
15818: value = UNIX time record was last updated
15819:
15820: Used to improve speed of look-ups of access controls for each file.
15821:
15822: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15823:
1.1172.2.13 raeburn 15824: =item *
15825:
1.749 raeburn 15826: modify_access_controls():
15827:
15828: Modifies access controls for a portfolio file
15829: Args
15830: 1. file name
15831: 2. reference to hash of required changes,
15832: 3. domain
15833: 4. username
15834: where domain,username are the domain of the portfolio owner
15835: (either a user or a course)
15836:
15837: Returns:
15838: 1. result of additions or updates ('ok' or 'error', with error message).
15839: 2. result of deletions ('ok' or 'error', with error message).
15840: 3. reference to hash of any new or updated access controls.
15841: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15842: key = integer (inbound ID)
1.1172.2.13 raeburn 15843: value = uniqueID
15844:
15845: =item *
15846:
15847: get_timebased_id():
15848:
15849: Attempts to get a unique timestamp-based suffix for use with items added to a
15850: course via the Course Editor (e.g., folders, composite pages,
15851: group bulletin boards).
15852:
15853: Args: (first three required; six others optional)
15854:
15855: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15856: docssequence, or name of group
15857:
15858: 2. keyid (alphanumeric): name of temporary locking key in hash,
15859: e.g., num, boardids
15860:
15861: 3. namespace: name of gdbm file used to store suffixes already assigned;
15862: file will be named nohist_namespace.db
15863:
15864: 4. cdom: domain of course; default is current course domain from %env
15865:
15866: 5. cnum: course number; default is current course number from %env
15867:
15868: 6. idtype: set to concat if an additional digit is to be appended to the
15869: unix timestamp to form the suffix, if the plain timestamp is already
15870: in use. Default is to not do this, but simply increment the unix
15871: timestamp by 1 until a unique key is obtained.
15872:
15873: 7. who: holder of locking key; defaults to user:domain for user.
15874:
15875: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15876: retrying); default is 3.
15877:
15878: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15879:
15880: Returns:
15881:
15882: 1. suffix obtained (numeric)
15883:
15884: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15885:
15886: 3. error: contains (localized) error message if an error occurred.
15887:
1.747 albertel 15888:
1.608 albertel 15889: =back
15890:
1.243 albertel 15891: =head2 HTTP Helper Routines
15892:
15893: =over 4
15894:
1.191 harris41 15895: =item *
15896:
15897: escape() : unpack non-word characters into CGI-compatible hex codes
15898:
15899: =item *
15900:
15901: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15902:
1.243 albertel 15903: =back
15904:
15905: =head1 PRIVATE SUBROUTINES
15906:
15907: =head2 Underlying communication routines (Shouldn't call)
15908:
15909: =over 4
15910:
15911: =item *
15912:
15913: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15914:
15915: =item *
15916:
15917: reply() : uses subreply to send a message to remote machine, logs all failures
15918:
15919: =item *
15920:
15921: critical() : passes a critical message to another server; if cannot
15922: get through then place message in connection buffer directory and
15923: returns con_delayed, if incapable of saving message, returns
15924: con_failed
15925:
15926: =item *
15927:
15928: reconlonc() : tries to reconnect lonc client processes.
15929:
15930: =back
15931:
15932: =head2 Resource Access Logging
15933:
15934: =over 4
15935:
15936: =item *
15937:
15938: flushcourselogs() : flush (save) buffer logs and access logs
15939:
15940: =item *
15941:
15942: courselog($what) : save message for course in hash
15943:
15944: =item *
15945:
15946: courseacclog($what) : save message for course using &courselog(). Perform
15947: special processing for specific resource types (problems, exams, quizzes, etc).
15948:
1.191 harris41 15949: =item *
15950:
15951: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15952: as a PerlChildExitHandler
1.243 albertel 15953:
15954: =back
15955:
15956: =head2 Other
15957:
15958: =over 4
15959:
15960: =item *
15961:
15962: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 15963:
15964: =back
15965:
15966: =cut
1.877 foxr 15967:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>