Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1355
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1355 ! raeburn 4: # $Id: lonnet.pm,v 1.1354 2017/08/27 17:49:49 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.486 www 74: use HTTP::Date;
1.977 amueller 75: use Image::Magick;
76:
1.1182 foxr 77:
1.1173 foxr 78: use Encode;
79:
1.1245 raeburn 80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 81: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
82: %managerstab);
1.871 albertel 83:
84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
85: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
86: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 87: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 88:
1.1 albertel 89: use IO::Socket;
1.31 www 90: use GDBM_File;
1.208 albertel 91: use HTML::LCParser;
1.88 www 92: use Fcntl qw(:flock);
1.870 albertel 93: use Storable qw(thaw nfreeze);
1.1289 damieng 94: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599 albertel 95: use Cache::Memcached;
1.676 albertel 96: use Digest::MD5;
1.790 albertel 97: use Math::Random;
1.1024 raeburn 98: use File::MMagic;
1.807 albertel 99: use LONCAPA qw(:DEFAULT :match);
1.740 www 100: use LONCAPA::Configuration;
1.1160 www 101: use LONCAPA::lonmetadata;
1.1167 droeschl 102: use LONCAPA::Lond;
1.1345 raeburn 103: use LONCAPA::LWPReq;
1.1117 foxr 104:
1.1090 raeburn 105: use File::Copy;
1.676 albertel 106:
1.195 www 107: my $readit;
1.1288 damieng 108: my $max_connection_retries = 20; # Or some such value.
1.1 albertel 109:
1.619 albertel 110: require Exporter;
111:
112: our @ISA = qw (Exporter);
113: our @EXPORT = qw(%env);
114:
1.449 matthew 115:
1.1187 raeburn 116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 117: {
118: my $logid;
1.1187 raeburn 119: sub write_log {
1.1188 raeburn 120: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184 raeburn 121: if ($context eq 'course') {
122: if (($cnum eq '') || ($cdom eq '')) {
123: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
124: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
125: }
1.957 raeburn 126: }
1.1184 raeburn 127: $logid ++;
1.957 raeburn 128: my $now = time();
129: my $id=$now.'00000'.$$.'00000'.$logid;
1.1184 raeburn 130: my $logentry = {
131: $id => {
132: 'exe_uname' => $env{'user.name'},
133: 'exe_udom' => $env{'user.domain'},
134: 'exe_time' => $now,
135: 'exe_ip' => $ENV{'REMOTE_ADDR'},
136: 'delflag' => $delflag,
137: 'logentry' => $storehash,
138: 'uname' => $uname,
139: 'udom' => $udom,
140: }
141: };
142: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 143: }
144: }
1.1 albertel 145:
1.163 harris41 146: sub logtouch {
147: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 148: unless (-e "$execdir/logs/lonnet.log") {
149: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 150: close $fh;
151: }
152: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
153: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
154: }
155:
1.1 albertel 156: sub logthis {
157: my $message=shift;
158: my $execdir=$perlvar{'lonDaemons'};
159: my $now=time;
160: my $local=localtime($now);
1.448 albertel 161: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 162: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
163: print $fh $logstring;
1.448 albertel 164: close($fh);
165: }
1.1 albertel 166: return 1;
167: }
168:
169: sub logperm {
170: my $message=shift;
171: my $execdir=$perlvar{'lonDaemons'};
172: my $now=time;
173: my $local=localtime($now);
1.448 albertel 174: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
175: print $fh "$now:$message:$local\n";
176: close($fh);
177: }
1.1 albertel 178: return 1;
179: }
180:
1.850 albertel 181: sub create_connection {
1.853 albertel 182: my ($hostname,$lonid) = @_;
1.851 albertel 183: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 184: Type => SOCK_STREAM,
185: Timeout => 10);
186: return 0 if (!$client);
1.890 albertel 187: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 188: my $result = <$client>;
189: chomp($result);
190: return 1 if ($result eq 'done');
191: return 0;
192: }
193:
1.983 raeburn 194: sub get_server_timezone {
195: my ($cnum,$cdom) = @_;
196: my $home=&homeserver($cnum,$cdom);
197: if ($home ne 'no_host') {
198: my $cachetime = 24*3600;
199: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
200: if (defined($cached)) {
201: return $timezone;
202: } else {
203: my $timezone = &reply('servertimezone',$home);
204: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
205: }
206: }
207: }
1.850 albertel 208:
1.1106 raeburn 209: sub get_server_distarch {
210: my ($lonhost,$ignore_cache) = @_;
211: if (defined($lonhost)) {
212: if (!defined(&hostname($lonhost))) {
213: return;
214: }
215: my $cachetime = 12*3600;
216: if (!$ignore_cache) {
217: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
218: if (defined($cached)) {
219: return $distarch;
220: }
221: }
222: my $rep = &reply('serverdistarch',$lonhost);
223: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
224: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
225: $rep eq '') {
226: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
227: }
228: }
229: return;
230: }
231:
1.1315 raeburn 232: sub get_servercerts_info {
233: my ($lonhost,$context) = @_;
234: my ($rep,$uselocal);
235: if (grep { $_ eq $lonhost } ¤t_machine_ids()) {
236: $uselocal = 1;
237: }
1.1316 raeburn 238: if (($context ne 'cgi') && ($uselocal)) {
1.1315 raeburn 239: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323 raeburn 240: if ($distro eq '') {
241: $uselocal = 0;
242: } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315 raeburn 243: if ($1 < 6) {
244: $uselocal = 0;
245: }
1.1346 raeburn 246: } elsif ($distro =~ /^(?:sles)(\d+)$/) {
247: if ($1 < 12) {
248: $uselocal = 0;
249: }
1.1315 raeburn 250: }
251: }
252: if ($uselocal) {
253: $rep = LONCAPA::Lond::server_certs(\%perlvar);
254: } else {
255: $rep=&reply('servercerts',$lonhost);
256: }
257: my ($result,%returnhash);
258: if (defined($lonhost)) {
259: if (!defined(&hostname($lonhost))) {
260: return;
261: }
262: }
263: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
264: ($rep eq 'unknown_cmd')) {
265: $result = $rep;
266: } else {
267: $result = 'ok';
268: my @pairs=split(/\&/,$rep);
269: foreach my $item (@pairs) {
270: my ($key,$value)=split(/=/,$item,2);
271: my $what = &unescape($key);
272: $returnhash{$what}=&thaw_unescape($value);
273: }
274: }
275: return ($result,\%returnhash);
276: }
277:
1.993 raeburn 278: sub get_server_loncaparev {
1.1073 raeburn 279: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 280: if (defined($lonhost)) {
281: if (!defined(&hostname($lonhost))) {
282: undef($lonhost);
283: }
284: }
285: if (!defined($lonhost)) {
286: if (defined(&domain($dom,'primary'))) {
287: $lonhost=&domain($dom,'primary');
288: if ($lonhost eq 'no_host') {
289: undef($lonhost);
290: }
291: }
292: }
293: if (defined($lonhost)) {
1.1073 raeburn 294: my $cachetime = 12*3600;
295: if (!$ignore_cache) {
296: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
297: if (defined($cached)) {
298: return $loncaparev;
299: }
300: }
301: my ($answer,$loncaparev);
302: my @ids=¤t_machine_ids();
303: if (grep(/^\Q$lonhost\E$/,@ids)) {
304: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 305: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 306: $loncaparev = $1;
307: }
308: } else {
309: $answer = &reply('serverloncaparev',$lonhost);
310: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
311: if ($caller eq 'loncron') {
312: my $protocol = $protocol{$lonhost};
313: $protocol = 'http' if ($protocol ne 'https');
314: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
315: my $request=new HTTP::Request('GET',$url);
1.1345 raeburn 316: my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073 raeburn 317: unless ($response->is_error()) {
318: my $content = $response->content;
1.1081 raeburn 319: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 320: $loncaparev = $1;
321: }
322: }
323: } else {
324: $loncaparev = $loncaparevs{$lonhost};
325: }
1.1081 raeburn 326: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 327: $loncaparev = $1;
328: }
1.993 raeburn 329: }
1.1073 raeburn 330: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 331: }
332: }
333:
1.1074 raeburn 334: sub get_server_homeID {
335: my ($hostname,$ignore_cache,$caller) = @_;
336: unless ($ignore_cache) {
337: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
338: if (defined($cached)) {
339: return $serverhomeID;
340: }
341: }
342: my $cachetime = 12*3600;
343: my $serverhomeID;
344: if ($caller eq 'loncron') {
345: my @machine_ids = &machine_ids($hostname);
346: foreach my $id (@machine_ids) {
347: my $response = &reply('serverhomeID',$id);
348: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
349: $serverhomeID = $response;
350: last;
351: }
352: }
353: if ($serverhomeID eq '') {
354: $serverhomeID = $machine_ids[-1];
355: }
356: } else {
357: $serverhomeID = $serverhomeIDs{$hostname};
358: }
359: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
360: }
361:
1.1121 raeburn 362: sub get_remote_globals {
363: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 364: my ($result,%returnhash,%whatneeded);
365: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 366: foreach my $what (sort(keys(%{$whathash}))) {
367: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 368: my ($response,$cached);
1.1121 raeburn 369: unless ($ignore_cache) {
1.1125 raeburn 370: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 371: }
372: if (defined($cached)) {
1.1125 raeburn 373: $returnhash{$what} = $response;
1.1121 raeburn 374: } else {
1.1125 raeburn 375: $whatneeded{$what} = 1;
1.1121 raeburn 376: }
377: }
1.1125 raeburn 378: if (keys(%whatneeded) == 0) {
379: $result = 'ok';
380: } else {
1.1121 raeburn 381: my $requested = &freeze_escape(\%whatneeded);
382: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 383: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
384: ($rep eq 'unknown_cmd')) {
385: $result = $rep;
386: } else {
387: $result = 'ok';
1.1121 raeburn 388: my @pairs=split(/\&/,$rep);
1.1125 raeburn 389: foreach my $item (@pairs) {
390: my ($key,$value)=split(/=/,$item,2);
391: my $what = &unescape($key);
392: my $hashid = $lonhost.'-'.$what;
393: $returnhash{$what}=&thaw_unescape($value);
394: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 395: }
396: }
397: }
398: }
1.1125 raeburn 399: return ($result,\%returnhash);
1.1121 raeburn 400: }
401:
1.1124 raeburn 402: sub remote_devalidate_cache {
1.1241 raeburn 403: my ($lonhost,$cachekeys) = @_;
404: my $items;
405: return unless (ref($cachekeys) eq 'ARRAY');
406: my $cachestr = join('&',@{$cachekeys});
407: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 408: return $response;
409: }
410:
1.1 albertel 411: # -------------------------------------------------- Non-critical communication
412: sub subreply {
413: my ($cmd,$server)=@_;
1.838 albertel 414: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 415: #
416: # With loncnew process trimming, there's a timing hole between lonc server
417: # process exit and the master server picking up the listen on the AF_UNIX
418: # socket. In that time interval, a lock file will exist:
419:
420: my $lockfile=$peerfile.".lock";
421: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1289 damieng 422: sleep(0.1);
1.549 foxr 423: }
424: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 425: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 426: #
1.550 foxr 427: # We'll give the connection a few tries before abandoning it. If
428: # connection is not possible, we'll con_lost back to the client.
429: #
430: my $client;
431: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
432: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
433: Type => SOCK_STREAM,
434: Timeout => 10);
1.869 albertel 435: if ($client) {
1.550 foxr 436: last; # Connected!
1.850 albertel 437: } else {
1.853 albertel 438: &create_connection(&hostname($server),$server);
1.550 foxr 439: }
1.1289 damieng 440: sleep(0.1); # Try again later if failed connection.
1.550 foxr 441: }
442: my $answer;
443: if ($client) {
1.704 albertel 444: print $client "sethost:$server:$cmd\n";
1.550 foxr 445: $answer=<$client>;
446: if (!$answer) { $answer="con_lost"; }
447: chomp($answer);
448: } else {
449: $answer = 'con_lost'; # Failed connection.
450: }
1.1 albertel 451: return $answer;
452: }
453:
454: sub reply {
455: my ($cmd,$server)=@_;
1.838 albertel 456: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 457: my $answer=subreply($cmd,$server);
1.65 www 458: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 459: &logthis("<font color=\"blue\">WARNING:".
1.12 www 460: " $cmd to $server returned $answer</font>");
461: }
1.1 albertel 462: return $answer;
463: }
464:
465: # ----------------------------------------------------------- Send USR1 to lonc
466:
467: sub reconlonc {
1.891 albertel 468: my ($lonid) = @_;
469: if ($lonid) {
1.1295 raeburn 470: my $hostname = &hostname($lonid);
1.891 albertel 471: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
472: if ($hostname && -e $peerfile) {
473: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
474: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
475: Type => SOCK_STREAM,
476: Timeout => 10);
477: if ($client) {
478: print $client ("reset_retries\n");
479: my $answer=<$client>;
480: #reset just this one.
481: }
482: }
483: return;
484: }
485:
1.836 www 486: &logthis("Trying to reconnect lonc");
1.1 albertel 487: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 488: if (open(my $fh,"<$loncfile")) {
1.1 albertel 489: my $loncpid=<$fh>;
490: chomp($loncpid);
491: if (kill 0 => $loncpid) {
492: &logthis("lonc at pid $loncpid responding, sending USR1");
493: kill USR1 => $loncpid;
494: sleep 1;
1.1295 raeburn 495: } else {
1.12 www 496: &logthis(
1.672 albertel 497: "<font color=\"blue\">WARNING:".
1.12 www 498: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 499: }
500: } else {
1.836 www 501: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 502: }
503: }
504:
505: # ------------------------------------------------------ Critical communication
1.12 www 506:
1.1 albertel 507: sub critical {
508: my ($cmd,$server)=@_;
1.838 albertel 509: unless (&hostname($server)) {
1.672 albertel 510: &logthis("<font color=\"blue\">WARNING:".
1.89 www 511: " Critical message to unknown server ($server)</font>");
512: return 'no_such_host';
513: }
1.1 albertel 514: my $answer=reply($cmd,$server);
515: if ($answer eq 'con_lost') {
1.1295 raeburn 516: &reconlonc($server);
1.589 albertel 517: my $answer=reply($cmd,$server);
1.1 albertel 518: if ($answer eq 'con_lost') {
519: my $now=time;
520: my $middlename=$cmd;
1.5 www 521: $middlename=substr($middlename,0,16);
1.1 albertel 522: $middlename=~s/\W//g;
523: my $dfilename=
1.305 www 524: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
525: $dumpcount++;
1.1 albertel 526: {
1.448 albertel 527: my $dfh;
528: if (open($dfh,">$dfilename")) {
529: print $dfh "$cmd\n";
530: close($dfh);
531: }
1.1 albertel 532: }
1.1288 damieng 533: sleep 1;
1.1 albertel 534: my $wcmd='';
535: {
1.448 albertel 536: my $dfh;
537: if (open($dfh,"<$dfilename")) {
538: $wcmd=<$dfh>;
539: close($dfh);
540: }
1.1 albertel 541: }
542: chomp($wcmd);
1.7 www 543: if ($wcmd eq $cmd) {
1.672 albertel 544: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 545: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 546: &logperm("D:$server:$cmd");
547: return 'con_delayed';
548: } else {
1.672 albertel 549: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 550: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 551: &logperm("F:$server:$cmd");
552: return 'con_failed';
553: }
554: }
555: }
556: return $answer;
1.405 albertel 557: }
558:
1.755 albertel 559: # ------------------------------------------- check if return value is an error
560:
561: sub error {
562: my ($result) = @_;
1.756 albertel 563: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 564: if ($2 == 2) { return undef; }
565: return $1;
566: }
567: return undef;
568: }
569:
1.783 albertel 570: sub convert_and_load_session_env {
571: my ($lonidsdir,$handle)=@_;
572: my @profile;
573: {
1.917 albertel 574: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
575: if (!$opened) {
1.915 albertel 576: return 0;
577: }
1.783 albertel 578: flock($idf,LOCK_SH);
579: @profile=<$idf>;
580: close($idf);
581: }
582: my %temp_env;
583: foreach my $line (@profile) {
1.786 albertel 584: if ($line !~ m/=/) {
585: return 0;
586: }
1.783 albertel 587: chomp($line);
588: my ($envname,$envvalue)=split(/=/,$line,2);
589: $temp_env{&unescape($envname)} = &unescape($envvalue);
590: }
591: unlink("$lonidsdir/$handle.id");
592: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
593: 0640)) {
594: %disk_env = %temp_env;
595: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
596: untie(%disk_env);
597: }
1.786 albertel 598: return 1;
1.783 albertel 599: }
600:
1.374 www 601: # ------------------------------------------- Transfer profile into environment
1.780 albertel 602: my $env_loaded;
603: sub transfer_profile_to_env {
1.788 albertel 604: my ($lonidsdir,$handle,$force_transfer) = @_;
605: if (!$force_transfer && $env_loaded) { return; }
1.374 www 606:
1.720 albertel 607: if (!defined($lonidsdir)) {
608: $lonidsdir = $perlvar{'lonIDsDir'};
609: }
610: if (!defined($handle)) {
611: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
612: }
613:
1.786 albertel 614: my $convert;
615: {
1.917 albertel 616: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
617: if (!$opened) {
1.915 albertel 618: return;
619: }
1.786 albertel 620: flock($idf,LOCK_SH);
621: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
622: &GDBM_READER(),0640)) {
623: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
624: untie(%disk_env);
625: } else {
626: $convert = 1;
627: }
628: }
629: if ($convert) {
630: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
631: &logthis("Failed to load session, or convert session.");
632: }
1.374 www 633: }
1.783 albertel 634:
1.786 albertel 635: my %remove;
1.783 albertel 636: while ( my $envname = each(%env) ) {
1.433 matthew 637: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
638: if ($time < time-300) {
1.783 albertel 639: $remove{$key}++;
1.433 matthew 640: }
641: }
642: }
1.783 albertel 643:
1.619 albertel 644: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 645: $env_loaded=1;
1.783 albertel 646: foreach my $expired_key (keys(%remove)) {
1.433 matthew 647: &delenv($expired_key);
1.374 www 648: }
1.1 albertel 649: }
650:
1.916 albertel 651: # ---------------------------------------------------- Check for valid session
652: sub check_for_valid_session {
1.1355 ! raeburn 653: my ($r,$name,$userhashref,$domref) = @_;
1.916 albertel 654: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1337 raeburn 655: my ($linkname,$pubname);
1.1155 raeburn 656: if ($name eq '') {
657: $name = 'lonID';
1.1337 raeburn 658: $linkname = 'lonLinkID';
659: $pubname = 'lonPubID';
1.1155 raeburn 660: }
661: my $lonid=$cookies{$name};
1.1337 raeburn 662: if (!$lonid) {
663: if (($name eq 'lonID') && ($ENV{'SERVER_PORT'} != 443) && ($linkname)) {
664: $lonid=$cookies{$linkname};
665: }
666: if (!$lonid) {
667: if (($name eq 'lonID') && ($pubname)) {
668: $lonid=$cookies{$pubname};
669: }
670: }
671: }
1.916 albertel 672: return undef if (!$lonid);
673:
674: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 675: my $lonidsdir;
676: if ($name eq 'lonDAV') {
677: $lonidsdir=$r->dir_config('lonDAVsessDir');
678: } else {
679: $lonidsdir=$r->dir_config('lonIDsDir');
680: }
1.1355 ! raeburn 681: if (!-e "$lonidsdir/$handle.id") {
! 682: if ((ref($domref)) && ($name eq 'lonID') &&
! 683: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
! 684: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
! 685: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
! 686: $$domref = $possudom;
! 687: }
! 688: }
! 689: return undef;
! 690: }
1.916 albertel 691:
1.917 albertel 692: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
693: return undef if (!$opened);
1.916 albertel 694:
695: flock($idf,LOCK_SH);
696: my %disk_env;
697: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
698: &GDBM_READER(),0640)) {
699: return undef;
700: }
701:
702: if (!defined($disk_env{'user.name'})
703: || !defined($disk_env{'user.domain'})) {
704: return undef;
705: }
1.1245 raeburn 706:
707: if (ref($userhashref) eq 'HASH') {
708: $userhashref->{'name'} = $disk_env{'user.name'};
709: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212 raeburn 710: }
1.1245 raeburn 711:
1.916 albertel 712: return $handle;
713: }
714:
1.830 albertel 715: sub timed_flock {
716: my ($file,$lock_type) = @_;
717: my $failed=0;
718: eval {
719: local $SIG{__DIE__}='DEFAULT';
720: local $SIG{ALRM}=sub {
721: $failed=1;
722: die("failed lock");
723: };
724: alarm(13);
725: flock($file,$lock_type);
726: alarm(0);
727: };
728: if ($failed) {
729: return undef;
730: } else {
731: return 1;
732: }
733: }
734:
1.5 www 735: # ---------------------------------------------------------- Append Environment
736:
737: sub appenv {
1.949 raeburn 738: my ($newenv,$roles) = @_;
739: if (ref($newenv) eq 'HASH') {
740: foreach my $key (keys(%{$newenv})) {
741: my $refused = 0;
742: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
743: $refused = 1;
744: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 745: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 746: if (grep(/^\Q$role\E$/,@{$roles})) {
747: $refused = 0;
748: }
749: }
750: }
751: if ($refused) {
752: &logthis("<font color=\"blue\">WARNING: ".
753: "Attempt to modify environment ".$key." to ".$newenv->{$key}
754: .'</font>');
755: delete($newenv->{$key});
756: } else {
757: $env{$key}=$newenv->{$key};
758: }
759: }
760: my $opened = open(my $env_file,'+<',$env{'user.environment'});
761: if ($opened
762: && &timed_flock($env_file,LOCK_EX)
763: &&
764: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
765: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
766: while (my ($key,$value) = each(%{$newenv})) {
767: $disk_env{$key} = $value;
768: }
769: untie(%disk_env);
1.35 www 770: }
1.191 harris41 771: }
1.56 www 772: return 'ok';
773: }
774: # ----------------------------------------------------- Delete from Environment
775:
776: sub delenv {
1.1104 raeburn 777: my ($delthis,$regexp,$roles) = @_;
778: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
779: my $refused = 1;
780: if (ref($roles) eq 'ARRAY') {
781: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
782: if (grep(/^\Q$role\E$/,@{$roles})) {
783: $refused = 0;
784: }
785: }
786: if ($refused) {
787: &logthis("<font color=\"blue\">WARNING: ".
788: "Attempt to delete from environment ".$delthis);
789: return 'error';
790: }
1.56 www 791: }
1.917 albertel 792: my $opened = open(my $env_file,'+<',$env{'user.environment'});
793: if ($opened
1.915 albertel 794: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 795: &&
796: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
797: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 798: foreach my $key (keys(%disk_env)) {
1.987 raeburn 799: if ($regexp) {
800: if ($key=~/^$delthis/) {
801: delete($env{$key});
802: delete($disk_env{$key});
803: }
804: } else {
805: if ($key=~/^\Q$delthis\E/) {
806: delete($env{$key});
807: delete($disk_env{$key});
808: }
809: }
1.448 albertel 810: }
1.783 albertel 811: untie(%disk_env);
1.5 www 812: }
813: return 'ok';
1.369 albertel 814: }
815:
1.790 albertel 816: sub get_env_multiple {
817: my ($name) = @_;
818: my @values;
819: if (defined($env{$name})) {
820: # exists is it an array
821: if (ref($env{$name})) {
822: @values=@{ $env{$name} };
823: } else {
824: $values[0]=$env{$name};
825: }
826: }
827: return(@values);
828: }
829:
1.958 www 830: # ------------------------------------------------------------------- Locking
831:
832: sub set_lock {
833: my ($text)=@_;
834: $locknum++;
835: my $id=$$.'-'.$locknum;
836: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
837: 'session.lock.'.$id => $text});
838: return $id;
839: }
840:
841: sub get_locks {
842: my $num=0;
843: my %texts=();
844: foreach my $lock (split(/\,/,$env{'session.locks'})) {
845: if ($lock=~/\w/) {
846: $num++;
847: $texts{$lock}=$env{'session.lock.'.$lock};
848: }
849: }
850: return ($num,%texts);
851: }
852:
853: sub remove_lock {
854: my ($id)=@_;
855: my $newlocks='';
856: foreach my $lock (split(/\,/,$env{'session.locks'})) {
857: if (($lock=~/\w/) && ($lock ne $id)) {
858: $newlocks.=','.$lock;
859: }
860: }
861: &appenv({'session.locks' => $newlocks});
862: &delenv('session.lock.'.$id);
863: }
864:
865: sub remove_all_locks {
866: my $activelocks=$env{'session.locks'};
867: foreach my $lock (split(/\,/,$env{'session.locks'})) {
868: if ($lock=~/\w/) {
869: &remove_lock($lock);
870: }
871: }
872: }
873:
874:
1.369 albertel 875: # ------------------------------------------ Find out current server userload
876: sub userload {
877: my $numusers=0;
878: {
879: opendir(LONIDS,$perlvar{'lonIDsDir'});
880: my $filename;
881: my $curtime=time;
882: while ($filename=readdir(LONIDS)) {
1.925 albertel 883: next if ($filename eq '.' || $filename eq '..');
884: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 885: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 886: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 887: }
888: closedir(LONIDS);
889: }
890: my $userloadpercent=0;
891: my $maxuserload=$perlvar{'lonUserLoadLim'};
892: if ($maxuserload) {
1.371 albertel 893: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 894: }
1.372 albertel 895: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 896: return $userloadpercent;
1.283 www 897: }
898:
1.1 albertel 899: # ------------------------------ Find server with least workload from spare.tab
1.11 www 900:
1.1 albertel 901: sub spareserver {
1.1083 raeburn 902: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 903: my $spare_server;
1.370 albertel 904: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 905: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
906: : $userloadpercent;
1.1083 raeburn 907: my ($uint_dom,$remotesessions);
908: if (($udom ne '') && (&domain($udom) ne '')) {
909: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
910: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
911: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
912: $remotesessions = $udomdefaults{'remotesessions'};
913: }
1.1123 raeburn 914: my $spareshash = &this_host_spares($udom);
915: if (ref($spareshash) eq 'HASH') {
916: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
917: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279 raeburn 918: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
919: $try_server));
1.1123 raeburn 920: ($spare_server, $lowest_load) =
921: &compare_server_load($try_server, $spare_server, $lowest_load);
922: }
1.1083 raeburn 923: }
1.784 albertel 924:
1.1123 raeburn 925: my $found_server = ($spare_server ne '' && $lowest_load < 100);
926:
927: if (!$found_server) {
928: if (ref($spareshash->{'default'}) eq 'ARRAY') {
929: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279 raeburn 930: next unless (&spare_can_host($udom,$uint_dom,
931: $remotesessions,$try_server));
1.1123 raeburn 932: ($spare_server, $lowest_load) =
933: &compare_server_load($try_server, $spare_server, $lowest_load);
934: }
935: }
936: }
1.784 albertel 937: }
938:
939: if (!$want_server_name) {
1.968 raeburn 940: my $protocol = 'http';
941: if ($protocol{$spare_server} eq 'https') {
942: $protocol = $protocol{$spare_server};
943: }
1.1001 raeburn 944: if (defined($spare_server)) {
945: my $hostname = &hostname($spare_server);
1.1083 raeburn 946: if (defined($hostname)) {
1.1001 raeburn 947: $spare_server = $protocol.'://'.$hostname;
948: }
949: }
1.784 albertel 950: }
951: return $spare_server;
952: }
953:
954: sub compare_server_load {
1.1253 raeburn 955: my ($try_server, $spare_server, $lowest_load, $required) = @_;
956:
957: if ($required) {
958: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
959: my $remoterev = &get_server_loncaparev(undef,$try_server);
960: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
961: if (($major eq '' && $minor eq '') ||
962: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
963: return ($spare_server,$lowest_load);
964: }
965: }
1.784 albertel 966:
967: my $loadans = &reply('load', $try_server);
968: my $userloadans = &reply('userload',$try_server);
969:
970: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 971: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 972: }
973:
974: my $load;
975: if ($loadans =~ /\d/) {
976: if ($userloadans =~ /\d/) {
977: #both are numbers, pick the bigger one
978: $load = ($loadans > $userloadans) ? $loadans
979: : $userloadans;
1.411 albertel 980: } else {
1.784 albertel 981: $load = $loadans;
1.411 albertel 982: }
1.784 albertel 983: } else {
984: $load = $userloadans;
985: }
986:
987: if (($load =~ /\d/) && ($load < $lowest_load)) {
988: $spare_server = $try_server;
989: $lowest_load = $load;
1.370 albertel 990: }
1.784 albertel 991: return ($spare_server,$lowest_load);
1.202 matthew 992: }
1.914 albertel 993:
994: # --------------------------- ask offload servers if user already has a session
995: sub find_existing_session {
996: my ($udom,$uname) = @_;
1.1123 raeburn 997: my $spareshash = &this_host_spares($udom);
998: if (ref($spareshash) eq 'HASH') {
999: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1000: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1001: return $try_server if (&has_user_session($try_server, $udom, $uname));
1002: }
1003: }
1004: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1005: foreach my $try_server (@{ $spareshash->{'default'} }) {
1006: return $try_server if (&has_user_session($try_server, $udom, $uname));
1007: }
1008: }
1.914 albertel 1009: }
1010: return;
1011: }
1012:
1013: # -------------------------------- ask if server already has a session for user
1014: sub has_user_session {
1015: my ($lonid,$udom,$uname) = @_;
1016: my $result = &reply(join(':','userhassession',
1017: map {&escape($_)} ($udom,$uname)),$lonid);
1018: return 1 if ($result eq 'ok');
1019:
1020: return 0;
1021: }
1022:
1.1076 raeburn 1023: # --------- determine least loaded server in a user's domain which allows login
1024:
1025: sub choose_server {
1.1259 raeburn 1026: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1027: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1028: my %servers = &get_servers($udom);
1.1076 raeburn 1029: my $lowest_load = 30000;
1.1259 raeburn 1030: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1031: if ($skiploadbal) {
1032: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1033: unless (defined($cached)) {
1034: my $cachetime = 60*60*24;
1035: my %domconfig =
1036: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1037: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1038: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1039: $cachetime);
1040: }
1041: }
1042: }
1.1076 raeburn 1043: foreach my $lonhost (keys(%servers)) {
1.1259 raeburn 1044: if ($skiploadbal) {
1045: if (ref($balancers) eq 'HASH') {
1046: next if (exists($balancers->{$lonhost}));
1047: }
1048: }
1.1115 raeburn 1049: my $loginvia;
1050: if ($checkloginvia) {
1051: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1052: if ($loginvia) {
1053: my ($server,$path) = split(/:/,$loginvia);
1054: ($login_host, $lowest_load) =
1.1253 raeburn 1055: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1056: if ($login_host eq $server) {
1057: $portal_path = $path;
1.1151 raeburn 1058: $isredirect = 1;
1.1116 raeburn 1059: }
1060: } else {
1061: ($login_host, $lowest_load) =
1.1253 raeburn 1062: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1063: if ($login_host eq $lonhost) {
1064: $portal_path = '';
1.1151 raeburn 1065: $isredirect = '';
1.1116 raeburn 1066: }
1067: }
1068: } else {
1.1076 raeburn 1069: ($login_host, $lowest_load) =
1.1253 raeburn 1070: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1071: }
1072: }
1073: if ($login_host ne '') {
1.1116 raeburn 1074: $hostname = &hostname($login_host);
1.1076 raeburn 1075: }
1.1331 raeburn 1076: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1077: }
1078:
1.202 matthew 1079: # --------------------------------------------- Try to change a user's password
1080:
1081: sub changepass {
1.799 raeburn 1082: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1083: $currentpass = &escape($currentpass);
1084: $newpass = &escape($newpass);
1.1030 raeburn 1085: my $lonhost = $perlvar{'lonHostID'};
1086: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1087: $server);
1088: if (! $answer) {
1089: &logthis("No reply on password change request to $server ".
1090: "by $uname in domain $udom.");
1091: } elsif ($answer =~ "^ok") {
1092: &logthis("$uname in $udom successfully changed their password ".
1093: "on $server.");
1094: } elsif ($answer =~ "^pwchange_failure") {
1095: &logthis("$uname in $udom was unable to change their password ".
1096: "on $server. The action was blocked by either lcpasswd ".
1097: "or pwchange");
1098: } elsif ($answer =~ "^non_authorized") {
1099: &logthis("$uname in $udom did not get their password correct when ".
1100: "attempting to change it on $server.");
1101: } elsif ($answer =~ "^auth_mode_error") {
1102: &logthis("$uname in $udom attempted to change their password despite ".
1103: "not being locally or internally authenticated on $server.");
1104: } elsif ($answer =~ "^unknown_user") {
1105: &logthis("$uname in $udom attempted to change their password ".
1106: "on $server but were unable to because $server is not ".
1107: "their home server.");
1108: } elsif ($answer =~ "^refused") {
1109: &logthis("$server refused to change $uname in $udom password because ".
1110: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1111: } elsif ($answer =~ "invalid_client") {
1112: &logthis("$server refused to change $uname in $udom password because ".
1113: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1114: }
1115: return $answer;
1.1 albertel 1116: }
1117:
1.169 harris41 1118: # ----------------------- Try to determine user's current authentication scheme
1119:
1120: sub queryauthenticate {
1121: my ($uname,$udom)=@_;
1.456 albertel 1122: my $uhome=&homeserver($uname,$udom);
1123: if (!$uhome) {
1124: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1125: return 'no_host';
1126: }
1127: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1128: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1129: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1130: }
1.456 albertel 1131: return $answer;
1.169 harris41 1132: }
1133:
1.1 albertel 1134: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1135:
1.1 albertel 1136: sub authenticate {
1.1073 raeburn 1137: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1138: $upass=&escape($upass);
1139: $uname= &LONCAPA::clean_username($uname);
1.836 www 1140: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1141: my $newhome;
1.836 www 1142: if ((!$uhome) || ($uhome eq 'no_host')) {
1143: # Maybe the machine was offline and only re-appeared again recently?
1144: &reconlonc();
1145: # One more
1.952 raeburn 1146: $uhome=&homeserver($uname,$udom,1);
1147: if (($uhome eq 'no_host') && $checkdefauth) {
1148: if (defined(&domain($udom,'primary'))) {
1149: $newhome=&domain($udom,'primary');
1150: }
1151: if ($newhome ne '') {
1152: $uhome = $newhome;
1153: }
1154: }
1.836 www 1155: if ((!$uhome) || ($uhome eq 'no_host')) {
1156: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1157: return 'no_host';
1158: }
1.1 albertel 1159: }
1.1073 raeburn 1160: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1161: if ($answer eq 'authorized') {
1.952 raeburn 1162: if ($newhome) {
1163: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1164: return 'no_account_on_host';
1165: } else {
1166: &logthis("User $uname at $udom authorized by $uhome");
1167: return $uhome;
1168: }
1.471 albertel 1169: }
1170: if ($answer eq 'non_authorized') {
1171: &logthis("User $uname at $udom rejected by $uhome");
1172: return 'no_host';
1.9 www 1173: }
1.471 albertel 1174: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1175: return 'no_host';
1176: }
1177:
1.1073 raeburn 1178: sub can_host_session {
1.1074 raeburn 1179: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1180: my $canhost = 1;
1.1074 raeburn 1181: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1182: if (ref($remotesessions) eq 'HASH') {
1183: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1184: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1185: $canhost = 0;
1186: } else {
1187: $canhost = 1;
1188: }
1189: }
1190: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1191: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1192: $canhost = 1;
1193: } else {
1194: $canhost = 0;
1195: }
1196: }
1197: if ($canhost) {
1198: if ($remotesessions->{'version'} ne '') {
1199: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1200: if ($reqmajor ne '' && $reqminor ne '') {
1201: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1202: my $major = $1;
1203: my $minor = $2;
1204: if (($major < $reqmajor ) ||
1205: (($major == $reqmajor) && ($minor < $reqminor))) {
1206: $canhost = 0;
1207: }
1208: } else {
1209: $canhost = 0;
1210: }
1211: }
1212: }
1213: }
1214: }
1215: if ($canhost) {
1216: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1217: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1218: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1219: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1220: if (($uint_dom ne '') &&
1221: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1222: $canhost = 0;
1223: } else {
1224: $canhost = 1;
1225: }
1226: }
1227: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1228: if (($uint_dom ne '') &&
1229: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1230: $canhost = 1;
1231: } else {
1232: $canhost = 0;
1233: }
1234: }
1235: }
1236: }
1237: return $canhost;
1238: }
1239:
1.1083 raeburn 1240: sub spare_can_host {
1241: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1242: my $canhost=1;
1.1279 raeburn 1243: my $try_server_hostname = &hostname($try_server);
1244: my $serverhomeID = &get_server_homeID($try_server_hostname);
1245: my $serverhomedom = &host_domain($serverhomeID);
1246: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1247: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1248: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1249: $canhost = 0;
1250: }
1251: }
1252: if (($canhost) && ($uint_dom)) {
1253: my @intdoms;
1254: my $internet_names = &get_internet_names($try_server);
1255: if (ref($internet_names) eq 'ARRAY') {
1256: @intdoms = @{$internet_names};
1257: }
1258: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1259: my $remoterev = &get_server_loncaparev(undef,$try_server);
1260: $canhost = &can_host_session($udom,$try_server,$remoterev,
1261: $remotesessions,
1262: $defdomdefaults{'hostedsessions'});
1263: }
1.1083 raeburn 1264: }
1265: return $canhost;
1266: }
1267:
1.1123 raeburn 1268: sub this_host_spares {
1269: my ($dom) = @_;
1.1126 raeburn 1270: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1271: my @hosts = ¤t_machine_ids();
1272: foreach my $lonhost (@hosts) {
1273: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1274: $dom_in_use = $dom;
1275: $lonhost_in_use = $lonhost;
1.1123 raeburn 1276: last;
1277: }
1278: }
1.1126 raeburn 1279: if ($dom_in_use ne '') {
1280: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1281: }
1282: if (ref($result) ne 'HASH') {
1283: $lonhost_in_use = $perlvar{'lonHostID'};
1284: $dom_in_use = &host_domain($lonhost_in_use);
1285: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1286: if (ref($result) ne 'HASH') {
1287: $result = \%spareid;
1288: }
1289: }
1290: return $result;
1291: }
1292:
1293: sub spares_for_offload {
1294: my ($dom_in_use,$lonhost_in_use) = @_;
1295: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1296: if (defined($cached)) {
1297: return $result;
1298: } else {
1.1126 raeburn 1299: my $cachetime = 60*60*24;
1300: my %domconfig =
1301: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1302: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1303: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1304: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1305: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1306: }
1307: }
1308: }
1309: }
1.1126 raeburn 1310: return;
1.1123 raeburn 1311: }
1312:
1.1129 raeburn 1313: sub get_lonbalancer_config {
1314: my ($servers) = @_;
1315: my ($currbalancer,$currtargets);
1316: if (ref($servers) eq 'HASH') {
1317: foreach my $server (keys(%{$servers})) {
1318: my %what = (
1319: spareid => 1,
1320: perlvar => 1,
1321: );
1322: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1323: if ($result eq 'ok') {
1324: if (ref($returnhash) eq 'HASH') {
1325: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1326: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1327: $currbalancer = $server;
1328: $currtargets = {};
1329: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1330: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1331: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1332: }
1333: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1334: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1335: }
1336: }
1337: last;
1338: }
1339: }
1340: }
1341: }
1342: }
1343: }
1344: return ($currbalancer,$currtargets);
1345: }
1346:
1347: sub check_loadbalancing {
1.1331 raeburn 1348: my ($uname,$udom,$caller) = @_;
1.1191 raeburn 1349: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1350: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1351: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1352: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1353: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1354: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1355: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1356: my $serverhomedom = &host_domain($lonhost);
1.1307 raeburn 1357: my $domneedscache;
1.1129 raeburn 1358: my $cachetime = 60*60*24;
1359:
1360: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1361: $dom_in_use = $udom;
1362: $homeintdom = 1;
1363: } else {
1364: $dom_in_use = $serverhomedom;
1365: }
1366: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1367: unless (defined($cached)) {
1368: my %domconfig =
1369: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1370: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1371: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307 raeburn 1372: } else {
1373: $domneedscache = $dom_in_use;
1.1129 raeburn 1374: }
1375: }
1376: if (ref($result) eq 'HASH') {
1.1191 raeburn 1377: ($is_balancer,$currtargets,$currrules) =
1378: &check_balancer_result($result,@hosts);
1.1129 raeburn 1379: if ($is_balancer) {
1380: if (ref($currrules) eq 'HASH') {
1381: if ($homeintdom) {
1382: if ($uname ne '') {
1383: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1384: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1385: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1386: $rule_in_effect = $currrules->{'_LC_author'};
1387: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1388: $rule_in_effect = $currrules->{'_LC_adv'}
1389: }
1390: }
1391: if ($rule_in_effect eq '') {
1392: my %userenv = &userenvironment($udom,$uname,'inststatus');
1393: if ($userenv{'inststatus'} ne '') {
1394: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1395: my ($othertitle,$usertypes,$types) =
1396: &Apache::loncommon::sorted_inst_types($udom);
1397: if (ref($types) eq 'ARRAY') {
1398: foreach my $type (@{$types}) {
1399: if (grep(/^\Q$type\E$/,@statuses)) {
1400: if (exists($currrules->{$type})) {
1401: $rule_in_effect = $currrules->{$type};
1402: }
1403: }
1404: }
1405: }
1406: } else {
1407: if (exists($currrules->{'default'})) {
1408: $rule_in_effect = $currrules->{'default'};
1409: }
1410: }
1411: }
1412: } else {
1413: if (exists($currrules->{'default'})) {
1414: $rule_in_effect = $currrules->{'default'};
1415: }
1416: }
1417: } else {
1418: if ($currrules->{'_LC_external'} ne '') {
1419: $rule_in_effect = $currrules->{'_LC_external'};
1420: }
1421: }
1422: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1423: $uname,$udom);
1424: }
1425: }
1426: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1427: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1428: unless (defined($cached)) {
1429: my %domconfig =
1430: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1431: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307 raeburn 1432: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1433: } else {
1434: $domneedscache = $serverhomedom;
1.1129 raeburn 1435: }
1436: }
1437: if (ref($result) eq 'HASH') {
1.1191 raeburn 1438: ($is_balancer,$currtargets,$currrules) =
1439: &check_balancer_result($result,@hosts);
1440: if ($is_balancer) {
1.1129 raeburn 1441: if (ref($currrules) eq 'HASH') {
1442: if ($currrules->{'_LC_internetdom'} ne '') {
1443: $rule_in_effect = $currrules->{'_LC_internetdom'};
1444: }
1445: }
1446: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1447: $uname,$udom);
1448: }
1449: } else {
1450: if ($perlvar{'lonBalancer'} eq 'yes') {
1451: $is_balancer = 1;
1452: $offloadto = &this_host_spares($dom_in_use);
1453: }
1.1307 raeburn 1454: unless (defined($cached)) {
1455: $domneedscache = $serverhomedom;
1456: }
1.1129 raeburn 1457: }
1458: } else {
1459: if ($perlvar{'lonBalancer'} eq 'yes') {
1460: $is_balancer = 1;
1461: $offloadto = &this_host_spares($dom_in_use);
1462: }
1.1307 raeburn 1463: unless (defined($cached)) {
1464: $domneedscache = $serverhomedom;
1465: }
1466: }
1467: if ($domneedscache) {
1468: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1469: }
1.1176 raeburn 1470: if ($is_balancer) {
1471: my $lowest_load = 30000;
1472: if (ref($offloadto) eq 'HASH') {
1473: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1474: foreach my $try_server (@{$offloadto->{'primary'}}) {
1475: ($otherserver,$lowest_load) =
1476: &compare_server_load($try_server,$otherserver,$lowest_load);
1477: }
1.1129 raeburn 1478: }
1.1176 raeburn 1479: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1480:
1.1176 raeburn 1481: if (!$found_server) {
1482: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1483: foreach my $try_server (@{$offloadto->{'default'}}) {
1484: ($otherserver,$lowest_load) =
1485: &compare_server_load($try_server,$otherserver,$lowest_load);
1486: }
1487: }
1488: }
1489: } elsif (ref($offloadto) eq 'ARRAY') {
1490: if (@{$offloadto} == 1) {
1491: $otherserver = $offloadto->[0];
1492: } elsif (@{$offloadto} > 1) {
1493: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1494: ($otherserver,$lowest_load) =
1495: &compare_server_load($try_server,$otherserver,$lowest_load);
1496: }
1497: }
1498: }
1.1331 raeburn 1499: unless ($caller eq 'login') {
1500: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1501: $is_balancer = 0;
1502: if ($uname ne '' && $udom ne '') {
1503: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1176 raeburn 1504:
1.1331 raeburn 1505: &appenv({'user.loadbalexempt' => $lonhost,
1506: 'user.loadbalcheck.time' => time});
1507: }
1.1176 raeburn 1508: }
1.1129 raeburn 1509: }
1510: }
1511: }
1512: return ($is_balancer,$otherserver);
1513: }
1514:
1.1191 raeburn 1515: sub check_balancer_result {
1516: my ($result,@hosts) = @_;
1517: my ($is_balancer,$currtargets,$currrules);
1518: if (ref($result) eq 'HASH') {
1519: if ($result->{'lonhost'} ne '') {
1520: my $currbalancer = $result->{'lonhost'};
1521: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1522: $is_balancer = 1;
1523: $currtargets = $result->{'targets'};
1524: $currrules = $result->{'rules'};
1525: }
1526: } else {
1527: foreach my $key (keys(%{$result})) {
1528: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1529: (ref($result->{$key}) eq 'HASH')) {
1530: $is_balancer = 1;
1531: $currrules = $result->{$key}{'rules'};
1532: $currtargets = $result->{$key}{'targets'};
1533: last;
1534: }
1535: }
1536: }
1537: }
1538: return ($is_balancer,$currtargets,$currrules);
1539: }
1540:
1.1129 raeburn 1541: sub get_loadbalancer_targets {
1542: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1543: my $offloadto;
1.1175 raeburn 1544: if ($rule_in_effect eq 'none') {
1545: return [$perlvar{'lonHostID'}];
1546: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1547: $offloadto = $currtargets;
1548: } else {
1549: if ($rule_in_effect eq 'homeserver') {
1550: my $homeserver = &homeserver($uname,$udom);
1551: if ($homeserver ne 'no_host') {
1552: $offloadto = [$homeserver];
1553: }
1554: } elsif ($rule_in_effect eq 'externalbalancer') {
1555: my %domconfig =
1556: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1557: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1558: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1559: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1560: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1561: }
1562: }
1563: } else {
1.1178 raeburn 1564: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1565: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1566: if (&hostname($remotebalancer) ne '') {
1567: $offloadto = [$remotebalancer];
1568: }
1569: }
1570: } elsif (&hostname($rule_in_effect) ne '') {
1571: $offloadto = [$rule_in_effect];
1572: }
1573: }
1574: return $offloadto;
1575: }
1576:
1.1127 raeburn 1577: sub internet_dom_servers {
1578: my ($dom) = @_;
1579: my (%uniqservers,%servers);
1580: my $primaryserver = &hostname(&domain($dom,'primary'));
1581: my @machinedoms = &machine_domains($primaryserver);
1582: foreach my $mdom (@machinedoms) {
1583: my %currservers = %servers;
1584: my %server = &get_servers($mdom);
1585: %servers = (%currservers,%server);
1586: }
1587: my %by_hostname;
1588: foreach my $id (keys(%servers)) {
1589: push(@{$by_hostname{$servers{$id}}},$id);
1590: }
1591: foreach my $hostname (sort(keys(%by_hostname))) {
1592: if (@{$by_hostname{$hostname}} > 1) {
1593: my $match = 0;
1594: foreach my $id (@{$by_hostname{$hostname}}) {
1595: if (&host_domain($id) eq $dom) {
1596: $uniqservers{$id} = $hostname;
1597: $match = 1;
1598: }
1599: }
1600: unless ($match) {
1601: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1602: }
1603: } else {
1604: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1605: }
1606: }
1607: return %uniqservers;
1608: }
1609:
1.1347 raeburn 1610: sub trusted_domains {
1611: my ($cmdtype,$calldom) = @_;
1.1349 raeburn 1612: my ($trusted,$untrusted);
1.1347 raeburn 1613: if (&domain($calldom) eq '') {
1.1349 raeburn 1614: return ($trusted,$untrusted);
1.1347 raeburn 1615: }
1616: unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
1.1349 raeburn 1617: return ($trusted,$untrusted);
1.1347 raeburn 1618: }
1619: my $callprimary = &domain($calldom,'primary');
1620: my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
1621: if ($intcalldom eq '') {
1.1349 raeburn 1622: return ($trusted,$untrusted);
1.1347 raeburn 1623: }
1624:
1625: my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
1626: unless (defined($cached)) {
1627: my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
1628: &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
1629: $trustconfig = $domconfig{'trust'};
1630: }
1631: if (ref($trustconfig)) {
1632: my (%possexc,%possinc,@allexc,@allinc);
1633: if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
1634: if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
1635: map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}};
1636: }
1637: if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1638: map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
1639: }
1640: }
1641: if (keys(%possexc)) {
1642: if (keys(%possinc)) {
1643: foreach my $key (sort(keys(%possexc))) {
1644: next if ($key eq $intcalldom);
1645: unless ($possinc{$key}) {
1646: push(@allexc,$key);
1647: }
1648: }
1649: } else {
1650: @allexc = sort(keys(%possexc));
1651: }
1652: }
1653: if (keys(%possinc)) {
1654: $possinc{$intcalldom} = 1;
1655: @allinc = sort(keys(%possinc));
1656: }
1657: if ((@allexc > 0) || (@allinc > 0)) {
1658: my %doms_by_intdom;
1659: my %allintdoms = &all_host_intdom();
1660: my %alldoms = &all_host_domain();
1661: foreach my $key (%allintdoms) {
1662: if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
1663: unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
1664: push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
1665: }
1666: } else {
1667: $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}];
1668: }
1669: }
1670: foreach my $exc (@allexc) {
1671: if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1349 raeburn 1672: $untrusted = $doms_by_intdom{$exc};
1.1347 raeburn 1673: }
1674: }
1675: foreach my $inc (@allinc) {
1676: if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1349 raeburn 1677: $trusted = $doms_by_intdom{$inc};
1.1347 raeburn 1678: }
1679: }
1680: }
1681: }
1.1349 raeburn 1682: return ($trusted,$untrusted);
1.1347 raeburn 1683: }
1684:
1685: sub will_trust {
1686: my ($cmdtype,$domain,$possdom) = @_;
1687: return 1 if ($domain eq $possdom);
1688: my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
1689: my $willtrust;
1690: if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
1691: if (grep(/^\Q$domain\E$/,@{$trustedref})) {
1692: $willtrust = 1;
1693: }
1694: } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
1695: unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
1696: $willtrust = 1;
1697: }
1698: } else {
1699: $willtrust = 1;
1700: }
1701: return $willtrust;
1702: }
1703:
1.1 albertel 1704: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1705:
1.599 albertel 1706: my %homecache;
1.1 albertel 1707: sub homeserver {
1.230 stredwic 1708: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1709: my $index="$uname:$udom";
1.426 albertel 1710:
1.599 albertel 1711: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1712:
1713: my %servers = &get_servers($udom,'library');
1714: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1715: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1716: exists($badServerCache{$tryserver}));
1.841 albertel 1717:
1718: my $answer=reply("home:$udom:$uname",$tryserver);
1719: if ($answer eq 'found') {
1720: delete($badServerCache{$tryserver});
1721: return $homecache{$index}=$tryserver;
1722: } elsif ($answer eq 'no_host') {
1723: $badServerCache{$tryserver}=1;
1724: }
1.1 albertel 1725: }
1726: return 'no_host';
1.70 www 1727: }
1728:
1.1300 raeburn 1729: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70 www 1730:
1731: sub idget {
1.1300 raeburn 1732: my ($udom,$idsref,$namespace)=@_;
1.70 www 1733: my %returnhash=();
1.1300 raeburn 1734: my @ids=();
1735: if (ref($idsref) eq 'ARRAY') {
1736: @ids = @{$idsref};
1737: } else {
1738: return %returnhash;
1739: }
1740: if ($namespace eq '') {
1741: $namespace = 'ids';
1742: }
1.70 www 1743:
1.841 albertel 1744: my %servers = &get_servers($udom,'library');
1745: foreach my $tryserver (keys(%servers)) {
1.1299 raeburn 1746: my $idlist=join('&', map { &escape($_); } @ids);
1.1300 raeburn 1747: if ($namespace eq 'ids') {
1748: $idlist=~tr/A-Z/a-z/;
1749: }
1750: my $reply;
1751: if ($namespace eq 'ids') {
1752: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1753: } else {
1754: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1755: }
1.841 albertel 1756: my @answer=();
1757: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1758: @answer=split(/\&/,$reply);
1759: } ;
1760: my $i;
1761: for ($i=0;$i<=$#ids;$i++) {
1762: if ($answer[$i]) {
1.1299 raeburn 1763: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300 raeburn 1764: }
1.841 albertel 1765: }
1.1300 raeburn 1766: }
1.70 www 1767: return %returnhash;
1768: }
1769:
1770: # ------------------------------------- Find the IDs behind a list of usernames
1771:
1772: sub idrget {
1773: my ($udom,@unames)=@_;
1774: my %returnhash=();
1.800 albertel 1775: foreach my $uname (@unames) {
1776: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1777: }
1.70 www 1778: return %returnhash;
1779: }
1780:
1.1300 raeburn 1781: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70 www 1782:
1783: sub idput {
1.1300 raeburn 1784: my ($udom,$idsref,$uhom,$namespace)=@_;
1.70 www 1785: my %servers=();
1.1300 raeburn 1786: my %ids=();
1787: my %byid = ();
1788: if (ref($idsref) eq 'HASH') {
1789: %ids=%{$idsref};
1790: }
1791: if ($namespace eq '') {
1792: $namespace = 'ids';
1793: }
1.800 albertel 1794: foreach my $uname (keys(%ids)) {
1795: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300 raeburn 1796: if ($uhom eq '') {
1797: $uhom=&homeserver($uname,$udom);
1798: }
1.70 www 1799: if ($uhom ne 'no_host') {
1.800 albertel 1800: my $esc_unam=&escape($uname);
1.1300 raeburn 1801: if ($namespace eq 'ids') {
1802: my $id=&escape($ids{$uname});
1803: $id=~tr/A-Z/a-z/;
1804: my $esc_unam=&escape($uname);
1805: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70 www 1806: } else {
1.1300 raeburn 1807: my @currids = split(/,/,$ids{$uname});
1808: foreach my $id (@currids) {
1809: $byid{$uhom}{$id} .= $uname.',';
1810: }
1811: }
1812: }
1813: }
1814: if ($namespace eq 'clickers') {
1815: foreach my $server (keys(%byid)) {
1816: if (ref($byid{$server}) eq 'HASH') {
1817: foreach my $id (keys(%{$byid{$server}})) {
1818: $byid{$server} =~ s/,$//;
1819: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
1820: }
1.70 www 1821: }
1822: }
1.191 harris41 1823: }
1.800 albertel 1824: foreach my $server (keys(%servers)) {
1.1300 raeburn 1825: $servers{$server} =~ s/\&$//;
1826: if ($namespace eq 'ids') {
1827: &critical('idput:'.$udom.':'.$servers{$server},$server);
1828: } else {
1829: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
1830: }
1.191 harris41 1831: }
1.344 www 1832: }
1833:
1.1300 raeburn 1834: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231 raeburn 1835:
1836: sub iddel {
1.1300 raeburn 1837: my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231 raeburn 1838: my %result=();
1.1300 raeburn 1839: my %ids=();
1840: my %byid = ();
1841: if (ref($idshashref) eq 'HASH') {
1842: %ids=%{$idshashref};
1843: } else {
1.1231 raeburn 1844: return %result;
1845: }
1.1300 raeburn 1846: if ($namespace eq '') {
1847: $namespace = 'ids';
1848: }
1.1231 raeburn 1849: my %servers=();
1.1300 raeburn 1850: while (my ($id,$unamestr) = each(%ids)) {
1851: if ($namespace eq 'ids') {
1852: my $uhom = $uhome;
1853: if ($uhom eq '') {
1854: $uhom=&homeserver($unamestr,$udom);
1855: }
1856: if ($uhom ne 'no_host') {
1857: $servers{$uhom}.='&'.&escape($id);
1858: }
1859: } else {
1860: my @curritems = split(/,/,$ids{$id});
1861: foreach my $uname (@curritems) {
1862: my $uhom = $uhome;
1863: if ($uhom eq '') {
1864: $uhom=&homeserver($uname,$udom);
1865: }
1866: if ($uhom ne 'no_host') {
1867: $byid{$uhom}{$id} .= $uname.',';
1868: }
1869: }
1.1231 raeburn 1870: }
1.1300 raeburn 1871: }
1872: if ($namespace eq 'clickers') {
1873: foreach my $server (keys(%byid)) {
1874: if (ref($byid{$server}) eq 'HASH') {
1875: foreach my $id (keys(%{$byid{$server}})) {
1876: $byid{$server}{$id} =~ s/,$//;
1877: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
1878: }
1.1231 raeburn 1879: }
1880: }
1881: }
1882: foreach my $server (keys(%servers)) {
1.1300 raeburn 1883: $servers{$server} =~ s/\&$//;
1884: if ($namespace eq 'ids') {
1885: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1886: } elsif ($namespace eq 'clickers') {
1887: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
1888: }
1.1231 raeburn 1889: }
1890: return %result;
1891: }
1892:
1.1300 raeburn 1893: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
1894:
1895: sub updateclickers {
1896: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
1897: my %clickers;
1898: if (ref($idshashref) eq 'HASH') {
1899: %clickers=%{$idshashref};
1900: } else {
1901: return;
1902: }
1903: my $items='';
1904: foreach my $item (keys(%clickers)) {
1905: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
1906: }
1907: $items=~s/\&$//;
1908: my $request = "updateclickers:$udom:$action:$items";
1909: if ($critical) {
1910: return &critical($request,$uhome);
1911: } else {
1912: return &reply($request,$uhome);
1913: }
1914: }
1915:
1.1023 raeburn 1916: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1917: sub dump_dom {
1.1165 droeschl 1918: my ($namespace, $udom, $regexp) = @_;
1919:
1920: $udom ||= $env{'user.domain'};
1921:
1922: return () unless $udom;
1923:
1924: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1925: }
1926:
1.1023 raeburn 1927: # ------------------------------------------ get items from domain db files
1.806 raeburn 1928:
1929: sub get_dom {
1.860 raeburn 1930: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267 raeburn 1931: return if ($udom eq 'public');
1.806 raeburn 1932: my $items='';
1933: foreach my $item (@$storearr) {
1934: $items.=&escape($item).'&';
1935: }
1936: $items=~s/\&$//;
1.860 raeburn 1937: if (!$udom) {
1938: $udom=$env{'user.domain'};
1.1267 raeburn 1939: return if ($udom eq 'public');
1.860 raeburn 1940: if (defined(&domain($udom,'primary'))) {
1941: $uhome=&domain($udom,'primary');
1942: } else {
1.874 albertel 1943: undef($uhome);
1.860 raeburn 1944: }
1945: } else {
1946: if (!$uhome) {
1947: if (defined(&domain($udom,'primary'))) {
1948: $uhome=&domain($udom,'primary');
1949: }
1950: }
1951: }
1952: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344 raeburn 1953: my $rep;
1954: if ($namespace =~ /^enc/) {
1955: $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
1956: } else {
1957: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1958: }
1.866 raeburn 1959: my %returnhash;
1.875 albertel 1960: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1961: return %returnhash;
1962: }
1.806 raeburn 1963: my @pairs=split(/\&/,$rep);
1964: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1965: return @pairs;
1966: }
1967: my $i=0;
1968: foreach my $item (@$storearr) {
1969: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1970: $i++;
1971: }
1972: return %returnhash;
1973: } else {
1.880 banghart 1974: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1975: }
1976: }
1977:
1978: # -------------------------------------------- put items in domain db files
1979:
1980: sub put_dom {
1.860 raeburn 1981: my ($namespace,$storehash,$udom,$uhome)=@_;
1982: if (!$udom) {
1983: $udom=$env{'user.domain'};
1984: if (defined(&domain($udom,'primary'))) {
1985: $uhome=&domain($udom,'primary');
1986: } else {
1.874 albertel 1987: undef($uhome);
1.860 raeburn 1988: }
1989: } else {
1990: if (!$uhome) {
1991: if (defined(&domain($udom,'primary'))) {
1992: $uhome=&domain($udom,'primary');
1993: }
1994: }
1995: }
1996: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1997: my $items='';
1998: foreach my $item (keys(%$storehash)) {
1999: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
2000: }
2001: $items=~s/\&$//;
1.1344 raeburn 2002: if ($namespace =~ /^enc/) {
2003: return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
2004: } else {
2005: return &reply("putdom:$udom:$namespace:$items",$uhome);
2006: }
1.806 raeburn 2007: } else {
1.860 raeburn 2008: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 2009: }
2010: }
2011:
1.1023 raeburn 2012: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 2013: sub newput_dom {
1.1023 raeburn 2014: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 2015: my $result;
2016: if (!$udom) {
2017: $udom=$env{'user.domain'};
2018: }
1.1023 raeburn 2019: if ($udom) {
2020: my $uname = &get_domainconfiguser($udom);
2021: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 2022: }
2023: return $result;
2024: }
2025:
1.1023 raeburn 2026: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 2027: sub del_dom {
1.1023 raeburn 2028: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 2029: if (ref($storearr) eq 'ARRAY') {
2030: if (!$udom) {
2031: $udom=$env{'user.domain'};
2032: }
1.1023 raeburn 2033: if ($udom) {
2034: my $uname = &get_domainconfiguser($udom);
2035: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 2036: }
2037: }
2038: }
2039:
1.1023 raeburn 2040: # ----------------------------------construct domainconfig user for a domain
2041: sub get_domainconfiguser {
2042: my ($udom) = @_;
2043: return $udom.'-domainconfig';
2044: }
2045:
1.837 raeburn 2046: sub retrieve_inst_usertypes {
2047: my ($udom) = @_;
2048: my (%returnhash,@order);
1.989 raeburn 2049: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
2050: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2051: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 2052: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 2053: } else {
2054: if (defined(&domain($udom,'primary'))) {
2055: my $uhome=&domain($udom,'primary');
2056: my $rep=&reply("inst_usertypes:$udom",$uhome);
2057: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 2058: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 2059: return (\%returnhash,\@order);
2060: }
2061: my ($hashitems,$orderitems) = split(/:/,$rep);
2062: my @pairs=split(/\&/,$hashitems);
2063: foreach my $item (@pairs) {
2064: my ($key,$value)=split(/=/,$item,2);
2065: $key = &unescape($key);
2066: next if ($key =~ /^error: 2 /);
2067: $returnhash{$key}=&thaw_unescape($value);
2068: }
2069: my @esc_order = split(/\&/,$orderitems);
2070: foreach my $item (@esc_order) {
2071: push(@order,&unescape($item));
2072: }
2073: } else {
1.1256 raeburn 2074: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 2075: }
1.1256 raeburn 2076: return (\%returnhash,\@order);
1.837 raeburn 2077: }
2078: }
2079:
1.868 raeburn 2080: sub is_domainimage {
2081: my ($url) = @_;
1.1306 raeburn 2082: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 2083: if (&domain($1) ne '') {
2084: return '1';
2085: }
2086: }
2087: return;
2088: }
2089:
1.899 raeburn 2090: sub inst_directory_query {
2091: my ($srch) = @_;
2092: my $udom = $srch->{'srchdomain'};
2093: my %results;
2094: my $homeserver = &domain($udom,'primary');
1.909 raeburn 2095: my $outcome;
1.899 raeburn 2096: if ($homeserver ne '') {
1.904 albertel 2097: my $queryid=&reply("querysend:instdirsearch:".
2098: &escape($srch->{'srchby'}).':'.
2099: &escape($srch->{'srchterm'}).':'.
2100: &escape($srch->{'srchtype'}),$homeserver);
2101: my $host=&hostname($homeserver);
2102: if ($queryid !~/^\Q$host\E\_/) {
1.1343 raeburn 2103: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 2104: return;
2105: }
2106: my $response = &get_query_reply($queryid);
2107: my $maxtries = 5;
2108: my $tries = 1;
2109: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2110: $response = &get_query_reply($queryid);
2111: $tries ++;
2112: }
2113:
2114: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2115: if ($response eq 'unavailable') {
2116: $outcome = $response;
2117: } else {
2118: $outcome = 'ok';
2119: my @matches = split(/\n/,$response);
2120: foreach my $match (@matches) {
2121: my ($key,$value) = split(/=/,$match);
2122: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2123: }
1.899 raeburn 2124: }
2125: }
2126: }
1.909 raeburn 2127: return ($outcome,%results);
1.899 raeburn 2128: }
2129:
2130: sub usersearch {
2131: my ($srch) = @_;
2132: my $dom = $srch->{'srchdomain'};
2133: my %results;
2134: my %libserv = &all_library();
2135: my $query = 'usersearch';
2136: foreach my $tryserver (keys(%libserv)) {
2137: if (&host_domain($tryserver) eq $dom) {
2138: my $host=&hostname($tryserver);
2139: my $queryid=
1.911 raeburn 2140: &reply("querysend:".&escape($query).':'.
2141: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2142: &escape($srch->{'srchtype'}).':'.
2143: &escape($srch->{'srchterm'}),$tryserver);
2144: if ($queryid !~/^\Q$host\E\_/) {
2145: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2146: next;
1.899 raeburn 2147: }
2148: my $reply = &get_query_reply($queryid);
2149: my $maxtries = 1;
2150: my $tries = 1;
2151: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2152: $reply = &get_query_reply($queryid);
2153: $tries ++;
2154: }
2155: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2156: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2157: } else {
1.911 raeburn 2158: my @matches;
2159: if ($reply =~ /\n/) {
2160: @matches = split(/\n/,$reply);
2161: } else {
2162: @matches = split(/\&/,$reply);
2163: }
1.899 raeburn 2164: foreach my $match (@matches) {
2165: my ($uname,$udom,%userhash);
1.911 raeburn 2166: foreach my $entry (split(/:/,$match)) {
2167: my ($key,$value) =
2168: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2169: $userhash{$key} = $value;
2170: if ($key eq 'username') {
2171: $uname = $value;
2172: } elsif ($key eq 'domain') {
2173: $udom = $value;
1.911 raeburn 2174: }
1.899 raeburn 2175: }
2176: $results{$uname.':'.$udom} = \%userhash;
2177: }
2178: }
2179: }
2180: }
2181: return %results;
2182: }
2183:
1.912 raeburn 2184: sub get_instuser {
2185: my ($udom,$uname,$id) = @_;
2186: my $homeserver = &domain($udom,'primary');
2187: my ($outcome,%results);
2188: if ($homeserver ne '') {
2189: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2190: &escape($id).':'.&escape($udom),$homeserver);
2191: my $host=&hostname($homeserver);
2192: if ($queryid !~/^\Q$host\E\_/) {
2193: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2194: return;
2195: }
2196: my $response = &get_query_reply($queryid);
2197: my $maxtries = 5;
2198: my $tries = 1;
2199: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2200: $response = &get_query_reply($queryid);
2201: $tries ++;
2202: }
2203: if (!&error($response) && $response ne 'refused') {
2204: if ($response eq 'unavailable') {
2205: $outcome = $response;
2206: } else {
2207: $outcome = 'ok';
2208: my @matches = split(/\n/,$response);
2209: foreach my $match (@matches) {
2210: my ($key,$value) = split(/=/,$match);
2211: $results{&unescape($key)} = &thaw_unescape($value);
2212: }
2213: }
2214: }
2215: }
2216: my %userinfo;
2217: if (ref($results{$uname}) eq 'HASH') {
2218: %userinfo = %{$results{$uname}};
2219: }
2220: return ($outcome,%userinfo);
2221: }
2222:
1.1290 raeburn 2223: sub get_multiple_instusers {
2224: my ($udom,$users,$caller) = @_;
2225: my ($outcome,$results);
2226: if (ref($users) eq 'HASH') {
2227: my $count = keys(%{$users});
2228: my $requested = &freeze_escape($users);
2229: my $homeserver = &domain($udom,'primary');
2230: if ($homeserver ne '') {
2231: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2232: my $host=&hostname($homeserver);
2233: if ($queryid !~/^\Q$host\E\_/) {
2234: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2235: ' for host: '.$homeserver.'in domain '.$udom);
2236: return ($outcome,$results);
2237: }
2238: my $response = &get_query_reply($queryid);
2239: my $maxtries = 5;
2240: if ($count > 100) {
2241: $maxtries = 1+int($count/20);
2242: }
2243: my $tries = 1;
2244: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2245: $response = &get_query_reply($queryid);
2246: $tries ++;
2247: }
2248: if ($response eq '') {
2249: $results = {};
2250: foreach my $key (keys(%{$users})) {
2251: my ($uname,$id);
2252: if ($caller eq 'id') {
2253: $id = $key;
2254: } else {
2255: $uname = $key;
2256: }
2257: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291 raeburn 2258: $outcome = $resp;
1.1290 raeburn 2259: if ($resp eq 'ok') {
2260: %{$results} = (%{$results}, %info);
2261: } else {
2262: last;
2263: }
2264: }
2265: } elsif(!&error($response) && ($response ne 'refused')) {
2266: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2267: $outcome = $response;
2268: } else {
1.1291 raeburn 2269: ($outcome,my $userdata) = split(/=/,$response,2);
1.1290 raeburn 2270: if ($outcome eq 'ok') {
2271: $results = &thaw_unescape($userdata);
2272: }
2273: }
2274: }
2275: }
2276: }
2277: return ($outcome,$results);
2278: }
2279:
1.912 raeburn 2280: sub inst_rulecheck {
1.923 raeburn 2281: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2282: my %returnhash;
2283: if ($udom ne '') {
2284: if (ref($rules) eq 'ARRAY') {
2285: @{$rules} = map {&escape($_);} (@{$rules});
2286: my $rulestr = join(':',@{$rules});
2287: my $homeserver=&domain($udom,'primary');
2288: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2289: my $response;
2290: if ($item eq 'username') {
2291: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2292: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2293: $homeserver));
1.923 raeburn 2294: } elsif ($item eq 'id') {
2295: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2296: ':'.&escape($id).':'.$rulestr,
2297: $homeserver));
1.945 raeburn 2298: } elsif ($item eq 'selfcreate') {
2299: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2300: &escape($udom).':'.&escape($uname).
2301: ':'.$rulestr,$homeserver));
1.923 raeburn 2302: }
1.912 raeburn 2303: if ($response ne 'refused') {
2304: my @pairs=split(/\&/,$response);
2305: foreach my $item (@pairs) {
2306: my ($key,$value)=split(/=/,$item,2);
2307: $key = &unescape($key);
2308: next if ($key =~ /^error: 2 /);
2309: $returnhash{$key}=&thaw_unescape($value);
2310: }
2311: }
2312: }
2313: }
2314: }
2315: return %returnhash;
2316: }
2317:
2318: sub inst_userrules {
1.923 raeburn 2319: my ($udom,$check) = @_;
1.912 raeburn 2320: my (%ruleshash,@ruleorder);
2321: if ($udom ne '') {
2322: my $homeserver=&domain($udom,'primary');
2323: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2324: my $response;
2325: if ($check eq 'id') {
2326: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2327: $homeserver);
1.943 raeburn 2328: } elsif ($check eq 'email') {
2329: $response=&reply('instemailrules:'.&escape($udom),
2330: $homeserver);
1.923 raeburn 2331: } else {
2332: $response=&reply('instuserrules:'.&escape($udom),
2333: $homeserver);
2334: }
1.912 raeburn 2335: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2336: ($response ne 'unknown_cmd') &&
1.912 raeburn 2337: ($response ne 'no_such_host')) {
2338: my ($hashitems,$orderitems) = split(/:/,$response);
2339: my @pairs=split(/\&/,$hashitems);
2340: foreach my $item (@pairs) {
2341: my ($key,$value)=split(/=/,$item,2);
2342: $key = &unescape($key);
2343: next if ($key =~ /^error: 2 /);
2344: $ruleshash{$key}=&thaw_unescape($value);
2345: }
2346: my @esc_order = split(/\&/,$orderitems);
2347: foreach my $item (@esc_order) {
2348: push(@ruleorder,&unescape($item));
2349: }
2350: }
2351: }
2352: }
2353: return (\%ruleshash,\@ruleorder);
2354: }
2355:
1.976 raeburn 2356: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2357:
2358: sub get_domain_defaults {
1.1240 raeburn 2359: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2360: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2361: my $cachetime = 60*60*24;
1.1240 raeburn 2362: unless ($ignore_cache) {
2363: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2364: if (defined($cached)) {
2365: if (ref($result) eq 'HASH') {
2366: return %{$result};
2367: }
1.943 raeburn 2368: }
2369: }
2370: my %domdefaults;
2371: my %domconfig =
1.989 raeburn 2372: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2373: 'requestcourses','inststatus',
1.1183 raeburn 2374: 'coursedefaults','usersessions',
1.1258 raeburn 2375: 'requestauthor','selfenrollment',
1.1320 raeburn 2376: 'coursecategories','ssl','autoenroll',
1.1332 raeburn 2377: 'trust','helpsettings'],$domain);
1.1305 raeburn 2378: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2379: if (ref($domconfig{'defaults'}) eq 'HASH') {
2380: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2381: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2382: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2383: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2384: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2385: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340 raeburn 2386: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2387: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2388: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943 raeburn 2389: } else {
2390: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2391: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2392: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2393: }
1.976 raeburn 2394: if (ref($domconfig{'quotas'}) eq 'HASH') {
2395: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2396: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2397: } else {
2398: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2399: }
1.1177 raeburn 2400: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2401: foreach my $item (@usertools) {
2402: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2403: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2404: }
2405: }
1.1229 raeburn 2406: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2407: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2408: }
1.976 raeburn 2409: }
1.985 raeburn 2410: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 raeburn 2411: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2412: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2413: }
2414: }
1.1183 raeburn 2415: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2416: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2417: }
1.989 raeburn 2418: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2419: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2420: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2421: }
2422: }
1.1047 raeburn 2423: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2424: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2425: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2426: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2427: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2428: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2429: }
1.1254 raeburn 2430: foreach my $type (@coursetypes) {
2431: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2432: unless ($type eq 'community') {
2433: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2434: }
2435: }
2436: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2437: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2438: }
1.1277 raeburn 2439: if ($domdefaults{'postsubmit'} eq 'on') {
2440: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2441: $domdefaults{$type.'postsubtimeout'} =
2442: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2443: }
2444: }
1.1230 raeburn 2445: }
1.1286 raeburn 2446: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2447: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2448: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2449: if (@clonecodes) {
2450: $domdefaults{'canclone'} = join('+',@clonecodes);
2451: }
2452: }
2453: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2454: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2455: }
1.1047 raeburn 2456: }
1.1073 raeburn 2457: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2458: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2459: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2460: }
2461: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2462: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2463: }
1.1279 raeburn 2464: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2465: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2466: }
1.1073 raeburn 2467: }
1.1254 raeburn 2468: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2469: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2470: my @settings = ('types','registered','enroll_dates','access_dates','section',
2471: 'approval','limit');
2472: foreach my $type (@coursetypes) {
2473: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2474: my @mgrdc = ();
2475: foreach my $item (@settings) {
2476: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2477: push(@mgrdc,$item);
2478: }
2479: }
2480: if (@mgrdc) {
2481: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2482: }
2483: }
2484: }
2485: }
2486: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2487: foreach my $type (@coursetypes) {
2488: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2489: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2490: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2491: }
2492: }
2493: }
2494: }
2495: }
1.1258 raeburn 2496: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2497: $domdefaults{'catauth'} = 'std';
2498: $domdefaults{'catunauth'} = 'std';
2499: if ($domconfig{'coursecategories'}{'auth'}) {
2500: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2501: }
2502: if ($domconfig{'coursecategories'}{'unauth'}) {
2503: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2504: }
2505: }
1.1315 raeburn 2506: if (ref($domconfig{'ssl'}) eq 'HASH') {
2507: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2508: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2509: }
1.1338 raeburn 2510: if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
2511: $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
2512: }
2513: if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
2514: $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315 raeburn 2515: }
2516: }
1.1320 raeburn 2517: if (ref($domconfig{'trust'}) eq 'HASH') {
2518: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2519: foreach my $prefix (@prefixes) {
2520: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2521: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2522: }
2523: }
2524: }
1.1314 raeburn 2525: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2526: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2527: }
1.1332 raeburn 2528: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2529: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2530: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2531: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2532: }
2533: }
1.1219 raeburn 2534: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2535: return %domdefaults;
2536: }
2537:
1.1311 raeburn 2538: sub course_portal_url {
2539: my ($cnum,$cdom) = @_;
2540: my $chome = &homeserver($cnum,$cdom);
2541: my $hostname = &hostname($chome);
2542: my $protocol = $protocol{$chome};
2543: $protocol = 'http' if ($protocol ne 'https');
2544: my %domdefaults = &get_domain_defaults($cdom);
2545: my $firsturl;
2546: if ($domdefaults{'portal_def'}) {
2547: $firsturl = $domdefaults{'portal_def'};
2548: } else {
2549: $firsturl = $protocol.'://'.$hostname;
2550: }
2551: return $firsturl;
2552: }
2553:
1.344 www 2554: # --------------------------------------------------- Assign a key to a student
2555:
2556: sub assign_access_key {
1.364 www 2557: #
2558: # a valid key looks like uname:udom#comments
2559: # comments are being appended
2560: #
1.498 www 2561: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2562: $kdom=
1.620 albertel 2563: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2564: $knum=
1.620 albertel 2565: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2566: $cdom=
1.620 albertel 2567: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2568: $cnum=
1.620 albertel 2569: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2570: $udom=$env{'user.name'} unless (defined($udom));
2571: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2572: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2573: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2574: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2575: # assigned to this person
2576: # - this should not happen,
1.345 www 2577: # unless something went wrong
2578: # the first time around
2579: # ready to assign
1.364 www 2580: $logentry=$1.'; '.$logentry;
1.496 www 2581: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2582: $kdom,$knum) eq 'ok') {
1.345 www 2583: # key now belongs to user
1.346 www 2584: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2585: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2586: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2587: return 'ok';
2588: } else {
2589: return
2590: 'error: Count not permanently assign key, will need to be re-entered later.';
2591: }
2592: } else {
2593: return 'error: Could not assign key, try again later.';
2594: }
1.364 www 2595: } elsif (!$existing{$ckey}) {
1.345 www 2596: # the key does not exist
2597: return 'error: The key does not exist';
2598: } else {
2599: # the key is somebody else's
2600: return 'error: The key is already in use';
2601: }
1.344 www 2602: }
2603:
1.364 www 2604: # ------------------------------------------ put an additional comment on a key
2605:
2606: sub comment_access_key {
2607: #
2608: # a valid key looks like uname:udom#comments
2609: # comments are being appended
2610: #
2611: my ($ckey,$cdom,$cnum,$logentry)=@_;
2612: $cdom=
1.620 albertel 2613: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2614: $cnum=
1.620 albertel 2615: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2616: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2617: if ($existing{$ckey}) {
2618: $existing{$ckey}.='; '.$logentry;
2619: # ready to assign
1.367 www 2620: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2621: $cdom,$cnum) eq 'ok') {
2622: return 'ok';
2623: } else {
2624: return 'error: Count not store comment.';
2625: }
2626: } else {
2627: # the key does not exist
2628: return 'error: The key does not exist';
2629: }
2630: }
2631:
1.344 www 2632: # ------------------------------------------------------ Generate a set of keys
2633:
2634: sub generate_access_keys {
1.364 www 2635: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2636: $cdom=
1.620 albertel 2637: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2638: $cnum=
1.620 albertel 2639: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2640: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2641: unless (($cdom) && ($cnum)) { return 0; }
2642: if ($number>10000) { return 0; }
2643: sleep(2); # make sure don't get same seed twice
2644: srand(time()^($$+($$<<15))); # from "Programming Perl"
2645: my $total=0;
2646: for (my $i=1;$i<=$number;$i++) {
2647: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2648: sprintf("%lx",int(100000*rand)).'-'.
2649: sprintf("%lx",int(100000*rand));
2650: $newkey=~s/1/g/g; # folks mix up 1 and l
2651: $newkey=~s/0/h/g; # and also 0 and O
2652: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2653: if ($existing{$newkey}) {
2654: $i--;
2655: } else {
1.364 www 2656: if (&put('accesskeys',
2657: { $newkey => '# generated '.localtime().
1.620 albertel 2658: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2659: '; '.$logentry },
2660: $cdom,$cnum) eq 'ok') {
1.344 www 2661: $total++;
2662: }
2663: }
2664: }
1.620 albertel 2665: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2666: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2667: return $total;
2668: }
2669:
2670: # ------------------------------------------------------- Validate an accesskey
2671:
2672: sub validate_access_key {
2673: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2674: $cdom=
1.620 albertel 2675: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2676: $cnum=
1.620 albertel 2677: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2678: $udom=$env{'user.domain'} unless (defined($udom));
2679: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2680: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2681: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2682: }
2683:
2684: # ------------------------------------- Find the section of student in a course
1.652 albertel 2685: sub devalidate_getsection_cache {
2686: my ($udom,$unam,$courseid)=@_;
2687: my $hashid="$udom:$unam:$courseid";
2688: &devalidate_cache_new('getsection',$hashid);
2689: }
1.298 matthew 2690:
1.815 albertel 2691: sub courseid_to_courseurl {
2692: my ($courseid) = @_;
2693: #already url style courseid
2694: return $courseid if ($courseid =~ m{^/});
2695:
2696: if (exists($env{'course.'.$courseid.'.num'})) {
2697: my $cnum = $env{'course.'.$courseid.'.num'};
2698: my $cdom = $env{'course.'.$courseid.'.domain'};
2699: return "/$cdom/$cnum";
2700: }
2701:
2702: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2703: if (exists($courseinfo{'num'})) {
2704: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2705: }
2706:
2707: return undef;
2708: }
2709:
1.298 matthew 2710: sub getsection {
2711: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2712: my $cachetime=1800;
1.551 albertel 2713:
2714: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2715: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2716: if (defined($cached)) { return $result; }
2717:
1.298 matthew 2718: my %Pending;
2719: my %Expired;
2720: #
2721: # Each role can either have not started yet (pending), be active,
2722: # or have expired.
2723: #
2724: # If there is an active role, we are done.
2725: #
2726: # If there is more than one role which has not started yet,
2727: # choose the one which will start sooner
2728: # If there is one role which has not started yet, return it.
2729: #
2730: # If there is more than one expired role, choose the one which ended last.
2731: # If there is a role which has expired, return it.
2732: #
1.815 albertel 2733: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2734: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2735: foreach my $key (keys(%roleshash)) {
1.479 albertel 2736: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2737: my $section=$1;
2738: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2739: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2740: my $now=time;
1.548 albertel 2741: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2742: $Expired{$end}=$section;
2743: next;
2744: }
1.548 albertel 2745: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2746: $Pending{$start}=$section;
2747: next;
2748: }
1.599 albertel 2749: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2750: }
2751: #
2752: # Presumedly there will be few matching roles from the above
2753: # loop and the sorting time will be negligible.
2754: if (scalar(keys(%Pending))) {
2755: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2756: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2757: }
2758: if (scalar(keys(%Expired))) {
2759: my @sorted = sort {$a <=> $b} keys(%Expired);
2760: my $time = pop(@sorted);
1.599 albertel 2761: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2762: }
1.599 albertel 2763: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2764: }
1.70 www 2765:
1.599 albertel 2766: sub save_cache {
2767: &purge_remembered();
1.722 albertel 2768: #&Apache::loncommon::validate_page();
1.620 albertel 2769: undef(%env);
1.780 albertel 2770: undef($env_loaded);
1.599 albertel 2771: }
1.452 albertel 2772:
1.599 albertel 2773: my $to_remember=-1;
2774: my %remembered;
2775: my %accessed;
2776: my $kicks=0;
2777: my $hits=0;
1.849 albertel 2778: sub make_key {
2779: my ($name,$id) = @_;
1.872 albertel 2780: if (length($id) > 65
2781: && length(&escape($id)) > 200) {
2782: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2783: }
1.849 albertel 2784: return &escape($name.':'.$id);
2785: }
2786:
1.599 albertel 2787: sub devalidate_cache_new {
2788: my ($name,$id,$debug) = @_;
2789: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319 damieng 2790: my $remembered_id=$name.':'.$id;
1.849 albertel 2791: $id=&make_key($name,$id);
1.599 albertel 2792: $memcache->delete($id);
1.1319 damieng 2793: delete($remembered{$remembered_id});
2794: delete($accessed{$remembered_id});
1.599 albertel 2795: }
2796:
2797: sub is_cached_new {
2798: my ($name,$id,$debug) = @_;
1.1319 damieng 2799: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
2800: if (exists($remembered{$remembered_id})) {
2801: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2802: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2803: $hits++;
1.1319 damieng 2804: return ($remembered{$remembered_id},1);
1.599 albertel 2805: }
1.1319 damieng 2806: $id=&make_key($name,$id);
1.599 albertel 2807: my $value = $memcache->get($id);
2808: if (!(defined($value))) {
2809: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2810: return (undef,undef);
1.416 albertel 2811: }
1.599 albertel 2812: if ($value eq '__undef__') {
2813: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2814: $value=undef;
2815: }
1.1319 damieng 2816: &make_room($remembered_id,$value,$debug);
1.599 albertel 2817: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2818: return ($value,1);
2819: }
2820:
2821: sub do_cache_new {
2822: my ($name,$id,$value,$time,$debug) = @_;
1.1319 damieng 2823: my $remembered_id=$name.':'.$id;
1.849 albertel 2824: $id=&make_key($name,$id);
1.599 albertel 2825: my $setvalue=$value;
2826: if (!defined($setvalue)) {
2827: $setvalue='__undef__';
2828: }
1.623 albertel 2829: if (!defined($time) ) {
2830: $time=600;
2831: }
1.599 albertel 2832: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2833: my $result = $memcache->set($id,$setvalue,$time);
2834: if (! $result) {
1.872 albertel 2835: &logthis("caching of id -> $id failed");
1.910 albertel 2836: $memcache->disconnect_all();
1.872 albertel 2837: }
1.600 albertel 2838: # need to make a copy of $value
1.1319 damieng 2839: &make_room($remembered_id,$value,$debug);
1.599 albertel 2840: return $value;
2841: }
2842:
2843: sub make_room {
1.1319 damieng 2844: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2845:
1.1319 damieng 2846: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2847: : $value;
1.599 albertel 2848: if ($to_remember<0) { return; }
1.1319 damieng 2849: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2850: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2851: my $to_kick;
2852: my $max_time=0;
2853: foreach my $other (keys(%accessed)) {
2854: if (&tv_interval($accessed{$other}) > $max_time) {
2855: $to_kick=$other;
2856: $max_time=&tv_interval($accessed{$other});
2857: }
2858: }
2859: delete($remembered{$to_kick});
2860: delete($accessed{$to_kick});
2861: $kicks++;
2862: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2863: return;
2864: }
2865:
1.599 albertel 2866: sub purge_remembered {
1.604 albertel 2867: #&logthis("Tossing ".scalar(keys(%remembered)));
2868: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2869: undef(%remembered);
2870: undef(%accessed);
1.428 albertel 2871: }
1.70 www 2872: # ------------------------------------- Read an entry from a user's environment
2873:
2874: sub userenvironment {
2875: my ($udom,$unam,@what)=@_;
1.976 raeburn 2876: my $items;
2877: foreach my $item (@what) {
2878: $items.=&escape($item).'&';
2879: }
2880: $items=~s/\&$//;
1.70 www 2881: my %returnhash=();
1.1009 raeburn 2882: my $uhome = &homeserver($unam,$udom);
2883: unless ($uhome eq 'no_host') {
2884: my @answer=split(/\&/,
2885: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2886: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2887: return %returnhash;
2888: }
1.1009 raeburn 2889: my $i;
2890: for ($i=0;$i<=$#what;$i++) {
2891: $returnhash{$what[$i]}=&unescape($answer[$i]);
2892: }
1.70 www 2893: }
2894: return %returnhash;
1.1 albertel 2895: }
2896:
1.617 albertel 2897: # ---------------------------------------------------------- Get a studentphoto
2898: sub studentphoto {
2899: my ($udom,$unam,$ext) = @_;
2900: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2901: if (defined($env{'request.course.id'})) {
1.708 raeburn 2902: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2903: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2904: return(&retrievestudentphoto($udom,$unam,$ext));
2905: } else {
2906: my ($result,$perm_reqd)=
1.707 albertel 2907: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2908: if ($result eq 'ok') {
2909: if (!($perm_reqd eq 'yes')) {
2910: return(&retrievestudentphoto($udom,$unam,$ext));
2911: }
2912: }
2913: }
2914: }
2915: } else {
2916: my ($result,$perm_reqd) =
1.707 albertel 2917: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2918: if ($result eq 'ok') {
2919: if (!($perm_reqd eq 'yes')) {
2920: return(&retrievestudentphoto($udom,$unam,$ext));
2921: }
2922: }
2923: }
2924: return '/adm/lonKaputt/lonlogo_broken.gif';
2925: }
2926:
2927: sub retrievestudentphoto {
2928: my ($udom,$unam,$ext,$type) = @_;
2929: my $home=&Apache::lonnet::homeserver($unam,$udom);
2930: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2931: if ($ret eq 'ok') {
2932: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2933: if ($type eq 'thumbnail') {
2934: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2935: }
2936: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2937: return $tokenurl;
2938: } else {
2939: if ($type eq 'thumbnail') {
2940: return '/adm/lonKaputt/genericstudent_tn.gif';
2941: } else {
2942: return '/adm/lonKaputt/lonlogo_broken.gif';
2943: }
1.617 albertel 2944: }
2945: }
2946:
1.263 www 2947: # -------------------------------------------------------------------- New chat
2948:
2949: sub chatsend {
1.724 raeburn 2950: my ($newentry,$anon,$group)=@_;
1.620 albertel 2951: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2952: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2953: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2954: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2955: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2956: &escape($newentry)).':'.$group,$chome);
1.292 www 2957: }
2958:
2959: # ------------------------------------------ Find current version of a resource
2960:
2961: sub getversion {
2962: my $fname=&clutter(shift);
1.1189 raeburn 2963: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2964: return ¤tversion(&filelocation('',$fname));
2965: }
2966:
2967: sub currentversion {
2968: my $fname=shift;
2969: my $author=$fname;
2970: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2971: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2972: my $home=&homeserver($uname,$udom);
1.292 www 2973: if ($home eq 'no_host') {
2974: return -1;
2975: }
1.1112 www 2976: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2977: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2978: return -1;
2979: }
1.1112 www 2980: return $answer;
1.263 www 2981: }
2982:
1.1111 www 2983: #
2984: # Return special version number of resource if set by override, empty otherwise
2985: #
2986: sub usedversion {
2987: my $fname=shift;
2988: unless ($fname) { $fname=$env{'request.uri'}; }
2989: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2990: if ($urlversion) { return $urlversion; }
2991: return '';
2992: }
2993:
1.1 albertel 2994: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2995:
1.1 albertel 2996: sub subscribe {
2997: my $fname=shift;
1.761 raeburn 2998: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2999: $fname=~s/[\n\r]//g;
1.1 albertel 3000: my $author=$fname;
3001: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3002: my ($udom,$uname)=split(/\//,$author);
3003: my $home=homeserver($uname,$udom);
1.335 albertel 3004: if ($home eq 'no_host') {
3005: return 'not_found';
1.1 albertel 3006: }
3007: my $answer=reply("sub:$fname",$home);
1.64 www 3008: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3009: $answer.=' by '.$home;
3010: }
1.1 albertel 3011: return $answer;
3012: }
3013:
1.8 www 3014: # -------------------------------------------------------------- Replicate file
3015:
3016: sub repcopy {
3017: my $filename=shift;
1.23 www 3018: $filename=~s/\/+/\//g;
1.1142 raeburn 3019: my $londocroot = $perlvar{'lonDocRoot'};
3020: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3021: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3022: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3023: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3024: return &repcopy_userfile($filename);
3025: }
1.532 albertel 3026: $filename=~s/[\n\r]//g;
1.8 www 3027: my $transname="$filename.in.transfer";
1.828 www 3028: # FIXME: this should flock
1.607 raeburn 3029: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3030: my $remoteurl=subscribe($filename);
1.64 www 3031: if ($remoteurl =~ /^con_lost by/) {
3032: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3033: return 'unavailable';
1.8 www 3034: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3035: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3036: return 'not_found';
1.64 www 3037: } elsif ($remoteurl =~ /^rejected by/) {
3038: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3039: return 'forbidden';
1.20 www 3040: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3041: return 'ok';
1.8 www 3042: } else {
1.290 www 3043: my $author=$filename;
3044: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3045: my ($udom,$uname)=split(/\//,$author);
3046: my $home=homeserver($uname,$udom);
3047: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3048: my @parts=split(/\//,$filename);
3049: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3050: if ($path ne "$londocroot/res") {
1.8 www 3051: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3052: return 'bad_request';
1.8 www 3053: }
3054: my $count;
3055: for ($count=5;$count<$#parts;$count++) {
3056: $path.="/$parts[$count]";
3057: if ((-e $path)!=1) {
3058: mkdir($path,0777);
3059: }
3060: }
3061: my $request=new HTTP::Request('GET',"$remoteurl");
1.1345 raeburn 3062: my $response;
3063: if ($remoteurl =~ m{/raw/}) {
3064: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
3065: } else {
3066: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
3067: }
1.8 www 3068: if ($response->is_error()) {
3069: unlink($transname);
3070: my $message=$response->status_line;
1.672 albertel 3071: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3072: ." LWP get: $message: $filename</font>");
1.607 raeburn 3073: return 'unavailable';
1.8 www 3074: } else {
1.16 www 3075: if ($remoteurl!~/\.meta$/) {
3076: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345 raeburn 3077: my $mresponse;
3078: if ($remoteurl =~ m{/raw/}) {
3079: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
3080: } else {
3081: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
3082: }
1.16 www 3083: if ($mresponse->is_error()) {
3084: unlink($filename.'.meta');
3085: &logthis(
1.672 albertel 3086: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3087: }
3088: }
1.8 www 3089: rename($transname,$filename);
1.607 raeburn 3090: return 'ok';
1.8 www 3091: }
1.290 www 3092: }
1.8 www 3093: }
1.330 www 3094: }
3095:
3096: # ------------------------------------------------ Get server side include body
3097: sub ssi_body {
1.381 albertel 3098: my ($filelink,%form)=@_;
1.606 matthew 3099: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3100: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3101: }
1.953 www 3102: my $output='';
3103: my $response;
1.980 raeburn 3104: if ($filelink=~/^https?\:/) {
1.954 raeburn 3105: ($output,$response)=&externalssi($filelink);
1.953 www 3106: } else {
1.1004 droeschl 3107: $filelink .= $filelink=~/\?/ ? '&' : '?';
3108: $filelink .= 'inhibitmenu=yes';
1.953 www 3109: ($output,$response)=&ssi($filelink,%form);
3110: }
1.778 albertel 3111: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3112: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3113: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3114: if (wantarray) {
3115: return ($output, $response);
3116: } else {
3117: return $output;
3118: }
1.8 www 3119: }
3120:
1.15 www 3121: # --------------------------------------------------------- Server Side Include
3122:
1.782 albertel 3123: sub absolute_url {
3124: my ($host_name) = @_;
3125: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3126: if ($host_name eq '') {
3127: $host_name = $ENV{'SERVER_NAME'};
3128: }
3129: return $protocol.$host_name;
3130: }
3131:
1.942 foxr 3132: #
3133: # Server side include.
3134: # Parameters:
3135: # fn Possibly encrypted resource name/id.
3136: # form Hash that describes how the rendering should be done
3137: # and other things.
1.944 foxr 3138: # Returns:
1.950 raeburn 3139: # Scalar context: The content of the response.
3140: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3141: #
1.15 www 3142: sub ssi {
3143:
1.944 foxr 3144: my ($fn,%form)=@_;
1.23 www 3145: my $request;
1.711 albertel 3146:
3147: $form{'no_update_last_known'}=1;
1.895 albertel 3148: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3149: if (%form) {
1.782 albertel 3150: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272 droeschl 3151: $request->content(join('&',map {
3152: my $name = escape($_);
3153: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3154: ? join("&$name=", map {escape($_) } @{$form{$_}})
3155: : &escape($form{$_}) );
3156: } keys(%form)));
1.23 www 3157: } else {
1.782 albertel 3158: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 3159: }
3160:
1.15 www 3161: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345 raeburn 3162: my $lonhost = $perlvar{'lonHostID'};
3163: my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar);
1.1182 foxr 3164:
1.944 foxr 3165: if (wantarray) {
1.1345 raeburn 3166: return ($response->content, $response);
1.944 foxr 3167: } else {
1.1345 raeburn 3168: return $response->content;
1.942 foxr 3169: }
1.324 www 3170: }
3171:
3172: sub externalssi {
3173: my ($url)=@_;
3174: my $request=new HTTP::Request('GET',$url);
1.1345 raeburn 3175: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954 raeburn 3176: if (wantarray) {
3177: return ($response->content, $response);
3178: } else {
3179: return $response->content;
3180: }
1.15 www 3181: }
1.254 www 3182:
1.1354 raeburn 3183:
3184: # If the local copy of a replicated resource is outdated, trigger a
3185: # connection from the homeserver to flush the delayed queue. If no update
3186: # happens, remove local copies of outdated resource (and corresponding
3187: # metadata file).
3188:
1.1352 raeburn 3189: sub remove_stale_resfile {
3190: my ($url) = @_;
1.1354 raeburn 3191: my $removed;
1.1352 raeburn 3192: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3193: my $audom = $1;
3194: my $auname = $2;
1.1353 raeburn 3195: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352 raeburn 3196: my $homeserver = &homeserver($auname,$audom);
3197: unless (($homeserver eq 'no_host') ||
3198: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3199: my $fname = &filelocation('',$url);
3200: if (-e $fname) {
3201: my $protocol = $protocol{$homeserver};
3202: $protocol = 'http' if ($protocol ne 'https');
3203: my $hostname = &hostname($homeserver);
3204: if ($hostname) {
3205: my $uri = &declutter($url);
3206: my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
3207: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
3208: if ($response->is_success()) {
3209: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3210: my $locmodtime = (stat($fname))[9];
3211: if ($locmodtime < $remmodtime) {
1.1354 raeburn 3212: my $stale;
3213: my $answer = &reply('pong',$homeserver);
3214: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3215: sleep(0.2);
3216: $locmodtime = (stat($fname))[9];
3217: if ($locmodtime < $remmodtime) {
3218: my $posstransfer = $fname.'.in.transfer';
3219: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3220: $removed = 1;
3221: } else {
3222: $stale = 1;
3223: }
3224: } else {
3225: $removed = 1;
3226: }
3227: } else {
3228: $stale = 1;
3229: }
3230: if ($stale) {
3231: unlink($fname);
3232: if ($uri!~/\.meta$/) {
3233: unlink($fname.'.meta');
3234: }
3235: &reply("unsub:$fname",$homeserver);
3236: $removed = 1;
1.1352 raeburn 3237: }
3238: }
3239: }
3240: }
3241: }
3242: }
3243: }
3244: }
1.1354 raeburn 3245: return $removed;
1.1352 raeburn 3246: }
3247:
1.492 albertel 3248: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3249:
3250: sub allowuploaded {
3251: my ($srcurl,$url)=@_;
3252: $url=&clutter(&declutter($url));
3253: my $dir=$url;
3254: $dir=~s/\/[^\/]+$//;
3255: my %httpref=();
3256: my $httpurl=&hreflocation('',$url);
3257: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3258: &Apache::lonnet::appenv(\%httpref);
1.254 www 3259: }
1.477 raeburn 3260:
1.1193 raeburn 3261: #
3262: # Determine if the current user should be able to edit a particular resource,
3263: # when viewing in course context.
3264: # (a) When viewing resource used to determine if "Edit" item is included in
3265: # Functions.
3266: # (b) When displaying folder contents in course editor, used to determine if
3267: # "Edit" link will be displayed alongside resource.
3268: #
1.1196 raeburn 3269: # input: six args -- filename (decluttered), course number, course domain,
3270: # url, symb (if registered) and group (if this is a group
3271: # item -- e.g., bulletin board, group page etc.).
3272: # output: array of five scalars --
1.1193 raeburn 3273: # $cfile -- url for file editing if editable on current server
3274: # $home -- homeserver of resource (i.e., for author if published,
3275: # or course if uploaded.).
3276: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 3277: # $forceedit -- 1 if icon/link should be to go to edit mode
3278: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 3279: #
3280:
3281: sub can_edit_resource {
1.1194 raeburn 3282: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3283: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3284: #
3285: # For aboutme pages user can only edit his/her own.
3286: #
1.1199 raeburn 3287: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 3288: my ($sdom,$sname) = ($1,$2);
3289: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3290: $home = $env{'user.home'};
3291: $cfile = $resurl;
3292: if ($env{'form.forceedit'}) {
3293: $forceview = 1;
3294: } else {
3295: $forceedit = 1;
3296: }
3297: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3298: } else {
3299: return;
3300: }
3301: }
3302:
3303: if ($env{'request.course.id'}) {
3304: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3305: if ($group ne '') {
3306: # if this is a group homepage or group bulletin board, check group privs
3307: my $allowed = 0;
1.1197 raeburn 3308: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3309: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3310: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3311: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3312: $allowed = 1;
3313: }
1.1197 raeburn 3314: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3315: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3316: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3317: $allowed = 1;
3318: }
3319: }
3320: if ($allowed) {
3321: $home=&homeserver($cnum,$cdom);
3322: if ($env{'form.forceedit'}) {
3323: $forceview = 1;
3324: } else {
3325: $forceedit = 1;
3326: }
3327: $cfile = $resurl;
3328: } else {
3329: return;
3330: }
3331: } else {
1.1208 raeburn 3332: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3333: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3334: return;
3335: }
3336: } elsif (!$crsedit) {
1.1194 raeburn 3337: #
3338: # No edit allowed where CC has switched to student role.
3339: #
3340: return;
3341: }
3342: }
3343: }
3344:
1.1193 raeburn 3345: if ($file ne '') {
3346: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3347: if (&is_course_upload($file,$cnum,$cdom)) {
3348: $uploaded = 1;
3349: $incourse = 1;
1.1193 raeburn 3350: if ($file =~/\.(htm|html|css|js|txt)$/) {
3351: $cfile = &hreflocation('',$file);
1.1201 raeburn 3352: if ($env{'form.forceedit'}) {
3353: $forceview = 1;
3354: } else {
3355: $forceedit = 1;
3356: }
1.1194 raeburn 3357: }
3358: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3359: $incourse = 1;
3360: if ($env{'form.forceedit'}) {
3361: $forceview = 1;
3362: } else {
3363: $forceedit = 1;
3364: }
3365: $cfile = $resurl;
3366: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3367: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3368: $incourse = 1;
3369: if ($env{'form.forceedit'}) {
3370: $forceview = 1;
3371: } else {
3372: $forceedit = 1;
3373: }
3374: $cfile = $resurl;
1.1199 raeburn 3375: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3376: $incourse = 1;
3377: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3378: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3379: $incourse = 1;
1.1199 raeburn 3380: if ($env{'form.forceedit'}) {
3381: $forceview = 1;
3382: } else {
3383: $forceedit = 1;
3384: }
3385: $cfile = $resurl;
1.1343 raeburn 3386: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3387: $incourse = 1;
3388: if ($env{'form.forceedit'}) {
3389: $forceview = 1;
3390: } else {
3391: $forceedit = 1;
3392: }
3393: $cfile = $resurl;
1.1208 raeburn 3394: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3395: $incourse = 1;
3396: if ($env{'form.forceedit'}) {
3397: $forceview = 1;
3398: } else {
3399: $forceedit = 1;
3400: }
3401: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3402: }
3403: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3404: my $template = '/res/lib/templates/simpleproblem.problem';
3405: if (&is_on_map($template)) {
3406: $incourse = 1;
3407: $forceview = 1;
3408: $cfile = $template;
1.1193 raeburn 3409: }
1.1199 raeburn 3410: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3411: $incourse = 1;
3412: if ($env{'form.forceedit'}) {
3413: $forceview = 1;
3414: } else {
3415: $forceedit = 1;
3416: }
3417: $cfile = $resurl;
1.1343 raeburn 3418: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298 raeburn 3419: $incourse = 1;
3420: if ($env{'form.forceedit'}) {
3421: $forceview = 1;
3422: } else {
3423: $forceedit = 1;
3424: }
3425: $cfile = $resurl;
1.1199 raeburn 3426: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3427: $incourse = 1;
3428: $forceview = 1;
3429: if ($symb) {
3430: my ($map,$id,$res)=&decode_symb($symb);
3431: $env{'request.symb'} = $symb;
3432: $cfile = &clutter($res);
3433: } else {
3434: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3435: my $escfile = &unescape($cfile);
1.1343 raeburn 3436: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3437: $cfile = '/adm/wrapper'.$escfile;
3438: } else {
3439: $escfile =~ s{^http://}{};
3440: $cfile = &escape("/adm/wrapper/ext/$escfile");
3441: }
1.1199 raeburn 3442: }
1.1234 raeburn 3443: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3444: if ($env{'form.forceedit'}) {
3445: $forceview = 1;
3446: } else {
3447: $forceedit = 1;
3448: }
3449: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 3450: }
3451: }
1.1194 raeburn 3452: if ($uploaded || $incourse) {
3453: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 3454: } elsif ($file !~ m{/$}) {
1.1193 raeburn 3455: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3456: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3457: # Check that the user has permission to edit this resource
3458: my $setpriv = 1;
3459: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3460: if (defined($cfudom)) {
3461: $home=&homeserver($cfuname,$cfudom);
3462: $cfile=$file;
3463: }
3464: }
1.1194 raeburn 3465: if (($cfile ne '') && (!$incourse || $uploaded) &&
3466: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 3467: my @ids=¤t_machine_ids();
3468: unless (grep(/^\Q$home\E$/,@ids)) {
3469: $switchserver=1;
3470: }
3471: }
3472: }
1.1194 raeburn 3473: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 3474: }
3475:
3476: sub is_course_upload {
3477: my ($file,$cnum,$cdom) = @_;
3478: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3479: $uploadpath =~ s{^\/}{};
1.1201 raeburn 3480: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3481: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 3482: return 1;
3483: }
3484: return;
3485: }
3486:
1.1194 raeburn 3487: sub in_course {
1.1195 raeburn 3488: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3489: if ($hideprivileged) {
3490: my $skipuser;
1.1219 raeburn 3491: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3492: my @possdoms = ($cdom);
3493: if ($coursehash{'checkforpriv'}) {
3494: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3495: }
3496: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3497: $skipuser = 1;
3498: if ($coursehash{'nothideprivileged'}) {
3499: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3500: my $user;
3501: if ($item =~ /:/) {
3502: $user = $item;
3503: } else {
3504: $user = join(':',split(/[\@]/,$item));
3505: }
3506: if ($user eq $uname.':'.$udom) {
3507: undef($skipuser);
3508: last;
3509: }
3510: }
3511: }
3512: if ($skipuser) {
3513: return 0;
3514: }
3515: }
3516: }
1.1194 raeburn 3517: $type ||= 'any';
3518: if (!defined($cdom) || !defined($cnum)) {
3519: my $cid = $env{'request.course.id'};
3520: $cdom = $env{'course.'.$cid.'.domain'};
3521: $cnum = $env{'course.'.$cid.'.num'};
3522: }
3523: my $typesref;
1.1195 raeburn 3524: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3525: $typesref = ['active','previous','future'];
3526: } elsif ($type eq 'previous' || $type eq 'future') {
3527: $typesref = [$type];
3528: }
3529: my %roles = &get_my_roles($uname,$udom,'userroles',
3530: $typesref,undef,[$cdom]);
3531: my ($tmp) = keys(%roles);
3532: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3533: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3534: if (@course_roles > 0) {
3535: return 1;
3536: }
3537: return 0;
3538: }
3539:
1.478 albertel 3540: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3541: # input: action, courseID, current domain, intended
1.637 raeburn 3542: # path to file, source of file, instruction to parse file for objects,
3543: # ref to hash for embedded objects,
3544: # ref to hash for codebase of java objects.
1.1095 raeburn 3545: # reference to scalar to accommodate mime type determined
3546: # from File::MMagic if $parser = parse.
1.637 raeburn 3547: #
1.485 raeburn 3548: # output: url to file (if action was uploaddoc),
3549: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3550: #
1.478 albertel 3551: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3552: # course.
1.477 raeburn 3553: #
1.478 albertel 3554: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3555: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3556: # course's home server.
1.477 raeburn 3557: #
1.478 albertel 3558: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3559: # be copied from $source (current location) to
3560: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3561: # and will then be copied to
3562: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3563: # course's home server.
1.485 raeburn 3564: #
1.481 raeburn 3565: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3566: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3567: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3568: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3569: # in course's home server.
1.637 raeburn 3570: #
1.477 raeburn 3571:
3572: sub process_coursefile {
1.1095 raeburn 3573: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3574: $mimetype)=@_;
1.477 raeburn 3575: my $fetchresult;
1.638 albertel 3576: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3577: if ($action eq 'propagate') {
1.638 albertel 3578: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3579: $home);
1.481 raeburn 3580: } else {
1.477 raeburn 3581: my $fpath = '';
3582: my $fname = $file;
1.478 albertel 3583: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3584: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3585: my $filepath = &build_filepath($fpath);
1.481 raeburn 3586: if ($action eq 'copy') {
3587: if ($source eq '') {
3588: $fetchresult = 'no source file';
3589: return $fetchresult;
3590: } else {
3591: my $destination = $filepath.'/'.$fname;
3592: rename($source,$destination);
3593: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3594: $home);
1.481 raeburn 3595: }
3596: } elsif ($action eq 'uploaddoc') {
3597: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3598: print $fh $env{'form.'.$source};
1.481 raeburn 3599: close($fh);
1.637 raeburn 3600: if ($parser eq 'parse') {
1.1024 raeburn 3601: my $mm = new File::MMagic;
1.1095 raeburn 3602: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3603: if ($type eq 'text/html') {
1.1024 raeburn 3604: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3605: unless ($parse_result eq 'ok') {
3606: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3607: }
1.637 raeburn 3608: }
1.1095 raeburn 3609: if (ref($mimetype)) {
3610: $$mimetype = $type;
3611: }
1.637 raeburn 3612: }
1.477 raeburn 3613: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3614: $home);
1.481 raeburn 3615: if ($fetchresult eq 'ok') {
3616: return '/uploaded/'.$fpath.'/'.$fname;
3617: } else {
3618: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3619: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3620: return '/adm/notfound.html';
3621: }
1.477 raeburn 3622: }
3623: }
1.485 raeburn 3624: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3625: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3626: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3627: }
3628: return $fetchresult;
3629: }
3630:
1.637 raeburn 3631: sub build_filepath {
3632: my ($fpath) = @_;
3633: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3634: unless ($fpath eq '') {
3635: my @parts=split('/',$fpath);
3636: foreach my $part (@parts) {
3637: $filepath.= '/'.$part;
3638: if ((-e $filepath)!=1) {
3639: mkdir($filepath,0777);
3640: }
3641: }
3642: }
3643: return $filepath;
3644: }
3645:
3646: sub store_edited_file {
1.638 albertel 3647: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3648: my $file = $primary_url;
3649: $file =~ s#^/uploaded/$docudom/$docuname/##;
3650: my $fpath = '';
3651: my $fname = $file;
3652: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3653: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3654: my $filepath = &build_filepath($fpath);
3655: open(my $fh,'>'.$filepath.'/'.$fname);
3656: print $fh $content;
3657: close($fh);
1.638 albertel 3658: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3659: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3660: $home);
1.637 raeburn 3661: if ($$fetchresult eq 'ok') {
3662: return '/uploaded/'.$fpath.'/'.$fname;
3663: } else {
1.638 albertel 3664: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3665: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3666: return '/adm/notfound.html';
3667: }
3668: }
3669:
1.531 albertel 3670: sub clean_filename {
1.831 albertel 3671: my ($fname,$args)=@_;
1.315 www 3672: # Replace Windows backslashes by forward slashes
1.257 www 3673: $fname=~s/\\/\//g;
1.831 albertel 3674: if (!$args->{'keep_path'}) {
3675: # Get rid of everything but the actual filename
3676: $fname=~s/^.*\/([^\/]+)$/$1/;
3677: }
1.315 www 3678: # Replace spaces by underscores
3679: $fname=~s/\s+/\_/g;
3680: # Replace all other weird characters by nothing
1.831 albertel 3681: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3682: # Replace all .\d. sequences with _\d. so they no longer look like version
3683: # numbers
3684: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3685: return $fname;
3686: }
1.1051 raeburn 3687: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3688: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3689: # image with the same aspect ratio as the original, but with dimensions which do
3690: # not exceed $resizewidth and $resizeheight.
3691:
1.984 neumanie 3692: sub resizeImage {
1.1051 raeburn 3693: my ($img_path,$resizewidth,$resizeheight) = @_;
3694: my $ima = Image::Magick->new;
3695: my $resized;
3696: if (-e $img_path) {
3697: $ima->Read($img_path);
3698: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3699: my $width = $ima->Get('width');
3700: my $height = $ima->Get('height');
3701: if ($width > $resizewidth) {
3702: my $factor = $width/$resizewidth;
3703: my $newheight = $height/$factor;
3704: $ima->Scale(width=>$resizewidth,height=>$newheight);
3705: $resized = 1;
3706: }
3707: }
3708: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3709: my $width = $ima->Get('width');
3710: my $height = $ima->Get('height');
3711: if ($height > $resizeheight) {
3712: my $factor = $height/$resizeheight;
3713: my $newwidth = $width/$factor;
3714: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3715: $resized = 1;
3716: }
3717: }
3718: if ($resized) {
3719: $ima->Write($img_path);
3720: }
3721: }
3722: return;
1.977 amueller 3723: }
3724:
1.608 albertel 3725: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3726: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3727: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3728: # $context - possible values: coursedoc, existingfile, overwrite,
3729: # canceloverwrite, or ''.
3730: # if 'coursedoc': upload to the current course
3731: # if 'existingfile': write file to tmp/overwrites directory
3732: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3733: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3734: # $subdir - directory in userfile to store the file into
1.858 raeburn 3735: # $parser - instruction to parse file for objects ($parser = parse)
3736: # $allfiles - reference to hash for embedded objects
3737: # $codebase - reference to hash for codebase of java objects
3738: # $desuname - username for permanent storage of uploaded file
3739: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3740: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3741: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3742: # $resizewidth - width (pixels) to which to resize uploaded image
3743: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3744: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3745: # from File::MMagic.
1.858 raeburn 3746: #
1.686 albertel 3747: # output: url of file in userspace, or error: <message>
3748: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3749:
1.531 albertel 3750: sub userfileupload {
1.1090 raeburn 3751: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3752: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3753: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3754: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3755: $fname=&clean_filename($fname);
1.1090 raeburn 3756: # See if there is anything left
1.257 www 3757: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3758: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3759: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3760: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3761: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3762: my $now = time;
1.1090 raeburn 3763: my $filepath;
1.1095 raeburn 3764: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3765: $filepath = 'tmp/helprequests/'.$now;
3766: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3767: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3768: '_'.$env{'user.domain'}.'/pending';
3769: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3770: my ($docuname,$docudom);
1.1350 raeburn 3771: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 3772: $docudom = $destudom;
3773: } else {
3774: $docudom = $env{'user.domain'};
3775: }
1.1350 raeburn 3776: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 3777: $docuname = $destuname;
3778: } else {
3779: $docuname = $env{'user.name'};
3780: }
3781: if (exists($env{'form.group'})) {
3782: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3783: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3784: }
3785: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3786: if ($context eq 'canceloverwrite') {
3787: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3788: if (-e $tempfile) {
3789: my @info = stat($tempfile);
3790: if ($info[9] eq $env{'form.timestamp'}) {
3791: unlink($tempfile);
3792: }
3793: }
3794: return;
1.523 raeburn 3795: }
3796: }
1.1090 raeburn 3797: # Create the directory if not present
1.741 raeburn 3798: my @parts=split(/\//,$filepath);
3799: my $fullpath = $perlvar{'lonDaemons'};
3800: for (my $i=0;$i<@parts;$i++) {
3801: $fullpath .= '/'.$parts[$i];
3802: if ((-e $fullpath)!=1) {
3803: mkdir($fullpath,0777);
3804: }
3805: }
3806: open(my $fh,'>'.$fullpath.'/'.$fname);
3807: print $fh $env{'form.'.$formname};
3808: close($fh);
1.1090 raeburn 3809: if ($context eq 'existingfile') {
3810: my @info = stat($fullpath.'/'.$fname);
3811: return ($fullpath.'/'.$fname,$info[9]);
3812: } else {
3813: return $fullpath.'/'.$fname;
3814: }
1.523 raeburn 3815: }
1.995 raeburn 3816: if ($subdir eq 'scantron') {
3817: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3818: } else {
1.995 raeburn 3819: $fname="$subdir/$fname";
3820: }
1.1090 raeburn 3821: if ($context eq 'coursedoc') {
1.638 albertel 3822: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3823: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3824: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3825: return &finishuserfileupload($docuname,$docudom,
3826: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3827: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3828: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3829: } else {
1.1218 raeburn 3830: if ($env{'form.folder'}) {
3831: $fname=$env{'form.folder'}.'/'.$fname;
3832: }
1.638 albertel 3833: return &process_coursefile('uploaddoc',$docuname,$docudom,
3834: $fname,$formname,$parser,
1.1095 raeburn 3835: $allfiles,$codebase,$mimetype);
1.481 raeburn 3836: }
1.719 banghart 3837: } elsif (defined($destuname)) {
3838: my $docuname=$destuname;
3839: my $docudom=$destudom;
1.860 raeburn 3840: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3841: $parser,$allfiles,$codebase,
1.1051 raeburn 3842: $thumbwidth,$thumbheight,
1.1095 raeburn 3843: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3844: } else {
1.638 albertel 3845: my $docuname=$env{'user.name'};
3846: my $docudom=$env{'user.domain'};
1.1220 raeburn 3847: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3848: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3849: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3850: }
1.860 raeburn 3851: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3852: $parser,$allfiles,$codebase,
1.1051 raeburn 3853: $thumbwidth,$thumbheight,
1.1095 raeburn 3854: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3855: }
1.271 www 3856: }
3857:
3858: sub finishuserfileupload {
1.860 raeburn 3859: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3860: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3861: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3862: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3863:
1.860 raeburn 3864: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3865: $file=$fname;
3866: if ($fname=~m|/|) {
3867: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3868: $path.=$fnamepath.'/';
3869: }
1.259 www 3870: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3871: my $count;
3872: for ($count=4;$count<=$#parts;$count++) {
3873: $filepath.="/$parts[$count]";
3874: if ((-e $filepath)!=1) {
3875: mkdir($filepath,0777);
3876: }
3877: }
1.984 neumanie 3878:
1.258 www 3879: # Save the file
3880: {
1.701 albertel 3881: if (!open(FH,'>'.$filepath.'/'.$file)) {
3882: &logthis('Failed to create '.$filepath.'/'.$file);
3883: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3884: return '/adm/notfound.html';
3885: }
1.1090 raeburn 3886: if ($context eq 'overwrite') {
1.1117 foxr 3887: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3888: my $target = $filepath.'/'.$file;
3889: if (-e $source) {
3890: my @info = stat($source);
3891: if ($info[9] eq $env{'form.timestamp'}) {
3892: unless (&File::Copy::move($source,$target)) {
3893: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3894: return "Moving from $source failed";
3895: }
3896: } else {
3897: return "Temporary file: $source had unexpected date/time for last modification";
3898: }
3899: } else {
3900: return "Temporary file: $source missing";
3901: }
3902: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3903: &logthis('Failed to write to '.$filepath.'/'.$file);
3904: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3905: return '/adm/notfound.html';
3906: }
1.570 albertel 3907: close(FH);
1.1051 raeburn 3908: if ($resizewidth && $resizeheight) {
3909: my $mm = new File::MMagic;
3910: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3911: if ($mime_type =~ m{^image/}) {
3912: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3913: }
1.977 amueller 3914: }
1.258 www 3915: }
1.1152 raeburn 3916: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3917: if (ref($mimetype)) {
3918: if ($$mimetype eq '') {
3919: my $mm = new File::MMagic;
3920: my $type = $mm->checktype_filename($filepath.'/'.$file);
3921: $$mimetype = $type;
3922: }
3923: }
3924: }
1.637 raeburn 3925: if ($parser eq 'parse') {
1.1152 raeburn 3926: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3927: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3928: $allfiles,$codebase);
3929: unless ($parse_result eq 'ok') {
3930: &logthis('Failed to parse '.$filepath.$file.
3931: ' for embedded media: '.$parse_result);
3932: }
1.637 raeburn 3933: }
3934: }
1.860 raeburn 3935: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3936: my $input = $filepath.'/'.$file;
3937: my $output = $filepath.'/'.'tn-'.$file;
3938: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3939: system("convert -sample $thumbsize $input $output");
3940: if (-e $filepath.'/'.'tn-'.$file) {
3941: $fetchthumb = 1;
3942: }
3943: }
1.858 raeburn 3944:
1.259 www 3945: # Notify homeserver to grep it
3946: #
1.984 neumanie 3947: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3948: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3949: if ($fetchresult eq 'ok') {
1.860 raeburn 3950: if ($fetchthumb) {
3951: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3952: if ($thumbresult ne 'ok') {
3953: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3954: $docuhome.': '.$thumbresult);
3955: }
3956: }
1.259 www 3957: #
1.258 www 3958: # Return the URL to it
1.494 albertel 3959: return '/uploaded/'.$path.$file;
1.263 www 3960: } else {
1.494 albertel 3961: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3962: ': '.$fetchresult);
1.263 www 3963: return '/adm/notfound.html';
1.858 raeburn 3964: }
1.493 albertel 3965: }
3966:
1.637 raeburn 3967: sub extract_embedded_items {
1.961 raeburn 3968: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3969: my @state = ();
1.1164 raeburn 3970: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3971: my %javafiles = (
3972: codebase => '',
3973: code => '',
3974: archive => ''
3975: );
3976: my %mediafiles = (
3977: src => '',
3978: movie => '',
3979: );
1.648 raeburn 3980: my $p;
3981: if ($content) {
3982: $p = HTML::LCParser->new($content);
3983: } else {
1.961 raeburn 3984: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3985: }
1.641 albertel 3986: while (my $t=$p->get_token()) {
1.640 albertel 3987: if ($t->[0] eq 'S') {
3988: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3989: push(@state, $tagname);
1.648 raeburn 3990: if (lc($tagname) eq 'allow') {
3991: &add_filetype($allfiles,$attr->{'src'},'src');
3992: }
1.640 albertel 3993: if (lc($tagname) eq 'img') {
3994: &add_filetype($allfiles,$attr->{'src'},'src');
3995: }
1.886 albertel 3996: if (lc($tagname) eq 'a') {
1.1222 raeburn 3997: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3998: &add_filetype($allfiles,$attr->{'href'},'href');
3999: }
1.886 albertel 4000: }
1.645 raeburn 4001: if (lc($tagname) eq 'script') {
1.1164 raeburn 4002: my $src;
1.645 raeburn 4003: if ($attr->{'archive'} =~ /\.jar$/i) {
4004: &add_filetype($allfiles,$attr->{'archive'},'archive');
4005: } else {
1.1164 raeburn 4006: if ($attr->{'src'} ne '') {
4007: $src = $attr->{'src'};
4008: &add_filetype($allfiles,$src,'src');
4009: }
4010: }
4011: my $text = $p->get_trimmed_text();
4012: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4013: my @swfargs = split(/,/,$1);
4014: foreach my $item (@swfargs) {
4015: $item =~ s/["']//g;
4016: $item =~ s/^\s+//;
4017: $item =~ s/\s+$//;
4018: }
4019: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4020: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4021: push(@{$related{$swfargs[0]}},$swfargs[2]);
4022: } else {
4023: $related{$swfargs[0]} = [$swfargs[2]];
4024: }
4025: }
1.645 raeburn 4026: }
4027: }
4028: if (lc($tagname) eq 'link') {
4029: if (lc($attr->{'rel'}) eq 'stylesheet') {
4030: &add_filetype($allfiles,$attr->{'href'},'href');
4031: }
4032: }
1.640 albertel 4033: if (lc($tagname) eq 'object' ||
4034: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4035: foreach my $item (keys(%javafiles)) {
4036: $javafiles{$item} = '';
4037: }
1.1164 raeburn 4038: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4039: $lastids{lc($tagname)} = $attr->{'id'};
4040: }
1.640 albertel 4041: }
4042: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4043: my $name = lc($attr->{'name'});
4044: foreach my $item (keys(%javafiles)) {
4045: if ($name eq $item) {
4046: $javafiles{$item} = $attr->{'value'};
4047: last;
4048: }
4049: }
1.1164 raeburn 4050: my $pathfrom;
1.640 albertel 4051: foreach my $item (keys(%mediafiles)) {
4052: if ($name eq $item) {
1.1164 raeburn 4053: $pathfrom = $attr->{'value'};
4054: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4055: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4056: last;
4057: }
4058: }
1.1164 raeburn 4059: if ($name eq 'flashvars') {
4060: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4061: }
4062: if ($pathfrom ne '') {
4063: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4064: $pathfrom);
4065: }
1.640 albertel 4066: }
4067: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4068: foreach my $item (keys(%javafiles)) {
4069: if ($attr->{$item}) {
4070: $javafiles{$item} = $attr->{$item};
4071: last;
4072: }
4073: }
4074: foreach my $item (keys(%mediafiles)) {
4075: if ($attr->{$item}) {
4076: &add_filetype($allfiles,$attr->{$item},$item);
4077: last;
4078: }
4079: }
1.1164 raeburn 4080: if (lc($tagname) eq 'embed') {
4081: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4082: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4083: $attr->{'src'});
4084: }
4085: }
1.640 albertel 4086: }
1.1243 raeburn 4087: if (lc($tagname) eq 'iframe') {
4088: my $src = $attr->{'src'} ;
4089: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4090: &add_filetype($allfiles,$src,'src');
4091: } elsif ($src =~ m{^/}) {
4092: if ($env{'request.course.id'}) {
4093: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4094: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4095: my $url = &hreflocation('',$fullpath);
4096: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4097: my $relpath = $1;
4098: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4099: &add_filetype($allfiles,$1,'src');
4100: }
4101: }
4102: }
4103: }
4104: }
1.1164 raeburn 4105: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 4106: pop(@state);
1.1164 raeburn 4107: }
1.640 albertel 4108: } elsif ($t->[0] eq 'E') {
4109: my ($tagname) = ($t->[1]);
4110: if ($javafiles{'codebase'} ne '') {
4111: $javafiles{'codebase'} .= '/';
4112: }
4113: if (lc($tagname) eq 'applet' ||
4114: lc($tagname) eq 'object' ||
4115: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4116: ) {
4117: foreach my $item (keys(%javafiles)) {
4118: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4119: my $file=$javafiles{'codebase'}.$javafiles{$item};
4120: &add_filetype($allfiles,$file,$item);
4121: }
4122: }
4123: }
4124: pop @state;
4125: }
4126: }
1.1164 raeburn 4127: foreach my $id (sort(keys(%flashvars))) {
4128: if ($shockwave{$id} ne '') {
4129: my @pairs = split(/\&/,$flashvars{$id});
4130: foreach my $pair (@pairs) {
4131: my ($key,$value) = split(/\=/,$pair);
4132: if ($key eq 'thumb') {
4133: &add_filetype($allfiles,$value,$key);
4134: } elsif ($key eq 'content') {
4135: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4136: my ($ext) = ($value =~ /\.([^.]+)$/);
4137: if ($ext ne '') {
4138: &add_filetype($allfiles,$path.$value,$ext);
4139: }
4140: }
4141: }
4142: }
4143: }
1.637 raeburn 4144: return 'ok';
4145: }
4146:
1.639 albertel 4147: sub add_filetype {
4148: my ($allfiles,$file,$type)=@_;
4149: if (exists($allfiles->{$file})) {
4150: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4151: push(@{$allfiles->{$file}}, &escape($type));
4152: }
4153: } else {
4154: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4155: }
4156: }
4157:
1.1164 raeburn 4158: sub embedded_dependency {
4159: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4160: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4161: if (($identifier ne '') &&
4162: (ref($related->{$identifier}) eq 'ARRAY') &&
4163: ($pathfrom ne '')) {
4164: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4165: foreach my $dep (@{$related->{$identifier}}) {
4166: &add_filetype($allfiles,$path.$dep,'object');
4167: }
4168: }
4169: }
4170: return;
4171: }
4172:
1.493 albertel 4173: sub removeuploadedurl {
1.984 neumanie 4174: my ($url)=@_;
4175: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4176: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4177: }
4178:
4179: sub removeuserfile {
4180: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4181: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4182: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4183: if ($result eq 'ok') {
1.798 raeburn 4184: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4185: my $metafile = $fname.'.meta';
4186: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4187: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4188: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4189: my $sqlresult =
1.823 albertel 4190: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4191: 'portfolio_metadata',$group,
4192: 'delete');
1.798 raeburn 4193: }
4194: }
4195: return $result;
1.257 www 4196: }
1.15 www 4197:
1.530 albertel 4198: sub mkdiruserfile {
4199: my ($docuname,$docudom,$dir)=@_;
4200: my $home=&homeserver($docuname,$docudom);
4201: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4202: }
4203:
1.531 albertel 4204: sub renameuserfile {
4205: my ($docuname,$docudom,$old,$new)=@_;
4206: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4207: my $result = &reply("renameuserfile:$docudom:$docuname:".
4208: &escape("$old").':'.&escape("$new"),$home);
4209: if ($result eq 'ok') {
4210: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4211: my $oldmeta = $old.'.meta';
4212: my $newmeta = $new.'.meta';
4213: my $metaresult =
4214: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4215: my $url = "/uploaded/$docudom/$docuname/$old";
4216: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4217: my $sqlresult =
1.823 albertel 4218: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4219: 'portfolio_metadata',$group,
4220: 'delete');
1.798 raeburn 4221: }
4222: }
4223: return $result;
1.531 albertel 4224: }
4225:
1.14 www 4226: # ------------------------------------------------------------------------- Log
4227:
4228: sub log {
4229: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4230: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4231: }
4232:
4233: # ------------------------------------------------------------------ Course Log
1.352 www 4234: #
4235: # This routine flushes several buffers of non-mission-critical nature
4236: #
1.157 www 4237:
4238: sub flushcourselogs {
1.352 www 4239: &logthis('Flushing log buffers');
4240: #
4241: # course logs
4242: # This is a log of all transactions in a course, which can be used
4243: # for data mining purposes
4244: #
4245: # It also collects the courseid database, which lists last transaction
4246: # times and course titles for all courseids
4247: #
4248: my %courseidbuffer=();
1.921 raeburn 4249: foreach my $crsid (keys(%courselogs)) {
1.352 www 4250: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4251: &escape($courselogs{$crsid}),
4252: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4253: delete $courselogs{$crsid};
4254: } else {
4255: &logthis('Failed to flush log buffer for '.$crsid);
4256: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4257: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4258: " exceeded maximum size, deleting.</font>");
4259: delete $courselogs{$crsid};
4260: }
1.352 www 4261: }
1.920 raeburn 4262: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4263: 'description' => $coursedescrbuf{$crsid},
4264: 'inst_code' => $courseinstcodebuf{$crsid},
4265: 'type' => $coursetypebuf{$crsid},
4266: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4267: };
1.191 harris41 4268: }
1.352 www 4269: #
4270: # Write course id database (reverse lookup) to homeserver of courses
4271: # Is used in pickcourse
4272: #
1.840 albertel 4273: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4274: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4275: $courseidbuffer{$crs_home},
4276: $crs_home,'timeonly');
1.352 www 4277: }
4278: #
4279: # File accesses
4280: # Writes to the dynamic metadata of resources to get hit counts, etc.
4281: #
1.449 matthew 4282: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4283: if ($entry =~ /___count$/) {
4284: my ($dom,$name);
1.807 albertel 4285: ($dom,$name,undef)=
1.811 albertel 4286: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4287: if (! defined($dom) || $dom eq '' ||
4288: ! defined($name) || $name eq '') {
1.620 albertel 4289: my $cid = $env{'request.course.id'};
4290: $dom = $env{'request.'.$cid.'.domain'};
4291: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4292: }
1.450 matthew 4293: my $value = $accesshash{$entry};
4294: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4295: my %temphash=($url => $value);
1.449 matthew 4296: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4297: if ($result eq 'ok') {
4298: delete $accesshash{$entry};
4299: }
4300: } else {
1.811 albertel 4301: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4302: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4303: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4304: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4305: delete $accesshash{$entry};
4306: }
1.185 www 4307: }
1.191 harris41 4308: }
1.352 www 4309: #
4310: # Roles
4311: # Reverse lookup of user roles for course faculty/staff and co-authorship
4312: #
1.800 albertel 4313: foreach my $entry (keys(%userrolehash)) {
1.351 www 4314: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4315: split(/\:/,$entry);
4316: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4317: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4318: $rudom,$runame) eq 'ok') {
4319: delete $userrolehash{$entry};
4320: }
4321: }
1.662 raeburn 4322: #
1.1334 raeburn 4323: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4324: #
4325: my %domrolebuffer = ();
1.1000 raeburn 4326: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4327: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4328: if ($domrolebuffer{$rudom}) {
4329: $domrolebuffer{$rudom}.='&'.&escape($entry).
4330: '='.&escape($domainrolehash{$entry});
4331: } else {
4332: $domrolebuffer{$rudom}.=&escape($entry).
4333: '='.&escape($domainrolehash{$entry});
4334: }
4335: delete $domainrolehash{$entry};
4336: }
4337: foreach my $dom (keys(%domrolebuffer)) {
1.1324 raeburn 4338: my %servers;
4339: if (defined(&domain($dom,'primary'))) {
4340: my $primary=&domain($dom,'primary');
4341: my $hostname=&hostname($primary);
4342: $servers{$primary} = $hostname;
4343: } else {
4344: %servers = &get_servers($dom,'library');
4345: }
1.841 albertel 4346: foreach my $tryserver (keys(%servers)) {
1.1324 raeburn 4347: if (&reply('domroleput:'.$dom.':'.
4348: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4349: last;
4350: } else {
1.841 albertel 4351: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4352: }
1.662 raeburn 4353: }
4354: }
1.186 www 4355: $dumpcount++;
1.157 www 4356: }
4357:
4358: sub courselog {
4359: my $what=shift;
1.158 www 4360: $what=time.':'.$what;
1.620 albertel 4361: unless ($env{'request.course.id'}) { return ''; }
4362: $coursedombuf{$env{'request.course.id'}}=
4363: $env{'course.'.$env{'request.course.id'}.'.domain'};
4364: $coursenumbuf{$env{'request.course.id'}}=
4365: $env{'course.'.$env{'request.course.id'}.'.num'};
4366: $coursehombuf{$env{'request.course.id'}}=
4367: $env{'course.'.$env{'request.course.id'}.'.home'};
4368: $coursedescrbuf{$env{'request.course.id'}}=
4369: $env{'course.'.$env{'request.course.id'}.'.description'};
4370: $courseinstcodebuf{$env{'request.course.id'}}=
4371: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4372: $courseownerbuf{$env{'request.course.id'}}=
4373: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4374: $coursetypebuf{$env{'request.course.id'}}=
4375: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4376: if (defined $courselogs{$env{'request.course.id'}}) {
4377: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4378: } else {
1.620 albertel 4379: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4380: }
1.620 albertel 4381: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4382: &flushcourselogs();
4383: }
1.158 www 4384: }
4385:
4386: sub courseacclog {
4387: my $fnsymb=shift;
1.620 albertel 4388: unless ($env{'request.course.id'}) { return ''; }
4389: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4390: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4391: $what.=':POST';
1.583 matthew 4392: # FIXME: Probably ought to escape things....
1.800 albertel 4393: foreach my $key (keys(%env)) {
4394: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4395: my $formitem = $1;
4396: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4397: $what.=':'.$formitem.'='.$env{$key};
4398: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4399: $what.=':'.$formitem.'='.$env{$key};
4400: }
1.158 www 4401: }
1.191 harris41 4402: }
1.583 matthew 4403: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4404: # FIXME: We should not be depending on a form parameter that someone
4405: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4406: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4407: $what.= ':POST';
4408: # FIXME: Probably ought to escape things....
4409: foreach my $element ('courseexp','crsfulltext','crsrelated',
4410: 'crsdiscuss') {
1.620 albertel 4411: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4412: }
4413: }
1.158 www 4414: }
4415: &courselog($what);
1.149 www 4416: }
4417:
1.185 www 4418: sub countacc {
4419: my $url=&declutter(shift);
1.458 matthew 4420: return if (! defined($url) || $url eq '');
1.620 albertel 4421: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4422: #
4423: # Mark that this url was used in this course
4424: #
1.620 albertel 4425: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4426: #
4427: # Increase the access count for this resource in this child process
4428: #
1.281 www 4429: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4430: $accesshash{$key}++;
1.185 www 4431: }
1.349 www 4432:
1.361 www 4433: sub linklog {
4434: my ($from,$to)=@_;
4435: $from=&declutter($from);
4436: $to=&declutter($to);
4437: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4438: $accesshash{$to.'___'.$from.'___goto'}=1;
4439: }
1.1160 www 4440:
4441: sub statslog {
4442: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4443: if ($users<2) { return; }
4444: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4445: 'course' => $env{'request.course.id'},
4446: 'sections' => '"all"',
4447: 'num_students' => $users,
4448: 'part' => $part,
4449: 'symb' => $symb,
4450: 'mean_tries' => $av_attempts,
4451: 'deg_of_diff' => $degdiff});
4452: foreach my $key (keys(%dynstore)) {
4453: $accesshash{$key}=$dynstore{$key};
4454: }
4455: }
1.361 www 4456:
1.349 www 4457: sub userrolelog {
4458: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4459: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4460: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4461: $userrolehash
4462: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4463: =$tend.':'.$tstart;
1.662 raeburn 4464: }
1.1169 droeschl 4465: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4466: $userrolehash
4467: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4468: =$tend.':'.$tstart;
4469: }
1.1334 raeburn 4470: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4471: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4472: $domainrolehash
4473: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4474: = $tend.':'.$tstart;
4475: }
1.351 www 4476: }
4477:
1.957 raeburn 4478: sub courserolelog {
4479: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 4480: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4481: my $cdom = $1;
4482: my $cnum = $2;
4483: my $sec = $3;
4484: my $namespace = 'rolelog';
4485: my %storehash = (
4486: role => $trole,
4487: start => $tstart,
4488: end => $tend,
4489: selfenroll => $selfenroll,
4490: context => $context,
4491: );
4492: if ($trole eq 'gr') {
4493: $namespace = 'groupslog';
4494: $storehash{'group'} = $sec;
4495: } else {
4496: $storehash{'section'} = $sec;
4497: }
1.1188 raeburn 4498: &write_log('course',$namespace,\%storehash,$delflag,$username,
4499: $domain,$cnum,$cdom);
1.1184 raeburn 4500: if (($trole ne 'st') || ($sec ne '')) {
4501: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4502: }
4503: }
4504: return;
4505: }
4506:
1.1184 raeburn 4507: sub domainrolelog {
4508: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4509: if ($area =~ m{^/($match_domain)/$}) {
4510: my $cdom = $1;
4511: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4512: my $namespace = 'rolelog';
4513: my %storehash = (
4514: role => $trole,
4515: start => $tstart,
4516: end => $tend,
4517: context => $context,
4518: );
1.1188 raeburn 4519: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4520: $domain,$domconfiguser,$cdom);
1.1184 raeburn 4521: }
4522: return;
4523:
4524: }
4525:
4526: sub coauthorrolelog {
4527: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4528: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4529: my $audom = $1;
4530: my $auname = $2;
4531: my $namespace = 'rolelog';
4532: my %storehash = (
4533: role => $trole,
4534: start => $tstart,
4535: end => $tend,
4536: context => $context,
4537: );
1.1188 raeburn 4538: &write_log('author',$namespace,\%storehash,$delflag,$username,
4539: $domain,$auname,$audom);
1.1184 raeburn 4540: }
4541: return;
4542: }
4543:
1.351 www 4544: sub get_course_adv_roles {
1.948 raeburn 4545: my ($cid,$codes) = @_;
1.620 albertel 4546: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4547: my %coursehash=&coursedescription($cid);
1.988 raeburn 4548: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4549: my %nothide=();
1.800 albertel 4550: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4551: if ($user !~ /:/) {
4552: $nothide{join(':',split(/[\@]/,$user))}=1;
4553: } else {
4554: $nothide{$user}=1;
4555: }
1.470 www 4556: }
1.1219 raeburn 4557: my @possdoms = ($coursehash{'domain'});
4558: if ($coursehash{'checkforpriv'}) {
4559: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4560: }
1.351 www 4561: my %returnhash=();
4562: my %dumphash=
4563: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4564: my $now=time;
1.997 raeburn 4565: my %privileged;
1.1000 raeburn 4566: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4567: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4568: if (($tstart) && ($tstart<0)) { next; }
4569: if (($tend) && ($tend<$now)) { next; }
4570: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4571: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4572: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 4573: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4574: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4575: if ($role eq 'cr') { next; }
1.948 raeburn 4576: if ($codes) {
4577: if ($section) { $role .= ':'.$section; }
4578: if ($returnhash{$role}) {
4579: $returnhash{$role}.=','.$username.':'.$domain;
4580: } else {
4581: $returnhash{$role}=$username.':'.$domain;
4582: }
1.351 www 4583: } else {
1.988 raeburn 4584: my $key=&plaintext($role,$crstype);
1.973 bisitz 4585: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4586: if ($returnhash{$key}) {
4587: $returnhash{$key}.=','.$username.':'.$domain;
4588: } else {
4589: $returnhash{$key}=$username.':'.$domain;
4590: }
1.351 www 4591: }
1.948 raeburn 4592: }
1.400 www 4593: return %returnhash;
4594: }
4595:
4596: sub get_my_roles {
1.937 raeburn 4597: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4598: unless (defined($uname)) { $uname=$env{'user.name'}; }
4599: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4600: my (%dumphash,%nothide);
1.1086 raeburn 4601: if ($context eq 'userroles') {
1.1166 raeburn 4602: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4603: } else {
1.1219 raeburn 4604: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4605: if ($hidepriv) {
4606: my %coursehash=&coursedescription($udom.'_'.$uname);
4607: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4608: if ($user !~ /:/) {
4609: $nothide{join(':',split(/[\@]/,$user))} = 1;
4610: } else {
4611: $nothide{$user} = 1;
4612: }
4613: }
4614: }
1.858 raeburn 4615: }
1.400 www 4616: my %returnhash=();
4617: my $now=time;
1.999 raeburn 4618: my %privileged;
1.800 albertel 4619: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4620: my ($role,$tend,$tstart);
4621: if ($context eq 'userroles') {
1.1149 raeburn 4622: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4623: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4624: } else {
4625: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4626: }
1.400 www 4627: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4628: my $status = 'active';
1.939 raeburn 4629: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4630: $status = 'previous';
4631: }
4632: if (($tstart) && ($now<$tstart)) {
4633: $status = 'future';
4634: }
4635: if (ref($types) eq 'ARRAY') {
4636: if (!grep(/^\Q$status\E$/,@{$types})) {
4637: next;
4638: }
4639: } else {
4640: if ($status ne 'active') {
4641: next;
4642: }
4643: }
1.867 raeburn 4644: my ($rolecode,$username,$domain,$section,$area);
4645: if ($context eq 'userroles') {
1.1186 raeburn 4646: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4647: (undef,$domain,$username,$section) = split(/\//,$area);
4648: } else {
4649: ($role,$username,$domain,$section) = split(/\:/,$entry);
4650: }
1.832 raeburn 4651: if (ref($roledoms) eq 'ARRAY') {
4652: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4653: next;
4654: }
4655: }
4656: if (ref($roles) eq 'ARRAY') {
4657: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4658: if ($role =~ /^cr\//) {
4659: if (!grep(/^cr$/,@{$roles})) {
4660: next;
4661: }
1.1104 raeburn 4662: } elsif ($role =~ /^gr\//) {
4663: if (!grep(/^gr$/,@{$roles})) {
4664: next;
4665: }
1.922 raeburn 4666: } else {
4667: next;
4668: }
1.832 raeburn 4669: }
1.867 raeburn 4670: }
1.937 raeburn 4671: if ($hidepriv) {
1.1219 raeburn 4672: my @privroles = ('dc','su');
1.999 raeburn 4673: if ($context eq 'userroles') {
1.1219 raeburn 4674: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4675: } else {
1.1219 raeburn 4676: my $possdoms = [$domain];
4677: if (ref($roledoms) eq 'ARRAY') {
4678: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4679: }
1.1219 raeburn 4680: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4681: if (!$nothide{$username.':'.$domain}) {
4682: next;
4683: }
4684: }
1.937 raeburn 4685: }
4686: }
1.933 raeburn 4687: if ($withsec) {
4688: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4689: $tstart.':'.$tend;
4690: } else {
4691: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4692: }
1.832 raeburn 4693: }
1.373 www 4694: return %returnhash;
1.399 www 4695: }
4696:
1.1333 raeburn 4697: sub get_all_adhocroles {
4698: my ($dom) = @_;
4699: my @roles_by_num = ();
4700: my %domdefaults = &get_domain_defaults($dom);
4701: my (%description,%access_in_dom,%access_info);
4702: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
4703: my $count = 0;
4704: my %domcurrent = %{$domdefaults{'adhocroles'}};
4705: my %ordered;
4706: foreach my $role (sort(keys(%domcurrent))) {
4707: my ($order,$desc,$access_in_dom);
4708: if (ref($domcurrent{$role}) eq 'HASH') {
4709: $order = $domcurrent{$role}{'order'};
4710: $desc = $domcurrent{$role}{'desc'};
4711: $access_in_dom{$role} = $domcurrent{$role}{'access'};
4712: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
4713: }
4714: if ($order eq '') {
4715: $order = $count;
4716: }
4717: $ordered{$order} = $role;
4718: if ($desc ne '') {
4719: $description{$role} = $desc;
4720: } else {
4721: $description{$role}= $role;
4722: }
4723: $count++;
4724: }
4725: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
4726: push(@roles_by_num,$ordered{$item});
4727: }
4728: }
4729: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
4730: }
4731:
1.1332 raeburn 4732: sub get_my_adhocroles {
1.1333 raeburn 4733: my ($cid,$checkreg) = @_;
4734: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
4735: if ($env{'request.course.id'} eq $cid) {
4736: $cdom = $env{'course.'.$cid.'.domain'};
4737: $cnum = $env{'course.'.$cid.'.num'};
4738: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
4739: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
4740: $cdom = $1;
4741: $cnum = $2;
4742: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
4743: $cdom,$cnum);
4744: }
4745: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
4746: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4747: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
4748: if ($rosterhash{$user} ne '') {
4749: my $type = (split(/:/,$rosterhash{$user}))[5];
4750: return ([],{}) if ($type eq 'auto');
4751: }
4752: }
4753: if (($cdom ne '') && ($cnum ne '')) {
1.1334 raeburn 4754: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332 raeburn 4755: my $then=$env{'user.login.time'};
4756: my $update=$env{'user.update.time'};
1.1335 raeburn 4757: if (!$update) {
4758: $update = $then;
4759: }
4760: my @liveroles;
1.1334 raeburn 4761: foreach my $role ('dh','da') {
4762: if ($env{"user.role.$role./$cdom/"}) {
1.1335 raeburn 4763: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334 raeburn 4764: my $limit = $update;
4765: if ($env{'request.role'} eq "$role./$cdom/") {
4766: $limit = $then;
4767: }
1.1335 raeburn 4768: my $activerole = 1;
4769: if ($tstart && $tstart>$limit) { $activerole = 0; }
4770: if ($tend && $tend <$limit) { $activerole = 0; }
4771: if ($activerole) {
4772: push(@liveroles,$role);
4773: }
1.1334 raeburn 4774: }
1.1332 raeburn 4775: }
1.1335 raeburn 4776: if (@liveroles) {
1.1332 raeburn 4777: if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333 raeburn 4778: my ($accessref,$accessinfo,%access_in_dom);
4779: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
4780: if (ref($roles_by_num) eq 'ARRAY') {
4781: if (@{$roles_by_num}) {
1.1332 raeburn 4782: my %settings;
4783: if ($env{'request.course.id'} eq $cid) {
4784: foreach my $envkey (keys(%env)) {
4785: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
4786: $settings{$1} = $env{$envkey};
4787: }
4788: }
4789: } else {
4790: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
4791: }
4792: my %setincrs;
4793: if ($settings{'internal.adhocaccess'}) {
4794: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
4795: }
4796: my @statuses;
4797: if ($env{'environment.inststatus'}) {
4798: @statuses = split(/,/,$env{'environment.inststatus'});
4799: }
4800: my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333 raeburn 4801: if (ref($accessref) eq 'HASH') {
4802: %access_in_dom = %{$accessref};
4803: }
4804: foreach my $role (@{$roles_by_num}) {
1.1332 raeburn 4805: my ($curraccess,@okstatus,@personnel);
4806: if ($setincrs{$role}) {
4807: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
4808: if ($curraccess eq 'status') {
4809: @okstatus = split(/\&/,$rest);
4810: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4811: @personnel = split(/\&/,$rest);
4812: }
4813: } else {
4814: $curraccess = $access_in_dom{$role};
1.1333 raeburn 4815: if (ref($accessinfo) eq 'HASH') {
4816: if ($curraccess eq 'status') {
4817: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4818: @okstatus = @{$accessinfo->{$role}};
4819: }
4820: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4821: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4822: @personnel = @{$accessinfo->{$role}};
4823: }
1.1332 raeburn 4824: }
4825: }
4826: }
4827: if ($curraccess eq 'none') {
4828: next;
4829: } elsif ($curraccess eq 'all') {
4830: push(@possroles,$role);
1.1336 raeburn 4831: } elsif ($curraccess eq 'dh') {
1.1335 raeburn 4832: if (grep(/^dh$/,@liveroles)) {
4833: push(@possroles,$role);
4834: } else {
4835: next;
4836: }
1.1336 raeburn 4837: } elsif ($curraccess eq 'da') {
1.1335 raeburn 4838: if (grep(/^da$/,@liveroles)) {
4839: push(@possroles,$role);
4840: } else {
4841: next;
4842: }
1.1332 raeburn 4843: } elsif ($curraccess eq 'status') {
4844: if (@okstatus) {
4845: if (!@statuses) {
4846: if (grep(/^default$/,@okstatus)) {
4847: push(@possroles,$role);
4848: }
4849: } else {
4850: foreach my $status (@okstatus) {
4851: if (grep(/^\Q$status\E$/,@statuses)) {
4852: push(@possroles,$role);
4853: last;
4854: }
4855: }
4856: }
4857: }
4858: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4859: if (grep(/^\Q$user\E$/,@personnel)) {
4860: if ($curraccess eq 'exc') {
4861: push(@possroles,$role);
4862: }
4863: } elsif ($curraccess eq 'inc') {
4864: push(@possroles,$role);
4865: }
4866: }
4867: }
4868: }
4869: }
4870: }
4871: }
4872: }
4873: }
1.1333 raeburn 4874: unless (ref($description) eq 'HASH') {
4875: if (ref($roles_by_num) eq 'ARRAY') {
4876: my %desc;
4877: map { $desc{$_} = $_; } (@{$roles_by_num});
4878: $description = \%desc;
4879: } else {
4880: $description = {};
4881: }
4882: }
4883: return (\@possroles,$description);
1.1332 raeburn 4884: }
4885:
1.399 www 4886: # ----------------------------------------------------- Frontpage Announcements
4887: #
4888: #
4889:
4890: sub postannounce {
4891: my ($server,$text)=@_;
1.844 albertel 4892: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4893: unless ($text=~/\w/) { $text=''; }
4894: return &reply('setannounce:'.&escape($text),$server);
4895: }
4896:
4897: sub getannounce {
1.448 albertel 4898:
4899: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4900: my $announcement='';
1.800 albertel 4901: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4902: close($fh);
1.399 www 4903: if ($announcement=~/\w/) {
4904: return
4905: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4906: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4907: } else {
4908: return '';
4909: }
4910: } else {
4911: return '';
4912: }
1.351 www 4913: }
1.353 www 4914:
4915: # ---------------------------------------------------------- Course ID routines
4916: # Deal with domain's nohist_courseid.db files
4917: #
4918:
4919: sub courseidput {
1.921 raeburn 4920: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4921: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4922: my $outcome;
4923: if ($caller eq 'timeonly') {
4924: my $cids = '';
4925: foreach my $item (keys(%$storehash)) {
4926: $cids.=&escape($item).'&';
4927: }
4928: $cids=~s/\&$//;
4929: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4930: $coursehome);
4931: } else {
4932: my $items = '';
4933: foreach my $item (keys(%$storehash)) {
4934: $items.= &escape($item).'='.
4935: &freeze_escape($$storehash{$item}).'&';
4936: }
4937: $items=~s/\&$//;
4938: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4939: $coursehome);
1.918 raeburn 4940: }
4941: if ($outcome eq 'unknown_cmd') {
4942: my $what;
4943: foreach my $cid (keys(%$storehash)) {
4944: $what .= &escape($cid).'=';
1.921 raeburn 4945: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4946: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4947: }
4948: $what =~ s/\:$/&/;
4949: }
4950: $what =~ s/\&$//;
4951: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4952: } else {
4953: return $outcome;
4954: }
1.353 www 4955: }
4956:
4957: sub courseiddump {
1.921 raeburn 4958: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4959: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4960: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4961: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 4962: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4963: my $as_hash = 1;
4964: my %returnhash;
4965: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4966: my %libserv = &all_library();
4967: foreach my $tryserver (keys(%libserv)) {
4968: if ( ( $hostidflag == 1
4969: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4970: || (!defined($hostidflag)) ) {
4971:
1.918 raeburn 4972: if (($domfilter eq '') ||
4973: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4974: my $rep;
4975: if (grep { $_ eq $tryserver } current_machine_ids()) {
4976: $rep = LONCAPA::Lond::dump_course_id_handler(
4977: join(":", (&host_domain($tryserver), $sincefilter,
4978: &escape($descfilter), &escape($instcodefilter),
4979: &escape($ownerfilter), &escape($coursefilter),
4980: &escape($typefilter), &escape($regexp_ok),
4981: $as_hash, &escape($selfenrollonly),
4982: &escape($catfilter), $showhidden, $caller,
4983: &escape($cloner), &escape($cc_clone), $cloneonly,
4984: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 4985: &escape($creationcontext),$domcloner,$hasuniquecode,
4986: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 4987: } else {
4988: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4989: $sincefilter.':'.&escape($descfilter).':'.
4990: &escape($instcodefilter).':'.&escape($ownerfilter).
4991: ':'.&escape($coursefilter).':'.&escape($typefilter).
4992: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4993: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4994: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4995: &escape($cc_clone).':'.$cloneonly.':'.
4996: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 4997: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4998: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 4999: }
5000:
1.918 raeburn 5001: my @pairs=split(/\&/,$rep);
5002: foreach my $item (@pairs) {
5003: my ($key,$value)=split(/\=/,$item,2);
5004: $key = &unescape($key);
5005: next if ($key =~ /^error: 2 /);
5006: my $result = &thaw_unescape($value);
5007: if (ref($result) eq 'HASH') {
5008: $returnhash{$key}=$result;
5009: } else {
1.921 raeburn 5010: my @responses = split(/:/,$value);
5011: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5012: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5013: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5014: }
1.1008 raeburn 5015: }
1.353 www 5016: }
5017: }
5018: }
5019: }
5020: return %returnhash;
5021: }
5022:
1.1055 raeburn 5023: sub courselastaccess {
5024: my ($cdom,$cnum,$hostidref) = @_;
5025: my %returnhash;
5026: if ($cdom && $cnum) {
5027: my $chome = &homeserver($cnum,$cdom);
5028: if ($chome ne 'no_host') {
5029: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5030: &extract_lastaccess(\%returnhash,$rep);
5031: }
5032: } else {
5033: if (!$cdom) { $cdom=''; }
5034: my %libserv = &all_library();
5035: foreach my $tryserver (keys(%libserv)) {
5036: if (ref($hostidref) eq 'ARRAY') {
5037: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5038: }
5039: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5040: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5041: &extract_lastaccess(\%returnhash,$rep);
5042: }
5043: }
5044: }
5045: return %returnhash;
5046: }
5047:
5048: sub extract_lastaccess {
5049: my ($returnhash,$rep) = @_;
5050: if (ref($returnhash) eq 'HASH') {
5051: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5052: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5053: $rep eq '') {
5054: my @pairs=split(/\&/,$rep);
5055: foreach my $item (@pairs) {
5056: my ($key,$value)=split(/\=/,$item,2);
5057: $key = &unescape($key);
5058: next if ($key =~ /^error: 2 /);
5059: $returnhash->{$key} = &thaw_unescape($value);
5060: }
5061: }
5062: }
5063: return;
5064: }
5065:
1.658 raeburn 5066: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5067:
5068: sub dcmailput {
1.685 raeburn 5069: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 5070: my $status = &Apache::lonnet::critical(
1.740 www 5071: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5072: &escape($message),$server);
1.662 raeburn 5073: return $status;
5074: }
5075:
1.658 raeburn 5076: sub dcmaildump {
5077: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5078: my %returnhash=();
1.846 albertel 5079:
5080: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5081: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5082: &escape($enddate).':';
5083: my @esc_senders=map { &escape($_)} @$senders;
5084: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5085: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5086: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5087: if (($key) && ($value)) {
5088: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5089: }
5090: }
5091: }
5092: return %returnhash;
5093: }
1.662 raeburn 5094: # ---------------------------------------------------------- Domain roles
5095:
5096: sub get_domain_roles {
5097: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5098: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5099: $startdate = '.';
5100: }
1.1018 raeburn 5101: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5102: $enddate = '.';
5103: }
1.922 raeburn 5104: my $rolelist;
5105: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 5106: $rolelist = join('&',@{$roles});
1.922 raeburn 5107: }
1.662 raeburn 5108: my %personnel = ();
1.841 albertel 5109:
5110: my %servers = &get_servers($dom,'library');
5111: foreach my $tryserver (keys(%servers)) {
5112: %{$personnel{$tryserver}}=();
5113: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5114: &escape($startdate).':'.
5115: &escape($enddate).':'.
5116: &escape($rolelist), $tryserver))) {
5117: my ($key,$value) = split(/\=/,$line,2);
5118: if (($key) && ($value)) {
5119: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5120: }
5121: }
1.662 raeburn 5122: }
5123: return %personnel;
5124: }
1.658 raeburn 5125:
1.1332 raeburn 5126: sub get_active_domroles {
5127: my ($dom,$roles) = @_;
5128: return () unless (ref($roles) eq 'ARRAY');
5129: my $now = time;
5130: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5131: my %domroles;
5132: foreach my $server (keys(%dompersonnel)) {
5133: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5134: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5135: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5136: }
5137: }
5138: return %domroles;
5139: }
5140:
1.1057 www 5141: # ----------------------------------------------------------- Interval timing
1.149 www 5142:
1.1153 www 5143: {
5144: # Caches needed for speedup of navmaps
5145: # We don't want to cache this for very long at all (5 seconds at most)
5146: #
5147: # The user for whom we cache
5148: my $cachedkey='';
5149: # The cached times for this user
5150: my %cachedtimes=();
5151: # When this was last done
1.1282 raeburn 5152: my $cachedtime='';
1.1153 www 5153:
5154: sub load_all_first_access {
1.1308 raeburn 5155: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 5156: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 raeburn 5157: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5158: (!$ignorecache)) {
1.1154 raeburn 5159: return;
5160: }
5161: $cachedtime=time;
5162: $cachedkey=$uname.':'.$udom;
5163: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5164: }
5165:
1.504 albertel 5166: sub get_first_access {
1.1308 raeburn 5167: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 5168: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5169: if ($argsymb) { $symb=$argsymb; }
5170: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5171: if ($argmap) { $map = $argmap; }
1.926 albertel 5172: if ($type eq 'course') {
5173: $res='course';
5174: } elsif ($type eq 'map') {
1.588 albertel 5175: $res=&symbread($map);
5176: } else {
5177: $res=$symb;
5178: }
1.1308 raeburn 5179: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 5180: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5181: }
5182:
5183: sub set_first_access {
1.1162 raeburn 5184: my ($type,$interval)=@_;
1.790 albertel 5185: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5186: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5187: if ($type eq 'course') {
5188: $res='course';
5189: } elsif ($type eq 'map') {
1.588 albertel 5190: $res=&symbread($map);
5191: } else {
5192: $res=$symb;
5193: }
1.1153 www 5194: $cachedkey='';
1.1162 raeburn 5195: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 5196: if (!$firstaccess) {
1.1162 raeburn 5197: my $start = time;
5198: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5199: $udom,$uname);
5200: if ($putres eq 'ok') {
5201: &put('timerinterval',{"$courseid\0$res"=>$interval},
5202: $udom,$uname);
5203: &appenv(
5204: {
5205: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5206: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5207: }
5208: );
5209: }
5210: return $putres;
1.505 albertel 5211: }
5212: return 'already_set';
1.504 albertel 5213: }
1.1153 www 5214: }
1.1282 raeburn 5215:
1.110 www 5216: # --------------------------------------------- Set Expire Date for Spreadsheet
5217:
5218: sub expirespread {
5219: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5220: my $cid=$env{'request.course.id'};
1.110 www 5221: if ($cid) {
5222: my $now=time;
5223: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5224: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5225: $env{'course.'.$cid.'.num'}.
1.110 www 5226: ':nohist_expirationdates:'.
5227: &escape($key).'='.$now,
1.620 albertel 5228: $env{'course.'.$cid.'.home'})
1.110 www 5229: }
5230: return 'ok';
1.14 www 5231: }
5232:
1.109 www 5233: # ----------------------------------------------------- Devalidate Spreadsheets
5234:
5235: sub devalidate {
1.325 www 5236: my ($symb,$uname,$udom)=@_;
1.620 albertel 5237: my $cid=$env{'request.course.id'};
1.109 www 5238: if ($cid) {
1.391 matthew 5239: # delete the stored spreadsheets for
5240: # - the student level sheet of this user in course's homespace
5241: # - the assessment level sheet for this resource
5242: # for this user in user's homespace
1.553 albertel 5243: # - current conditional state info
1.325 www 5244: my $key=$uname.':'.$udom.':';
1.109 www 5245: my $status=
1.299 matthew 5246: &del('nohist_calculatedsheets',
1.391 matthew 5247: [$key.'studentcalc:'],
1.620 albertel 5248: $env{'course.'.$cid.'.domain'},
5249: $env{'course.'.$cid.'.num'})
1.133 albertel 5250: .' '.
5251: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5252: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5253: unless ($status eq 'ok ok') {
5254: &logthis('Could not devalidate spreadsheet '.
1.325 www 5255: $uname.' at '.$udom.' for '.
1.109 www 5256: $symb.': '.$status);
1.133 albertel 5257: }
1.553 albertel 5258: &delenv('user.state.'.$cid);
1.109 www 5259: }
5260: }
5261:
1.265 albertel 5262: sub get_scalar {
5263: my ($string,$end) = @_;
5264: my $value;
5265: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5266: $value = $1;
5267: } elsif ($$string =~ s/^([^&]*?)&//) {
5268: $value = $1;
5269: }
5270: return &unescape($value);
5271: }
5272:
5273: sub array2str {
5274: my (@array) = @_;
5275: my $result=&arrayref2str(\@array);
5276: $result=~s/^__ARRAY_REF__//;
5277: $result=~s/__END_ARRAY_REF__$//;
5278: return $result;
5279: }
5280:
1.204 albertel 5281: sub arrayref2str {
5282: my ($arrayref) = @_;
1.265 albertel 5283: my $result='__ARRAY_REF__';
1.204 albertel 5284: foreach my $elem (@$arrayref) {
1.265 albertel 5285: if(ref($elem) eq 'ARRAY') {
5286: $result.=&arrayref2str($elem).'&';
5287: } elsif(ref($elem) eq 'HASH') {
5288: $result.=&hashref2str($elem).'&';
5289: } elsif(ref($elem)) {
5290: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5291: } else {
5292: $result.=&escape($elem).'&';
5293: }
5294: }
5295: $result=~s/\&$//;
1.265 albertel 5296: $result .= '__END_ARRAY_REF__';
1.204 albertel 5297: return $result;
5298: }
5299:
1.168 albertel 5300: sub hash2str {
1.204 albertel 5301: my (%hash) = @_;
5302: my $result=&hashref2str(\%hash);
1.265 albertel 5303: $result=~s/^__HASH_REF__//;
5304: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5305: return $result;
5306: }
5307:
5308: sub hashref2str {
5309: my ($hashref)=@_;
1.265 albertel 5310: my $result='__HASH_REF__';
1.800 albertel 5311: foreach my $key (sort(keys(%$hashref))) {
5312: if (ref($key) eq 'ARRAY') {
5313: $result.=&arrayref2str($key).'=';
5314: } elsif (ref($key) eq 'HASH') {
5315: $result.=&hashref2str($key).'=';
5316: } elsif (ref($key)) {
1.265 albertel 5317: $result.='=';
1.800 albertel 5318: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5319: } else {
1.1132 raeburn 5320: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5321: }
5322:
1.800 albertel 5323: if(ref($hashref->{$key}) eq 'ARRAY') {
5324: $result.=&arrayref2str($hashref->{$key}).'&';
5325: } elsif(ref($hashref->{$key}) eq 'HASH') {
5326: $result.=&hashref2str($hashref->{$key}).'&';
5327: } elsif(ref($hashref->{$key})) {
1.265 albertel 5328: $result.='&';
1.800 albertel 5329: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5330: } else {
1.800 albertel 5331: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5332: }
5333: }
1.168 albertel 5334: $result=~s/\&$//;
1.265 albertel 5335: $result .= '__END_HASH_REF__';
1.168 albertel 5336: return $result;
5337: }
5338:
5339: sub str2hash {
1.265 albertel 5340: my ($string)=@_;
5341: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5342: return %$hash;
5343: }
5344:
5345: sub str2hashref {
1.168 albertel 5346: my ($string) = @_;
1.265 albertel 5347:
5348: my %hash;
5349:
5350: if($string !~ /^__HASH_REF__/) {
5351: if (! ($string eq '' || !defined($string))) {
5352: $hash{'error'}='Not hash reference';
5353: }
5354: return (\%hash, $string);
5355: }
5356:
5357: $string =~ s/^__HASH_REF__//;
5358:
5359: while($string !~ /^__END_HASH_REF__/) {
5360: #key
5361: my $key='';
5362: if($string =~ /^__HASH_REF__/) {
5363: ($key, $string)=&str2hashref($string);
5364: if(defined($key->{'error'})) {
5365: $hash{'error'}='Bad data';
5366: return (\%hash, $string);
5367: }
5368: } elsif($string =~ /^__ARRAY_REF__/) {
5369: ($key, $string)=&str2arrayref($string);
5370: if($key->[0] eq 'Array reference error') {
5371: $hash{'error'}='Bad data';
5372: return (\%hash, $string);
5373: }
5374: } else {
5375: $string =~ s/^(.*?)=//;
1.267 albertel 5376: $key=&unescape($1);
1.265 albertel 5377: }
5378: $string =~ s/^=//;
5379:
5380: #value
5381: my $value='';
5382: if($string =~ /^__HASH_REF__/) {
5383: ($value, $string)=&str2hashref($string);
5384: if(defined($value->{'error'})) {
5385: $hash{'error'}='Bad data';
5386: return (\%hash, $string);
5387: }
5388: } elsif($string =~ /^__ARRAY_REF__/) {
5389: ($value, $string)=&str2arrayref($string);
5390: if($value->[0] eq 'Array reference error') {
5391: $hash{'error'}='Bad data';
5392: return (\%hash, $string);
5393: }
5394: } else {
5395: $value=&get_scalar(\$string,'__END_HASH_REF__');
5396: }
5397: $string =~ s/^&//;
5398:
5399: $hash{$key}=$value;
1.204 albertel 5400: }
1.265 albertel 5401:
5402: $string =~ s/^__END_HASH_REF__//;
5403:
5404: return (\%hash, $string);
1.204 albertel 5405: }
5406:
5407: sub str2array {
1.265 albertel 5408: my ($string)=@_;
5409: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5410: return @$array;
5411: }
5412:
5413: sub str2arrayref {
1.204 albertel 5414: my ($string) = @_;
1.265 albertel 5415: my @array;
5416:
5417: if($string !~ /^__ARRAY_REF__/) {
5418: if (! ($string eq '' || !defined($string))) {
5419: $array[0]='Array reference error';
5420: }
5421: return (\@array, $string);
5422: }
5423:
5424: $string =~ s/^__ARRAY_REF__//;
5425:
5426: while($string !~ /^__END_ARRAY_REF__/) {
5427: my $value='';
5428: if($string =~ /^__HASH_REF__/) {
5429: ($value, $string)=&str2hashref($string);
5430: if(defined($value->{'error'})) {
5431: $array[0] ='Array reference error';
5432: return (\@array, $string);
5433: }
5434: } elsif($string =~ /^__ARRAY_REF__/) {
5435: ($value, $string)=&str2arrayref($string);
5436: if($value->[0] eq 'Array reference error') {
5437: $array[0] ='Array reference error';
5438: return (\@array, $string);
5439: }
5440: } else {
5441: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5442: }
5443: $string =~ s/^&//;
5444:
5445: push(@array, $value);
1.191 harris41 5446: }
1.265 albertel 5447:
5448: $string =~ s/^__END_ARRAY_REF__//;
5449:
5450: return (\@array, $string);
1.168 albertel 5451: }
5452:
1.167 albertel 5453: # -------------------------------------------------------------------Temp Store
5454:
1.168 albertel 5455: sub tmpreset {
5456: my ($symb,$namespace,$domain,$stuname) = @_;
5457: if (!$symb) {
5458: $symb=&symbread();
1.620 albertel 5459: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5460: }
5461: $symb=escape($symb);
5462:
1.620 albertel 5463: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5464: $namespace=~s/\//\_/g;
5465: $namespace=~s/\W//g;
5466:
1.620 albertel 5467: if (!$domain) { $domain=$env{'user.domain'}; }
5468: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5469: if ($domain eq 'public' && $stuname eq 'public') {
5470: $stuname=$ENV{'REMOTE_ADDR'};
5471: }
1.1117 foxr 5472: my $path=LONCAPA::tempdir();
1.168 albertel 5473: my %hash;
5474: if (tie(%hash,'GDBM_File',
5475: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5476: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5477: foreach my $key (keys(%hash)) {
1.180 albertel 5478: if ($key=~ /:$symb/) {
1.168 albertel 5479: delete($hash{$key});
5480: }
5481: }
5482: }
5483: }
5484:
1.167 albertel 5485: sub tmpstore {
1.168 albertel 5486: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5487:
5488: if (!$symb) {
5489: $symb=&symbread();
1.620 albertel 5490: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5491: }
5492: $symb=escape($symb);
5493:
5494: if (!$namespace) {
5495: # I don't think we would ever want to store this for a course.
5496: # it seems this will only be used if we don't have a course.
1.620 albertel 5497: #$namespace=$env{'request.course.id'};
1.168 albertel 5498: #if (!$namespace) {
1.620 albertel 5499: $namespace=$env{'request.state'};
1.168 albertel 5500: #}
5501: }
5502: $namespace=~s/\//\_/g;
5503: $namespace=~s/\W//g;
1.620 albertel 5504: if (!$domain) { $domain=$env{'user.domain'}; }
5505: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5506: if ($domain eq 'public' && $stuname eq 'public') {
5507: $stuname=$ENV{'REMOTE_ADDR'};
5508: }
1.168 albertel 5509: my $now=time;
5510: my %hash;
1.1117 foxr 5511: my $path=LONCAPA::tempdir();
1.168 albertel 5512: if (tie(%hash,'GDBM_File',
5513: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5514: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5515: $hash{"version:$symb"}++;
5516: my $version=$hash{"version:$symb"};
5517: my $allkeys='';
5518: foreach my $key (keys(%$storehash)) {
5519: $allkeys.=$key.':';
1.591 albertel 5520: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5521: }
5522: $hash{"$version:$symb:timestamp"}=$now;
5523: $allkeys.='timestamp';
5524: $hash{"$version:keys:$symb"}=$allkeys;
5525: if (untie(%hash)) {
5526: return 'ok';
5527: } else {
5528: return "error:$!";
5529: }
5530: } else {
5531: return "error:$!";
5532: }
5533: }
1.167 albertel 5534:
1.168 albertel 5535: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5536:
1.168 albertel 5537: sub tmprestore {
5538: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5539:
1.168 albertel 5540: if (!$symb) {
5541: $symb=&symbread();
1.620 albertel 5542: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5543: }
5544: $symb=escape($symb);
5545:
1.620 albertel 5546: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5547:
1.620 albertel 5548: if (!$domain) { $domain=$env{'user.domain'}; }
5549: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5550: if ($domain eq 'public' && $stuname eq 'public') {
5551: $stuname=$ENV{'REMOTE_ADDR'};
5552: }
1.168 albertel 5553: my %returnhash;
5554: $namespace=~s/\//\_/g;
5555: $namespace=~s/\W//g;
5556: my %hash;
1.1117 foxr 5557: my $path=LONCAPA::tempdir();
1.168 albertel 5558: if (tie(%hash,'GDBM_File',
5559: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5560: &GDBM_READER(),0640)) {
1.168 albertel 5561: my $version=$hash{"version:$symb"};
5562: $returnhash{'version'}=$version;
5563: my $scope;
5564: for ($scope=1;$scope<=$version;$scope++) {
5565: my $vkeys=$hash{"$scope:keys:$symb"};
5566: my @keys=split(/:/,$vkeys);
5567: my $key;
5568: $returnhash{"$scope:keys"}=$vkeys;
5569: foreach $key (@keys) {
1.591 albertel 5570: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5571: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5572: }
5573: }
1.168 albertel 5574: if (!(untie(%hash))) {
5575: return "error:$!";
5576: }
5577: } else {
5578: return "error:$!";
5579: }
5580: return %returnhash;
1.167 albertel 5581: }
5582:
1.9 www 5583: # ----------------------------------------------------------------------- Store
5584:
5585: sub store {
1.1269 raeburn 5586: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5587: my $home='';
5588:
1.168 albertel 5589: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5590:
1.213 www 5591: $symb=&symbclean($symb);
1.122 albertel 5592: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5593:
1.620 albertel 5594: if (!$domain) { $domain=$env{'user.domain'}; }
5595: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5596:
5597: &devalidate($symb,$stuname,$domain);
1.109 www 5598:
5599: $symb=escape($symb);
1.187 www 5600: if (!$namespace) {
1.620 albertel 5601: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5602: return '';
5603: }
5604: }
1.620 albertel 5605: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5606:
5607: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5608: $$storehash{'host'}=$perlvar{'lonHostID'};
5609:
1.12 www 5610: my $namevalue='';
1.800 albertel 5611: foreach my $key (keys(%$storehash)) {
5612: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5613: }
1.12 www 5614: $namevalue=~s/\&$//;
1.187 www 5615: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 5616: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5617: }
5618:
1.47 www 5619: # -------------------------------------------------------------- Critical Store
5620:
5621: sub cstore {
1.1269 raeburn 5622: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5623: my $home='';
5624:
1.168 albertel 5625: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5626:
1.213 www 5627: $symb=&symbclean($symb);
1.122 albertel 5628: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5629:
1.620 albertel 5630: if (!$domain) { $domain=$env{'user.domain'}; }
5631: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5632:
5633: &devalidate($symb,$stuname,$domain);
1.109 www 5634:
5635: $symb=escape($symb);
1.187 www 5636: if (!$namespace) {
1.620 albertel 5637: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5638: return '';
5639: }
5640: }
1.620 albertel 5641: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5642:
5643: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5644: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5645:
1.47 www 5646: my $namevalue='';
1.800 albertel 5647: foreach my $key (keys(%$storehash)) {
5648: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5649: }
1.47 www 5650: $namevalue=~s/\&$//;
1.187 www 5651: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5652: return critical
1.1269 raeburn 5653: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5654: }
5655:
1.9 www 5656: # --------------------------------------------------------------------- Restore
5657:
5658: sub restore {
1.124 www 5659: my ($symb,$namespace,$domain,$stuname) = @_;
5660: my $home='';
5661:
1.168 albertel 5662: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5663:
1.122 albertel 5664: if (!$symb) {
1.1224 raeburn 5665: return if ($namespace eq 'courserequests');
5666: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5667: } else {
1.1224 raeburn 5668: unless ($namespace eq 'courserequests') {
5669: $symb=&escape(&symbclean($symb));
5670: }
1.122 albertel 5671: }
1.188 www 5672: if (!$namespace) {
1.620 albertel 5673: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5674: return '';
5675: }
5676: }
1.620 albertel 5677: if (!$domain) { $domain=$env{'user.domain'}; }
5678: if (!$stuname) { $stuname=$env{'user.name'}; }
5679: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5680: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5681:
1.12 www 5682: my %returnhash=();
1.800 albertel 5683: foreach my $line (split(/\&/,$answer)) {
5684: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5685: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5686: }
1.75 www 5687: my $version;
5688: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5689: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5690: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5691: }
1.75 www 5692: }
1.13 www 5693: return %returnhash;
1.34 www 5694: }
5695:
5696: # ---------------------------------------------------------- Course Description
1.1118 foxr 5697: #
5698: #
1.34 www 5699:
5700: sub coursedescription {
1.731 albertel 5701: my ($courseid,$args)=@_;
1.34 www 5702: $courseid=~s/^\///;
1.49 www 5703: $courseid=~s/\_/\//g;
1.34 www 5704: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5705: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5706: my $normalid=$cdomain.'_'.$cnum;
5707: # need to always cache even if we get errors otherwise we keep
5708: # trying and trying and trying to get the course description.
5709: my %envhash=();
5710: my %returnhash=();
1.731 albertel 5711:
5712: my $expiretime=600;
5713: if ($env{'request.course.id'} eq $normalid) {
5714: $expiretime=120;
5715: }
5716:
5717: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5718: if (!$args->{'freshen_cache'}
5719: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5720: foreach my $key (keys(%env)) {
5721: next if ($key !~ /^\Q$prefix\E(.*)/);
5722: my ($setting) = $1;
5723: $returnhash{$setting} = $env{$key};
5724: }
5725: return %returnhash;
5726: }
5727:
1.1118 foxr 5728: # get the data again
5729:
1.731 albertel 5730: if (!$args->{'one_time'}) {
5731: $envhash{'course.'.$normalid.'.last_cache'}=time;
5732: }
1.811 albertel 5733:
1.34 www 5734: if ($chome ne 'no_host') {
1.302 albertel 5735: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5736: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5737: my $username = $env{'user.name'}; # Defult username
5738: if(defined $args->{'user'}) {
5739: $username = $args->{'user'};
5740: }
1.129 albertel 5741: $returnhash{'home'}= $chome;
5742: $returnhash{'domain'} = $cdomain;
5743: $returnhash{'num'} = $cnum;
1.741 raeburn 5744: if (!defined($returnhash{'type'})) {
5745: $returnhash{'type'} = 'Course';
5746: }
1.130 albertel 5747: while (my ($name,$value) = each %returnhash) {
1.53 www 5748: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5749: }
1.270 www 5750: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5751: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5752: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5753: $envhash{'course.'.$normalid.'.home'}=$chome;
5754: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5755: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5756: }
5757: }
1.731 albertel 5758: if (!$args->{'one_time'}) {
1.949 raeburn 5759: &appenv(\%envhash);
1.731 albertel 5760: }
1.302 albertel 5761: return %returnhash;
1.461 www 5762: }
5763:
1.1080 raeburn 5764: sub update_released_required {
5765: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5766: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5767: $cid = $env{'request.course.id'};
5768: $cdom = $env{'course.'.$cid.'.domain'};
5769: $cnum = $env{'course.'.$cid.'.num'};
5770: $chome = $env{'course.'.$cid.'.home'};
5771: }
5772: if ($needsrelease) {
5773: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5774: my $needsupdate;
5775: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5776: $needsupdate = 1;
5777: } else {
5778: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5779: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5780: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5781: $needsupdate = 1;
5782: }
5783: }
5784: if ($needsupdate) {
5785: my %needshash = (
5786: 'internal.releaserequired' => $needsrelease,
5787: );
5788: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5789: if ($putresult eq 'ok') {
5790: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5791: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5792: if (ref($crsinfo{$cid}) eq 'HASH') {
5793: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5794: &courseidput($cdom,\%crsinfo,$chome,'notime');
5795: }
5796: }
5797: }
5798: }
5799: return;
5800: }
5801:
1.461 www 5802: # -------------------------------------------------See if a user is privileged
5803:
5804: sub privileged {
1.1219 raeburn 5805: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5806: my $now = time;
1.1219 raeburn 5807: my $roles;
5808: if (ref($possroles) eq 'ARRAY') {
5809: $roles = $possroles;
5810: } else {
5811: $roles = ['dc','su'];
5812: }
5813: if (ref($possdomains) eq 'ARRAY') {
5814: my %privileged = &privileged_by_domain($possdomains,$roles);
5815: foreach my $dom (@{$possdomains}) {
5816: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5817: (ref($privileged{$dom}) eq 'HASH')) {
5818: foreach my $role (@{$roles}) {
5819: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5820: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5821: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5822: return 1 unless (($end && $end < $now) ||
5823: ($start && $start > $now));
5824: }
5825: }
5826: }
5827: }
5828: }
5829: } else {
5830: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5831: my $now = time;
1.1170 droeschl 5832:
1.1275 musolffc 5833: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5834: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5835: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5836: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5837: or ($tstart && $tstart > $now);
1.1170 droeschl 5838: }
1.1219 raeburn 5839: }
5840: }
5841: return 0;
5842: }
1.1170 droeschl 5843:
1.1219 raeburn 5844: sub privileged_by_domain {
5845: my ($domains,$roles) = @_;
5846: my %privileged = ();
5847: my $cachetime = 60*60*24;
5848: my $now = time;
5849: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5850: return %privileged;
5851: }
5852: foreach my $dom (@{$domains}) {
5853: next if (ref($privileged{$dom}) eq 'HASH');
5854: my $needroles;
5855: foreach my $role (@{$roles}) {
5856: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5857: if (defined($cached)) {
5858: if (ref($result) eq 'HASH') {
5859: $privileged{$dom}{$role} = $result;
5860: }
5861: } else {
5862: $needroles = 1;
5863: }
5864: }
5865: if ($needroles) {
5866: my %dompersonnel = &get_domain_roles($dom,$roles);
5867: $privileged{$dom} = {};
5868: foreach my $server (keys(%dompersonnel)) {
5869: if (ref($dompersonnel{$server}) eq 'HASH') {
5870: foreach my $item (keys(%{$dompersonnel{$server}})) {
5871: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5872: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5873: next if ($end && $end < $now);
5874: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5875: $dompersonnel{$server}{$item};
5876: }
5877: }
5878: }
5879: if (ref($privileged{$dom}) eq 'HASH') {
5880: foreach my $role (@{$roles}) {
5881: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5882: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5883: } else {
5884: my %hash = ();
5885: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5886: }
5887: }
5888: }
5889: }
5890: }
5891: return %privileged;
1.9 www 5892: }
1.1 albertel 5893:
1.103 harris41 5894: # -------------------------------------------------------- Get user privileges
1.11 www 5895:
5896: sub rolesinit {
1.1169 droeschl 5897: my ($domain, $username) = @_;
5898: my %userroles = ('user.login.time' => time);
5899: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5900:
5901: # firstaccess and timerinterval are related to timed maps/resources.
5902: # also, blocking can be triggered by an activating timer
5903: # it's saved in the user's %env.
5904: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5905: my %timerinterval = &dump('timerinterval', $domain, $username);
5906: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5907: %timerintchk, %timerintenv);
5908:
1.1162 raeburn 5909: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5910: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5911: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5912: }
1.1169 droeschl 5913:
1.1162 raeburn 5914: foreach my $key (keys(%timerinterval)) {
5915: my ($cid,$rest) = split(/\0/,$key);
5916: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5917: }
1.1169 droeschl 5918:
1.11 www 5919: my %allroles=();
1.1162 raeburn 5920: my %allgroups=();
1.11 www 5921:
1.1274 raeburn 5922: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5923: my $role = $rolesdump{$area};
5924: $area =~ s/\_\w\w$//;
5925:
5926: my ($trole, $tend, $tstart, $group_privs);
5927:
5928: if ($role =~ /^cr/) {
5929: # Custom role, defined by a user
5930: # e.g., user.role.cr/msu/smith/mynewrole
5931: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5932: $trole = $1;
5933: ($tend, $tstart) = split('_', $2);
5934: } else {
5935: $trole = $role;
5936: }
5937: } elsif ($role =~ m|^gr/|) {
5938: # Role of member in a group, defined within a course/community
5939: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5940: ($trole, $tend, $tstart) = split(/_/, $role);
5941: next if $tstart eq '-1';
5942: ($trole, $group_privs) = split(/\//, $trole);
5943: $group_privs = &unescape($group_privs);
5944: } else {
5945: # Just a normal role, defined in roles.tab
5946: ($trole, $tend, $tstart) = split(/_/,$role);
5947: }
5948:
5949: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5950: $username);
5951: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5952:
5953: # role expired or not available yet?
5954: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5955: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5956:
5957: next if $area eq '' or $trole eq '';
5958:
5959: my $spec = "$trole.$area";
5960: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5961:
5962: if ($trole =~ /^cr\//) {
5963: # Custom role, defined by a user
5964: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5965: } elsif ($trole eq 'gr') {
5966: # Role of a member in a group, defined within a course/community
5967: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5968: next;
5969: } else {
5970: # Normal role, defined in roles.tab
5971: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5972: }
5973:
5974: my $cid = $tdomain.'_'.$trest;
5975: unless ($firstaccchk{$cid}) {
5976: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5977: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5978: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5979: $coursetimerstarts{$cid}{$item};
5980: }
5981: }
5982: $firstaccchk{$cid} = 1;
5983: }
5984: unless ($timerintchk{$cid}) {
5985: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5986: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5987: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5988: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5989: }
1.12 www 5990: }
1.1169 droeschl 5991: $timerintchk{$cid} = 1;
1.191 harris41 5992: }
1.11 www 5993: }
1.1169 droeschl 5994:
1.1341 raeburn 5995: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
5996: \%allroles, \%allgroups);
1.1169 droeschl 5997: $env{'user.adv'} = $userroles{'user.adv'};
1.1341 raeburn 5998: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 5999:
1.1162 raeburn 6000: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 6001: }
6002:
1.567 raeburn 6003: sub set_arearole {
1.1215 raeburn 6004: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6005: unless ($nolog) {
1.567 raeburn 6006: # log the associated role with the area
1.1215 raeburn 6007: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6008: }
1.743 albertel 6009: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6010: }
6011:
6012: sub custom_roleprivs {
6013: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6014: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 6015: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6016: if (&hostname($homsvr) ne '') {
1.567 raeburn 6017: my ($rdummy,$roledef)=
6018: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6019: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6020: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6021: if (defined($syspriv)) {
1.1043 raeburn 6022: if ($trest =~ /^$match_community$/) {
6023: $syspriv =~ s/bre\&S//;
6024: }
1.567 raeburn 6025: $$allroles{'cm./'}.=':'.$syspriv;
6026: $$allroles{$spec.'./'}.=':'.$syspriv;
6027: }
6028: if ($tdomain ne '') {
6029: if (defined($dompriv)) {
6030: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6031: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6032: }
6033: if (($trest ne '') && (defined($coursepriv))) {
1.1332 raeburn 6034: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6035: my $rolename = $1;
6036: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6037: }
1.567 raeburn 6038: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6039: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6040: }
6041: }
6042: }
6043: }
6044: }
6045:
1.1332 raeburn 6046: sub course_adhocrole_privs {
6047: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6048: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6049: if ($overrides{"internal.adhocpriv.$rolename"}) {
6050: my (%currprivs,%storeprivs);
6051: foreach my $item (split(/:/,$coursepriv)) {
6052: my ($priv,$restrict) = split(/\&/,$item);
6053: $currprivs{$priv} = $restrict;
6054: }
6055: my (%possadd,%possremove,%full);
6056: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6057: my ($priv,$restrict)=split(/\&/,$item);
6058: $full{$priv} = $restrict;
6059: }
6060: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6061: next if ($item eq '');
6062: my ($rule,$rest) = split(/=/,$item);
6063: next unless (($rule eq 'off') || ($rule eq 'on'));
6064: foreach my $priv (split(/:/,$rest)) {
6065: if ($priv ne '') {
6066: if ($rule eq 'off') {
6067: $possremove{$priv} = 1;
6068: } else {
6069: $possadd{$priv} = 1;
6070: }
6071: }
6072: }
6073: }
6074: foreach my $priv (sort(keys(%full))) {
6075: if (exists($currprivs{$priv})) {
6076: unless (exists($possremove{$priv})) {
6077: $storeprivs{$priv} = $currprivs{$priv};
6078: }
6079: } elsif (exists($possadd{$priv})) {
6080: $storeprivs{$priv} = $full{$priv};
6081: }
6082: }
6083: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6084: }
6085: return $coursepriv;
6086: }
6087:
1.678 raeburn 6088: sub group_roleprivs {
6089: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6090: my $access = 1;
6091: my $now = time;
6092: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6093: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6094: if ($access) {
1.811 albertel 6095: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6096: $$allgroups{$course}{$group} .=':'.$group_privs;
6097: }
6098: }
1.567 raeburn 6099:
6100: sub standard_roleprivs {
6101: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6102: if (defined($pr{$trole.':s'})) {
6103: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6104: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6105: }
6106: if ($tdomain ne '') {
6107: if (defined($pr{$trole.':d'})) {
6108: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6109: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6110: }
6111: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6112: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6113: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6114: }
6115: }
6116: }
6117:
6118: sub set_userprivs {
1.1064 raeburn 6119: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6120: my $author=0;
6121: my $adv=0;
1.1341 raeburn 6122: my $rar=0;
1.678 raeburn 6123: my %grouproles = ();
6124: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6125: my @groupkeys;
1.1000 raeburn 6126: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6127: push(@groupkeys,$role);
6128: }
6129: if (ref($groups_roles) eq 'HASH') {
6130: foreach my $key (keys(%{$groups_roles})) {
6131: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6132: push(@groupkeys,$key);
6133: }
6134: }
6135: }
6136: if (@groupkeys > 0) {
6137: foreach my $role (@groupkeys) {
6138: my ($trole,$area,$sec,$extendedarea);
6139: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6140: $trole = $1;
6141: $area = $2;
6142: $sec = $3;
6143: $extendedarea = $area.$sec;
6144: if (exists($$allgroups{$area})) {
6145: foreach my $group (keys(%{$$allgroups{$area}})) {
6146: my $spec = $trole.'.'.$extendedarea;
6147: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6148: $$allgroups{$area}{$group};
1.1064 raeburn 6149: }
1.678 raeburn 6150: }
6151: }
6152: }
6153: }
6154: }
1.800 albertel 6155: foreach my $group (keys(%grouproles)) {
6156: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6157: }
1.800 albertel 6158: foreach my $role (keys(%{$allroles})) {
6159: my %thesepriv;
1.941 raeburn 6160: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6161: foreach my $item (split(/:/,$$allroles{$role})) {
6162: if ($item ne '') {
6163: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 6164: if ($restrictions eq '') {
6165: $thesepriv{$privilege}='F';
6166: } elsif ($thesepriv{$privilege} ne 'F') {
6167: $thesepriv{$privilege}.=$restrictions;
6168: }
6169: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341 raeburn 6170: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 6171: }
6172: }
6173: my $thesestr='';
1.1104 raeburn 6174: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 6175: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6176: }
6177: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 6178: }
1.1341 raeburn 6179: return ($author,$adv,$rar);
1.567 raeburn 6180: }
6181:
1.994 raeburn 6182: sub role_status {
1.1104 raeburn 6183: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 6184: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 6185: my ($one,$two) = split(m{\./},$rolekey,2);
6186: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 6187: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 6188: $$where = '/'.$two;
1.994 raeburn 6189: $$trolecode=$$role.'.'.$$where;
6190: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6191: $$tstatus='is';
1.1104 raeburn 6192: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6193: $$tstatus='future';
1.1034 raeburn 6194: if ($$tstart<$now) {
6195: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6196: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6197: my (%allroles,%allgroups,$group_privs,
6198: %groups_roles,@rolecodes);
1.1002 raeburn 6199: my %userroles = (
6200: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6201: );
1.1064 raeburn 6202: @rolecodes = ('cm');
1.1002 raeburn 6203: my $spec=$$role.'.'.$$where;
6204: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6205: if ($$role =~ /^cr\//) {
6206: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6207: push(@rolecodes,'cr');
1.1002 raeburn 6208: } elsif ($$role eq 'gr') {
1.1064 raeburn 6209: push(@rolecodes,$$role);
1.1002 raeburn 6210: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6211: $env{'user.name'});
1.1064 raeburn 6212: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6213: (undef,my $group_privs) = split(/\//,$trole);
6214: $group_privs = &unescape($group_privs);
6215: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6216: 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 6217: &get_groups_roles($tdomain,$trest,
6218: \%course_roles,\@rolecodes,
6219: \%groups_roles);
1.1002 raeburn 6220: } else {
1.1064 raeburn 6221: push(@rolecodes,$$role);
1.1002 raeburn 6222: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6223: }
1.1341 raeburn 6224: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6225: \%groups_roles);
1.1064 raeburn 6226: &appenv(\%userroles,\@rolecodes);
1.1342 raeburn 6227: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 6228: }
6229: }
1.1034 raeburn 6230: $$tstatus = 'is';
1.1002 raeburn 6231: }
1.994 raeburn 6232: }
6233: if ($$tend) {
1.1104 raeburn 6234: if ($$tend<$update) {
1.994 raeburn 6235: $$tstatus='expired';
6236: } elsif ($$tend<$now) {
6237: $$tstatus='will_not';
6238: }
6239: }
6240: }
6241: }
6242: }
6243:
1.1104 raeburn 6244: sub get_groups_roles {
6245: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6246: return unless((ref($cdom_courseroles) eq 'HASH') &&
6247: (ref($rolecodes) eq 'ARRAY') &&
6248: (ref($groups_roles) eq 'HASH'));
6249: if (keys(%{$cdom_courseroles}) > 0) {
6250: my ($cnum) = ($rest =~ /^($match_courseid)/);
6251: if ($cdom ne '' && $cnum ne '') {
6252: foreach my $key (keys(%{$cdom_courseroles})) {
6253: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6254: my $crsrole = $1;
6255: my $crssec = $2;
6256: if ($crsrole =~ /^cr/) {
6257: unless (grep(/^cr$/,@{$rolecodes})) {
6258: push(@{$rolecodes},'cr');
6259: }
6260: } else {
6261: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6262: push(@{$rolecodes},$crsrole);
6263: }
6264: }
6265: my $rolekey = "$crsrole./$cdom/$cnum";
6266: if ($crssec ne '') {
6267: $rolekey .= "/$crssec";
6268: }
6269: $rolekey .= './';
6270: $groups_roles->{$rolekey} = $rolecodes;
6271: }
6272: }
6273: }
6274: }
6275: return;
6276: }
6277:
6278: sub delete_env_groupprivs {
6279: my ($where,$courseroles,$possroles) = @_;
6280: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6281: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6282: unless (ref($courseroles->{$udom}) eq 'HASH') {
6283: %{$courseroles->{$udom}} =
6284: &get_my_roles('','','userroles',['active'],
6285: $possroles,[$udom],1);
6286: }
6287: if (ref($courseroles->{$udom}) eq 'HASH') {
6288: foreach my $item (keys(%{$courseroles->{$udom}})) {
6289: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6290: my $area = '/'.$cdom.'/'.$cnum;
6291: my $privkey = "user.priv.$crsrole.$area";
6292: if ($crssec ne '') {
6293: $privkey .= '/'.$crssec;
6294: }
6295: $privkey .= ".$area/$group";
6296: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6297: }
6298: }
6299: return;
6300: }
6301:
1.994 raeburn 6302: sub check_adhoc_privs {
1.1329 raeburn 6303: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6304: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329 raeburn 6305: if ($sec) {
6306: $cckey .= '/'.$sec;
6307: }
1.1185 raeburn 6308: my $setprivs;
1.994 raeburn 6309: if ($env{$cckey}) {
6310: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6311: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6312: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329 raeburn 6313: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 6314: $setprivs = 1;
1.994 raeburn 6315: }
6316: } else {
1.1330 raeburn 6317: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 6318: $setprivs = 1;
1.994 raeburn 6319: }
1.1185 raeburn 6320: return $setprivs;
1.994 raeburn 6321: }
6322:
6323: sub set_adhoc_privileges {
1.1326 raeburn 6324: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329 raeburn 6325: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6326: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329 raeburn 6327: if ($sec ne '') {
6328: $area .= '/'.$sec;
6329: }
1.994 raeburn 6330: my $spec = $role.'.'.$area;
6331: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 6332: $env{'user.name'},1);
1.1326 raeburn 6333: my %rolehash = ();
1.1332 raeburn 6334: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6335: my $rolename = $1;
1.1326 raeburn 6336: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332 raeburn 6337: my %domdef = &get_domain_defaults($dcdom);
6338: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6339: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6340: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6341: }
6342: }
1.1326 raeburn 6343: } else {
6344: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6345: }
1.1341 raeburn 6346: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6347: &appenv(\%userroles,[$role,'cm']);
1.1342 raeburn 6348: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088 raeburn 6349: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6350: &appenv( {'request.role' => $spec,
6351: 'request.role.domain' => $dcdom,
1.1332 raeburn 6352: 'request.course.sec' => $sec,
1.1088 raeburn 6353: }
6354: );
6355: my $tadv=0;
6356: if (&allowed('adv') eq 'F') { $tadv=1; }
6357: &appenv({'request.role.adv' => $tadv});
6358: }
1.994 raeburn 6359: }
6360:
1.12 www 6361: # --------------------------------------------------------------- get interface
6362:
6363: sub get {
1.131 albertel 6364: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6365: my $items='';
1.800 albertel 6366: foreach my $item (@$storearr) {
6367: $items.=&escape($item).'&';
1.191 harris41 6368: }
1.12 www 6369: $items=~s/\&$//;
1.620 albertel 6370: if (!$udomain) { $udomain=$env{'user.domain'}; }
6371: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6372: my $uhome=&homeserver($uname,$udomain);
6373:
1.133 albertel 6374: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6375: my @pairs=split(/\&/,$rep);
1.273 albertel 6376: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6377: return @pairs;
6378: }
1.15 www 6379: my %returnhash=();
1.42 www 6380: my $i=0;
1.800 albertel 6381: foreach my $item (@$storearr) {
6382: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6383: $i++;
1.191 harris41 6384: }
1.15 www 6385: return %returnhash;
1.27 www 6386: }
6387:
6388: # --------------------------------------------------------------- del interface
6389:
6390: sub del {
1.133 albertel 6391: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6392: my $items='';
1.800 albertel 6393: foreach my $item (@$storearr) {
6394: $items.=&escape($item).'&';
1.191 harris41 6395: }
1.984 neumanie 6396:
1.27 www 6397: $items=~s/\&$//;
1.620 albertel 6398: if (!$udomain) { $udomain=$env{'user.domain'}; }
6399: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6400: my $uhome=&homeserver($uname,$udomain);
6401: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6402: }
6403:
6404: # -------------------------------------------------------------- dump interface
6405:
1.1180 droeschl 6406: sub unserialize {
6407: my ($rep, $escapedkeys) = @_;
6408:
6409: return {} if $rep =~ /^error/;
6410:
6411: my %returnhash=();
1.1252 raeburn 6412: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 6413: my ($key, $value) = split(/=/, $item, 2);
6414: $key = unescape($key) unless $escapedkeys;
6415: next if $key =~ /^error: 2 /;
1.1252 raeburn 6416: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 6417: }
6418: #return %returnhash;
6419: return \%returnhash;
6420: }
6421:
6422: # see Lond::dump_with_regexp
6423: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6424: sub dump {
1.1180 droeschl 6425: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6426: if (!$udomain) { $udomain=$env{'user.domain'}; }
6427: if (!$uname) { $uname=$env{'user.name'}; }
6428: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6429:
1.1266 raeburn 6430: if ($regexp) {
6431: $regexp=&escape($regexp);
6432: } else {
6433: $regexp='.';
6434: }
1.1180 droeschl 6435: if (grep { $_ eq $uhome } current_machine_ids()) {
6436: # user is hosted on this machine
1.1266 raeburn 6437: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 6438: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 6439: return %{unserialize($reply, $escapedkeys)};
6440: }
1.1166 raeburn 6441: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6442: my @pairs=split(/\&/,$rep);
6443: my %returnhash=();
1.1098 foxr 6444: if (!($rep =~ /^error/ )) {
6445: foreach my $item (@pairs) {
6446: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 6447: $key = unescape($key) unless $escapedkeys;
6448: #$key = &unescape($key);
1.1098 foxr 6449: next if ($key =~ /^error: 2 /);
6450: $returnhash{$key}=&thaw_unescape($value);
6451: }
1.755 albertel 6452: }
6453: return %returnhash;
1.407 www 6454: }
6455:
1.1098 foxr 6456:
1.717 albertel 6457: # --------------------------------------------------------- dumpstore interface
6458:
6459: sub dumpstore {
6460: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 6461: # same as dump but keys must be escaped. They may contain colon separated
6462: # lists of values that may themself contain colons (e.g. symbs).
6463: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6464: }
6465:
1.407 www 6466: # -------------------------------------------------------------- keys interface
6467:
6468: sub getkeys {
6469: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6470: if (!$udomain) { $udomain=$env{'user.domain'}; }
6471: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6472: my $uhome=&homeserver($uname,$udomain);
6473: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6474: my @keyarray=();
1.800 albertel 6475: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6476: next if ($key =~ /^error: 2 /);
1.800 albertel 6477: push(@keyarray,&unescape($key));
1.407 www 6478: }
6479: return @keyarray;
1.318 matthew 6480: }
6481:
1.319 matthew 6482: # --------------------------------------------------------------- currentdump
6483: sub currentdump {
1.328 matthew 6484: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6485: $courseid = $env{'request.course.id'} if (! defined($courseid));
6486: $sdom = $env{'user.domain'} if (! defined($sdom));
6487: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6488: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 6489: my $rep;
6490:
6491: if (grep { $_ eq $uhome } current_machine_ids()) {
6492: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6493: $courseid)));
6494: } else {
6495: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6496: }
6497:
1.318 matthew 6498: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6499: #
1.318 matthew 6500: my %returnhash=();
1.319 matthew 6501: #
1.1343 raeburn 6502: if ($rep eq 'unknown_cmd') {
1.319 matthew 6503: # an old lond will not know currentdump
6504: # Do a dump and make it look like a currentdump
1.822 albertel 6505: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6506: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6507: my %hash = @tmp;
6508: @tmp=();
1.424 matthew 6509: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6510: } else {
6511: my @pairs=split(/\&/,$rep);
1.800 albertel 6512: foreach my $pair (@pairs) {
6513: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6514: my ($symb,$param) = split(/:/,$key);
6515: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6516: &thaw_unescape($value);
1.319 matthew 6517: }
1.191 harris41 6518: }
1.12 www 6519: return %returnhash;
1.424 matthew 6520: }
6521:
6522: sub convert_dump_to_currentdump{
6523: my %hash = %{shift()};
6524: my %returnhash;
6525: # Code ripped from lond, essentially. The only difference
6526: # here is the unescaping done by lonnet::dump(). Conceivably
6527: # we might run in to problems with parameter names =~ /^v\./
6528: while (my ($key,$value) = each(%hash)) {
6529: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 6530: $symb = &unescape($symb);
6531: $param = &unescape($param);
1.424 matthew 6532: next if ($v eq 'version' || $symb eq 'keys');
6533: next if (exists($returnhash{$symb}) &&
6534: exists($returnhash{$symb}->{$param}) &&
6535: $returnhash{$symb}->{'v.'.$param} > $v);
6536: $returnhash{$symb}->{$param}=$value;
6537: $returnhash{$symb}->{'v.'.$param}=$v;
6538: }
6539: #
6540: # Remove all of the keys in the hashes which keep track of
6541: # the version of the parameter.
6542: while (my ($symb,$param_hash) = each(%returnhash)) {
6543: # use a foreach because we are going to delete from the hash.
6544: foreach my $key (keys(%$param_hash)) {
6545: delete($param_hash->{$key}) if ($key =~ /^v\./);
6546: }
6547: }
6548: return \%returnhash;
1.12 www 6549: }
6550:
1.627 albertel 6551: # ------------------------------------------------------ critical inc interface
6552:
6553: sub cinc {
6554: return &inc(@_,'critical');
6555: }
6556:
1.449 matthew 6557: # --------------------------------------------------------------- inc interface
6558:
6559: sub inc {
1.627 albertel 6560: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 6561: if (!$udomain) { $udomain=$env{'user.domain'}; }
6562: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 6563: my $uhome=&homeserver($uname,$udomain);
6564: my $items='';
6565: if (! ref($store)) {
6566: # got a single value, so use that instead
6567: $items = &escape($store).'=&';
6568: } elsif (ref($store) eq 'SCALAR') {
6569: $items = &escape($$store).'=&';
6570: } elsif (ref($store) eq 'ARRAY') {
6571: $items = join('=&',map {&escape($_);} @{$store});
6572: } elsif (ref($store) eq 'HASH') {
6573: while (my($key,$value) = each(%{$store})) {
6574: $items.= &escape($key).'='.&escape($value).'&';
6575: }
6576: }
6577: $items=~s/\&$//;
1.627 albertel 6578: if ($critical) {
6579: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6580: } else {
6581: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6582: }
1.449 matthew 6583: }
6584:
1.12 www 6585: # --------------------------------------------------------------- put interface
6586:
6587: sub put {
1.134 albertel 6588: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6589: if (!$udomain) { $udomain=$env{'user.domain'}; }
6590: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6591: my $uhome=&homeserver($uname,$udomain);
1.12 www 6592: my $items='';
1.800 albertel 6593: foreach my $item (keys(%$storehash)) {
6594: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6595: }
1.12 www 6596: $items=~s/\&$//;
1.134 albertel 6597: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6598: }
6599:
1.631 albertel 6600: # ------------------------------------------------------------ newput interface
6601:
6602: sub newput {
6603: my ($namespace,$storehash,$udomain,$uname)=@_;
6604: if (!$udomain) { $udomain=$env{'user.domain'}; }
6605: if (!$uname) { $uname=$env{'user.name'}; }
6606: my $uhome=&homeserver($uname,$udomain);
6607: my $items='';
6608: foreach my $key (keys(%$storehash)) {
6609: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6610: }
6611: $items=~s/\&$//;
6612: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6613: }
6614:
6615: # --------------------------------------------------------- putstore interface
6616:
1.524 raeburn 6617: sub putstore {
1.1269 raeburn 6618: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6619: if (!$udomain) { $udomain=$env{'user.domain'}; }
6620: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6621: my $uhome=&homeserver($uname,$udomain);
6622: my $items='';
1.715 albertel 6623: foreach my $key (keys(%$storehash)) {
6624: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6625: }
1.715 albertel 6626: $items=~s/\&$//;
1.716 albertel 6627: my $esc_symb=&escape($symb);
6628: my $esc_v=&escape($version);
1.715 albertel 6629: my $reply =
1.716 albertel 6630: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6631: $uhome);
1.1269 raeburn 6632: if (($tolog) && ($reply eq 'ok')) {
6633: my $namevalue='';
6634: foreach my $key (keys(%{$storehash})) {
6635: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6636: }
6637: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6638: '&host='.&escape($perlvar{'lonHostID'}).
6639: '&version='.$esc_v.
6640: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6641: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6642: }
1.715 albertel 6643: if ($reply eq 'unknown_cmd') {
1.716 albertel 6644: # gfall back to way things use to be done
1.715 albertel 6645: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6646: $uname);
1.524 raeburn 6647: }
1.715 albertel 6648: return $reply;
6649: }
6650:
6651: sub old_putstore {
1.716 albertel 6652: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6653: if (!$udomain) { $udomain=$env{'user.domain'}; }
6654: if (!$uname) { $uname=$env{'user.name'}; }
6655: my $uhome=&homeserver($uname,$udomain);
6656: my %newstorehash;
1.800 albertel 6657: foreach my $item (keys(%$storehash)) {
6658: my $key = $version.':'.&escape($symb).':'.$item;
6659: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6660: }
6661: my $items='';
6662: my %allitems = ();
1.800 albertel 6663: foreach my $item (keys(%newstorehash)) {
6664: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6665: my $key = $1.':keys:'.$2;
6666: $allitems{$key} .= $3.':';
6667: }
1.800 albertel 6668: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6669: }
1.800 albertel 6670: foreach my $item (keys(%allitems)) {
6671: $allitems{$item} =~ s/\:$//;
6672: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6673: }
6674: $items=~s/\&$//;
6675: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6676: }
6677:
1.47 www 6678: # ------------------------------------------------------ critical put interface
6679:
6680: sub cput {
1.134 albertel 6681: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6682: if (!$udomain) { $udomain=$env{'user.domain'}; }
6683: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6684: my $uhome=&homeserver($uname,$udomain);
1.47 www 6685: my $items='';
1.800 albertel 6686: foreach my $item (keys(%$storehash)) {
6687: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6688: }
1.47 www 6689: $items=~s/\&$//;
1.134 albertel 6690: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6691: }
6692:
6693: # -------------------------------------------------------------- eget interface
6694:
6695: sub eget {
1.133 albertel 6696: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6697: my $items='';
1.800 albertel 6698: foreach my $item (@$storearr) {
6699: $items.=&escape($item).'&';
1.191 harris41 6700: }
1.12 www 6701: $items=~s/\&$//;
1.620 albertel 6702: if (!$udomain) { $udomain=$env{'user.domain'}; }
6703: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6704: my $uhome=&homeserver($uname,$udomain);
6705: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6706: my @pairs=split(/\&/,$rep);
6707: my %returnhash=();
1.42 www 6708: my $i=0;
1.800 albertel 6709: foreach my $item (@$storearr) {
6710: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6711: $i++;
1.191 harris41 6712: }
1.12 www 6713: return %returnhash;
6714: }
6715:
1.667 albertel 6716: # ------------------------------------------------------------ tmpput interface
6717: sub tmpput {
1.802 raeburn 6718: my ($storehash,$server,$context)=@_;
1.667 albertel 6719: my $items='';
1.800 albertel 6720: foreach my $item (keys(%$storehash)) {
6721: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6722: }
6723: $items=~s/\&$//;
1.802 raeburn 6724: if (defined($context)) {
6725: $items .= ':'.&escape($context);
6726: }
1.667 albertel 6727: return &reply("tmpput:$items",$server);
6728: }
6729:
6730: # ------------------------------------------------------------ tmpget interface
6731: sub tmpget {
1.688 albertel 6732: my ($token,$server)=@_;
6733: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6734: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6735: my %returnhash;
1.1328 raeburn 6736: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
6737: return %returnhash;
6738: }
1.667 albertel 6739: foreach my $item (split(/\&/,$rep)) {
6740: my ($key,$value)=split(/=/,$item);
6741: $returnhash{&unescape($key)}=&thaw_unescape($value);
6742: }
6743: return %returnhash;
6744: }
6745:
1.1113 raeburn 6746: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6747: sub tmpdel {
6748: my ($token,$server)=@_;
6749: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6750: return &reply("tmpdel:$token",$server);
6751: }
6752:
1.1198 raeburn 6753: # ------------------------------------------------------------ get_timebased_id
6754:
6755: sub get_timebased_id {
6756: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6757: $maxtries) = @_;
6758: my ($newid,$error,$dellock);
6759: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6760: return ('','ok','invalid call to get suffix');
6761: }
6762:
6763: # set defaults for any optional args for which values were not supplied
6764: if ($who eq '') {
6765: $who = $env{'user.name'}.':'.$env{'user.domain'};
6766: }
6767: if (!$locktries) {
6768: $locktries = 3;
6769: }
6770: if (!$maxtries) {
6771: $maxtries = 10;
6772: }
6773:
6774: if (($cdom eq '') || ($cnum eq '')) {
6775: if ($env{'request.course.id'}) {
6776: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6777: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6778: }
6779: if (($cdom eq '') || ($cnum eq '')) {
6780: return ('','ok','call to get suffix not in course context');
6781: }
6782: }
6783:
6784: # construct locking item
6785: my $lockhash = {
6786: $prefix."\0".'locked_'.$keyid => $who,
6787: };
6788: my $tries = 0;
6789:
6790: # attempt to get lock on nohist_$namespace file
6791: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6792: while (($gotlock ne 'ok') && $tries <$locktries) {
6793: $tries ++;
6794: sleep 1;
6795: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6796: }
6797:
6798: # attempt to get unique identifier, based on current timestamp
6799: if ($gotlock eq 'ok') {
6800: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6801: my $id = time;
6802: $newid = $id;
1.1268 raeburn 6803: if ($idtype eq 'addcode') {
6804: $newid .= &sixnum_code();
6805: }
1.1198 raeburn 6806: my $idtries = 0;
6807: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6808: if ($idtype eq 'concat') {
6809: $newid = $id.$idtries;
1.1268 raeburn 6810: } elsif ($idtype eq 'addcode') {
6811: $newid = $newid.&sixnum_code();
1.1198 raeburn 6812: } else {
6813: $newid ++;
6814: }
6815: $idtries ++;
6816: }
6817: if (!exists($inuse{$prefix."\0".$newid})) {
6818: my %new_item = (
6819: $prefix."\0".$newid => $who,
6820: );
6821: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6822: $cdom,$cnum);
6823: if ($putresult ne 'ok') {
6824: undef($newid);
6825: $error = 'error saving new item: '.$putresult;
6826: }
6827: } else {
1.1268 raeburn 6828: undef($newid);
1.1198 raeburn 6829: $error = ('error: no unique suffix available for the new item ');
6830: }
6831: # remove lock
6832: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6833: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6834: } else {
6835: $error = "error: could not obtain lockfile\n";
6836: $dellock = 'ok';
1.1276 raeburn 6837: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6838: $dellock = 'nolock';
6839: }
1.1198 raeburn 6840: }
6841: return ($newid,$dellock,$error);
6842: }
6843:
1.1268 raeburn 6844: sub sixnum_code {
6845: my $code;
6846: for (0..6) {
6847: $code .= int( rand(9) );
6848: }
6849: return $code;
6850: }
6851:
1.765 albertel 6852: # -------------------------------------------------- portfolio access checking
6853:
6854: sub portfolio_access {
1.1270 raeburn 6855: my ($requrl,$clientip) = @_;
1.765 albertel 6856: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 6857: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6858: if ($result) {
6859: my %setters;
6860: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6861: my ($startblock,$endblock) =
6862: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6863: if ($startblock && $endblock) {
6864: return 'B';
6865: }
6866: } else {
6867: my ($startblock,$endblock) =
6868: &Apache::loncommon::blockcheck(\%setters,'port');
6869: if ($startblock && $endblock) {
6870: return 'B';
6871: }
6872: }
6873: }
1.765 albertel 6874: if ($result eq 'ok') {
1.766 albertel 6875: return 'F';
1.765 albertel 6876: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6877: return 'A';
1.765 albertel 6878: }
1.766 albertel 6879: return '';
1.765 albertel 6880: }
6881:
6882: sub get_portfolio_access {
1.1270 raeburn 6883: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6884:
6885: if (!ref($access_hash)) {
6886: my $current_perms = &get_portfile_permissions($udom,$unum);
6887: my %access_controls = &get_access_controls($current_perms,$group,
6888: $file_name);
6889: $access_hash = $access_controls{$file_name};
6890: }
6891:
1.1270 raeburn 6892: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6893: my $now = time;
6894: if (ref($access_hash) eq 'HASH') {
6895: foreach my $key (keys(%{$access_hash})) {
6896: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6897: if ($start > $now) {
6898: next;
6899: }
6900: if ($end && $end<$now) {
6901: next;
6902: }
6903: if ($scope eq 'public') {
6904: $public = $key;
6905: last;
6906: } elsif ($scope eq 'guest') {
6907: $guest = $key;
6908: } elsif ($scope eq 'domains') {
6909: push(@domains,$key);
6910: } elsif ($scope eq 'users') {
6911: push(@users,$key);
6912: } elsif ($scope eq 'course') {
6913: push(@courses,$key);
6914: } elsif ($scope eq 'group') {
6915: push(@groups,$key);
1.1270 raeburn 6916: } elsif ($scope eq 'ip') {
6917: push(@ips,$key);
1.765 albertel 6918: }
6919: }
6920: if ($public) {
6921: return 'ok';
1.1270 raeburn 6922: } elsif (@ips > 0) {
6923: my $allowed;
6924: foreach my $ipkey (@ips) {
6925: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6926: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6927: $allowed = 1;
6928: last;
6929: }
6930: }
6931: }
6932: if ($allowed) {
6933: return 'ok';
6934: }
1.765 albertel 6935: }
6936: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6937: if ($guest) {
6938: return $guest;
6939: }
6940: } else {
6941: if (@domains > 0) {
6942: foreach my $domkey (@domains) {
6943: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6944: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6945: return 'ok';
6946: }
6947: }
6948: }
6949: }
6950: if (@users > 0) {
6951: foreach my $userkey (@users) {
1.865 raeburn 6952: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6953: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6954: if (ref($item) eq 'HASH') {
6955: if (($item->{'uname'} eq $env{'user.name'}) &&
6956: ($item->{'udom'} eq $env{'user.domain'})) {
6957: return 'ok';
6958: }
6959: }
6960: }
6961: }
1.765 albertel 6962: }
6963: }
6964: my %roleshash;
6965: my @courses_and_groups = @courses;
6966: push(@courses_and_groups,@groups);
6967: if (@courses_and_groups > 0) {
6968: my (%allgroups,%allroles);
6969: my ($start,$end,$role,$sec,$group);
6970: foreach my $envkey (%env) {
1.1060 raeburn 6971: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6972: my $cid = $2.'_'.$3;
6973: if ($1 eq 'gr') {
6974: $group = $4;
6975: $allgroups{$cid}{$group} = $env{$envkey};
6976: } else {
6977: if ($4 eq '') {
6978: $sec = 'none';
6979: } else {
6980: $sec = $4;
6981: }
6982: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6983: }
1.811 albertel 6984: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6985: my $cid = $2.'_'.$3;
6986: if ($4 eq '') {
6987: $sec = 'none';
6988: } else {
6989: $sec = $4;
6990: }
6991: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6992: }
6993: }
6994: if (keys(%allroles) == 0) {
6995: return;
6996: }
6997: foreach my $key (@courses_and_groups) {
6998: my %content = %{$$access_hash{$key}};
6999: my $cnum = $content{'number'};
7000: my $cdom = $content{'domain'};
7001: my $cid = $cdom.'_'.$cnum;
7002: if (!exists($allroles{$cid})) {
7003: next;
7004: }
7005: foreach my $role_id (keys(%{$content{'roles'}})) {
7006: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7007: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7008: my @status = @{$content{'roles'}{$role_id}{'access'}};
7009: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7010: foreach my $role (keys(%{$allroles{$cid}})) {
7011: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7012: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7013: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7014: if (grep/^all$/,@sections) {
7015: return 'ok';
7016: } else {
7017: if (grep/^$sec$/,@sections) {
7018: return 'ok';
7019: }
7020: }
7021: }
7022: }
7023: if (keys(%{$allgroups{$cid}}) == 0) {
7024: if (grep/^none$/,@groups) {
7025: return 'ok';
7026: }
7027: } else {
7028: if (grep/^all$/,@groups) {
7029: return 'ok';
7030: }
7031: foreach my $group (keys(%{$allgroups{$cid}})) {
7032: if (grep/^$group$/,@groups) {
7033: return 'ok';
7034: }
7035: }
7036: }
7037: }
7038: }
7039: }
7040: }
7041: }
7042: if ($guest) {
7043: return $guest;
7044: }
7045: }
7046: }
7047: return;
7048: }
7049:
7050: sub course_group_datechecker {
7051: my ($dates,$now,$status) = @_;
7052: my ($start,$end) = split(/\./,$dates);
7053: if (!$start && !$end) {
7054: return 'ok';
7055: }
7056: if (grep/^active$/,@{$status}) {
7057: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7058: return 'ok';
7059: }
7060: }
7061: if (grep/^previous$/,@{$status}) {
7062: if ($end > $now ) {
7063: return 'ok';
7064: }
7065: }
7066: if (grep/^future$/,@{$status}) {
7067: if ($start > $now) {
7068: return 'ok';
7069: }
7070: }
7071: return;
7072: }
7073:
7074: sub parse_portfolio_url {
7075: my ($url) = @_;
7076:
7077: my ($type,$udom,$unum,$group,$file_name);
7078:
1.823 albertel 7079: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7080: $type = 1;
7081: $udom = $1;
7082: $unum = $2;
7083: $file_name = $3;
1.823 albertel 7084: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7085: $type = 2;
7086: $udom = $1;
7087: $unum = $2;
7088: $group = $3;
7089: $file_name = $3.'/'.$4;
7090: }
7091: if (wantarray) {
7092: return ($type,$udom,$unum,$file_name,$group);
7093: }
7094: return $type;
7095: }
7096:
7097: sub is_portfolio_url {
7098: my ($url) = @_;
7099: return scalar(&parse_portfolio_url($url));
7100: }
7101:
1.798 raeburn 7102: sub is_portfolio_file {
7103: my ($file) = @_;
1.820 raeburn 7104: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7105: return 1;
7106: }
7107: return;
7108: }
7109:
1.976 raeburn 7110: sub usertools_access {
1.1084 raeburn 7111: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7112: my ($access,%tools);
7113: if ($context eq '') {
7114: $context = 'tools';
7115: }
7116: if ($context eq 'requestcourses') {
7117: %tools = (
7118: official => 1,
7119: unofficial => 1,
1.1006 raeburn 7120: community => 1,
1.1246 raeburn 7121: textbook => 1,
1.1305 raeburn 7122: placement => 1,
1.985 raeburn 7123: );
1.1183 raeburn 7124: } elsif ($context eq 'requestauthor') {
7125: %tools = (
7126: requestauthor => 1,
7127: );
1.985 raeburn 7128: } else {
7129: %tools = (
7130: aboutme => 1,
7131: blog => 1,
1.1177 raeburn 7132: webdav => 1,
1.985 raeburn 7133: portfolio => 1,
7134: );
7135: }
1.976 raeburn 7136: return if (!defined($tools{$tool}));
7137:
1.1242 raeburn 7138: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7139: $udom = $env{'user.domain'};
7140: $uname = $env{'user.name'};
7141: }
7142:
1.978 raeburn 7143: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7144: if ($action ne 'reload') {
1.985 raeburn 7145: if ($context eq 'requestcourses') {
7146: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 7147: } elsif ($context eq 'requestauthor') {
7148: return $env{'environment.canrequest.author'};
1.985 raeburn 7149: } else {
7150: return $env{'environment.availabletools.'.$tool};
7151: }
7152: }
1.976 raeburn 7153: }
7154:
1.1183 raeburn 7155: my ($toolstatus,$inststatus,$envkey);
7156: if ($context eq 'requestauthor') {
7157: $envkey = $context;
7158: } else {
7159: $envkey = $context.'.'.$tool;
7160: }
1.976 raeburn 7161:
1.985 raeburn 7162: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7163: ($action ne 'reload')) {
1.1183 raeburn 7164: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 7165: $inststatus = $env{'environment.inststatus'};
7166: } else {
1.1084 raeburn 7167: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 7168: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 7169: $inststatus = $userenvref->{'inststatus'};
7170: } else {
1.1183 raeburn 7171: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7172: $toolstatus = $userenv{$envkey};
1.1084 raeburn 7173: $inststatus = $userenv{'inststatus'};
7174: }
1.976 raeburn 7175: }
7176:
7177: if ($toolstatus ne '') {
7178: if ($toolstatus) {
7179: $access = 1;
7180: } else {
7181: $access = 0;
7182: }
7183: return $access;
7184: }
7185:
1.1084 raeburn 7186: my ($is_adv,%domdef);
7187: if (ref($is_advref) eq 'HASH') {
7188: $is_adv = $is_advref->{'is_adv'};
7189: } else {
7190: $is_adv = &is_advanced_user($udom,$uname);
7191: }
7192: if (ref($domdefref) eq 'HASH') {
7193: %domdef = %{$domdefref};
7194: } else {
7195: %domdef = &get_domain_defaults($udom);
7196: }
1.976 raeburn 7197: if (ref($domdef{$tool}) eq 'HASH') {
7198: if ($is_adv) {
7199: if ($domdef{$tool}{'_LC_adv'} ne '') {
7200: if ($domdef{$tool}{'_LC_adv'}) {
7201: $access = 1;
7202: } else {
7203: $access = 0;
7204: }
7205: return $access;
7206: }
7207: }
7208: if ($inststatus ne '') {
7209: my ($hasaccess,$hasnoaccess);
7210: foreach my $affiliation (split(/:/,$inststatus)) {
7211: if ($domdef{$tool}{$affiliation} ne '') {
7212: if ($domdef{$tool}{$affiliation}) {
7213: $hasaccess = 1;
7214: } else {
7215: $hasnoaccess = 1;
7216: }
7217: }
7218: }
7219: if ($hasaccess || $hasnoaccess) {
7220: if ($hasaccess) {
7221: $access = 1;
7222: } elsif ($hasnoaccess) {
7223: $access = 0;
7224: }
7225: return $access;
7226: }
7227: } else {
7228: if ($domdef{$tool}{'default'} ne '') {
7229: if ($domdef{$tool}{'default'}) {
7230: $access = 1;
7231: } elsif ($domdef{$tool}{'default'} == 0) {
7232: $access = 0;
7233: }
7234: return $access;
7235: }
7236: }
7237: } else {
1.1177 raeburn 7238: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7239: $access = 1;
7240: } else {
7241: $access = 0;
7242: }
1.976 raeburn 7243: return $access;
7244: }
7245: }
7246:
1.1050 raeburn 7247: sub is_course_owner {
7248: my ($cdom,$cnum,$udom,$uname) = @_;
7249: if (($udom eq '') || ($uname eq '')) {
7250: $udom = $env{'user.domain'};
7251: $uname = $env{'user.name'};
7252: }
7253: unless (($udom eq '') || ($uname eq '')) {
7254: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7255: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7256: return 1;
7257: } else {
7258: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7259: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7260: return 1;
7261: }
7262: }
7263: }
7264: }
7265: return;
7266: }
7267:
1.976 raeburn 7268: sub is_advanced_user {
7269: my ($udom,$uname) = @_;
1.1085 raeburn 7270: if ($udom ne '' && $uname ne '') {
7271: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7272: if (wantarray) {
7273: return ($env{'user.adv'},$env{'user.author'});
7274: } else {
7275: return $env{'user.adv'};
7276: }
1.1085 raeburn 7277: }
7278: }
1.976 raeburn 7279: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7280: my %allroles;
1.1128 raeburn 7281: my ($is_adv,$is_author);
1.976 raeburn 7282: foreach my $role (keys(%roleshash)) {
7283: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7284: my $area = '/'.$tdomain.'/'.$trest;
7285: if ($sec ne '') {
7286: $area .= '/'.$sec;
7287: }
7288: if (($area ne '') && ($trole ne '')) {
7289: my $spec=$trole.'.'.$area;
7290: if ($trole =~ /^cr\//) {
7291: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7292: } elsif ($trole ne 'gr') {
7293: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7294: }
1.1128 raeburn 7295: if ($trole eq 'au') {
7296: $is_author = 1;
7297: }
1.976 raeburn 7298: }
7299: }
7300: foreach my $role (keys(%allroles)) {
7301: last if ($is_adv);
7302: foreach my $item (split(/:/,$allroles{$role})) {
7303: if ($item ne '') {
7304: my ($privilege,$restrictions)=split(/&/,$item);
7305: if ($privilege eq 'adv') {
7306: $is_adv = 1;
7307: last;
7308: }
7309: }
7310: }
7311: }
1.1128 raeburn 7312: if (wantarray) {
7313: return ($is_adv,$is_author);
7314: }
1.976 raeburn 7315: return $is_adv;
7316: }
1.798 raeburn 7317:
1.1035 raeburn 7318: sub check_can_request {
1.1036 raeburn 7319: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7320: my $canreq = 0;
7321: my ($types,$typename) = &Apache::loncommon::course_types();
7322: my @options = ('approval','validate','autolimit');
7323: my $optregex = join('|',@options);
7324: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7325: foreach my $type (@{$types}) {
7326: if (&usertools_access($env{'user.name'},
7327: $env{'user.domain'},
7328: $type,undef,'requestcourses')) {
7329: $canreq ++;
1.1036 raeburn 7330: if (ref($request_domains) eq 'HASH') {
7331: push(@{$request_domains->{$type}},$env{'user.domain'});
7332: }
1.1035 raeburn 7333: if ($dom eq $env{'user.domain'}) {
7334: $can_request->{$type} = 1;
7335: }
7336: }
7337: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7338: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7339: if (@curr > 0) {
1.1036 raeburn 7340: foreach my $item (@curr) {
7341: if (ref($request_domains) eq 'HASH') {
7342: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7343: if ($otherdom ne '') {
7344: if (ref($request_domains->{$type}) eq 'ARRAY') {
7345: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7346: push(@{$request_domains->{$type}},$otherdom);
7347: }
7348: } else {
7349: push(@{$request_domains->{$type}},$otherdom);
7350: }
7351: }
7352: }
7353: }
7354: unless($dom eq $env{'user.domain'}) {
7355: $canreq ++;
1.1035 raeburn 7356: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7357: $can_request->{$type} = 1;
7358: }
7359: }
7360: }
7361: }
7362: }
7363: }
7364: return $canreq;
7365: }
7366:
1.341 www 7367: # ---------------------------------------------- Custom access rule evaluation
7368:
7369: sub customaccess {
7370: my ($priv,$uri)=@_;
1.807 albertel 7371: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7372: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7373: $udom = &LONCAPA::clean_domain($udom);
7374: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7375: my $access=0;
1.800 albertel 7376: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7377: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7378: if ($type eq 'user') {
7379: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7380: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7381: if ($tdom) {
7382: if ($tdom ne $env{'user.domain'}) { next; }
7383: }
1.896 albertel 7384: if ($tuname) {
7385: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7386: }
7387: $access=($effect eq 'allow');
7388: last;
7389: }
7390: } else {
7391: if ($role) {
7392: if ($role ne $urole) { next; }
7393: }
7394: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7395: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7396: if ($tdom) {
7397: if ($tdom ne $udom) { next; }
7398: }
7399: if ($tcrs) {
7400: if ($tcrs ne $ucrs) { next; }
7401: }
7402: if ($tsec) {
7403: if ($tsec ne $usec) { next; }
7404: }
7405: $access=($effect eq 'allow');
7406: last;
7407: }
7408: if ($realm eq '' && $role eq '') {
7409: $access=($effect eq 'allow');
7410: }
1.402 bowersj2 7411: }
1.341 www 7412: }
7413: return $access;
7414: }
7415:
1.103 harris41 7416: # ------------------------------------------------- Check for a user privilege
1.12 www 7417:
7418: sub allowed {
1.1281 raeburn 7419: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 7420: my $ver_orguri=$uri;
1.439 www 7421: $uri=&deversion($uri);
1.152 www 7422: my $orguri=$uri;
1.52 www 7423: $uri=&declutter($uri);
1.809 raeburn 7424:
1.810 raeburn 7425: if ($priv eq 'evb') {
7426: # Evade communication block restrictions for specified role in a course
7427: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7428: return $1;
7429: } else {
7430: return;
7431: }
7432: }
7433:
1.620 albertel 7434: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7435: # Free bre access to adm and meta resources
1.1343 raeburn 7436: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$}))
1.769 albertel 7437: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7438: && ($priv eq 'bre')) {
1.14 www 7439: return 'F';
1.159 www 7440: }
7441:
1.545 banghart 7442: # Free bre access to user's own portfolio contents
1.714 raeburn 7443: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7444: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7445: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7446: my %setters;
7447: my ($startblock,$endblock) =
7448: &Apache::loncommon::blockcheck(\%setters,'port');
7449: if ($startblock && $endblock) {
7450: return 'B';
7451: } else {
7452: return 'F';
7453: }
1.545 banghart 7454: }
7455:
1.762 raeburn 7456: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7457: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7458: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7459: if (exists($env{'request.course.id'})) {
7460: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7461: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7462: if (($domain eq $cdom) && ($name eq $cnum)) {
7463: my $courseprivid=$env{'request.course.id'};
7464: $courseprivid=~s/\_/\//;
7465: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7466: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7467: return $1;
1.762 raeburn 7468: } else {
7469: if ($env{'request.course.sec'}) {
7470: $courseprivid.='/'.$env{'request.course.sec'};
7471: }
7472: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7473: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7474: return $2;
7475: }
1.714 raeburn 7476: }
7477: }
7478: }
7479: }
7480:
1.159 www 7481: # Free bre to public access
7482:
7483: if ($priv eq 'bre') {
1.238 www 7484: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7485: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7486: return 'F';
7487: }
1.238 www 7488: if ($copyright eq 'priv') {
7489: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7490: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7491: return '';
7492: }
7493: }
7494: if ($copyright eq 'domain') {
7495: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7496: unless (($env{'user.domain'} eq $1) ||
7497: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7498: return '';
7499: }
1.262 matthew 7500: }
1.620 albertel 7501: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7502: # Library role, so allow browsing of resources in this domain.
7503: return 'F';
1.238 www 7504: }
1.341 www 7505: if ($copyright eq 'custom') {
7506: unless (&customaccess($priv,$uri)) { return ''; }
7507: }
1.14 www 7508: }
1.264 matthew 7509: # Domain coordinator is trying to create a course
1.620 albertel 7510: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7511: # uri is the requested domain in this case.
7512: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7513: # a role of dc for the domain in question.
1.620 albertel 7514: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7515: }
1.29 www 7516:
1.52 www 7517: my $thisallowed='';
7518: my $statecond=0;
7519: my $courseprivid='';
7520:
1.1039 raeburn 7521: my $ownaccess;
1.1043 raeburn 7522: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7523: if (($priv eq 'bro') && ($env{'user.author'})) {
7524: if ($uri eq '') {
7525: $ownaccess = 1;
7526: } else {
7527: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7528: my $udom = $env{'user.domain'};
7529: my $uname = $env{'user.name'};
7530: if ($uri =~ m{^\Q$udom\E/?$}) {
7531: $ownaccess = 1;
1.1040 raeburn 7532: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 7533: unless ($uri =~ m{\.\./}) {
7534: $ownaccess = 1;
7535: }
7536: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7537: my $now = time;
7538: if ($uri =~ m{^([^/]+)/?$}) {
7539: my $adom = $1;
7540: foreach my $key (keys(%env)) {
1.1042 raeburn 7541: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 7542: my ($start,$end) = split('.',$env{$key});
7543: if (($now >= $start) && (!$end || $end < $now)) {
7544: $ownaccess = 1;
7545: last;
7546: }
7547: }
7548: }
7549: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7550: my $adom = $1;
7551: my $aname = $2;
1.1042 raeburn 7552: foreach my $role ('ca','aa') {
7553: if ($env{"user.role.$role./$adom/$aname"}) {
7554: my ($start,$end) =
7555: split('.',$env{"user.role.$role./$adom/$aname"});
7556: if (($now >= $start) && (!$end || $end < $now)) {
7557: $ownaccess = 1;
7558: last;
7559: }
1.1039 raeburn 7560: }
7561: }
7562: }
7563: }
7564: }
7565: }
7566: }
7567:
1.52 www 7568: # Course
7569:
1.620 albertel 7570: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7571: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7572: $thisallowed.=$1;
7573: }
1.52 www 7574: }
1.29 www 7575:
1.52 www 7576: # Domain
7577:
1.620 albertel 7578: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7579: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7580: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7581: $thisallowed.=$1;
7582: }
1.12 www 7583: }
1.52 www 7584:
1.1141 raeburn 7585: # User who is not author or co-author might still be able to edit
7586: # resource of an author in the domain (e.g., if Domain Coordinator).
7587: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7588: (&allowed('mdc',$env{'request.course.id'}))) {
7589: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7590: $thisallowed.=$1;
7591: }
7592: }
7593:
1.52 www 7594: # Course: uri itself is a course
1.66 www 7595: my $courseuri=$uri;
7596: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 7597: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7598:
1.620 albertel 7599: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7600: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7601: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7602: $thisallowed.=$1;
7603: }
1.12 www 7604: }
1.29 www 7605:
1.665 albertel 7606: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7607: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7608: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7609: $thisallowed='';
1.671 raeburn 7610: my ($match)=&is_on_map($uri);
7611: if ($match) {
7612: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7613: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 7614: my $value = $1;
7615: if ($noblockcheck) {
7616: $thisallowed.=$value;
1.1162 raeburn 7617: } else {
1.1281 raeburn 7618: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7619: if (@blockers > 0) {
7620: $thisallowed = 'B';
7621: } else {
7622: $thisallowed.=$value;
7623: }
1.1162 raeburn 7624: }
1.671 raeburn 7625: }
7626: } else {
1.705 albertel 7627: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7628: if ($refuri) {
7629: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7630: $thisallowed='F';
1.671 raeburn 7631: } else {
7632: $refuri=&declutter($refuri);
7633: my ($match) = &is_on_map($refuri);
7634: if ($match) {
1.1281 raeburn 7635: if ($noblockcheck) {
7636: $thisallowed='F';
1.1162 raeburn 7637: } else {
1.1281 raeburn 7638: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7639: if (@blockers > 0) {
7640: $thisallowed = 'B';
7641: } else {
7642: $thisallowed='F';
7643: }
1.1162 raeburn 7644: }
1.671 raeburn 7645: }
1.669 raeburn 7646: }
1.671 raeburn 7647: }
7648: }
1.314 www 7649: }
1.492 albertel 7650:
1.766 albertel 7651: if ($priv eq 'bre'
7652: && $thisallowed ne 'F'
7653: && $thisallowed ne '2'
7654: && &is_portfolio_url($uri)) {
1.1270 raeburn 7655: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7656: }
1.1250 raeburn 7657:
1.52 www 7658: # Full access at system, domain or course-wide level? Exit.
1.29 www 7659: if ($thisallowed=~/F/) {
7660: return 'F';
7661: }
7662:
1.52 www 7663: # If this is generating or modifying users, exit with special codes
1.29 www 7664:
1.643 www 7665: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7666: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7667: my ($audom,$auname)=split('/',$uri);
1.643 www 7668: # no author name given, so this just checks on the general right to make a co-author in this domain
7669: unless ($auname) { return $thisallowed; }
7670: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7671: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7672: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7673: ($audom ne $env{'request.role.domain'}))) { return ''; }
7674: }
1.52 www 7675: return $thisallowed;
7676: }
7677: #
1.103 harris41 7678: # Gathered so far: system, domain and course wide privileges
1.52 www 7679: #
7680: # Course: See if uri or referer is an individual resource that is part of
7681: # the course
7682:
1.620 albertel 7683: if ($env{'request.course.id'}) {
1.232 www 7684:
1.620 albertel 7685: $courseprivid=$env{'request.course.id'};
7686: if ($env{'request.course.sec'}) {
7687: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7688: }
7689: $courseprivid=~s/\_/\//;
7690: my $checkreferer=1;
1.232 www 7691: my ($match,$cond)=&is_on_map($uri);
7692: if ($match) {
7693: $statecond=$cond;
1.620 albertel 7694: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7695: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7696: my $value = $1;
7697: if ($priv eq 'bre') {
1.1281 raeburn 7698: if ($noblockcheck) {
7699: $thisallowed.=$value;
1.1162 raeburn 7700: } else {
1.1281 raeburn 7701: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7702: if (@blockers > 0) {
7703: $thisallowed = 'B';
7704: } else {
7705: $thisallowed.=$value;
7706: }
1.1162 raeburn 7707: }
7708: } else {
7709: $thisallowed.=$value;
7710: }
1.52 www 7711: $checkreferer=0;
7712: }
1.29 www 7713: }
1.83 www 7714:
1.148 www 7715: if ($checkreferer) {
1.620 albertel 7716: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7717: unless ($refuri) {
1.800 albertel 7718: foreach my $key (keys(%env)) {
7719: if ($key=~/^httpref\..*\*/) {
7720: my $pattern=$key;
1.156 www 7721: $pattern=~s/^httpref\.\/res\///;
1.148 www 7722: $pattern=~s/\*/\[\^\/\]\+/g;
7723: $pattern=~s/\//\\\//g;
1.152 www 7724: if ($orguri=~/$pattern/) {
1.800 albertel 7725: $refuri=$env{$key};
1.148 www 7726: }
7727: }
1.191 harris41 7728: }
1.148 www 7729: }
1.232 www 7730:
1.148 www 7731: if ($refuri) {
1.152 www 7732: $refuri=&declutter($refuri);
1.232 www 7733: my ($match,$cond)=&is_on_map($refuri);
7734: if ($match) {
7735: my $refstatecond=$cond;
1.620 albertel 7736: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7737: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7738: my $value = $1;
7739: if ($priv eq 'bre') {
1.1281 raeburn 7740: if ($noblockcheck) {
7741: $thisallowed.=$value;
1.1162 raeburn 7742: } else {
1.1281 raeburn 7743: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7744: if (@blockers > 0) {
7745: $thisallowed = 'B';
7746: } else {
7747: $thisallowed.=$value;
7748: }
1.1162 raeburn 7749: }
7750: } else {
7751: $thisallowed.=$value;
7752: }
1.53 www 7753: $uri=$refuri;
7754: $statecond=$refstatecond;
1.52 www 7755: }
7756: }
1.148 www 7757: }
1.29 www 7758: }
1.52 www 7759: }
1.29 www 7760:
1.52 www 7761: #
1.103 harris41 7762: # Gathered now: all privileges that could apply, and condition number
1.52 www 7763: #
7764: #
7765: # Full or no access?
7766: #
1.29 www 7767:
1.52 www 7768: if ($thisallowed=~/F/) {
7769: return 'F';
7770: }
1.29 www 7771:
1.52 www 7772: unless ($thisallowed) {
7773: return '';
7774: }
1.29 www 7775:
1.52 www 7776: # Restrictions exist, deal with them
7777: #
7778: # C:according to course preferences
7779: # R:according to resource settings
7780: # L:unless locked
7781: # X:according to user session state
7782: #
7783:
7784: # Possibly locked functionality, check all courses
1.54 www 7785: # Locks might take effect only after 10 minutes cache expiration for other
7786: # courses, and 2 minutes for current course
1.52 www 7787:
7788: my $envkey;
7789: if ($thisallowed=~/L/) {
1.1000 raeburn 7790: foreach $envkey (keys(%env)) {
1.54 www 7791: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7792: my $courseid=$2;
7793: my $roleid=$1.'.'.$2;
1.92 www 7794: $courseid=~s/^\///;
1.54 www 7795: my $expiretime=600;
1.620 albertel 7796: if ($env{'request.role'} eq $roleid) {
1.54 www 7797: $expiretime=120;
7798: }
7799: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7800: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7801: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7802: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7803: }
1.620 albertel 7804: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7805: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7806: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7807: &log($env{'user.domain'},$env{'user.name'},
7808: $env{'user.home'},
1.57 www 7809: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7810: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7811: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7812: return '';
7813: }
7814: }
1.620 albertel 7815: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7816: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7817: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7818: &log($env{'user.domain'},$env{'user.name'},
7819: $env{'user.home'},
1.57 www 7820: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7821: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7822: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7823: return '';
7824: }
7825: }
7826: }
1.29 www 7827: }
1.52 www 7828: }
7829:
7830: #
7831: # Rest of the restrictions depend on selected course
7832: #
7833:
1.620 albertel 7834: unless ($env{'request.course.id'}) {
1.766 albertel 7835: if ($thisallowed eq 'A') {
7836: return 'A';
1.814 raeburn 7837: } elsif ($thisallowed eq 'B') {
7838: return 'B';
1.766 albertel 7839: } else {
7840: return '1';
7841: }
1.52 www 7842: }
1.29 www 7843:
1.52 www 7844: #
7845: # Now user is definitely in a course
7846: #
1.53 www 7847:
7848:
7849: # Course preferences
7850:
7851: if ($thisallowed=~/C/) {
1.620 albertel 7852: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7853: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7854: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7855: =~/\Q$rolecode\E/) {
1.1304 raeburn 7856: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7857: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7858: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7859: $env{'request.course.id'});
7860: }
1.237 www 7861: return '';
7862: }
7863:
1.620 albertel 7864: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7865: =~/\Q$unamedom\E/) {
1.1304 raeburn 7866: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7867: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7868: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7869: $env{'request.course.id'});
7870: }
1.54 www 7871: return '';
7872: }
1.53 www 7873: }
7874:
7875: # Resource preferences
7876:
7877: if ($thisallowed=~/R/) {
1.620 albertel 7878: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7879: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7880: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7881: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7882: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7883: }
7884: return '';
1.54 www 7885: }
1.53 www 7886: }
1.30 www 7887:
1.246 www 7888: # Restricted by state or randomout?
1.30 www 7889:
1.52 www 7890: if ($thisallowed=~/X/) {
1.620 albertel 7891: if ($env{'acc.randomout'}) {
1.579 albertel 7892: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7893: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7894: return '';
7895: }
1.247 www 7896: }
7897: if (&condval($statecond)) {
1.52 www 7898: return '2';
7899: } else {
7900: return '';
7901: }
7902: }
1.30 www 7903:
1.766 albertel 7904: if ($thisallowed eq 'A') {
7905: return 'A';
1.814 raeburn 7906: } elsif ($thisallowed eq 'B') {
7907: return 'B';
1.766 albertel 7908: }
1.52 www 7909: return 'F';
1.232 www 7910: }
1.1162 raeburn 7911:
1.1192 raeburn 7912: # ------------------------------------------- Check construction space access
7913:
7914: sub constructaccess {
7915: my ($url,$setpriv)=@_;
7916:
7917: # We do not allow editing of previous versions of files
7918: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7919:
7920: # Get username and domain from URL
7921: my ($ownername,$ownerdomain,$ownerhome);
7922:
7923: ($ownerdomain,$ownername) =
1.1325 raeburn 7924: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192 raeburn 7925:
7926: # The URL does not really point to any authorspace, forget it
7927: unless (($ownername) && ($ownerdomain)) { return ''; }
7928:
7929: # Now we need to see if the user has access to the authorspace of
7930: # $ownername at $ownerdomain
7931:
7932: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7933: # Real author for this?
7934: $ownerhome = $env{'user.home'};
7935: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7936: return ($ownername,$ownerdomain,$ownerhome);
7937: }
7938: } else {
7939: # Co-author for this?
7940: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7941: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7942: $ownerhome = &homeserver($ownername,$ownerdomain);
7943: return ($ownername,$ownerdomain,$ownerhome);
7944: }
1.1312 raeburn 7945: if ($env{'request.course.id'}) {
7946: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
7947: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
7948: if (&allowed('mdc',$env{'request.course.id'})) {
7949: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
7950: return ($ownername,$ownerdomain,$ownerhome);
7951: }
7952: }
7953: }
1.1192 raeburn 7954: }
7955:
7956: # We don't have any access right now. If we are not possibly going to do anything about this,
7957: # we might as well leave
7958: unless ($setpriv) { return ''; }
7959:
7960: # Backdoor access?
7961: my $allowed=&allowed('eco',$ownerdomain);
7962: # Nope
7963: unless ($allowed) { return ''; }
7964: # Looks like we may have access, but could be locked by the owner of the construction space
7965: if ($allowed eq 'U') {
7966: my %blocked=&get('environment',['domcoord.author'],
7967: $ownerdomain,$ownername);
7968: # Is blocked by owner
7969: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7970: }
7971: if (($allowed eq 'F') || ($allowed eq 'U')) {
7972: # Grant temporary access
7973: my $then=$env{'user.login.time'};
1.1209 raeburn 7974: my $update=$env{'user.update.time'};
1.1192 raeburn 7975: if (!$update) { $update = $then; }
7976: my $refresh=$env{'user.refresh.time'};
7977: if (!$refresh) { $refresh = $update; }
7978: my $now = time;
7979: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7980: $now,'ca','constructaccess');
7981: $ownerhome = &homeserver($ownername,$ownerdomain);
7982: return($ownername,$ownerdomain,$ownerhome);
7983: }
7984: # No business here
7985: return '';
7986: }
7987:
1.1282 raeburn 7988: # ----------------------------------------------------------- Content Blocking
7989:
7990: {
7991: # Caches for faster Course Contents display where content blocking
7992: # is in operation (i.e., interval param set) for timed quiz.
7993: #
7994: # User for whom data are being temporarily cached.
7995: my $cacheduser='';
7996: # Cached blockers for this user (a hash of blocking items).
7997: my %cachedblockers=();
7998: # When the data were last cached.
7999: my $cachedlast='';
8000:
8001: sub load_all_blockers {
8002: my ($uname,$udom,$blocks)=@_;
8003: if (($uname ne '') && ($udom ne '')) {
8004: if (($cacheduser eq $uname.':'.$udom) &&
8005: (abs($cachedlast-time)<5)) {
8006: return;
8007: }
8008: }
8009: $cachedlast=time;
8010: $cacheduser=$uname.':'.$udom;
8011: %cachedblockers = &get_commblock_resources($blocks);
8012: }
8013:
1.1162 raeburn 8014: sub get_comm_blocks {
8015: my ($cdom,$cnum) = @_;
8016: if ($cdom eq '' || $cnum eq '') {
8017: return unless ($env{'request.course.id'});
8018: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8019: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8020: }
8021: my %commblocks;
8022: my $hashid=$cdom.'_'.$cnum;
8023: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8024: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8025: %commblocks = %{$blocksref};
8026: } else {
8027: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8028: my $cachetime = 600;
8029: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8030: }
8031: return %commblocks;
8032: }
8033:
1.1282 raeburn 8034: sub get_commblock_resources {
8035: my ($blocks) = @_;
8036: my %blockers = ();
8037: return %blockers unless ($env{'request.course.id'});
8038: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 8039: my %commblocks;
8040: if (ref($blocks) eq 'HASH') {
8041: %commblocks = %{$blocks};
8042: } else {
8043: %commblocks = &get_comm_blocks();
8044: }
1.1282 raeburn 8045: return %blockers unless (keys(%commblocks) > 0);
8046: my $navmap = Apache::lonnavmaps::navmap->new();
8047: return %blockers unless (ref($navmap));
1.1162 raeburn 8048: my $now = time;
8049: foreach my $block (keys(%commblocks)) {
8050: if ($block =~ /^(\d+)____(\d+)$/) {
8051: my ($start,$end) = ($1,$2);
8052: if ($start <= $now && $end >= $now) {
8053: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8054: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8055: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 8056: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8057: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 8058: }
8059: }
8060: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 8061: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8062: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 8063: }
8064: }
8065: }
8066: }
8067: }
8068: } elsif ($block =~ /^firstaccess____(.+)$/) {
8069: my $item = $1;
1.1163 raeburn 8070: my @to_test;
1.1162 raeburn 8071: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8072: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282 raeburn 8073: my @interval;
8074: my $type = 'map';
8075: if ($item eq 'course') {
8076: $type = 'course';
8077: @interval=&EXT("resource.0.interval");
8078: } else {
8079: if ($item =~ /___\d+___/) {
8080: $type = 'resource';
8081: @interval=&EXT("resource.0.interval",$item);
8082: if (ref($navmap)) {
8083: my $res = $navmap->getBySymb($item);
8084: push(@to_test,$res);
8085: }
1.1162 raeburn 8086: } else {
1.1282 raeburn 8087: my $mapsymb = &symbread($item,1);
8088: if ($mapsymb) {
8089: if (ref($navmap)) {
8090: my $mapres = $navmap->getBySymb($mapsymb);
8091: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
8092: foreach my $res (@to_test) {
8093: my $symb = $res->symb();
8094: next if ($symb eq $mapsymb);
8095: if ($symb ne '') {
8096: @interval=&EXT("resource.0.interval",$symb);
8097: if ($interval[1] eq 'map') {
8098: last;
1.1162 raeburn 8099: }
8100: }
8101: }
8102: }
8103: }
8104: }
1.1282 raeburn 8105: }
1.1310 raeburn 8106: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 8107: my $timelimit = $1;
1.1282 raeburn 8108: my $first_access;
8109: if ($type eq 'resource') {
8110: $first_access=&get_first_access($interval[1],$item);
8111: } elsif ($type eq 'map') {
8112: $first_access=&get_first_access($interval[1],undef,$item);
8113: } else {
8114: $first_access=&get_first_access($interval[1]);
8115: }
8116: if ($first_access) {
1.1292 raeburn 8117: my $timesup = $first_access+$timelimit;
1.1282 raeburn 8118: if ($timesup > $now) {
8119: my $activeblock;
8120: foreach my $res (@to_test) {
1.1283 raeburn 8121: if ($res->answerable()) {
1.1282 raeburn 8122: $activeblock = 1;
8123: last;
8124: }
8125: }
8126: if ($activeblock) {
8127: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8128: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8129: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8130: }
8131: }
8132: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8133: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8134: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 8135: }
1.1162 raeburn 8136: }
8137: }
8138: }
8139: }
8140: }
8141: }
8142: }
8143: }
8144: }
1.1282 raeburn 8145: return %blockers;
1.1162 raeburn 8146: }
8147:
1.1282 raeburn 8148: sub has_comm_blocking {
8149: my ($priv,$symb,$uri,$blocks) = @_;
8150: my @blockers;
8151: return unless ($env{'request.course.id'});
8152: return unless ($priv eq 'bre');
8153: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8154: return if ($env{'request.state'} eq 'construct');
8155: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
8156: return unless (keys(%cachedblockers) > 0);
8157: my (%possibles,@symbs);
8158: if (!$symb) {
8159: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 8160: }
1.1282 raeburn 8161: if ($symb) {
8162: @symbs = ($symb);
8163: } elsif (keys(%possibles)) {
8164: @symbs = keys(%possibles);
8165: }
8166: my $noblock;
8167: foreach my $symb (@symbs) {
8168: last if ($noblock);
8169: my ($map,$resid,$resurl)=&decode_symb($symb);
8170: foreach my $block (keys(%cachedblockers)) {
8171: if ($block =~ /^firstaccess____(.+)$/) {
8172: my $item = $1;
8173: if (($item eq $map) || ($item eq $symb)) {
8174: $noblock = 1;
8175: last;
8176: }
8177: }
8178: if (ref($cachedblockers{$block}) eq 'HASH') {
8179: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
8180: if ($cachedblockers{$block}{'resources'}{$symb}) {
8181: unless (grep(/^\Q$block\E$/,@blockers)) {
8182: push(@blockers,$block);
8183: }
8184: }
8185: }
1.1162 raeburn 8186: }
1.1282 raeburn 8187: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
8188: if ($cachedblockers{$block}{'maps'}{$map}) {
8189: unless (grep(/^\Q$block\E$/,@blockers)) {
8190: push(@blockers,$block);
8191: }
8192: }
1.1162 raeburn 8193: }
8194: }
8195: }
1.1282 raeburn 8196: return if ($noblock);
8197: return @blockers;
8198: }
1.1162 raeburn 8199: }
8200:
1.1282 raeburn 8201: # -------------------------------- Deversion and split uri into path an filename
8202:
1.1133 foxr 8203: #
1.1282 raeburn 8204: # Removes the version from a URI and
1.1133 foxr 8205: # splits it in to its filename and path to the filename.
8206: # Seems like File::Basename could have done this more clearly.
8207: # Parameters:
8208: # $uri - input URI
8209: # Returns:
8210: # Two element list consisting of
8211: # $pathname - the URI up to and excluding the trailing /
8212: # $filename - The part of the URI following the last /
8213: # NOTE:
8214: # Another realization of this is simply:
8215: # use File::Basename;
8216: # ...
8217: # $uri = shift;
8218: # $filename = basename($uri);
8219: # $path = dirname($uri);
8220: # return ($filename, $path);
8221: #
8222: # The implementation below is probably faster however.
8223: #
1.710 albertel 8224: sub split_uri_for_cond {
8225: my $uri=&deversion(&declutter(shift));
8226: my @uriparts=split(/\//,$uri);
8227: my $filename=pop(@uriparts);
8228: my $pathname=join('/',@uriparts);
8229: return ($pathname,$filename);
8230: }
1.232 www 8231: # --------------------------------------------------- Is a resource on the map?
8232:
8233: sub is_on_map {
1.710 albertel 8234: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8235: #Trying to find the conditional for the file
1.620 albertel 8236: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8237: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8238: if ($match) {
1.289 bowersj2 8239: return (1,$1);
8240: } else {
1.434 www 8241: return (0,0);
1.289 bowersj2 8242: }
1.12 www 8243: }
8244:
1.427 www 8245: # --------------------------------------------------------- Get symb from alias
8246:
8247: sub get_symb_from_alias {
8248: my $symb=shift;
8249: my ($map,$resid,$url)=&decode_symb($symb);
8250: # Already is a symb
8251: if ($url) { return $symb; }
8252: # Must be an alias
8253: my $aliassymb='';
8254: my %bighash;
1.620 albertel 8255: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8256: &GDBM_READER(),0640)) {
8257: my $rid=$bighash{'mapalias_'.$symb};
8258: if ($rid) {
8259: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8260: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8261: $resid,$bighash{'src_'.$rid});
1.427 www 8262: }
8263: untie %bighash;
8264: }
8265: return $aliassymb;
8266: }
8267:
1.12 www 8268: # ----------------------------------------------------------------- Define Role
8269:
8270: sub definerole {
8271: if (allowed('mcr','/')) {
1.1326 raeburn 8272: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8273: foreach my $role (split(':',$sysrole)) {
8274: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8275: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8276: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8277: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8278: return "refused:s:$crole&$cqual";
8279: }
8280: }
1.191 harris41 8281: }
1.800 albertel 8282: foreach my $role (split(':',$domrole)) {
8283: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8284: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8285: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8286: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8287: return "refused:d:$crole&$cqual";
8288: }
8289: }
1.191 harris41 8290: }
1.800 albertel 8291: foreach my $role (split(':',$courole)) {
8292: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8293: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8294: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8295: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8296: return "refused:c:$crole&$cqual";
8297: }
8298: }
1.191 harris41 8299: }
1.1326 raeburn 8300: my $uhome;
8301: if (($uname ne '') && ($udom ne '')) {
8302: $uhome = &homeserver($uname,$udom);
8303: return $uhome if ($uhome eq 'no_host');
8304: } else {
8305: $uname = $env{'user.name'};
8306: $udom = $env{'user.domain'};
8307: $uhome = $env{'user.home'};
8308: }
1.620 albertel 8309: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326 raeburn 8310: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8311: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326 raeburn 8312: return reply($command,$uhome);
1.12 www 8313: } else {
8314: return 'refused';
8315: }
1.105 harris41 8316: }
8317:
8318: # ---------------- Make a metadata query against the network of library servers
8319:
8320: sub metadata_query {
1.1237 raeburn 8321: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8322: my %rhash;
1.845 albertel 8323: my %libserv = &all_library();
1.244 matthew 8324: my @server_list = (defined($server_array) ? @$server_array
8325: : keys(%libserv) );
8326: for my $server (@server_list) {
1.1237 raeburn 8327: my $domains = '';
8328: if (ref($domains_hash) eq 'HASH') {
8329: $domains = $domains_hash->{$server};
8330: }
1.118 harris41 8331: unless ($custom or $customshow) {
1.1237 raeburn 8332: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8333: $rhash{$server}=$reply;
8334: }
8335: else {
8336: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 8337: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8338: $server);
8339: $rhash{$server}=$reply;
8340: }
1.112 harris41 8341: }
1.118 harris41 8342: return \%rhash;
1.240 www 8343: }
8344:
8345: # ----------------------------------------- Send log queries and wait for reply
8346:
8347: sub log_query {
8348: my ($uname,$udom,$query,%filters)=@_;
8349: my $uhome=&homeserver($uname,$udom);
8350: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8351: my $uhost=&hostname($uhome);
1.800 albertel 8352: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8353: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8354: $uhome);
1.479 albertel 8355: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8356: return get_query_reply($queryid);
8357: }
8358:
1.818 raeburn 8359: # -------------------------- Update MySQL table for portfolio file
8360:
8361: sub update_portfolio_table {
1.821 raeburn 8362: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8363: if ($group ne '') {
8364: $file_name =~s /^\Q$group\E//;
8365: }
1.818 raeburn 8366: my $homeserver = &homeserver($uname,$udom);
8367: my $queryid=
1.821 raeburn 8368: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8369: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8370: my $reply = &get_query_reply($queryid);
8371: return $reply;
8372: }
8373:
1.899 raeburn 8374: # -------------------------- Update MySQL allusers table
8375:
8376: sub update_allusers_table {
8377: my ($uname,$udom,$names) = @_;
8378: my $homeserver = &homeserver($uname,$udom);
8379: my $queryid=
8380: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8381: 'lastname='.&escape($names->{'lastname'}).'%%'.
8382: 'firstname='.&escape($names->{'firstname'}).'%%'.
8383: 'middlename='.&escape($names->{'middlename'}).'%%'.
8384: 'generation='.&escape($names->{'generation'}).'%%'.
8385: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8386: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8387: return;
1.899 raeburn 8388: }
8389:
1.508 raeburn 8390: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8391:
8392: sub fetch_enrollment_query {
1.511 raeburn 8393: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 raeburn 8394: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8395: my $maxtries = 1;
1.508 raeburn 8396: if ($context eq 'automated') {
8397: $homeserver = $perlvar{'lonHostID'};
1.1317 raeburn 8398: $sleep = 2;
8399: $loopmax = 100;
1.547 raeburn 8400: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8401: } else {
8402: $homeserver = &homeserver($cnum,$dom);
8403: }
1.838 albertel 8404: my $host=&hostname($homeserver);
1.506 raeburn 8405: my $cmd = '';
1.1000 raeburn 8406: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8407: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8408: }
8409: $cmd =~ s/%%$//;
8410: $cmd = &escape($cmd);
8411: my $query = 'fetchenrollment';
1.620 albertel 8412: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8413: unless ($queryid=~/^\Q$host\E\_/) {
8414: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8415: return 'error: '.$queryid;
8416: }
1.1317 raeburn 8417: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8418: my $tries = 1;
8419: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 raeburn 8420: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8421: $tries ++;
8422: }
1.526 raeburn 8423: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 8424: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 8425: } else {
1.901 albertel 8426: my @responses = split(/:/,$reply);
1.1322 raeburn 8427: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 8428: foreach my $line (@responses) {
8429: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 8430: $$replyref{$key} = $value;
8431: }
8432: } else {
1.1117 foxr 8433: my $pathname = LONCAPA::tempdir();
1.800 albertel 8434: foreach my $line (@responses) {
8435: my ($key,$value) = split(/=/,$line);
1.506 raeburn 8436: $$replyref{$key} = $value;
8437: if ($value > 0) {
1.800 albertel 8438: foreach my $item (@{$$affiliatesref{$key}}) {
8439: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 8440: my $destname = $pathname.'/'.$filename;
8441: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 8442: if ($xml_classlist =~ /^error/) {
8443: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8444: } else {
1.506 raeburn 8445: if ( open(FILE,">$destname") ) {
8446: print FILE &unescape($xml_classlist);
8447: close(FILE);
1.526 raeburn 8448: } else {
8449: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 8450: }
8451: }
8452: }
8453: }
8454: }
8455: }
8456: return 'ok';
8457: }
8458: return 'error';
8459: }
8460:
1.242 www 8461: sub get_query_reply {
1.1317 raeburn 8462: my ($queryid,$sleep,$loopmax) = @_;;
8463: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8464: $sleep = 0.2;
8465: }
8466: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8467: $loopmax = 100;
8468: }
1.1117 foxr 8469: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 8470: my $reply='';
1.1317 raeburn 8471: for (1..$loopmax) {
8472: sleep($sleep);
1.240 www 8473: if (-e $replyfile.'.end') {
1.448 albertel 8474: if (open(my $fh,$replyfile)) {
1.904 albertel 8475: $reply = join('',<$fh>);
8476: close($fh);
1.240 www 8477: } else { return 'error: reply_file_error'; }
1.242 www 8478: return &unescape($reply);
8479: }
1.240 www 8480: }
1.242 www 8481: return 'timeout:'.$queryid;
1.240 www 8482: }
8483:
8484: sub courselog_query {
1.241 www 8485: #
8486: # possible filters:
8487: # url: url or symb
8488: # username
8489: # domain
8490: # action: view, submit, grade
8491: # start: timestamp
8492: # end: timestamp
8493: #
1.240 www 8494: my (%filters)=@_;
1.620 albertel 8495: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 8496: if ($filters{'url'}) {
8497: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8498: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8499: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8500: }
1.620 albertel 8501: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8502: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 8503: return &log_query($cname,$cdom,'courselog',%filters);
8504: }
8505:
8506: sub userlog_query {
1.858 raeburn 8507: #
8508: # possible filters:
8509: # action: log check role
8510: # start: timestamp
8511: # end: timestamp
8512: #
1.240 www 8513: my ($uname,$udom,%filters)=@_;
8514: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 8515: }
8516:
1.506 raeburn 8517: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8518:
8519: sub auto_run {
1.508 raeburn 8520: my ($cnum,$cdom) = @_;
1.876 raeburn 8521: my $response = 0;
8522: my $settings;
8523: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8524: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8525: $settings = $domconfig{'autoenroll'};
8526: if ($settings->{'run'} eq '1') {
8527: $response = 1;
8528: }
8529: } else {
1.934 raeburn 8530: my $homeserver;
8531: if (&is_course($cdom,$cnum)) {
8532: $homeserver = &homeserver($cnum,$cdom);
8533: } else {
8534: $homeserver = &domain($cdom,'primary');
8535: }
8536: if ($homeserver ne 'no_host') {
8537: $response = &reply('autorun:'.$cdom,$homeserver);
8538: }
1.876 raeburn 8539: }
1.506 raeburn 8540: return $response;
8541: }
1.776 albertel 8542:
1.506 raeburn 8543: sub auto_get_sections {
1.508 raeburn 8544: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 8545: my $homeserver;
8546: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8547: $homeserver = &homeserver($cnum,$cdom);
8548: }
8549: if (!defined($homeserver)) {
8550: if ($cdom =~ /^$match_domain$/) {
8551: $homeserver = &domain($cdom,'primary');
8552: }
8553: }
8554: my @secs;
8555: if (defined($homeserver)) {
8556: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8557: unless ($response eq 'refused') {
8558: @secs = split(/:/,$response);
8559: }
1.506 raeburn 8560: }
8561: return @secs;
8562: }
1.776 albertel 8563:
1.506 raeburn 8564: sub auto_new_course {
1.1099 raeburn 8565: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 8566: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 8567: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 8568: return $response;
8569: }
1.776 albertel 8570:
1.506 raeburn 8571: sub auto_validate_courseID {
1.508 raeburn 8572: my ($cnum,$cdom,$inst_course_id) = @_;
8573: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 8574: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 8575: return $response;
8576: }
1.776 albertel 8577:
1.1007 raeburn 8578: sub auto_validate_instcode {
1.1020 raeburn 8579: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 8580: my ($homeserver,$response);
8581: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8582: $homeserver = &homeserver($cnum,$cdom);
8583: }
8584: if (!defined($homeserver)) {
8585: if ($cdom =~ /^$match_domain$/) {
8586: $homeserver = &domain($cdom,'primary');
8587: }
8588: }
1.1065 raeburn 8589: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8590: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 8591: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
8592: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 8593: }
8594:
1.506 raeburn 8595: sub auto_create_password {
1.873 raeburn 8596: my ($cnum,$cdom,$authparam,$udom) = @_;
8597: my ($homeserver,$response);
1.506 raeburn 8598: my $create_passwd = 0;
8599: my $authchk = '';
1.873 raeburn 8600: if ($udom =~ /^$match_domain$/) {
8601: $homeserver = &domain($udom,'primary');
8602: }
8603: if ($homeserver eq '') {
8604: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8605: $homeserver = &homeserver($cnum,$cdom);
8606: }
8607: }
8608: if ($homeserver eq '') {
8609: $authchk = 'nodomain';
1.506 raeburn 8610: } else {
1.873 raeburn 8611: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8612: if ($response eq 'refused') {
8613: $authchk = 'refused';
8614: } else {
1.901 albertel 8615: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8616: }
1.506 raeburn 8617: }
8618: return ($authparam,$create_passwd,$authchk);
8619: }
8620:
1.706 raeburn 8621: sub auto_photo_permission {
8622: my ($cnum,$cdom,$students) = @_;
8623: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8624: my ($outcome,$perm_reqd,$conditions) =
8625: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8626: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8627: return (undef,undef);
8628: }
1.706 raeburn 8629: return ($outcome,$perm_reqd,$conditions);
8630: }
8631:
8632: sub auto_checkphotos {
8633: my ($uname,$udom,$pid) = @_;
8634: my $homeserver = &homeserver($uname,$udom);
8635: my ($result,$resulttype);
8636: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8637: &escape($uname).':'.&escape($pid),
8638: $homeserver));
1.709 albertel 8639: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8640: return (undef,undef);
8641: }
1.706 raeburn 8642: if ($outcome) {
8643: ($result,$resulttype) = split(/:/,$outcome);
8644: }
8645: return ($result,$resulttype);
8646: }
8647:
8648: sub auto_photochoice {
8649: my ($cnum,$cdom) = @_;
8650: my $homeserver = &homeserver($cnum,$cdom);
8651: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8652: &escape($cdom),
8653: $homeserver)));
1.709 albertel 8654: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8655: return (undef,undef);
8656: }
1.706 raeburn 8657: return ($update,$comment);
8658: }
8659:
8660: sub auto_photoupdate {
8661: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8662: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8663: my $host=&hostname($homeserver);
1.706 raeburn 8664: my $cmd = '';
8665: my $maxtries = 1;
1.800 albertel 8666: foreach my $affiliate (keys(%{$affiliatesref})) {
8667: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8668: }
8669: $cmd =~ s/%%$//;
8670: $cmd = &escape($cmd);
8671: my $query = 'institutionalphotos';
8672: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8673: unless ($queryid=~/^\Q$host\E\_/) {
8674: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8675: return 'error: '.$queryid;
8676: }
8677: my $reply = &get_query_reply($queryid);
8678: my $tries = 1;
8679: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8680: $reply = &get_query_reply($queryid);
8681: $tries ++;
8682: }
8683: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8684: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8685: } else {
8686: my @responses = split(/:/,$reply);
8687: my $outcome = shift(@responses);
8688: foreach my $item (@responses) {
8689: my ($key,$value) = split(/=/,$item);
8690: $$photo{$key} = $value;
8691: }
8692: return $outcome;
8693: }
8694: return 'error';
8695: }
8696:
1.521 raeburn 8697: sub auto_instcode_format {
1.793 albertel 8698: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8699: $cat_order) = @_;
1.521 raeburn 8700: my $courses = '';
1.772 raeburn 8701: my @homeservers;
1.521 raeburn 8702: if ($caller eq 'global') {
1.841 albertel 8703: my %servers = &get_servers($codedom,'library');
8704: foreach my $tryserver (keys(%servers)) {
8705: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8706: push(@homeservers,$tryserver);
8707: }
1.584 raeburn 8708: }
1.1022 raeburn 8709: } elsif ($caller eq 'requests') {
8710: if ($codedom =~ /^$match_domain$/) {
8711: my $chome = &domain($codedom,'primary');
8712: unless ($chome eq 'no_host') {
8713: push(@homeservers,$chome);
8714: }
8715: }
1.521 raeburn 8716: } else {
1.772 raeburn 8717: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8718: }
1.793 albertel 8719: foreach my $code (keys(%{$instcodes})) {
8720: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8721: }
8722: chop($courses);
1.772 raeburn 8723: my $ok_response = 0;
8724: my $response;
8725: while (@homeservers > 0 && $ok_response == 0) {
8726: my $server = shift(@homeservers);
8727: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8728: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8729: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8730: split(/:/,$response);
1.772 raeburn 8731: %{$codes} = (%{$codes},&str2hash($codes_str));
8732: push(@{$codetitles},&str2array($codetitles_str));
8733: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8734: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8735: $ok_response = 1;
8736: }
8737: }
8738: if ($ok_response) {
1.521 raeburn 8739: return 'ok';
1.772 raeburn 8740: } else {
8741: return $response;
1.521 raeburn 8742: }
8743: }
8744:
1.792 raeburn 8745: sub auto_instcode_defaults {
8746: my ($domain,$returnhash,$code_order) = @_;
8747: my @homeservers;
1.841 albertel 8748:
8749: my %servers = &get_servers($domain,'library');
8750: foreach my $tryserver (keys(%servers)) {
8751: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8752: push(@homeservers,$tryserver);
8753: }
1.792 raeburn 8754: }
1.841 albertel 8755:
1.792 raeburn 8756: my $response;
1.841 albertel 8757: foreach my $server (@homeservers) {
1.792 raeburn 8758: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8759: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8760:
8761: foreach my $pair (split(/\&/,$response)) {
8762: my ($name,$value)=split(/\=/,$pair);
8763: if ($name eq 'code_order') {
8764: @{$code_order} = split(/\&/,&unescape($value));
8765: } else {
8766: $returnhash->{&unescape($name)}=&unescape($value);
8767: }
8768: }
8769: return 'ok';
1.792 raeburn 8770: }
1.841 albertel 8771:
8772: return $response;
1.1003 raeburn 8773: }
8774:
8775: sub auto_possible_instcodes {
1.1007 raeburn 8776: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8777: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8778: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8779: return;
8780: }
1.1003 raeburn 8781: my (@homeservers,$uhome);
8782: if (defined(&domain($domain,'primary'))) {
8783: $uhome=&domain($domain,'primary');
8784: push(@homeservers,&domain($domain,'primary'));
8785: } else {
8786: my %servers = &get_servers($domain,'library');
8787: foreach my $tryserver (keys(%servers)) {
8788: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8789: push(@homeservers,$tryserver);
8790: }
8791: }
8792: }
8793: my $response;
8794: foreach my $server (@homeservers) {
8795: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8796: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8797: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8798: split(':',$response);
8799: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8800: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8801: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8802: my ($name,$value)=split('=',$item);
8803: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8804: }
8805: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8806: my ($name,$value)=split('=',$item);
8807: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8808: }
8809: return 'ok';
8810: }
8811: return $response;
8812: }
1.792 raeburn 8813:
1.1010 raeburn 8814: sub auto_courserequest_checks {
8815: my ($dom) = @_;
1.1020 raeburn 8816: my ($homeserver,%validations);
8817: if ($dom =~ /^$match_domain$/) {
8818: $homeserver = &domain($dom,'primary');
8819: }
8820: unless ($homeserver eq 'no_host') {
8821: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8822: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8823: my @items = split(/&/,$response);
8824: foreach my $item (@items) {
8825: my ($key,$value) = split('=',$item);
8826: $validations{&unescape($key)} = &thaw_unescape($value);
8827: }
8828: }
8829: }
1.1010 raeburn 8830: return %validations;
8831: }
8832:
1.1020 raeburn 8833: sub auto_courserequest_validation {
1.1255 raeburn 8834: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8835: my ($homeserver,$response);
8836: if ($dom =~ /^$match_domain$/) {
8837: $homeserver = &domain($dom,'primary');
8838: }
1.1255 raeburn 8839: unless ($homeserver eq 'no_host') {
8840: my $customdata;
8841: if (ref($custominfo) eq 'HASH') {
8842: $customdata = &freeze_escape($custominfo);
8843: }
1.1020 raeburn 8844: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8845: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 8846: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8847: $customdata,$homeserver));
1.1020 raeburn 8848: }
8849: return $response;
8850: }
8851:
1.777 albertel 8852: sub auto_validate_class_sec {
1.918 raeburn 8853: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8854: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8855: my $ownerlist;
8856: if (ref($owners) eq 'ARRAY') {
8857: $ownerlist = join(',',@{$owners});
8858: } else {
8859: $ownerlist = $owners;
8860: }
1.773 raeburn 8861: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8862: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8863: return $response;
8864: }
8865:
1.1248 raeburn 8866: sub auto_crsreq_update {
8867: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 8868: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 8869: my ($homeserver,%crsreqresponse);
8870: if ($cdom =~ /^$match_domain$/) {
8871: $homeserver = &domain($cdom,'primary');
8872: }
8873: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8874: my $info;
8875: if (ref($inbound) eq 'HASH') {
8876: $info = &freeze_escape($inbound);
8877: }
8878: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8879: ':'.&escape($action).':'.&escape($ownername).':'.
8880: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 8881: &escape($title).':'.&escape($code).':'.
8882: &escape($accessstart).':'.&escape($accessend).':'.$info,
8883: $homeserver);
1.1248 raeburn 8884: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8885: my @items = split(/&/,$response);
8886: foreach my $item (@items) {
8887: my ($key,$value) = split('=',$item);
8888: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8889: }
8890: }
8891: }
8892: return \%crsreqresponse;
8893: }
8894:
1.1305 raeburn 8895: sub auto_export_grades {
1.1309 raeburn 8896: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8897: my ($homeserver,%exportresponse);
8898: if ($cdom =~ /^$match_domain$/) {
8899: $homeserver = &domain($cdom,'primary');
8900: }
8901: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8902: my $info;
8903: if (ref($inforef) eq 'HASH') {
8904: $info = &freeze_escape($inforef);
8905: }
8906: if (ref($gradesref) eq 'HASH') {
8907: my $grades = &freeze_escape($gradesref);
8908: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8909: $info.':'.$grades,$homeserver);
8910: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8911: my @items = split(/&/,$response);
8912: foreach my $item (@items) {
8913: my ($key,$value) = split('=',$item);
8914: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8915: }
8916: }
8917: }
8918: }
8919: return \%exportresponse;
1.1305 raeburn 8920: }
8921:
1.1287 raeburn 8922: sub check_instcode_cloning {
8923: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8924: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8925: return;
8926: }
8927: my $canclone;
8928: if (@{$code_order} > 0) {
8929: my $instcoderegexp ='^';
8930: my @clonecodes = split(/\&/,$cloner);
8931: foreach my $item (@{$code_order}) {
8932: if (grep(/^\Q$item\E=/,@clonecodes)) {
8933: foreach my $pair (@clonecodes) {
8934: my ($key,$val) = split(/\=/,$pair,2);
8935: $val = &unescape($val);
8936: if ($key eq $item) {
8937: $instcoderegexp .= '('.$val.')';
8938: last;
8939: }
8940: }
8941: } else {
8942: $instcoderegexp .= $codedefaults->{$item};
8943: }
8944: }
8945: $instcoderegexp .= '$';
8946: my (@from,@to);
8947: eval {
8948: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8949: (@to) = ($clonetocode =~ /$instcoderegexp/);
8950: };
8951: if ((@from > 0) && (@to > 0)) {
8952: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8953: if (!@diffs) {
8954: $canclone = 1;
8955: }
8956: }
8957: }
8958: return $canclone;
8959: }
8960:
8961: sub default_instcode_cloning {
8962: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8963: my (%codedefaults,@code_order,$canclone);
8964: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8965: %codedefaults = %{$codedefaultsref};
8966: @code_order = @{$codeorderref};
8967: } elsif ($clonedom) {
8968: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8969: }
8970: if (($domdefclone) && (@code_order)) {
8971: my @clonecodes = split(/\+/,$domdefclone);
8972: my $instcoderegexp ='^';
8973: foreach my $item (@code_order) {
8974: if (grep(/^\Q$item\E$/,@clonecodes)) {
8975: $instcoderegexp .= '('.$codedefaults{$item}.')';
8976: } else {
8977: $instcoderegexp .= $codedefaults{$item};
8978: }
8979: }
8980: $instcoderegexp .= '$';
8981: my (@from,@to);
8982: eval {
8983: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8984: (@to) = ($clonetocode =~ /$instcoderegexp/);
8985: };
8986: if ((@from > 0) && (@to > 0)) {
8987: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8988: if (!@diffs) {
8989: $canclone = 1;
8990: }
8991: }
8992: }
8993: return $canclone;
8994: }
8995:
1.679 raeburn 8996: # ------------------------------------------------------- Course Group routines
8997:
8998: sub get_coursegroups {
1.809 raeburn 8999: my ($cdom,$cnum,$group,$namespace) = @_;
9000: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 9001: }
9002:
1.679 raeburn 9003: sub modify_coursegroup {
9004: my ($cdom,$cnum,$groupsettings) = @_;
9005: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9006: }
9007:
1.809 raeburn 9008: sub toggle_coursegroup_status {
9009: my ($cdom,$cnum,$group,$action) = @_;
9010: my ($from_namespace,$to_namespace);
9011: if ($action eq 'delete') {
9012: $from_namespace = 'coursegroups';
9013: $to_namespace = 'deleted_groups';
9014: } else {
9015: $from_namespace = 'deleted_groups';
9016: $to_namespace = 'coursegroups';
9017: }
9018: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 9019: if (my $tmp = &error(%curr_group)) {
9020: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9021: return ('read error',$tmp);
9022: } else {
9023: my %savedsettings = %curr_group;
1.809 raeburn 9024: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 9025: my $deloutcome;
9026: if ($result eq 'ok') {
1.809 raeburn 9027: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 9028: } else {
9029: return ('write error',$result);
9030: }
9031: if ($deloutcome eq 'ok') {
9032: return 'ok';
9033: } else {
9034: return ('delete error',$deloutcome);
9035: }
9036: }
9037: }
9038:
1.679 raeburn 9039: sub modify_group_roles {
1.957 raeburn 9040: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 9041: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9042: my $role = 'gr/'.&escape($userprivs);
9043: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 9044: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 9045: if ($result eq 'ok') {
9046: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9047: }
1.679 raeburn 9048: return $result;
9049: }
9050:
9051: sub modify_coursegroup_membership {
9052: my ($cdom,$cnum,$membership) = @_;
9053: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9054: return $result;
9055: }
9056:
1.682 raeburn 9057: sub get_active_groups {
9058: my ($udom,$uname,$cdom,$cnum) = @_;
9059: my $now = time;
9060: my %groups = ();
9061: foreach my $key (keys(%env)) {
1.811 albertel 9062: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 9063: my ($start,$end) = split(/\./,$env{$key});
9064: if (($end!=0) && ($end<$now)) { next; }
9065: if (($start!=0) && ($start>$now)) { next; }
9066: if ($1 eq $cdom && $2 eq $cnum) {
9067: $groups{$3} = $env{$key} ;
9068: }
9069: }
9070: }
9071: return %groups;
9072: }
9073:
1.683 raeburn 9074: sub get_group_membership {
9075: my ($cdom,$cnum,$group) = @_;
9076: return(&dump('groupmembership',$cdom,$cnum,$group));
9077: }
9078:
9079: sub get_users_groups {
9080: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 9081: my @usersgroups;
1.683 raeburn 9082: my $cachetime=1800;
9083:
9084: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 9085: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9086: if (defined($cached)) {
1.734 albertel 9087: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 9088: } else {
9089: $grouplist = '';
1.816 raeburn 9090: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 9091: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 9092: my $access_end = $env{'course.'.$courseid.
9093: '.default_enrollment_end_date'};
9094: my $now = time;
9095: foreach my $key (keys(%roleshash)) {
9096: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9097: my $group = $1;
9098: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9099: my $start = $2;
9100: my $end = $1;
9101: if ($start == -1) { next; } # deleted from group
9102: if (($start!=0) && ($start>$now)) { next; }
9103: if (($end!=0) && ($end<$now)) {
9104: if ($access_end && $access_end < $now) {
9105: if ($access_end - $end < 86400) {
9106: push(@usersgroups,$group);
1.733 raeburn 9107: }
9108: }
1.817 raeburn 9109: next;
1.733 raeburn 9110: }
1.817 raeburn 9111: push(@usersgroups,$group);
1.683 raeburn 9112: }
9113: }
9114: }
1.817 raeburn 9115: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9116: $grouplist = join(':',@usersgroups);
9117: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 9118: }
1.733 raeburn 9119: return @usersgroups;
1.683 raeburn 9120: }
9121:
9122: sub devalidate_getgroups_cache {
9123: my ($udom,$uname,$cdom,$cnum)=@_;
9124: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 9125:
1.683 raeburn 9126: my $hashid="$udom:$uname:$courseid";
9127: &devalidate_cache_new('getgroups',$hashid);
9128: }
9129:
1.12 www 9130: # ------------------------------------------------------------------ Plain Text
9131:
9132: sub plaintext {
1.988 raeburn 9133: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 9134: if ($short =~ m{^cr/}) {
1.758 albertel 9135: return (split('/',$short))[-1];
9136: }
1.742 raeburn 9137: if (!defined($cid)) {
9138: $cid = $env{'request.course.id'};
9139: }
9140: my %rolenames = (
1.1008 raeburn 9141: Course => 'std',
9142: Community => 'alt1',
1.1305 raeburn 9143: Placement => 'std',
1.742 raeburn 9144: );
1.1037 raeburn 9145: if ($cid ne '') {
9146: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9147: unless ($forcedefault) {
9148: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9149: &Apache::lonlocal::mt_escape(\$roletext);
9150: return &Apache::lonlocal::mt($roletext);
9151: }
9152: }
9153: }
9154: if ((defined($type)) && (defined($rolenames{$type})) &&
9155: (defined($rolenames{$type})) &&
9156: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 9157: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 9158: } elsif ($cid ne '') {
9159: my $crstype = $env{'course.'.$cid.'.type'};
9160: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9161: (defined($prp{$short}{$rolenames{$crstype}}))) {
9162: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9163: }
1.742 raeburn 9164: }
1.1037 raeburn 9165: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 9166: }
9167:
9168: # ----------------------------------------------------------------- Assign Role
9169:
9170: sub assignrole {
1.957 raeburn 9171: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9172: $context)=@_;
1.21 www 9173: my $mrole;
9174: if ($role =~ /^cr\//) {
1.393 www 9175: my $cwosec=$url;
1.811 albertel 9176: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 9177: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 9178: my $refused = 1;
9179: if ($context eq 'requestcourses') {
9180: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9181: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9182: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9183: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9184: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9185: if ($crsenv{'internal.courseowner'} eq
9186: $env{'user.name'}.':'.$env{'user.domain'}) {
9187: $refused = '';
9188: }
9189: }
9190: }
9191: }
9192: }
9193: if ($refused) {
9194: &logthis('Refused custom assignrole: '.
9195: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9196: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9197: return 'refused';
9198: }
1.104 www 9199: }
1.21 www 9200: $mrole='cr';
1.678 raeburn 9201: } elsif ($role =~ /^gr\//) {
9202: my $cwogrp=$url;
1.811 albertel 9203: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 9204: unless (&allowed('mdg',$cwogrp)) {
9205: &logthis('Refused group assignrole: '.
9206: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9207: $env{'user.name'}.' at '.$env{'user.domain'});
9208: return 'refused';
9209: }
9210: $mrole='gr';
1.21 www 9211: } else {
1.82 www 9212: my $cwosec=$url;
1.811 albertel 9213: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9214: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9215: my $refused;
9216: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9217: if (!(&allowed('c'.$role,$url))) {
9218: $refused = 1;
9219: }
9220: } else {
9221: $refused = 1;
9222: }
1.947 raeburn 9223: if ($refused) {
1.1045 raeburn 9224: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9225: if (!$selfenroll && $context eq 'course') {
9226: my %crsenv;
9227: if ($role eq 'cc' || $role eq 'co') {
9228: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9229: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9230: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9231: if ($crsenv{'internal.courseowner'} eq
9232: $env{'user.name'}.':'.$env{'user.domain'}) {
9233: $refused = '';
9234: }
9235: }
9236: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9237: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9238: if ($crsenv{'internal.courseowner'} eq
9239: $env{'user.name'}.':'.$env{'user.domain'}) {
9240: $refused = '';
9241: }
9242: }
9243: }
9244: }
9245: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 9246: $refused = '';
1.1017 raeburn 9247: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9248: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9249: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9250: my $wrongcc;
9251: if ($cnum =~ /^$match_community$/) {
9252: $wrongcc = 1 if ($role eq 'cc');
9253: } else {
9254: $wrongcc = 1 if ($role eq 'co');
9255: }
9256: unless ($wrongcc) {
9257: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9258: if ($crsenv{'internal.courseowner'} eq
9259: $env{'user.name'}.':'.$env{'user.domain'}) {
9260: $refused = '';
9261: }
1.1017 raeburn 9262: }
9263: }
1.1183 raeburn 9264: } elsif ($context eq 'requestauthor') {
9265: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9266: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9267: if ($env{'environment.requestauthor'} eq 'automatic') {
9268: $refused = '';
9269: } else {
9270: my %domdefaults = &get_domain_defaults($udom);
9271: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9272: my $checkbystatus;
9273: if ($env{'user.adv'}) {
9274: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9275: if ($disposition eq 'automatic') {
9276: $refused = '';
9277: } elsif ($disposition eq '') {
9278: $checkbystatus = 1;
9279: }
9280: } else {
9281: $checkbystatus = 1;
9282: }
9283: if ($checkbystatus) {
9284: if ($env{'environment.inststatus'}) {
9285: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9286: foreach my $type (@inststatuses) {
9287: if (($type ne '') &&
9288: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9289: $refused = '';
9290: }
9291: }
9292: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9293: $refused = '';
9294: }
9295: }
9296: }
9297: }
9298: }
1.1017 raeburn 9299: }
9300: if ($refused) {
1.947 raeburn 9301: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9302: ' '.$role.' '.$end.' '.$start.' by '.
9303: $env{'user.name'}.' at '.$env{'user.domain'});
9304: return 'refused';
9305: }
1.932 raeburn 9306: }
1.1131 raeburn 9307: } elsif ($role eq 'au') {
9308: if ($url ne '/'.$udom.'/') {
9309: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9310: ' to assign author role for '.$uname.':'.$udom.
9311: ' in domain: '.$url.' refused (wrong domain).');
9312: return 'refused';
9313: }
1.104 www 9314: }
1.21 www 9315: $mrole=$role;
9316: }
1.620 albertel 9317: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9318: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9319: if ($end) { $command.='_'.$end; }
1.21 www 9320: if ($start) {
9321: if ($end) {
1.81 www 9322: $command.='_'.$start;
1.21 www 9323: } else {
1.81 www 9324: $command.='_0_'.$start;
1.21 www 9325: }
9326: }
1.739 raeburn 9327: my $origstart = $start;
9328: my $origend = $end;
1.957 raeburn 9329: my $delflag;
1.357 www 9330: # actually delete
9331: if ($deleteflag) {
1.373 www 9332: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9333: # modify command to delete the role
1.620 albertel 9334: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9335: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9336: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9337: # set start and finish to negative values for userrolelog
9338: $start=-1;
9339: $end=-1;
1.957 raeburn 9340: $delflag = 1;
1.357 www 9341: }
9342: }
9343: # send command
1.349 www 9344: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9345: # log new user role if status is ok
1.349 www 9346: if ($answer eq 'ok') {
1.663 raeburn 9347: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 9348: if (($role eq 'cc') || ($role eq 'in') ||
9349: ($role eq 'ep') || ($role eq 'ad') ||
9350: ($role eq 'ta') || ($role eq 'st') ||
9351: ($role=~/^cr/) || ($role eq 'gr') ||
9352: ($role eq 'co')) {
1.1200 raeburn 9353: # for course roles, perform group memberships changes triggered by role change.
9354: unless ($role =~ /^gr/) {
9355: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9356: $origstart,$selfenroll,$context);
9357: }
1.1184 raeburn 9358: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9359: $selfenroll,$context);
9360: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334 raeburn 9361: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9362: ($role eq 'da')) {
1.1184 raeburn 9363: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9364: $context);
9365: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9366: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9367: $context);
9368: }
1.1053 raeburn 9369: if ($role eq 'cc') {
9370: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9371: }
1.349 www 9372: }
9373: return $answer;
1.169 harris41 9374: }
9375:
1.1053 raeburn 9376: sub autoupdate_coowners {
9377: my ($url,$end,$start,$uname,$udom) = @_;
9378: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9379: if (($cdom ne '') && ($cnum ne '')) {
9380: my $now = time;
9381: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9382: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9383: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9384: my $instcode = $coursehash{'internal.coursecode'};
9385: if ($instcode ne '') {
1.1056 raeburn 9386: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9387: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 9388: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 9389: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9390: if ($result eq 'valid') {
9391: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 9392: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9393: push(@newcoowners,$coowner);
9394: }
9395: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9396: push(@newcoowners,$uname.':'.$udom);
9397: }
9398: @newcoowners = sort(@newcoowners);
9399: } else {
9400: push(@newcoowners,$uname.':'.$udom);
9401: }
9402: } else {
9403: if ($coursehash{'internal.co-owners'}) {
9404: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9405: unless ($coowner eq $uname.':'.$udom) {
9406: push(@newcoowners,$coowner);
9407: }
9408: }
9409: unless (@newcoowners > 0) {
9410: $delcoowners = 1;
9411: $coowners = '';
9412: }
9413: }
9414: }
9415: if (@newcoowners || $delcoowners) {
9416: &store_coowners($cdom,$cnum,$coursehash{'home'},
9417: $delcoowners,@newcoowners);
9418: }
9419: }
9420: }
9421: }
9422: }
9423: }
9424: }
9425:
9426: sub store_coowners {
9427: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9428: my $cid = $cdom.'_'.$cnum;
9429: my ($coowners,$delresult,$putresult);
9430: if (@newcoowners) {
9431: $coowners = join(',',@newcoowners);
9432: my %coownershash = (
9433: 'internal.co-owners' => $coowners,
9434: );
9435: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9436: if ($putresult eq 'ok') {
9437: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9438: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9439: }
9440: }
9441: }
9442: if ($delcoowners) {
9443: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9444: if ($delresult eq 'ok') {
9445: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9446: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9447: }
9448: }
9449: }
9450: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9451: my %crsinfo =
9452: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9453: if (ref($crsinfo{$cid}) eq 'HASH') {
9454: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9455: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9456: }
9457: }
9458: }
9459:
1.169 harris41 9460: # -------------------------------------------------- Modify user authentication
1.197 www 9461: # Overrides without validation
9462:
1.169 harris41 9463: sub modifyuserauth {
9464: my ($udom,$uname,$umode,$upass)=@_;
9465: my $uhome=&homeserver($uname,$udom);
1.197 www 9466: unless (&allowed('mau',$udom)) { return 'refused'; }
9467: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 9468: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9469: ' in domain '.$env{'request.role.domain'});
1.169 harris41 9470: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9471: &escape($upass),$uhome);
1.620 albertel 9472: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 9473: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9474: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9475: &log($udom,,$uname,$uhome,
1.620 albertel 9476: 'Authentication changed by '.$env{'user.domain'}.', '.
9477: $env{'user.name'}.', '.$umode.
1.197 www 9478: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 9479: unless ($reply eq 'ok') {
1.197 www 9480: &logthis('Authentication mode error: '.$reply);
1.169 harris41 9481: return 'error: '.$reply;
9482: }
1.170 harris41 9483: return 'ok';
1.80 www 9484: }
9485:
1.81 www 9486: # --------------------------------------------------------------- Modify a user
1.80 www 9487:
1.81 www 9488: sub modifyuser {
1.206 matthew 9489: my ($udom, $uname, $uid,
9490: $umode, $upass, $first,
9491: $middle, $last, $gene,
1.1058 raeburn 9492: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 9493: $udom= &LONCAPA::clean_domain($udom);
9494: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 9495: my $showcandelete = 'none';
9496: if (ref($candelete) eq 'ARRAY') {
9497: if (@{$candelete} > 0) {
9498: $showcandelete = join(', ',@{$candelete});
9499: }
9500: }
1.81 www 9501: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 9502: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 9503: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 9504: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9505: ' desiredhome not specified').
1.620 albertel 9506: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9507: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 9508: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 9509: my $newuser;
9510: if ($uhome eq 'no_host') {
9511: $newuser = 1;
9512: }
1.80 www 9513: # ----------------------------------------------------------------- Create User
1.406 albertel 9514: if (($uhome eq 'no_host') &&
9515: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 9516: my $unhome='';
1.844 albertel 9517: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 9518: $unhome = $desiredhome;
1.620 albertel 9519: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9520: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 9521: } else { # load balancing routine for determining $unhome
1.81 www 9522: my $loadm=10000000;
1.841 albertel 9523: my %servers = &get_servers($udom,'library');
9524: foreach my $tryserver (keys(%servers)) {
9525: my $answer=reply('load',$tryserver);
9526: if (($answer=~/\d+/) && ($answer<$loadm)) {
9527: $loadm=$answer;
9528: $unhome=$tryserver;
9529: }
1.80 www 9530: }
9531: }
9532: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 9533: return 'error: unable to find a home server for '.$uname.
9534: ' in domain '.$udom;
1.80 www 9535: }
9536: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9537: &escape($upass),$unhome);
9538: unless ($reply eq 'ok') {
9539: return 'error: '.$reply;
9540: }
1.230 stredwic 9541: $uhome=&homeserver($uname,$udom,'true');
1.80 www 9542: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 9543: return 'error: unable verify users home machine.';
1.80 www 9544: }
1.209 matthew 9545: } # End of creation of new user
1.80 www 9546: # ---------------------------------------------------------------------- Add ID
9547: if ($uid) {
9548: $uid=~tr/A-Z/a-z/;
9549: my %uidhash=&idrget($udom,$uname);
1.196 www 9550: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
9551: && (!$forceid)) {
1.80 www 9552: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 9553: return 'error: user id "'.$uid.'" does not match '.
9554: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 9555: }
9556: } else {
1.1300 raeburn 9557: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 9558: }
9559: }
9560: # -------------------------------------------------------------- Add names, etc
1.313 matthew 9561: my @tmp=&get('environment',
1.899 raeburn 9562: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 9563: 'permanentemail','inststatus'],
1.134 albertel 9564: $udom,$uname);
1.1075 raeburn 9565: my (%names,%oldnames);
1.313 matthew 9566: if ($tmp[0] =~ m/^error:.*/) {
9567: %names=();
9568: } else {
9569: %names = @tmp;
1.1075 raeburn 9570: %oldnames = %names;
1.313 matthew 9571: }
1.388 www 9572: #
1.1058 raeburn 9573: # If name, email and/or uid are blank (e.g., because an uploaded file
9574: # of users did not contain them), do not overwrite existing values
9575: # unless field is in $candelete array ref.
9576: #
9577:
9578: my @fields = ('firstname','middlename','lastname','generation',
9579: 'permanentemail','id');
9580: my %newvalues;
9581: if (ref($candelete) eq 'ARRAY') {
9582: foreach my $field (@fields) {
9583: if (grep(/^\Q$field\E$/,@{$candelete})) {
9584: if ($field eq 'firstname') {
9585: $names{$field} = $first;
9586: } elsif ($field eq 'middlename') {
9587: $names{$field} = $middle;
9588: } elsif ($field eq 'lastname') {
9589: $names{$field} = $last;
9590: } elsif ($field eq 'generation') {
9591: $names{$field} = $gene;
9592: } elsif ($field eq 'permanentemail') {
9593: $names{$field} = $email;
9594: } elsif ($field eq 'id') {
9595: $names{$field} = $uid;
9596: }
9597: }
9598: }
9599: }
1.388 www 9600: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 9601: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 9602: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 9603: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 9604: if ($email) {
9605: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 9606: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 9607: }
1.899 raeburn 9608: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 9609: if (defined($inststatus)) {
9610: $names{'inststatus'} = '';
9611: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9612: if (ref($usertypes) eq 'HASH') {
9613: my @okstatuses;
9614: foreach my $item (split(/:/,$inststatus)) {
9615: if (defined($usertypes->{$item})) {
9616: push(@okstatuses,$item);
9617: }
9618: }
9619: if (@okstatuses) {
9620: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9621: }
9622: }
9623: }
1.1075 raeburn 9624: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 9625: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 9626: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 9627: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9628: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9629: } else {
9630: $logmsg .= ' during self creation';
9631: }
1.1075 raeburn 9632: my $changed;
9633: if ($newuser) {
9634: $changed = 1;
9635: } else {
9636: foreach my $field (@fields) {
9637: if ($names{$field} ne $oldnames{$field}) {
9638: $changed = 1;
9639: last;
9640: }
9641: }
9642: }
9643: unless ($changed) {
9644: $logmsg = 'No changes in user information needed for: '.$logmsg;
9645: &logthis($logmsg);
9646: return 'ok';
9647: }
9648: my $reply = &put('environment', \%names, $udom,$uname);
9649: if ($reply ne 'ok') {
9650: return 'error: '.$reply;
9651: }
1.1087 raeburn 9652: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9653: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9654: }
1.1075 raeburn 9655: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9656: &devalidate_cache_new('namescache',$uname.':'.$udom);
9657: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9658: &logthis($logmsg);
1.134 albertel 9659: return 'ok';
1.80 www 9660: }
9661:
1.81 www 9662: # -------------------------------------------------------------- Modify student
1.80 www 9663:
1.81 www 9664: sub modifystudent {
9665: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9666: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 9667: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 9668: if (!$cid) {
1.620 albertel 9669: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9670: return 'not_in_class';
9671: }
1.80 www 9672: }
9673: # --------------------------------------------------------------- Make the user
1.81 www 9674: my $reply=&modifyuser
1.209 matthew 9675: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9676: $desiredhome,$email,$inststatus);
1.80 www 9677: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9678: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 9679: # student's environment
1.297 matthew 9680: $uid = undef if (!$forceid);
1.455 albertel 9681: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 9682: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 9683: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 9684: return $reply;
9685: }
9686:
9687: sub modify_student_enrollment {
1.1216 raeburn 9688: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314 raeburn 9689: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 9690: my ($cdom,$cnum,$chome);
9691: if (!$cid) {
1.620 albertel 9692: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9693: return 'not_in_class';
9694: }
1.620 albertel 9695: $cdom=$env{'course.'.$cid.'.domain'};
9696: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9697: } else {
9698: ($cdom,$cnum)=split(/_/,$cid);
9699: }
1.620 albertel 9700: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9701: if (!$chome) {
1.457 raeburn 9702: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9703: }
1.455 albertel 9704: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9705: # Make sure the user exists
1.81 www 9706: my $uhome=&homeserver($uname,$udom);
9707: if (($uhome eq '') || ($uhome eq 'no_host')) {
9708: return 'error: no such user';
9709: }
1.297 matthew 9710: # Get student data if we were not given enough information
9711: if (!defined($first) || $first eq '' ||
9712: !defined($last) || $last eq '' ||
9713: !defined($uid) || $uid eq '' ||
9714: !defined($middle) || $middle eq '' ||
9715: !defined($gene) || $gene eq '') {
1.294 matthew 9716: # They did not supply us with enough data to enroll the student, so
9717: # we need to pick up more information.
1.297 matthew 9718: my %tmp = &get('environment',
1.294 matthew 9719: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9720: ,$udom,$uname);
9721:
1.800 albertel 9722: #foreach my $key (keys(%tmp)) {
9723: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9724: #}
1.294 matthew 9725: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9726: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9727: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9728: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9729: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9730: }
1.556 albertel 9731: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9732: my $user = "$uname:$udom";
9733: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9734: my $reply=cput('classlist',
1.1148 raeburn 9735: {$user =>
1.1314 raeburn 9736: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 9737: $cdom,$cnum);
1.1148 raeburn 9738: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9739: &devalidate_getsection_cache($udom,$uname,$cid);
9740: } else {
1.81 www 9741: return 'error: '.$reply;
9742: }
1.297 matthew 9743: # Add student role to user
1.83 www 9744: my $uurl='/'.$cid;
1.81 www 9745: $uurl=~s/\_/\//g;
9746: if ($usec) {
9747: $uurl.='/'.$usec;
9748: }
1.1148 raeburn 9749: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9750: $selfenroll,$context);
9751: if ($result ne 'ok') {
9752: if ($old_entry{$user} ne '') {
9753: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9754: } else {
9755: $reply = &del('classlist',[$user],$cdom,$cnum);
9756: }
9757: }
9758: return $result;
1.21 www 9759: }
9760:
1.556 albertel 9761: sub format_name {
9762: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9763: my $name;
9764: if ($first ne 'lastname') {
9765: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9766: } else {
9767: if ($lastname=~/\S/) {
9768: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9769: $name=~s/\s+,/,/;
9770: } else {
9771: $name.= $firstname.' '.$middlename.' '.$generation;
9772: }
9773: }
9774: $name=~s/^\s+//;
9775: $name=~s/\s+$//;
9776: $name=~s/\s+/ /g;
9777: return $name;
9778: }
9779:
1.84 www 9780: # ------------------------------------------------- Write to course preferences
9781:
9782: sub writecoursepref {
9783: my ($courseid,%prefs)=@_;
9784: $courseid=~s/^\///;
9785: $courseid=~s/\_/\//g;
9786: my ($cdomain,$cnum)=split(/\//,$courseid);
9787: my $chome=homeserver($cnum,$cdomain);
9788: if (($chome eq '') || ($chome eq 'no_host')) {
9789: return 'error: no such course';
9790: }
9791: my $cstring='';
1.800 albertel 9792: foreach my $pref (keys(%prefs)) {
9793: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9794: }
1.84 www 9795: $cstring=~s/\&$//;
9796: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9797: }
9798:
9799: # ---------------------------------------------------------- Make/modify course
9800:
9801: sub createcourse {
1.741 raeburn 9802: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9803: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9804: $url=&declutter($url);
9805: my $cid='';
1.1028 raeburn 9806: if ($context eq 'requestcourses') {
9807: my $can_create = 0;
9808: my ($ownername,$ownerdom) = split(':',$course_owner);
9809: if ($udom eq $ownerdom) {
9810: if (&usertools_access($ownername,$ownerdom,$category,undef,
9811: $context)) {
9812: $can_create = 1;
9813: }
9814: } else {
9815: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9816: $category);
9817: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9818: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9819: if (@curr > 0) {
9820: my @options = qw(approval validate autolimit);
9821: my $optregex = join('|',@options);
9822: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9823: $can_create = 1;
9824: }
9825: }
9826: }
9827: }
9828: if ($can_create) {
9829: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9830: unless (&allowed('ccc',$udom)) {
9831: return 'refused';
9832: }
1.1017 raeburn 9833: }
9834: } else {
9835: return 'refused';
9836: }
1.1028 raeburn 9837: } elsif (!&allowed('ccc',$udom)) {
9838: return 'refused';
1.84 www 9839: }
1.1011 raeburn 9840: # --------------------------------------------------------------- Get Unique ID
9841: my $uname;
9842: if ($cnum =~ /^$match_courseid$/) {
9843: my $chome=&homeserver($cnum,$udom,'true');
9844: if (($chome eq '') || ($chome eq 'no_host')) {
9845: $uname = $cnum;
9846: } else {
1.1038 raeburn 9847: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9848: }
9849: } else {
1.1038 raeburn 9850: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9851: }
9852: return $uname if ($uname =~ /^error/);
9853: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9854: if (!defined($course_server)) {
9855: if (defined(&domain($udom,'primary'))) {
9856: $course_server = &domain($udom,'primary');
9857: } else {
9858: $course_server = $env{'user.home'};
9859: }
9860: }
9861: my %host_servers =
9862: &Apache::lonnet::get_servers($udom,'library');
9863: unless ($host_servers{$course_server}) {
9864: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9865: }
1.84 www 9866: # ------------------------------------------------------------- Make the course
9867: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9868: $course_server);
1.84 www 9869: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9870: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9871: if (($uhome eq '') || ($uhome eq 'no_host')) {
9872: return 'error: no such course';
9873: }
1.271 www 9874: # ----------------------------------------------------------------- Course made
1.516 raeburn 9875: # log existence
1.1029 raeburn 9876: my $now = time;
1.918 raeburn 9877: my $newcourse = {
9878: $udom.'_'.$uname => {
1.921 raeburn 9879: description => $description,
9880: inst_code => $inst_code,
9881: owner => $course_owner,
9882: type => $crstype,
1.1029 raeburn 9883: creator => $env{'user.name'}.':'.
9884: $env{'user.domain'},
9885: created => $now,
9886: context => $context,
1.918 raeburn 9887: },
9888: };
1.921 raeburn 9889: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9890: # set toplevel url
1.271 www 9891: my $topurl=$url;
9892: unless ($nonstandard) {
9893: # ------------------------------------------ For standard courses, make top url
9894: my $mapurl=&clutter($url);
1.278 www 9895: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9896: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9897: <map>
9898: <resource id="1" type="start"></resource>
9899: <resource id="2" src="$mapurl"></resource>
9900: <resource id="3" type="finish"></resource>
9901: <link index="1" from="1" to="2"></link>
9902: <link index="2" from="2" to="3"></link>
9903: </map>
9904: ENDINITMAP
9905: $topurl=&declutter(
1.638 albertel 9906: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9907: );
9908: }
9909: # ----------------------------------------------------------- Write preferences
1.84 www 9910: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9911: ('description' => $description,
9912: 'url' => $topurl,
9913: 'internal.creator' => $env{'user.name'}.':'.
9914: $env{'user.domain'},
9915: 'internal.created' => $now,
9916: 'internal.creationcontext' => $context)
9917: );
1.84 www 9918: return '/'.$udom.'/'.$uname;
9919: }
9920:
1.1011 raeburn 9921: # ------------------------------------------------------------------- Create ID
9922: sub generate_coursenum {
1.1038 raeburn 9923: my ($udom,$crstype) = @_;
1.1011 raeburn 9924: my $domdesc = &domain($udom);
9925: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9926: my $first;
9927: if ($crstype eq 'Community') {
9928: $first = '0';
9929: } else {
9930: $first = int(1+rand(9));
9931: }
9932: my $uname=$first.
1.1011 raeburn 9933: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9934: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9935: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9936: # ----------------------------------------------- Make sure that does not exist
9937: my $uhome=&homeserver($uname,$udom,'true');
9938: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9939: if ($crstype eq 'Community') {
9940: $first = '0';
9941: } else {
9942: $first = int(1+rand(9));
9943: }
9944: $uname=$first.
1.1011 raeburn 9945: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9946: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9947: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9948: $uhome=&homeserver($uname,$udom,'true');
9949: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9950: return 'error: unable to generate unique course-ID';
9951: }
9952: }
9953: return $uname;
9954: }
9955:
1.813 albertel 9956: sub is_course {
1.1167 droeschl 9957: my ($cdom, $cnum) = scalar(@_) == 1 ?
9958: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9959:
9960: return unless $cdom and $cnum;
9961:
9962: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9963: '.');
9964:
1.1219 raeburn 9965: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9966: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9967: }
9968:
1.1015 raeburn 9969: sub store_userdata {
9970: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9971: my $result;
1.1016 raeburn 9972: if ($datakey ne '') {
1.1013 raeburn 9973: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9974: if ($udom eq '' || $uname eq '') {
9975: $udom = $env{'user.domain'};
9976: $uname = $env{'user.name'};
9977: }
9978: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9979: if (($uhome eq '') || ($uhome eq 'no_host')) {
9980: $result = 'error: no_host';
9981: } else {
9982: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9983: $storehash->{'host'} = $perlvar{'lonHostID'};
9984:
9985: my $namevalue='';
9986: foreach my $key (keys(%{$storehash})) {
9987: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9988: }
9989: $namevalue=~s/\&$//;
1.1224 raeburn 9990: unless ($namespace eq 'courserequests') {
9991: $datakey = &escape($datakey);
9992: }
1.1105 raeburn 9993: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9994: $namevalue,$uhome);
1.1013 raeburn 9995: }
9996: } else {
9997: $result = 'error: data to store was not a hash reference';
9998: }
9999: } else {
10000: $result= 'error: invalid requestkey';
10001: }
10002: return $result;
10003: }
10004:
1.21 www 10005: # ---------------------------------------------------------- Assign Custom Role
10006:
10007: sub assigncustomrole {
1.957 raeburn 10008: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10009: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 10010: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 10011: }
10012:
10013: # ----------------------------------------------------------------- Revoke Role
10014:
10015: sub revokerole {
1.957 raeburn 10016: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10017: my $now=time;
1.965 raeburn 10018: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 10019: }
10020:
10021: # ---------------------------------------------------------- Revoke Custom Role
10022:
10023: sub revokecustomrole {
1.957 raeburn 10024: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10025: my $now=time;
1.357 www 10026: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 10027: $deleteflag,$selfenroll,$context);
1.17 www 10028: }
10029:
1.533 banghart 10030: # ------------------------------------------------------------ Disk usage
1.535 albertel 10031: sub diskusage {
1.955 raeburn 10032: my ($udom,$uname,$directorypath,$getpropath)=@_;
10033: $directorypath =~ s/\/$//;
10034: my $listing=&reply('du2:'.&escape($directorypath).':'
10035: .&escape($getpropath).':'.&escape($uname).':'
10036: .&escape($udom),homeserver($uname,$udom));
10037: if ($listing eq 'unknown_cmd') {
10038: if ($getpropath) {
10039: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10040: }
10041: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10042: }
1.514 albertel 10043: return $listing;
1.512 banghart 10044: }
10045:
1.566 banghart 10046: sub is_locked {
1.1096 raeburn 10047: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 10048: my @check;
10049: my $is_locked;
1.1093 raeburn 10050: push (@check,$file_name);
1.613 albertel 10051: my %locked = &get('file_permissions',\@check,
1.620 albertel 10052: $env{'user.domain'},$env{'user.name'});
1.615 albertel 10053: my ($tmp)=keys(%locked);
10054: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 10055:
1.566 banghart 10056: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 10057: $is_locked = 'false';
10058: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 10059: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 10060: $is_locked = 'true';
1.1096 raeburn 10061: if (ref($which) eq 'ARRAY') {
10062: push(@{$which},$entry);
10063: } else {
10064: last;
10065: }
1.745 raeburn 10066: }
10067: }
1.566 banghart 10068: } else {
10069: $is_locked = 'false';
10070: }
1.1093 raeburn 10071: return $is_locked;
1.566 banghart 10072: }
10073:
1.759 albertel 10074: sub declutter_portfile {
10075: my ($file) = @_;
1.833 albertel 10076: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 10077: return $file;
10078: }
10079:
1.559 banghart 10080: # ------------------------------------------------------------- Mark as Read Only
10081:
10082: sub mark_as_readonly {
10083: my ($domain,$user,$files,$what) = @_;
1.613 albertel 10084: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10085: my ($tmp)=keys(%current_permissions);
10086: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 10087: foreach my $file (@{$files}) {
1.759 albertel 10088: $file = &declutter_portfile($file);
1.561 banghart 10089: push(@{$current_permissions{$file}},$what);
1.559 banghart 10090: }
1.613 albertel 10091: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10092: return;
10093: }
10094:
1.572 banghart 10095: # ------------------------------------------------------------Save Selected Files
10096:
10097: sub save_selected_files {
10098: my ($user, $path, @files) = @_;
10099: my $filename = $user."savedfiles";
1.573 banghart 10100: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 10101: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 10102: foreach my $file (@files) {
1.620 albertel 10103: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 10104: }
10105: foreach my $file (@other_files) {
1.574 banghart 10106: print (OUT $file."\n");
1.572 banghart 10107: }
1.574 banghart 10108: close (OUT);
1.572 banghart 10109: return 'ok';
10110: }
10111:
1.574 banghart 10112: sub clear_selected_files {
10113: my ($user) = @_;
10114: my $filename = $user."savedfiles";
1.1117 foxr 10115: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 10116: print (OUT undef);
10117: close (OUT);
10118: return ("ok");
10119: }
10120:
1.572 banghart 10121: sub files_in_path {
10122: my ($user, $path) = @_;
10123: my $filename = $user."savedfiles";
10124: my %return_files;
1.1117 foxr 10125: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 10126: while (my $line_in = <IN>) {
1.574 banghart 10127: chomp ($line_in);
10128: my @paths_and_file = split (m!/!, $line_in);
10129: my $file_part = pop (@paths_and_file);
10130: my $path_part = join ('/', @paths_and_file);
1.573 banghart 10131: $path_part.='/';
10132: my $path_and_file = $path_part.$file_part;
10133: if ($path_part eq $path) {
10134: $return_files{$file_part}= 'selected';
10135: }
10136: }
1.574 banghart 10137: close (IN);
10138: return (\%return_files);
1.572 banghart 10139: }
10140:
10141: # called in portfolio select mode, to show files selected NOT in current directory
10142: sub files_not_in_path {
10143: my ($user, $path) = @_;
10144: my $filename = $user."savedfiles";
10145: my @return_files;
10146: my $path_part;
1.1117 foxr 10147: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 10148: while (my $line = <IN>) {
1.572 banghart 10149: #ok, I know it's clunky, but I want it to work
1.800 albertel 10150: my @paths_and_file = split(m|/|, $line);
10151: my $file_part = pop(@paths_and_file);
10152: chomp($file_part);
10153: my $path_part = join('/', @paths_and_file);
1.572 banghart 10154: $path_part .= '/';
10155: my $path_and_file = $path_part.$file_part;
10156: if ($path_part ne $path) {
1.800 albertel 10157: push(@return_files, ($path_and_file));
1.572 banghart 10158: }
10159: }
1.800 albertel 10160: close(OUT);
1.574 banghart 10161: return (@return_files);
1.572 banghart 10162: }
10163:
1.1273 raeburn 10164: #------------------------------Submitted/Handedback Portfolio Files Versioning
10165:
10166: sub portfiles_versioning {
10167: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10168: my $portfolio_root = '/userfiles/portfolio';
10169: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10170: foreach my $file (@{$portfiles}) {
10171: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10172: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10173: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10174: my $getpropath = 1;
10175: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10176: $stu_name,$getpropath);
10177: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10178: my $new_answer =
10179: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10180: if ($new_answer ne 'problem getting file') {
10181: push(@{$versioned_portfiles}, $directory.$new_answer);
10182: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10183: [$symb,$env{'request.course.id'},'graded']);
10184: }
10185: }
10186: }
10187:
10188: sub get_next_version {
10189: my ($answer_name, $answer_ext, $dir_list) = @_;
10190: my $version;
10191: if (ref($dir_list) eq 'ARRAY') {
10192: foreach my $row (@{$dir_list}) {
10193: my ($file) = split(/\&/,$row,2);
10194: my ($file_name,$file_version,$file_ext) =
10195: &file_name_version_ext($file);
10196: if (($file_name eq $answer_name) &&
10197: ($file_ext eq $answer_ext)) {
10198: # gets here if filename and extension match,
10199: # regardless of version
10200: if ($file_version ne '') {
10201: # a versioned file is found so save it for later
10202: if ($file_version > $version) {
10203: $version = $file_version;
10204: }
10205: }
10206: }
10207: }
10208: }
10209: $version ++;
10210: return($version);
10211: }
10212:
10213: sub version_selected_portfile {
10214: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10215: my ($answer_name,$answer_ver,$answer_ext) =
10216: &file_name_version_ext($file_name);
10217: my $new_answer;
10218: $env{'form.copy'} =
10219: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10220: if($env{'form.copy'} eq '-1') {
10221: $new_answer = 'problem getting file';
10222: } else {
10223: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10224: my $copy_result =
10225: &finishuserfileupload($stu_name,$domain,'copy',
10226: '/portfolio'.$directory.$new_answer);
10227: }
10228: undef($env{'form.copy'});
10229: return ($new_answer);
10230: }
10231:
10232: sub file_name_version_ext {
10233: my ($file)=@_;
10234: my @file_parts = split(/\./, $file);
10235: my ($name,$version,$ext);
10236: if (@file_parts > 1) {
10237: $ext=pop(@file_parts);
10238: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10239: $version=pop(@file_parts);
10240: }
10241: $name=join('.',@file_parts);
10242: } else {
10243: $name=join('.',@file_parts);
10244: }
10245: return($name,$version,$ext);
10246: }
10247:
1.745 raeburn 10248: #----------------------------------------------Get portfolio file permissions
1.629 banghart 10249:
1.745 raeburn 10250: sub get_portfile_permissions {
10251: my ($domain,$user) = @_;
1.613 albertel 10252: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10253: my ($tmp)=keys(%current_permissions);
10254: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10255: return \%current_permissions;
10256: }
10257:
10258: #---------------------------------------------Get portfolio file access controls
10259:
1.749 raeburn 10260: sub get_access_controls {
1.745 raeburn 10261: my ($current_permissions,$group,$file) = @_;
1.769 albertel 10262: my %access;
10263: my $real_file = $file;
10264: $file =~ s/\.meta$//;
1.745 raeburn 10265: if (defined($file)) {
1.749 raeburn 10266: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10267: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 10268: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 10269: }
10270: }
1.745 raeburn 10271: } else {
1.749 raeburn 10272: foreach my $key (keys(%{$current_permissions})) {
10273: if ($key =~ /\0accesscontrol$/) {
10274: if (defined($group)) {
10275: if ($key !~ m-^\Q$group\E/-) {
10276: next;
10277: }
10278: }
10279: my ($fullpath) = split(/\0/,$key);
10280: if (ref($$current_permissions{$key}) eq 'HASH') {
10281: foreach my $control (keys(%{$$current_permissions{$key}})) {
10282: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10283: }
10284: }
10285: }
10286: }
10287: }
10288: return %access;
10289: }
10290:
10291: sub modify_access_controls {
10292: my ($file_name,$changes,$domain,$user)=@_;
10293: my ($outcome,$deloutcome);
10294: my %store_permissions;
10295: my %new_values;
10296: my %new_control;
10297: my %translation;
10298: my @deletions = ();
10299: my $now = time;
10300: if (exists($$changes{'activate'})) {
10301: if (ref($$changes{'activate'}) eq 'HASH') {
10302: my @newitems = sort(keys(%{$$changes{'activate'}}));
10303: my $numnew = scalar(@newitems);
10304: for (my $i=0; $i<$numnew; $i++) {
10305: my $newkey = $newitems[$i];
10306: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10307: if ($newkey =~ /^\d+:/) {
10308: $newkey =~ s/^(\d+)/$newid/;
10309: $translation{$1} = $newid;
10310: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10311: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10312: $translation{$1} = $newid;
10313: }
1.749 raeburn 10314: $new_values{$file_name."\0".$newkey} =
10315: $$changes{'activate'}{$newitems[$i]};
10316: $new_control{$newkey} = $now;
10317: }
10318: }
10319: }
10320: my %todelete;
10321: my %changed_items;
10322: foreach my $action ('delete','update') {
10323: if (exists($$changes{$action})) {
10324: if (ref($$changes{$action}) eq 'HASH') {
10325: foreach my $key (keys(%{$$changes{$action}})) {
10326: my ($itemnum) = ($key =~ /^([^:]+):/);
10327: if ($action eq 'delete') {
10328: $todelete{$itemnum} = 1;
10329: } else {
10330: $changed_items{$itemnum} = $key;
10331: }
10332: }
1.745 raeburn 10333: }
10334: }
1.749 raeburn 10335: }
10336: # get lock on access controls for file.
10337: my $lockhash = {
10338: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10339: ':'.$env{'user.domain'},
10340: };
10341: my $tries = 0;
10342: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10343:
1.1288 damieng 10344: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10345: $tries ++;
1.1289 damieng 10346: sleep(0.1);
1.749 raeburn 10347: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10348: }
10349: if ($gotlock eq 'ok') {
10350: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10351: my ($tmp)=keys(%curr_permissions);
10352: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10353: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10354: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10355: if (ref($curr_controls) eq 'HASH') {
10356: foreach my $control_item (keys(%{$curr_controls})) {
10357: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10358: if (defined($todelete{$itemnum})) {
10359: push(@deletions,$file_name."\0".$control_item);
10360: } else {
10361: if (defined($changed_items{$itemnum})) {
10362: $new_control{$changed_items{$itemnum}} = $now;
10363: push(@deletions,$file_name."\0".$control_item);
10364: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10365: } else {
10366: $new_control{$control_item} = $$curr_controls{$control_item};
10367: }
10368: }
1.745 raeburn 10369: }
10370: }
10371: }
1.970 raeburn 10372: my ($group);
10373: if (&is_course($domain,$user)) {
10374: ($group,my $file) = split(/\//,$file_name,2);
10375: }
1.749 raeburn 10376: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10377: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10378: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10379: # remove lock
10380: my @del_lock = ($file_name."\0".'locked_access_records');
10381: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 10382: my $sqlresult =
1.970 raeburn 10383: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 10384: $group);
1.749 raeburn 10385: } else {
10386: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 10387: }
1.749 raeburn 10388: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 10389: }
10390:
1.827 raeburn 10391: sub make_public_indefinitely {
1.1271 raeburn 10392: my (@requrl) = @_;
10393: return &automated_portfile_access('public',\@requrl);
10394: }
10395:
10396: sub automated_portfile_access {
10397: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 10398: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10399: return 'invalid';
10400: }
1.1271 raeburn 10401: my %urls;
10402: if (ref($addsref) eq 'ARRAY') {
10403: foreach my $requrl (@{$addsref}) {
10404: if (&is_portfolio_url($requrl)) {
10405: unless (exists($urls{$requrl})) {
10406: $urls{$requrl} = 'add';
10407: }
10408: }
10409: }
10410: }
10411: if (ref($delsref) eq 'ARRAY') {
10412: foreach my $requrl (@{$delsref}) {
10413: if (&is_portfolio_url($requrl)) {
10414: unless (exists($urls{$requrl})) {
10415: $urls{$requrl} = 'delete';
10416: }
10417: }
10418: }
10419: }
10420: unless (keys(%urls)) {
10421: return 'invalid';
10422: }
10423: my $ip;
10424: if ($accesstype eq 'ip') {
10425: if (ref($info) eq 'HASH') {
10426: if ($info->{'ip'} ne '') {
10427: $ip = $info->{'ip'};
10428: }
10429: }
10430: if ($ip eq '') {
10431: return 'invalid';
10432: }
10433: }
10434: my $errors;
1.827 raeburn 10435: my $now = time;
1.1271 raeburn 10436: my %current_perms;
10437: foreach my $requrl (sort(keys(%urls))) {
10438: my $action;
10439: if ($urls{$requrl} eq 'add') {
10440: $action = 'activate';
10441: } else {
10442: $action = 'none';
10443: }
10444: my $aclnum = 0;
1.827 raeburn 10445: my (undef,$udom,$unum,$file_name,$group) =
10446: &parse_portfolio_url($requrl);
1.1271 raeburn 10447: unless (exists($current_perms{$unum.':'.$udom})) {
10448: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10449: }
10450: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 10451: $group,$file_name);
10452: foreach my $key (keys(%{$access_controls{$file_name}})) {
10453: my ($num,$scope,$end,$start) =
10454: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 10455: if ($scope eq $accesstype) {
10456: if (($start <= $now) && ($end == 0)) {
10457: if ($accesstype eq 'ip') {
10458: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10459: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10460: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10461: if ($urls{$requrl} eq 'add') {
10462: $action = 'none';
10463: last;
10464: } else {
10465: $action = 'delete';
10466: $aclnum = $num;
10467: last;
10468: }
10469: }
10470: }
10471: }
10472: } elsif ($accesstype eq 'public') {
10473: if ($urls{$requrl} eq 'add') {
10474: $action = 'none';
10475: last;
10476: } else {
10477: $action = 'delete';
10478: $aclnum = $num;
10479: last;
10480: }
10481: }
10482: } elsif ($accesstype eq 'public') {
1.827 raeburn 10483: $action = 'update';
10484: $aclnum = $num;
1.1271 raeburn 10485: last;
1.827 raeburn 10486: }
10487: }
10488: }
10489: if ($action eq 'none') {
1.1271 raeburn 10490: next;
1.827 raeburn 10491: } else {
10492: my %changes;
10493: my $newend = 0;
10494: my $newstart = $now;
1.1271 raeburn 10495: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 10496: $changes{$action}{$newkey} = {
1.1271 raeburn 10497: type => $accesstype,
1.827 raeburn 10498: time => {
10499: start => $newstart,
10500: end => $newend,
10501: },
10502: };
1.1271 raeburn 10503: if ($accesstype eq 'ip') {
10504: $changes{$action}{$newkey}{'ip'} = [$ip];
10505: }
1.827 raeburn 10506: my ($outcome,$deloutcome,$new_values,$translation) =
10507: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 10508: unless ($outcome eq 'ok') {
10509: $errors .= $outcome.' ';
10510: }
1.827 raeburn 10511: }
1.1271 raeburn 10512: }
10513: if ($errors) {
10514: $errors =~ s/\s$//;
10515: return $errors;
1.827 raeburn 10516: } else {
1.1271 raeburn 10517: return 'ok';
1.827 raeburn 10518: }
10519: }
10520:
1.745 raeburn 10521: #------------------------------------------------------Get Marked as Read Only
10522:
10523: sub get_marked_as_readonly {
10524: my ($domain,$user,$what,$group) = @_;
10525: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 10526: my @readonly_files;
1.629 banghart 10527: my $cmp1=$what;
10528: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10529: while (my ($file_name,$value) = each(%{$current_permissions})) {
10530: if (defined($group)) {
10531: if ($file_name !~ m-^\Q$group\E/-) {
10532: next;
10533: }
10534: }
1.561 banghart 10535: if (ref($value) eq "ARRAY"){
10536: foreach my $stored_what (@{$value}) {
1.629 banghart 10537: my $cmp2=$stored_what;
1.759 albertel 10538: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 10539: $cmp2=join('',@{$stored_what});
1.745 raeburn 10540: }
1.629 banghart 10541: if ($cmp1 eq $cmp2) {
1.561 banghart 10542: push(@readonly_files, $file_name);
1.745 raeburn 10543: last;
1.563 banghart 10544: } elsif (!defined($what)) {
10545: push(@readonly_files, $file_name);
1.745 raeburn 10546: last;
1.561 banghart 10547: }
10548: }
1.745 raeburn 10549: }
1.561 banghart 10550: }
10551: return @readonly_files;
10552: }
1.577 banghart 10553: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 10554:
1.577 banghart 10555: sub get_marked_as_readonly_hash {
1.745 raeburn 10556: my ($current_permissions,$group,$what) = @_;
1.577 banghart 10557: my %readonly_files;
1.745 raeburn 10558: while (my ($file_name,$value) = each(%{$current_permissions})) {
10559: if (defined($group)) {
10560: if ($file_name !~ m-^\Q$group\E/-) {
10561: next;
10562: }
10563: }
1.577 banghart 10564: if (ref($value) eq "ARRAY"){
10565: foreach my $stored_what (@{$value}) {
1.745 raeburn 10566: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 10567: foreach my $lock_descriptor(@{$stored_what}) {
10568: if ($lock_descriptor eq 'graded') {
10569: $readonly_files{$file_name} = 'graded';
10570: } elsif ($lock_descriptor eq 'handback') {
10571: $readonly_files{$file_name} = 'handback';
10572: } else {
10573: if (!exists($readonly_files{$file_name})) {
10574: $readonly_files{$file_name} = 'locked';
10575: }
10576: }
1.745 raeburn 10577: }
1.750 banghart 10578: }
1.577 banghart 10579: }
10580: }
10581: }
10582: return %readonly_files;
10583: }
1.559 banghart 10584: # ------------------------------------------------------------ Unmark as Read Only
10585:
10586: sub unmark_as_readonly {
1.629 banghart 10587: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10588: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 10589: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 10590: $file_name = &declutter_portfile($file_name);
1.634 albertel 10591: my $symb_crs = $what;
10592: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 10593: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 10594: my ($tmp)=keys(%current_permissions);
10595: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10596: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 10597: foreach my $file (@readonly_files) {
1.759 albertel 10598: my $clean_file = &declutter_portfile($file);
10599: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 10600: my $current_locks = $current_permissions{$file};
1.563 banghart 10601: my @new_locks;
10602: my @del_keys;
10603: if (ref($current_locks) eq "ARRAY"){
10604: foreach my $locker (@{$current_locks}) {
1.632 albertel 10605: my $compare=$locker;
1.749 raeburn 10606: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 10607: $compare=join('',@{$locker});
1.746 raeburn 10608: if ($compare ne $symb_crs) {
10609: push(@new_locks, $locker);
10610: }
1.563 banghart 10611: }
10612: }
1.650 albertel 10613: if (scalar(@new_locks) > 0) {
1.563 banghart 10614: $current_permissions{$file} = \@new_locks;
10615: } else {
10616: push(@del_keys, $file);
1.613 albertel 10617: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 10618: delete($current_permissions{$file});
1.563 banghart 10619: }
10620: }
1.561 banghart 10621: }
1.613 albertel 10622: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10623: return;
10624: }
1.512 banghart 10625:
1.17 www 10626: # ------------------------------------------------------------ Directory lister
10627:
10628: sub dirlist {
1.955 raeburn 10629: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10630: $uri=~s/^\///;
10631: $uri=~s/\/$//;
1.253 stredwic 10632: my ($udom, $uname);
1.955 raeburn 10633: if ($getuserdir) {
1.253 stredwic 10634: $udom = $userdomain;
10635: $uname = $username;
1.955 raeburn 10636: } else {
10637: (undef,$udom,$uname)=split(/\//,$uri);
10638: if(defined($userdomain)) {
10639: $udom = $userdomain;
10640: }
10641: if(defined($username)) {
10642: $uname = $username;
10643: }
1.253 stredwic 10644: }
1.955 raeburn 10645: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10646:
1.955 raeburn 10647: $dirRoot = $perlvar{'lonDocRoot'};
10648: if (defined($getpropath)) {
10649: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10650: $dirRoot =~ s/\/$//;
1.955 raeburn 10651: } elsif (defined($getuserdir)) {
10652: my $subdir=$uname.'__';
10653: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10654: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10655: ."/$udom/$subdir/$uname";
10656: } elsif (defined($alternateRoot)) {
10657: $dirRoot = $alternateRoot;
1.751 banghart 10658: }
1.253 stredwic 10659:
10660: if($udom) {
10661: if($uname) {
1.1135 raeburn 10662: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10663: if ($uhome eq 'no_host') {
10664: return ([],'no_host');
10665: }
1.955 raeburn 10666: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10667: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10668: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10669: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10670: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10671: } else {
10672: @listing_results = map { &unescape($_); } split(/:/,$listing);
10673: }
1.605 matthew 10674: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10675: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10676: @listing_results = split(/:/,$listing);
10677: } else {
10678: @listing_results = map { &unescape($_); } split(/:/,$listing);
10679: }
1.1135 raeburn 10680: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10681: ($listing eq 'rejected') || ($listing eq 'refused') ||
10682: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10683: return ([],$listing);
10684: } else {
10685: return (\@listing_results);
1.1135 raeburn 10686: }
1.955 raeburn 10687: } elsif(!$alternateRoot) {
1.1136 raeburn 10688: my (%allusers,%listerror);
1.841 albertel 10689: my %servers = &get_servers($udom,'library');
1.955 raeburn 10690: foreach my $tryserver (keys(%servers)) {
10691: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10692: &escape($udom),$tryserver);
10693: if ($listing eq 'unknown_cmd') {
10694: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10695: $udom, $tryserver);
10696: } else {
10697: @listing_results = map { &unescape($_); } split(/:/,$listing);
10698: }
1.841 albertel 10699: if ($listing eq 'unknown_cmd') {
10700: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10701: $udom, $tryserver);
10702: @listing_results = split(/:/,$listing);
10703: } else {
10704: @listing_results =
10705: map { &unescape($_); } split(/:/,$listing);
10706: }
1.1136 raeburn 10707: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10708: ($listing eq 'rejected') || ($listing eq 'refused') ||
10709: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10710: $listerror{$tryserver} = $listing;
10711: } else {
1.841 albertel 10712: foreach my $line (@listing_results) {
10713: my ($entry) = split(/&/,$line,2);
10714: $allusers{$entry} = 1;
10715: }
10716: }
1.253 stredwic 10717: }
1.1136 raeburn 10718: my @alluserslist=();
1.800 albertel 10719: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 10720: push(@alluserslist,$user.'&user');
1.253 stredwic 10721: }
1.1318 droeschl 10722:
10723: if (!%listerror) {
10724: # no errors
10725: return (\@alluserslist);
10726: } elsif (scalar(keys(%servers)) == 1) {
10727: # one library server, one error
10728: my ($key) = keys(%listerror);
10729: return (\@alluserslist, $listerror{$key});
10730: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10731: # con_lost indicates that we might miss data from at least one
10732: # library server
10733: return (\@alluserslist, 'con_lost');
10734: } else {
10735: # multiple library servers and no con_lost -> data should be
10736: # complete.
10737: return (\@alluserslist);
10738: }
10739:
1.253 stredwic 10740: } else {
1.1136 raeburn 10741: return ([],'missing username');
1.253 stredwic 10742: }
1.955 raeburn 10743: } elsif(!defined($getpropath)) {
1.1136 raeburn 10744: my $path = $perlvar{'lonDocRoot'}.'/res/';
10745: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10746: return (\@all_domains);
1.955 raeburn 10747: } else {
1.1136 raeburn 10748: return ([],'missing domain');
1.275 stredwic 10749: }
10750: }
10751:
10752: # --------------------------------------------- GetFileTimestamp
10753: # This function utilizes dirlist and returns the date stamp for
10754: # when it was last modified. It will also return an error of -1
10755: # if an error occurs
10756:
10757: sub GetFileTimestamp {
1.955 raeburn 10758: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 10759: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10760: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 10761: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10762: undef,$getuserdir);
10763: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10764: return -1;
10765: }
10766: if (ref($fileref) eq 'ARRAY') {
10767: my @stats = split('&',$fileref->[0]);
1.375 matthew 10768: # @stats contains first the filename, then the stat output
10769: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 10770: } else {
10771: return -1;
1.253 stredwic 10772: }
1.26 www 10773: }
10774:
1.712 albertel 10775: sub stat_file {
10776: my ($uri) = @_;
1.787 albertel 10777: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 10778:
1.955 raeburn 10779: my ($udom,$uname,$file);
1.712 albertel 10780: if ($uri =~ m-^/(uploaded|editupload)/-) {
10781: ($udom,$uname,$file) =
1.811 albertel 10782: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 10783: $file = 'userfiles/'.$file;
10784: }
10785: if ($uri =~ m-^/res/-) {
10786: ($udom,$uname) =
1.807 albertel 10787: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 10788: $file = $uri;
10789: }
10790:
10791: if (!$udom || !$uname || !$file) {
10792: # unable to handle the uri
10793: return ();
10794: }
1.956 raeburn 10795: my $getpropath;
10796: if ($file =~ /^userfiles\//) {
10797: $getpropath = 1;
10798: }
1.1136 raeburn 10799: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10800: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10801: return ();
10802: } else {
10803: if (ref($listref) eq 'ARRAY') {
10804: my @stats = split('&',$listref->[0]);
10805: shift(@stats); #filename is first
10806: return @stats;
10807: }
1.712 albertel 10808: }
10809: return ();
10810: }
10811:
1.1313 raeburn 10812: # --------------------------------------------------------- recursedirs
10813: # Recursive function to traverse either a specific user's Authoring Space
10814: # or corresponding Published Resource Space, and populate the hash ref:
10815: # $dirhashref with URLs of all directories, and if $filehashref hash
10816: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
10817: # or .rights files in resource space, and .meta, .save, .log, and .bak
10818: # files in Authoring Space.
10819: #
10820: # Inputs:
10821: #
10822: # $is_home - true if current server is home server for user's space
10823: # $context - either: priv, or res respectively for Authoring or Resource Space.
10824: # $docroot - Document root (i.e., /home/httpd/html
10825: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
10826: # $relpath - Current path (relative to top level).
10827: # $dirhashref - reference to hash to populate with URLs of directories (Required)
10828: # $filehashref - reference to hash to populate with URLs of files (Optional)
10829: #
10830: # Returns: nothing
10831: #
10832: # Side Effects: populates $dirhashref, and $filehashref (if provided).
10833: #
10834: # Currently used by interface/londocs.pm to create linked select boxes for
10835: # directory and filename to import a Course "Author" resource into a course, and
10836: # also to create linked select boxes for Authoring Space and Directory to choose
10837: # save location for creation of a new "standard" problem from the Course Editor.
10838: #
10839:
10840: sub recursedirs {
10841: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
10842: return unless (ref($dirhashref) eq 'HASH');
10843: my $currpath = $docroot.$toppath;
10844: if ($relpath) {
10845: $currpath .= "/$relpath";
10846: }
10847: my $savefile;
10848: if (ref($filehashref)) {
10849: $savefile = 1;
10850: }
10851: if ($is_home) {
10852: if (opendir(my $dirh,$currpath)) {
10853: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
10854: next if ($item eq '');
10855: if (-d "$currpath/$item") {
10856: my $newpath;
10857: if ($relpath) {
10858: $newpath = "$relpath/$item";
10859: } else {
10860: $newpath = $item;
10861: }
10862: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10863: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10864: } elsif ($savefile) {
10865: if ($context eq 'priv') {
10866: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10867: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10868: }
10869: } else {
10870: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
10871: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10872: }
10873: }
10874: }
10875: }
10876: closedir($dirh);
10877: }
10878: } else {
10879: my ($dirlistref,$listerror) =
10880: &dirlist($toppath.$relpath);
10881: my @dir_lines;
10882: my $dirptr=16384;
10883: if (ref($dirlistref) eq 'ARRAY') {
10884: foreach my $dir_line (sort
10885: {
10886: my ($afile)=split('&',$a,2);
10887: my ($bfile)=split('&',$b,2);
10888: return (lc($afile) cmp lc($bfile));
10889: } (@{$dirlistref})) {
10890: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
10891: split(/\&/,$dir_line,16);
10892: $item =~ s/\s+$//;
10893: next if (($item =~ /^\.\.?$/) || ($obs));
10894: if ($dirptr&$testdir) {
10895: my $newpath;
10896: if ($relpath) {
10897: $newpath = "$relpath/$item";
10898: } else {
10899: $relpath = '/';
10900: $newpath = $item;
10901: }
10902: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10903: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10904: } elsif ($savefile) {
10905: if ($context eq 'priv') {
10906: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10907: $filehashref->{$relpath}{$item} = 1;
10908: }
10909: } else {
10910: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
10911: $filehashref->{$relpath}{$item} = 1;
10912: }
10913: }
10914: }
10915: }
10916: }
10917: }
10918: return;
10919: }
10920:
1.26 www 10921: # -------------------------------------------------------- Value of a Condition
10922:
1.713 albertel 10923: # gets the value of a specific preevaluated condition
10924: # stored in the string $env{user.state.<cid>}
10925: # or looks up a condition reference in the bighash and if if hasn't
10926: # already been evaluated recurses into docondval to get the value of
10927: # the condition, then memoizing it to
10928: # $env{user.state.<cid>.<condition>}
1.40 www 10929: sub directcondval {
10930: my $number=shift;
1.620 albertel 10931: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10932: &Apache::lonuserstate::evalstate();
10933: }
1.713 albertel 10934: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10935: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10936: } elsif ($number =~ /^_/) {
10937: my $sub_condition;
10938: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10939: &GDBM_READER(),0640)) {
10940: $sub_condition=$bighash{'conditions'.$number};
10941: untie(%bighash);
10942: }
10943: my $value = &docondval($sub_condition);
1.949 raeburn 10944: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10945: return $value;
10946: }
1.620 albertel 10947: if ($env{'user.state.'.$env{'request.course.id'}}) {
10948: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10949: } else {
10950: return 2;
10951: }
10952: }
10953:
1.713 albertel 10954: # get the collection of conditions for this resource
1.26 www 10955: sub condval {
10956: my $condidx=shift;
1.54 www 10957: my $allpathcond='';
1.713 albertel 10958: foreach my $cond (split(/\|/,$condidx)) {
10959: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10960: $allpathcond.=
10961: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10962: }
1.191 harris41 10963: }
1.54 www 10964: $allpathcond=~s/\|$//;
1.713 albertel 10965: return &docondval($allpathcond);
10966: }
10967:
10968: #evaluates an expression of conditions
10969: sub docondval {
10970: my ($allpathcond) = @_;
10971: my $result=0;
10972: if ($env{'request.course.id'}
10973: && defined($allpathcond)) {
10974: my $operand='|';
10975: my @stack;
10976: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10977: if ($chunk eq '(') {
10978: push @stack,($operand,$result);
10979: } elsif ($chunk eq ')') {
10980: my $before=pop @stack;
10981: if (pop @stack eq '&') {
10982: $result=$result>$before?$before:$result;
10983: } else {
10984: $result=$result>$before?$result:$before;
10985: }
10986: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10987: $operand=$chunk;
10988: } else {
10989: my $new=directcondval($chunk);
10990: if ($operand eq '&') {
10991: $result=$result>$new?$new:$result;
10992: } else {
10993: $result=$result>$new?$result:$new;
10994: }
10995: }
10996: }
1.26 www 10997: }
10998: return $result;
1.421 albertel 10999: }
11000:
11001: # ---------------------------------------------------- Devalidate courseresdata
11002:
11003: sub devalidatecourseresdata {
11004: my ($coursenum,$coursedomain)=@_;
11005: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11006: &devalidate_cache_new('courseres',$hashid);
1.28 www 11007: }
11008:
1.763 www 11009:
1.200 www 11010: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 11011: #
11012: # Parameters:
11013: # $coursenum - Number of the course.
11014: # $coursedomain - Domain at which the course was created.
11015: # Returns:
11016: # A hash of the course parameters along (I think) with timestamps
11017: # and version info.
1.877 foxr 11018:
1.624 albertel 11019: sub get_courseresdata {
11020: my ($coursenum,$coursedomain)=@_;
1.200 www 11021: my $coursehom=&homeserver($coursenum,$coursedomain);
11022: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11023: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 11024: my %dumpreply;
1.417 albertel 11025: unless (defined($cached)) {
1.624 albertel 11026: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 11027: $result=\%dumpreply;
1.251 albertel 11028: my ($tmp) = keys(%dumpreply);
11029: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 11030: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 11031: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11032: return $tmp;
1.416 albertel 11033: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 11034: $result=undef;
1.599 albertel 11035: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 11036: }
11037: }
1.624 albertel 11038: return $result;
11039: }
11040:
1.633 albertel 11041: sub devalidateuserresdata {
11042: my ($uname,$udom)=@_;
11043: my $hashid="$udom:$uname";
11044: &devalidate_cache_new('userres',$hashid);
11045: }
11046:
1.624 albertel 11047: sub get_userresdata {
11048: my ($uname,$udom)=@_;
11049: #most student don\'t have any data set, check if there is some data
11050: if (&EXT_cache_status($udom,$uname)) { return undef; }
11051:
11052: my $hashid="$udom:$uname";
11053: my ($result,$cached)=&is_cached_new('userres',$hashid);
11054: if (!defined($cached)) {
11055: my %resourcedata=&dump('resourcedata',$udom,$uname);
11056: $result=\%resourcedata;
11057: &do_cache_new('userres',$hashid,$result,600);
11058: }
11059: my ($tmp)=keys(%$result);
11060: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11061: return $result;
11062: }
11063: #error 2 occurs when the .db doesn't exist
11064: if ($tmp!~/error: 2 /) {
1.1294 raeburn 11065: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11066: &logthis("<font color=\"blue\">WARNING:".
11067: " Trying to get resource data for ".
11068: $uname." at ".$udom.": ".
11069: $tmp."</font>");
11070: }
1.624 albertel 11071: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 11072: #&EXT_cache_set($udom,$uname);
11073: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 11074: undef($tmp); # not really an error so don't send it back
1.624 albertel 11075: }
11076: return $tmp;
11077: }
1.879 foxr 11078: #----------------------------------------------- resdata - return resource data
11079: # Purpose:
11080: # Return resource data for either users or for a course.
11081: # Parameters:
11082: # $name - Course/user name.
11083: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 11084: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 11085: # $mapp - decluttered URL of enclosing map
11086: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
11087: # $recurseup - Ref to array of map URLs, starting with map containing
11088: # $mapp up through hierarchy of nested maps to top level map.
11089: # $courseid - CourseID (first part of param identifier).
11090: # $modifier - Middle part of param identifier.
11091: # $what - Last part of param identifier.
1.879 foxr 11092: # @which - Array of names of resources desired.
11093: # Returns:
11094: # The value of the first reasource in @which that is found in the
11095: # resource hash.
11096: # Exceptional Conditions:
11097: # If the $type passed in is not valid (not the string 'course' or
11098: # 'user', an undefined reference is returned.
11099: # If none of the resources are found, an undef is returned
1.624 albertel 11100: sub resdata {
1.1301 raeburn 11101: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11102: $modifier,$what,@which)=@_;
1.624 albertel 11103: my $result;
11104: if ($type eq 'course') {
11105: $result=&get_courseresdata($name,$domain);
11106: } elsif ($type eq 'user') {
11107: $result=&get_userresdata($name,$domain);
11108: }
11109: if (!ref($result)) { return $result; }
1.251 albertel 11110: foreach my $item (@which) {
1.1301 raeburn 11111: if ($item->[1] eq 'course') {
11112: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11113: unless ($$recursed) {
1.1302 raeburn 11114: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 11115: $$recursed = 1;
11116: }
11117: foreach my $item (@${recurseup}) {
11118: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11119: last if (defined($result->{$norecursechk}));
11120: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11121: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11122: }
11123: }
11124: }
11125: if (defined($result->{$item->[0]})) {
1.927 albertel 11126: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 11127: }
1.250 albertel 11128: }
1.291 albertel 11129: return undef;
1.200 www 11130: }
11131:
1.1298 raeburn 11132: sub get_domain_ltitools {
11133: my ($cdom) = @_;
11134: my %ltitools;
11135: my ($result,$cached)=&is_cached_new('ltitools',$cdom);
11136: if (defined($cached)) {
11137: if (ref($result) eq 'HASH') {
11138: %ltitools = %{$result};
11139: }
11140: } else {
11141: my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
11142: if (ref($domconfig{'ltitools'}) eq 'HASH') {
11143: %ltitools = %{$domconfig{'ltitools'}};
1.1344 raeburn 11144: my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
11145: if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
11146: foreach my $id (keys(%ltitools)) {
11147: if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
11148: foreach my $item ('key','secret') {
11149: $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
11150: }
11151: }
11152: }
11153: }
1.1298 raeburn 11154: }
11155: my $cachetime = 24*60*60;
11156: &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
11157: }
11158: return %ltitools;
11159: }
11160:
1.1236 raeburn 11161: sub get_numsuppfiles {
11162: my ($cnum,$cdom,$ignorecache)=@_;
11163: my $hashid=$cnum.':'.$cdom;
11164: my ($suppcount,$cached);
11165: unless ($ignorecache) {
11166: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11167: }
11168: unless (defined($cached)) {
11169: my $chome=&homeserver($cnum,$cdom);
11170: unless ($chome eq 'no_host') {
11171: ($suppcount,my $errors) = (0,0);
11172: my $suppmap = 'supplemental.sequence';
11173: ($suppcount,$errors) =
11174: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11175: }
11176: &do_cache_new('suppcount',$hashid,$suppcount,600);
11177: }
11178: return $suppcount;
11179: }
11180:
1.379 matthew 11181: #
11182: # EXT resource caching routines
11183: #
11184:
1.1302 raeburn 11185: {
11186: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11187: #
11188: # The course for which we cache
11189: my $cachedmapkey='';
11190: # The cached recursive maps for this course
11191: my %cachedmaps=();
11192: # When this was last done
11193: my $cachedmaptime='';
11194:
1.379 matthew 11195: sub clear_EXT_cache_status {
1.383 albertel 11196: &delenv('cache.EXT.');
1.379 matthew 11197: }
11198:
11199: sub EXT_cache_status {
11200: my ($target_domain,$target_user) = @_;
1.383 albertel 11201: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 11202: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 11203: # We know already the user has no data
11204: return 1;
11205: } else {
11206: return 0;
11207: }
11208: }
11209:
11210: sub EXT_cache_set {
11211: my ($target_domain,$target_user) = @_;
1.383 albertel 11212: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 11213: #&appenv({$cachename => time});
1.379 matthew 11214: }
11215:
1.28 www 11216: # --------------------------------------------------------- Value of a Variable
1.58 www 11217: sub EXT {
1.715 albertel 11218:
1.1228 raeburn 11219: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 11220: unless ($varname) { return ''; }
1.218 albertel 11221: #get real user name/domain, courseid and symb
11222: my $courseid;
1.359 albertel 11223: my $publicuser;
1.427 www 11224: if ($symbparm) {
11225: $symbparm=&get_symb_from_alias($symbparm);
11226: }
1.218 albertel 11227: if (!($uname && $udom)) {
1.790 albertel 11228: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 11229: if (!$symbparm) { $symbparm=$cursymb; }
11230: } else {
1.620 albertel 11231: $courseid=$env{'request.course.id'};
1.218 albertel 11232: }
1.48 www 11233: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11234: my $rest;
1.320 albertel 11235: if (defined($therest[0])) {
1.48 www 11236: $rest=join('.',@therest);
11237: } else {
11238: $rest='';
11239: }
1.320 albertel 11240:
1.57 www 11241: my $qualifierrest=$qualifier;
11242: if ($rest) { $qualifierrest.='.'.$rest; }
11243: my $spacequalifierrest=$space;
11244: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 11245: if ($realm eq 'user') {
1.48 www 11246: # --------------------------------------------------------------- user.resource
11247: if ($space eq 'resource') {
1.651 albertel 11248: if ( (defined($Apache::lonhomework::parsing_a_problem)
11249: || defined($Apache::lonhomework::parsing_a_task))
11250: &&
1.744 albertel 11251: ($symbparm eq &symbread()) ) {
11252: # if we are in the middle of processing the resource the
11253: # get the value we are planning on committing
11254: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11255: return $Apache::lonhomework::results{$qualifierrest};
11256: } else {
11257: return $Apache::lonhomework::history{$qualifierrest};
11258: }
1.335 albertel 11259: } else {
1.359 albertel 11260: my %restored;
1.620 albertel 11261: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 11262: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11263: } else {
11264: %restored=&restore($symbparm,$courseid,$udom,$uname);
11265: }
1.335 albertel 11266: return $restored{$qualifierrest};
11267: }
1.48 www 11268: # ----------------------------------------------------------------- user.access
11269: } elsif ($space eq 'access') {
1.218 albertel 11270: # FIXME - not supporting calls for a specific user
1.48 www 11271: return &allowed($qualifier,$rest);
11272: # ------------------------------------------ user.preferences, user.environment
11273: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 11274: if (($uname eq $env{'user.name'}) &&
11275: ($udom eq $env{'user.domain'})) {
11276: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 11277: } else {
1.359 albertel 11278: my %returnhash;
11279: if (!$publicuser) {
11280: %returnhash=&userenvironment($udom,$uname,
11281: $qualifierrest);
11282: }
1.218 albertel 11283: return $returnhash{$qualifierrest};
11284: }
1.48 www 11285: # ----------------------------------------------------------------- user.course
11286: } elsif ($space eq 'course') {
1.218 albertel 11287: # FIXME - not supporting calls for a specific user
1.620 albertel 11288: return $env{join('.',('request.course',$qualifier))};
1.48 www 11289: # ------------------------------------------------------------------- user.role
11290: } elsif ($space eq 'role') {
1.218 albertel 11291: # FIXME - not supporting calls for a specific user
1.620 albertel 11292: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 11293: if ($qualifier eq 'value') {
11294: return $role;
11295: } elsif ($qualifier eq 'extent') {
11296: return $where;
11297: }
11298: # ----------------------------------------------------------------- user.domain
11299: } elsif ($space eq 'domain') {
1.218 albertel 11300: return $udom;
1.48 www 11301: # ------------------------------------------------------------------- user.name
11302: } elsif ($space eq 'name') {
1.218 albertel 11303: return $uname;
1.48 www 11304: # ---------------------------------------------------- Any other user namespace
1.29 www 11305: } else {
1.359 albertel 11306: my %reply;
11307: if (!$publicuser) {
11308: %reply=&get($space,[$qualifierrest],$udom,$uname);
11309: }
11310: return $reply{$qualifierrest};
1.48 www 11311: }
1.236 www 11312: } elsif ($realm eq 'query') {
11313: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 11314: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11315: [$spacequalifierrest]);
1.620 albertel 11316: return $env{'form.'.$spacequalifierrest};
1.236 www 11317: } elsif ($realm eq 'request') {
1.48 www 11318: # ------------------------------------------------------------- request.browser
11319: if ($space eq 'browser') {
1.1145 bisitz 11320: return $env{'browser.'.$qualifier};
1.57 www 11321: # ------------------------------------------------------------ request.filename
11322: } else {
1.620 albertel 11323: return $env{'request.'.$spacequalifierrest};
1.29 www 11324: }
1.28 www 11325: } elsif ($realm eq 'course') {
1.48 www 11326: # ---------------------------------------------------------- course.description
1.620 albertel 11327: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 11328: } elsif ($realm eq 'resource') {
1.165 www 11329:
1.620 albertel 11330: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 11331: if (!$symbparm) { $symbparm=&symbread(); }
11332: }
1.693 albertel 11333:
1.1232 raeburn 11334: if ($qualifier eq '') {
11335: if ($space eq 'title') {
11336: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11337: return &gettitle($symbparm);
11338: }
1.693 albertel 11339:
1.1232 raeburn 11340: if ($space eq 'map') {
11341: my ($map) = &decode_symb($symbparm);
11342: return &symbread($map);
11343: }
11344: if ($space eq 'maptitle') {
11345: my ($map) = &decode_symb($symbparm);
11346: return &gettitle($map);
11347: }
11348: if ($space eq 'filename') {
11349: if ($symbparm) {
11350: return &clutter((&decode_symb($symbparm))[2]);
11351: }
11352: return &hreflocation('',$env{'request.filename'});
1.905 albertel 11353: }
1.1232 raeburn 11354:
1.1233 raeburn 11355: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11356: if ($space eq 'visibleparts') {
11357: my $navmap = Apache::lonnavmaps::navmap->new();
11358: my $item;
11359: if (ref($navmap)) {
11360: my $res = $navmap->getBySymb($symbparm);
11361: my $parts = $res->parts();
11362: if (ref($parts) eq 'ARRAY') {
11363: $item = join(',',@{$parts});
11364: }
11365: undef($navmap);
1.1232 raeburn 11366: }
1.1233 raeburn 11367: return $item;
1.1232 raeburn 11368: }
11369: }
11370: }
1.693 albertel 11371:
1.1301 raeburn 11372: my ($section, $group, @groups, @recurseup, $recursed);
11373: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 11374: if (($courseid eq '') && ($cid)) {
11375: $courseid = $cid;
11376: }
11377: if (($symbparm && $courseid) &&
11378: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 11379:
1.218 albertel 11380: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 11381:
1.60 www 11382: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 11383: my $symbp=$symbparm;
1.1301 raeburn 11384: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 11385: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 11386: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 11387: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 11388: if (($env{'user.name'} eq $uname) &&
11389: ($env{'user.domain'} eq $udom)) {
11390: $section=$env{'request.course.sec'};
1.733 raeburn 11391: @groups = split(/:/,$env{'request.course.groups'});
11392: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 11393: } else {
1.539 albertel 11394: if (! defined($usection)) {
1.551 albertel 11395: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 11396: } else {
11397: $section = $usection;
11398: }
1.733 raeburn 11399: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 11400: }
11401:
11402: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11403: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 11404: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 11405: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11406:
1.593 albertel 11407: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 11408: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 11409: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 11410: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 11411:
1.60 www 11412: # ----------------------------------------------------------- first, check user
1.624 albertel 11413:
1.1301 raeburn 11414: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11415: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 11416: ([$courselevelr,'resource'],
11417: [$courselevelm,'map' ],
1.1301 raeburn 11418: [$courseleveli,'map' ],
1.927 albertel 11419: [$courselevel, 'course' ]));
1.931 albertel 11420: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 11421:
1.594 albertel 11422: # ------------------------------------------------ second, check some of course
1.684 raeburn 11423: my $coursereply;
1.691 raeburn 11424: if (@groups > 0) {
11425: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 11426: $recurseparm,$mapparm,$spacequalifierrest,
11427: $mapp,\$recursed,\@recurseup);
11428: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 11429: }
1.96 www 11430:
1.684 raeburn 11431: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 11432: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 11433: 'course',$mapp,\$recursed,\@recurseup,
11434: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 11435: ([$seclevelr, 'resource'],
11436: [$seclevelm, 'map' ],
1.1301 raeburn 11437: [$secleveli, 'map' ],
1.927 albertel 11438: [$seclevel, 'course' ],
11439: [$courselevelr,'resource']));
11440: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 11441:
1.60 www 11442: # ------------------------------------------------------ third, check map parms
1.218 albertel 11443: my %parmhash=();
11444: my $thisparm='';
11445: if (tie(%parmhash,'GDBM_File',
1.620 albertel 11446: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 11447: &GDBM_READER(),0640)) {
1.218 albertel 11448: $thisparm=$parmhash{$symbparm};
11449: untie(%parmhash);
11450: }
1.927 albertel 11451: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 11452: }
1.594 albertel 11453: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 11454:
11455: my $what = $spacequalifierrest;
11456: $what=~s/\./\_/;
1.282 albertel 11457: my $filename;
11458: if (!$symbparm) { $symbparm=&symbread(); }
11459: if ($symbparm) {
1.409 www 11460: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 11461: } else {
1.620 albertel 11462: $filename=$env{'request.filename'};
1.282 albertel 11463: }
1.1301 raeburn 11464: my $metadata=&metadata($filename,$what);
1.927 albertel 11465: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301 raeburn 11466: $metadata=&metadata($filename,'parameter_'.$what);
1.927 albertel 11467: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 11468:
1.1301 raeburn 11469: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 11470: if ($symbparm && defined($courseid) &&
1.620 albertel 11471: $courseid eq $env{'request.course.id'}) {
1.624 albertel 11472: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11473: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 11474: 'course',$mapp,\$recursed,\@recurseup,
11475: $courseid,'.',$spacequalifierrest,
1.927 albertel 11476: ([$courselevelm,'map' ],
1.1301 raeburn 11477: [$courseleveli,'map' ],
1.927 albertel 11478: [$courselevel, 'course']));
11479: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 11480: }
1.145 www 11481: # ------------------------------------------------------------------ Cascade up
1.218 albertel 11482: unless ($space eq '0') {
1.336 albertel 11483: my @parts=split(/_/,$space);
11484: my $id=pop(@parts);
11485: my $part=join('_',@parts);
11486: if ($part eq '') { $part='0'; }
1.927 albertel 11487: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 11488: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 11489: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 11490: }
1.395 albertel 11491: if ($recurse) { return undef; }
11492: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 11493: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 11494: # ---------------------------------------------------- Any other user namespace
11495: } elsif ($realm eq 'environment') {
11496: # ----------------------------------------------------------------- environment
1.620 albertel 11497: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11498: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 11499: } else {
1.770 albertel 11500: if ($uname eq 'anonymous' && $udom eq '') {
11501: return '';
11502: }
1.219 albertel 11503: my %returnhash=&userenvironment($udom,$uname,
11504: $spacequalifierrest);
11505: return $returnhash{$spacequalifierrest};
11506: }
1.28 www 11507: } elsif ($realm eq 'system') {
1.48 www 11508: # ----------------------------------------------------------------- system.time
11509: if ($space eq 'time') {
11510: return time;
11511: }
1.696 albertel 11512: } elsif ($realm eq 'server') {
11513: # ----------------------------------------------------------------- system.time
11514: if ($space eq 'name') {
11515: return $ENV{'SERVER_NAME'};
11516: }
1.28 www 11517: }
1.48 www 11518: return '';
1.61 www 11519: }
11520:
1.927 albertel 11521: sub get_reply {
11522: my ($reply_value) = @_;
1.940 raeburn 11523: if (ref($reply_value) eq 'ARRAY') {
11524: if (wantarray) {
11525: return @$reply_value;
11526: }
11527: return $reply_value->[0];
11528: } else {
11529: return $reply_value;
1.927 albertel 11530: }
11531: }
11532:
1.691 raeburn 11533: sub check_group_parms {
1.1301 raeburn 11534: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11535: $recursed,$recurseupref) = @_;
11536: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11537: [$what,'course']);
11538: my $coursereply;
1.691 raeburn 11539: foreach my $group (@{$groups}) {
1.1301 raeburn 11540: my @groupitems = ();
1.691 raeburn 11541: foreach my $level (@levels) {
1.927 albertel 11542: my $item = $courseid.'.['.$group.'].'.$level->[0];
11543: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11544: }
1.1301 raeburn 11545: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11546: $env{'course.'.$courseid.'.domain'},
11547: 'course',$mapp,$recursed,$recurseupref,
11548: $courseid,'.['.$group.'].',$what,
11549: @groupitems);
11550: last if (defined($coursereply));
1.691 raeburn 11551: }
11552: return $coursereply;
11553: }
11554:
1.1301 raeburn 11555: sub get_map_hierarchy {
1.1302 raeburn 11556: my ($mapname,$courseid) = @_;
11557: my @recurseup = ();
1.1301 raeburn 11558: if ($mapname) {
1.1302 raeburn 11559: if (($cachedmapkey eq $courseid) &&
11560: (abs($cachedmaptime-time)<5)) {
11561: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11562: return @{$cachedmaps{$mapname}};
11563: }
11564: }
1.1301 raeburn 11565: my $navmap = Apache::lonnavmaps::navmap->new();
11566: if (ref($navmap)) {
11567: @recurseup = $navmap->recurseup_maps($mapname);
11568: undef($navmap);
1.1302 raeburn 11569: $cachedmaps{$mapname} = \@recurseup;
11570: $cachedmaptime=time;
11571: $cachedmapkey=$courseid;
1.1301 raeburn 11572: }
11573: }
11574: return @recurseup;
11575: }
11576:
1.1302 raeburn 11577: }
11578:
1.691 raeburn 11579: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11580: my ($courseid,@groups) = @_;
11581: @groups = sort(@groups);
1.691 raeburn 11582: return @groups;
11583: }
11584:
1.395 albertel 11585: sub packages_tab_default {
11586: my ($uri,$varname)=@_;
11587: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11588:
11589: my (@extension,@specifics,$do_default);
11590: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11591: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11592: if ($pack_type eq 'default') {
11593: $do_default=1;
11594: } elsif ($pack_type eq 'extension') {
11595: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11596: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11597: # only look at packages defaults for packages that this id is
1.738 albertel 11598: push(@specifics,[$package,$pack_type,$pack_part]);
11599: }
11600: }
11601: # first look for a package that matches the requested part id
11602: foreach my $package (@specifics) {
11603: my (undef,$pack_type,$pack_part)=@{$package};
11604: next if ($pack_part ne $part);
11605: if (defined($packagetab{"$pack_type&$name&default"})) {
11606: return $packagetab{"$pack_type&$name&default"};
11607: }
11608: }
11609: # look for any possible matching non extension_ package
11610: foreach my $package (@specifics) {
11611: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11612: if (defined($packagetab{"$pack_type&$name&default"})) {
11613: return $packagetab{"$pack_type&$name&default"};
11614: }
1.585 albertel 11615: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11616: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11617: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11618: }
11619: }
1.738 albertel 11620: # look for any posible extension_ match
11621: foreach my $package (@extension) {
11622: my ($package,$pack_type)=@{$package};
11623: if (defined($packagetab{"$pack_type&$name&default"})) {
11624: return $packagetab{"$pack_type&$name&default"};
11625: }
11626: if (defined($packagetab{$package."&$name&default"})) {
11627: return $packagetab{$package."&$name&default"};
11628: }
11629: }
11630: # look for a global default setting
11631: if ($do_default && defined($packagetab{"default&$name&default"})) {
11632: return $packagetab{"default&$name&default"};
11633: }
1.395 albertel 11634: return undef;
11635: }
11636:
1.334 albertel 11637: sub add_prefix_and_part {
11638: my ($prefix,$part)=@_;
11639: my $keyroot;
11640: if (defined($prefix) && $prefix !~ /^__/) {
11641: # prefix that has a part already
11642: $keyroot=$prefix;
11643: } elsif (defined($prefix)) {
11644: # prefix that is missing a part
11645: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11646: } else {
11647: # no prefix at all
11648: if (defined($part)) { $keyroot='_'.$part; }
11649: }
11650: return $keyroot;
11651: }
11652:
1.71 www 11653: # ---------------------------------------------------------------- Get metadata
11654:
1.599 albertel 11655: my %metaentry;
1.1070 www 11656: my %importedpartids;
1.71 www 11657: sub metadata {
1.176 www 11658: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11659: $uri=&declutter($uri);
1.288 albertel 11660: # if it is a non metadata possible uri return quickly
1.529 albertel 11661: if (($uri eq '') ||
11662: (($uri =~ m|^/*adm/|) &&
1.1343 raeburn 11663: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 11664: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11665: return undef;
11666: }
1.1261 raeburn 11667: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11668: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11669: return undef;
1.288 albertel 11670: }
1.73 www 11671: my $filename=$uri;
11672: $uri=~s/\.meta$//;
1.172 www 11673: #
11674: # Is the metadata already cached?
1.177 www 11675: # Look at timestamp of caching
1.172 www 11676: # Everything is cached by the main uri, libraries are never directly cached
11677: #
1.428 albertel 11678: if (!defined($liburi)) {
1.599 albertel 11679: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11680: if (defined($cached)) { return $result->{':'.$what}; }
11681: }
11682: {
1.1069 www 11683: # Imported parts would go here
1.1070 www 11684: my %importedids=();
11685: my @origfileimportpartids=();
1.1069 www 11686: my $importedparts=0;
1.172 www 11687: #
11688: # Is this a recursive call for a library?
11689: #
1.599 albertel 11690: # if (! exists($metacache{$uri})) {
11691: # $metacache{$uri}={};
11692: # }
1.924 albertel 11693: my $cachetime = 60*60;
1.171 www 11694: if ($liburi) {
11695: $liburi=&declutter($liburi);
11696: $filename=$liburi;
1.401 bowersj2 11697: } else {
1.599 albertel 11698: &devalidate_cache_new('meta',$uri);
11699: undef(%metaentry);
1.401 bowersj2 11700: }
1.140 www 11701: my %metathesekeys=();
1.73 www 11702: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 11703: my $metastring;
1.1140 www 11704: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 11705: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 11706: $metastring =
1.929 albertel 11707: &Apache::lonnet::ssi_body($which,
1.924 albertel 11708: ('grade_target' => 'meta'));
11709: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 11710: } elsif (($uri !~ m -^(editupload)/-) &&
11711: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 11712: my $file=&filelocation('',&clutter($filename));
1.599 albertel 11713: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 11714: $metastring=&getfile($file);
1.489 albertel 11715: }
1.208 albertel 11716: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 11717: my $token;
1.140 www 11718: undef %metathesekeys;
1.71 www 11719: while ($token=$parser->get_token) {
1.339 albertel 11720: if ($token->[0] eq 'S') {
11721: if (defined($token->[2]->{'package'})) {
1.172 www 11722: #
11723: # This is a package - get package info
11724: #
1.339 albertel 11725: my $package=$token->[2]->{'package'};
11726: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11727: if (defined($token->[2]->{'id'})) {
11728: $keyroot.='_'.$token->[2]->{'id'};
11729: }
1.599 albertel 11730: if ($metaentry{':packages'}) {
11731: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 11732: } else {
1.599 albertel 11733: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 11734: }
1.736 albertel 11735: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 11736: my $part=$keyroot;
11737: $part=~s/^\_//;
1.736 albertel 11738: if ($pack_entry=~/^\Q$package\E\&/ ||
11739: $pack_entry=~/^\Q$package\E_0\&/) {
11740: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11741: # ignore package.tab specified default values
11742: # here &package_tab_default() will fetch those
11743: if ($subp eq 'default') { next; }
1.736 albertel 11744: my $value=$packagetab{$pack_entry};
1.432 albertel 11745: my $unikey;
11746: if ($pack =~ /_0$/) {
11747: $unikey='parameter_0_'.$name;
11748: $part=0;
11749: } else {
11750: $unikey='parameter'.$keyroot.'_'.$name;
11751: }
1.339 albertel 11752: if ($subp eq 'display') {
11753: $value.=' [Part: '.$part.']';
11754: }
1.599 albertel 11755: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11756: $metathesekeys{$unikey}=1;
1.599 albertel 11757: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11758: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11759: }
1.599 albertel 11760: if (defined($metaentry{':'.$unikey.'.default'})) {
11761: $metaentry{':'.$unikey}=
11762: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11763: }
1.339 albertel 11764: }
11765: }
11766: } else {
1.172 www 11767: #
11768: # This is not a package - some other kind of start tag
1.339 albertel 11769: #
11770: my $entry=$token->[1];
1.1068 www 11771: my $unikey='';
1.175 www 11772:
1.339 albertel 11773: if ($entry eq 'import') {
1.175 www 11774: #
11775: # Importing a library here
1.339 albertel 11776: #
1.1067 www 11777: my $location=$parser->get_text('/import');
11778: my $dir=$filename;
11779: $dir=~s|[^/]*$||;
11780: $location=&filelocation($dir,$location);
1.1069 www 11781:
1.1068 www 11782: my $importmode=$token->[2]->{'importmode'};
11783: if ($importmode eq 'problem') {
1.1069 www 11784: # Import as problem/response
1.1068 www 11785: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11786: } elsif ($importmode eq 'part') {
11787: # Import as part(s)
1.1069 www 11788: $importedparts=1;
11789: # We need to get the original file and the imported file to get the part order correct
11790: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11791: # Load and inspect original file
1.1070 www 11792: if ($#origfileimportpartids<0) {
11793: undef(%importedpartids);
11794: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11795: my $origfile=&getfile($origfilelocation);
11796: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11797: }
11798:
1.1069 www 11799: # Load and inspect imported file
11800: my $impfile=&getfile($location);
11801: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11802: if ($#impfilepartids>=0) {
11803: # This problem had parts
1.1070 www 11804: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11805: } else {
11806: # Importing by turning a single problem into a problem part
11807: # It gets the import-tags ID as part-ID
11808: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11809: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11810: }
1.1068 www 11811: } else {
11812: # Normal import
11813: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11814: if (defined($token->[2]->{'id'})) {
11815: $unikey.='_'.$token->[2]->{'id'};
11816: }
1.1067 www 11817: }
11818:
1.339 albertel 11819: if ($depthcount<20) {
1.736 albertel 11820: my $metadata =
11821: &metadata($uri,'keys', $location,$unikey,
11822: $depthcount+1);
11823: foreach my $meta (split(',',$metadata)) {
11824: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11825: $metathesekeys{$meta}=1;
1.339 albertel 11826: }
1.1068 www 11827:
11828: }
1.1067 www 11829: } else {
11830: #
11831: # Not importing, some other kind of non-package, non-library start tag
11832: #
11833: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11834: if (defined($token->[2]->{'id'})) {
11835: $unikey.='_'.$token->[2]->{'id'};
11836: }
1.339 albertel 11837: if (defined($token->[2]->{'name'})) {
11838: $unikey.='_'.$token->[2]->{'name'};
11839: }
11840: $metathesekeys{$unikey}=1;
1.736 albertel 11841: foreach my $param (@{$token->[3]}) {
11842: $metaentry{':'.$unikey.'.'.$param} =
11843: $token->[2]->{$param};
1.339 albertel 11844: }
11845: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11846: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11847: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11848: # only ws inside the tag, and not in default, so use default
11849: # as value
1.599 albertel 11850: $metaentry{':'.$unikey}=$default;
1.908 albertel 11851: } elsif ( $internaltext =~ /\S/ ) {
11852: # something interesting inside the tag
11853: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11854: } else {
1.908 albertel 11855: # no interesting values, don't set a default
1.339 albertel 11856: }
1.172 www 11857: # end of not-a-package not-a-library import
1.339 albertel 11858: }
1.172 www 11859: # end of not-a-package start tag
1.339 albertel 11860: }
1.172 www 11861: # the next is the end of "start tag"
1.339 albertel 11862: }
11863: }
1.483 albertel 11864: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11865: $extension = lc($extension);
11866: if ($extension eq 'htm') { $extension='html'; }
11867:
1.737 albertel 11868: foreach my $key (keys(%packagetab)) {
1.483 albertel 11869: #no specific packages #how's our extension
11870: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11871: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11872: \%metathesekeys);
11873: }
1.883 albertel 11874:
11875: if (!exists($metaentry{':packages'})
11876: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11877: foreach my $key (keys(%packagetab)) {
1.483 albertel 11878: #no specific packages well let's get default then
11879: if ($key!~/^default&/) { next; }
1.488 albertel 11880: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 11881: \%metathesekeys);
11882: }
11883: }
1.338 www 11884: # are there custom rights to evaluate
1.599 albertel 11885: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 11886:
1.338 www 11887: #
11888: # Importing a rights file here
1.339 albertel 11889: #
11890: unless ($depthcount) {
1.599 albertel 11891: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 11892: my $dir=$filename;
11893: $dir=~s|[^/]*$||;
11894: $location=&filelocation($dir,$location);
1.736 albertel 11895: my $rights_metadata =
11896: &metadata($uri,'keys',$location,'_rights',
11897: $depthcount+1);
11898: foreach my $rights (split(',',$rights_metadata)) {
11899: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11900: $metathesekeys{$rights}=1;
1.339 albertel 11901: }
11902: }
11903: }
1.737 albertel 11904: # uniqifiy package listing
11905: my %seen;
11906: my @uniq_packages =
11907: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11908: $metaentry{':packages'} = join(',',@uniq_packages);
11909:
1.1070 www 11910: if ($importedparts) {
11911: # We had imported parts and need to rebuild partorder
11912: $metaentry{':partorder'}='';
11913: $metathesekeys{'partorder'}=1;
11914: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11915: if ($origfileimportpartids[$index] eq 'part') {
11916: # original part, part of the problem
11917: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11918: } else {
11919: # we have imported parts at this position
11920: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11921: }
11922: }
11923: $metaentry{':partorder'}=~s/^\,//;
11924: }
11925:
1.737 albertel 11926: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 11927: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 11928: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 11929: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 11930: # this is the end of "was not already recently cached
1.71 www 11931: }
1.599 albertel 11932: return $metaentry{':'.$what};
1.261 albertel 11933: }
11934:
1.488 albertel 11935: sub metadata_create_package_def {
1.483 albertel 11936: my ($uri,$key,$package,$metathesekeys)=@_;
11937: my ($pack,$name,$subp)=split(/\&/,$key);
11938: if ($subp eq 'default') { next; }
11939:
1.599 albertel 11940: if (defined($metaentry{':packages'})) {
11941: $metaentry{':packages'}.=','.$package;
1.483 albertel 11942: } else {
1.599 albertel 11943: $metaentry{':packages'}=$package;
1.483 albertel 11944: }
11945: my $value=$packagetab{$key};
11946: my $unikey;
11947: $unikey='parameter_0_'.$name;
1.599 albertel 11948: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 11949: $$metathesekeys{$unikey}=1;
1.599 albertel 11950: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11951: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 11952: }
1.599 albertel 11953: if (defined($metaentry{':'.$unikey.'.default'})) {
11954: $metaentry{':'.$unikey}=
11955: $metaentry{':'.$unikey.'.default'};
1.483 albertel 11956: }
11957: }
11958:
1.261 albertel 11959: sub metadata_generate_part0 {
11960: my ($metadata,$metacache,$uri) = @_;
11961: my %allnames;
1.737 albertel 11962: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 11963: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 11964: my $part=$$metacache{':'.$metakey.'.part'};
11965: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 11966: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 11967: $allnames{$name}=$part;
11968: }
11969: }
11970: }
11971: foreach my $name (keys(%allnames)) {
11972: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 11973: my $key=":parameter_0_$name";
1.261 albertel 11974: $$metacache{"$key.part"}='0';
11975: $$metacache{"$key.name"}=$name;
1.428 albertel 11976: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 11977: $allnames{$name}.'_'.$name.
11978: '.type'};
1.428 albertel 11979: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 11980: '.display'};
1.644 www 11981: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 11982: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 11983: $$metacache{"$key.display"}=$olddis;
11984: }
1.71 www 11985: }
11986:
1.764 albertel 11987: # ------------------------------------------------------ Devalidate title cache
11988:
11989: sub devalidate_title_cache {
11990: my ($url)=@_;
11991: if (!$env{'request.course.id'}) { return; }
11992: my $symb=&symbread($url);
11993: if (!$symb) { return; }
11994: my $key=$env{'request.course.id'}."\0".$symb;
11995: &devalidate_cache_new('title',$key);
11996: }
11997:
1.1014 droeschl 11998: # ------------------------------------------------- Get the title of a course
11999:
12000: sub current_course_title {
12001: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12002: }
1.301 www 12003: # ------------------------------------------------- Get the title of a resource
12004:
12005: sub gettitle {
12006: my $urlsymb=shift;
12007: my $symb=&symbread($urlsymb);
1.534 albertel 12008: if ($symb) {
1.620 albertel 12009: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 12010: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 12011: if (defined($cached)) {
12012: return $result;
12013: }
1.534 albertel 12014: my ($map,$resid,$url)=&decode_symb($symb);
12015: my $title='';
1.907 albertel 12016: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12017: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12018: } else {
12019: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12020: &GDBM_READER(),0640)) {
12021: my $mapid=$bighash{'map_pc_'.&clutter($map)};
12022: $title=$bighash{'title_'.$mapid.'.'.$resid};
12023: untie(%bighash);
12024: }
1.534 albertel 12025: }
12026: $title=~s/\&colon\;/\:/gs;
12027: if ($title) {
1.1159 www 12028: # Remember both $symb and $title for dynamic metadata
12029: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 12030: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 12031: # Cache this title and then return it
1.599 albertel 12032: return &do_cache_new('title',$key,$title,600);
1.534 albertel 12033: }
12034: $urlsymb=$url;
12035: }
12036: my $title=&metadata($urlsymb,'title');
12037: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
12038: return $title;
1.301 www 12039: }
1.613 albertel 12040:
1.614 albertel 12041: sub get_slot {
12042: my ($which,$cnum,$cdom)=@_;
12043: if (!$cnum || !$cdom) {
1.790 albertel 12044: (undef,my $courseid)=&whichuser();
1.620 albertel 12045: $cdom=$env{'course.'.$courseid.'.domain'};
12046: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 12047: }
1.703 albertel 12048: my $key=join("\0",'slots',$cdom,$cnum,$which);
12049: my %slotinfo;
12050: if (exists($remembered{$key})) {
12051: $slotinfo{$which} = $remembered{$key};
12052: } else {
12053: %slotinfo=&get('slots',[$which],$cdom,$cnum);
12054: &Apache::lonhomework::showhash(%slotinfo);
12055: my ($tmp)=keys(%slotinfo);
12056: if ($tmp=~/^error:/) { return (); }
12057: $remembered{$key} = $slotinfo{$which};
12058: }
1.616 albertel 12059: if (ref($slotinfo{$which}) eq 'HASH') {
12060: return %{$slotinfo{$which}};
12061: }
12062: return $slotinfo{$which};
1.614 albertel 12063: }
1.1150 raeburn 12064:
12065: sub get_reservable_slots {
12066: my ($cnum,$cdom,$uname,$udom) = @_;
12067: my $now = time;
12068: my $reservable_info;
12069: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12070: if (exists($remembered{$key})) {
12071: $reservable_info = $remembered{$key};
12072: } else {
12073: my %resv;
12074: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12075: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12076: $reservable_info = \%resv;
12077: $remembered{$key} = $reservable_info;
12078: }
12079: return $reservable_info;
12080: }
12081:
12082: sub get_course_slots {
12083: my ($cnum,$cdom) = @_;
12084: my $hashid=$cnum.':'.$cdom;
12085: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12086: if (defined($cached)) {
12087: if (ref($result) eq 'HASH') {
12088: return %{$result};
12089: }
12090: } else {
12091: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12092: my ($tmp) = keys(%slots);
12093: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 12094: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 12095: return %slots;
12096: }
12097: }
12098: return;
12099: }
12100:
12101: sub devalidate_slots_cache {
12102: my ($cnum,$cdom)=@_;
12103: my $hashid=$cnum.':'.$cdom;
12104: &devalidate_cache_new('allslots',$hashid);
12105: }
12106:
1.1181 raeburn 12107: sub get_coursechange {
12108: my ($cdom,$cnum) = @_;
12109: if ($cdom eq '' || $cnum eq '') {
12110: return unless ($env{'request.course.id'});
12111: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12112: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12113: }
12114: my $hashid=$cdom.'_'.$cnum;
12115: my ($change,$cached)=&is_cached_new('crschange',$hashid);
12116: if ((defined($cached)) && ($change ne '')) {
12117: return $change;
12118: } else {
12119: my %crshash;
12120: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12121: if ($crshash{'internal.contentchange'} eq '') {
12122: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12123: if ($change eq '') {
12124: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12125: $change = $crshash{'internal.created'};
12126: }
12127: } else {
12128: $change = $crshash{'internal.contentchange'};
12129: }
12130: my $cachetime = 600;
12131: &do_cache_new('crschange',$hashid,$change,$cachetime);
12132: }
12133: return $change;
12134: }
12135:
12136: sub devalidate_coursechange_cache {
12137: my ($cnum,$cdom)=@_;
12138: my $hashid=$cnum.':'.$cdom;
12139: &devalidate_cache_new('crschange',$hashid);
12140: }
12141:
1.31 www 12142: # ------------------------------------------------- Update symbolic store links
12143:
12144: sub symblist {
12145: my ($mapname,%newhash)=@_;
1.438 www 12146: $mapname=&deversion(&declutter($mapname));
1.31 www 12147: my %hash;
1.620 albertel 12148: if (($env{'request.course.fn'}) && (%newhash)) {
12149: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12150: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 12151: foreach my $url (keys(%newhash)) {
1.711 albertel 12152: next if ($url eq 'last_known'
12153: && $env{'form.no_update_last_known'});
12154: $hash{declutter($url)}=&encode_symb($mapname,
12155: $newhash{$url}->[1],
12156: $newhash{$url}->[0]);
1.191 harris41 12157: }
1.31 www 12158: if (untie(%hash)) {
12159: return 'ok';
12160: }
12161: }
12162: }
12163: return 'error';
1.212 www 12164: }
12165:
12166: # --------------------------------------------------------------- Verify a symb
12167:
12168: sub symbverify {
1.1190 raeburn 12169: my ($symb,$thisurl,$encstate)=@_;
1.510 www 12170: my $thisfn=$thisurl;
1.439 www 12171: $thisfn=&declutter($thisfn);
1.215 www 12172: # direct jump to resource in page or to a sequence - will construct own symbs
12173: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12174: # check URL part
1.409 www 12175: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 12176:
1.431 www 12177: unless ($url eq $thisfn) { return 0; }
1.213 www 12178:
1.216 www 12179: $symb=&symbclean($symb);
1.510 www 12180: $thisurl=&deversion($thisurl);
1.439 www 12181: $thisfn=&deversion($thisfn);
1.213 www 12182:
12183: my %bighash;
12184: my $okay=0;
1.431 www 12185:
1.620 albertel 12186: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12187: &GDBM_READER(),0640)) {
1.1204 raeburn 12188: my $noclutter;
1.1032 raeburn 12189: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12190: $thisurl =~ s/\?.+$//;
1.1204 raeburn 12191: if ($map =~ m{^uploaded/.+\.page$}) {
12192: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12193: $thisurl =~ s{^\Qhttp://https://\E}{https://};
12194: $noclutter = 1;
12195: }
12196: }
12197: my $ids;
12198: if ($noclutter) {
12199: $ids=$bighash{'ids_'.$thisurl};
12200: } else {
12201: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 12202: }
1.1102 raeburn 12203: unless ($ids) {
12204: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
12205: $ids=$bighash{$idkey};
1.216 www 12206: }
12207: if ($ids) {
12208: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 12209: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 12210: $symb =~ s/\?.+$//;
1.1202 raeburn 12211: }
1.800 albertel 12212: foreach my $id (split(/\,/,$ids)) {
12213: my ($mapid,$resid)=split(/\./,$id);
1.216 www 12214: if (
12215: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 12216: eq $symb) {
12217: if (ref($encstate)) {
12218: $$encstate = $bighash{'encrypted_'.$id};
12219: }
1.620 albertel 12220: if (($env{'request.role.adv'}) ||
1.1101 raeburn 12221: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12222: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 12223: $okay=1;
1.1202 raeburn 12224: last;
1.582 albertel 12225: }
12226: }
1.216 www 12227: }
12228: }
1.213 www 12229: untie(%bighash);
12230: }
12231: return $okay;
1.31 www 12232: }
12233:
1.210 www 12234: # --------------------------------------------------------------- Clean-up symb
12235:
12236: sub symbclean {
12237: my $symb=shift;
1.568 albertel 12238: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 12239: # remove version from map
12240: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 12241:
1.210 www 12242: # remove version from URL
12243: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 12244:
1.507 www 12245: # remove wrapper
12246:
1.510 www 12247: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 12248: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 12249: return $symb;
1.409 www 12250: }
12251:
12252: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 12253:
12254: sub encode_symb {
12255: my ($map,$resid,$url)=@_;
12256: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12257: }
1.409 www 12258:
12259: sub decode_symb {
1.568 albertel 12260: my $symb=shift;
12261: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12262: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 12263: return (&fixversion($map),$resid,&fixversion($url));
12264: }
12265:
12266: sub fixversion {
12267: my $fn=shift;
1.609 banghart 12268: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 12269: my %bighash;
12270: my $uri=&clutter($fn);
1.620 albertel 12271: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 12272: # is this cached?
1.599 albertel 12273: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 12274: if (defined($cached)) { return $result; }
12275: # unfortunately not cached, or expired
1.620 albertel 12276: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 12277: &GDBM_READER(),0640)) {
12278: if ($bighash{'version_'.$uri}) {
12279: my $version=$bighash{'version_'.$uri};
1.444 www 12280: unless (($version eq 'mostrecent') ||
12281: ($version==&getversion($uri))) {
1.440 www 12282: $uri=~s/\.(\w+)$/\.$version\.$1/;
12283: }
12284: }
12285: untie %bighash;
1.413 www 12286: }
1.599 albertel 12287: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 12288: }
12289:
12290: sub deversion {
12291: my $url=shift;
12292: $url=~s/\.\d+\.(\w+)$/\.$1/;
12293: return $url;
1.210 www 12294: }
12295:
1.31 www 12296: # ------------------------------------------------------ Return symb list entry
12297:
12298: sub symbread {
1.1282 raeburn 12299: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265 raeburn 12300: my $cache_str='request.symbread.cached.'.$thisfn;
1.1282 raeburn 12301: if (defined($env{$cache_str})) {
12302: if ($ignorecachednull) {
12303: return $env{$cache_str} unless ($env{$cache_str} eq '');
12304: } else {
12305: return $env{$cache_str};
12306: }
12307: }
1.242 www 12308: # no filename provided? try from environment
1.1265 raeburn 12309: unless ($thisfn) {
1.620 albertel 12310: if ($env{'request.symb'}) {
12311: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 12312: }
1.620 albertel 12313: $thisfn=$env{'request.filename'};
1.44 www 12314: }
1.569 albertel 12315: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 12316: # is that filename actually a symb? Verify, clean, and return
12317: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 12318: if (&symbverify($thisfn,$1)) {
1.620 albertel 12319: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 12320: }
1.242 www 12321: }
1.44 www 12322: $thisfn=declutter($thisfn);
1.31 www 12323: my %hash;
1.37 www 12324: my %bighash;
12325: my $syval='';
1.620 albertel 12326: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 12327: my $targetfn = $thisfn;
1.609 banghart 12328: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 12329: $targetfn = 'adm/wrapper/'.$thisfn;
12330: }
1.687 albertel 12331: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12332: $targetfn=$1;
12333: }
1.620 albertel 12334: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12335: &GDBM_READER(),0640)) {
1.481 raeburn 12336: $syval=$hash{$targetfn};
1.37 www 12337: untie(%hash);
12338: }
12339: # ---------------------------------------------------------- There was an entry
12340: if ($syval) {
1.601 albertel 12341: #unless ($syval=~/\_\d+$/) {
1.620 albertel 12342: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 12343: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12344: #return $env{$cache_str}='';
1.601 albertel 12345: #}
12346: #$syval.=$1;
12347: #}
1.37 www 12348: } else {
12349: # ------------------------------------------------------- Was not in symb table
1.620 albertel 12350: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12351: &GDBM_READER(),0640)) {
1.37 www 12352: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 12353: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 12354: unless ($ids) {
12355: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 12356: }
12357: unless ($ids) {
12358: # alias?
12359: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 12360: }
1.37 www 12361: if ($ids) {
12362: # ------------------------------------------------------------------- Has ID(s)
12363: my @possibilities=split(/\,/,$ids);
1.39 www 12364: if ($#possibilities==0) {
12365: # ----------------------------------------------- There is only one possibility
1.37 www 12366: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 12367: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12368: $resid,$thisfn);
1.1282 raeburn 12369: if (ref($possibles) eq 'HASH') {
12370: $possibles->{$syval} = 1;
12371: }
12372: if ($checkforblock) {
12373: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12374: if (@blockers) {
12375: $syval = '';
12376: return;
12377: }
12378: }
12379: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 12380: # ------------------------------------------ There is more than one possibility
12381: my $realpossible=0;
1.800 albertel 12382: foreach my $id (@possibilities) {
12383: my $file=$bighash{'src_'.$id};
1.1282 raeburn 12384: my $canaccess;
12385: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12386: $canaccess = 1;
12387: } else {
12388: $canaccess = &allowed('bre',$file);
12389: }
12390: if ($canaccess) {
12391: my ($mapid,$resid)=split(/\./,$id);
12392: if ($bighash{'map_type_'.$mapid} ne 'page') {
12393: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12394: $resid,$thisfn);
12395: if (ref($possibles) eq 'HASH') {
12396: $possibles->{$syval} = 1;
12397: }
12398: if ($checkforblock) {
12399: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12400: unless (@blockers > 0) {
12401: $syval = $poss_syval;
12402: $realpossible++;
12403: }
12404: } else {
12405: $syval = $poss_syval;
12406: $realpossible++;
12407: }
12408: }
1.39 www 12409: }
1.191 harris41 12410: }
1.39 www 12411: if ($realpossible!=1) { $syval=''; }
1.249 www 12412: } else {
12413: $syval='';
1.37 www 12414: }
12415: }
1.1282 raeburn 12416: untie(%bighash);
1.481 raeburn 12417: }
1.31 www 12418: }
1.62 www 12419: if ($syval) {
1.620 albertel 12420: return $env{$cache_str}=$syval;
1.62 www 12421: }
1.31 www 12422: }
1.949 raeburn 12423: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12424: return $env{$cache_str}='';
1.31 www 12425: }
12426:
12427: # ---------------------------------------------------------- Return random seed
12428:
1.32 www 12429: sub numval {
12430: my $txt=shift;
12431: $txt=~tr/A-J/0-9/;
12432: $txt=~tr/a-j/0-9/;
12433: $txt=~tr/K-T/0-9/;
12434: $txt=~tr/k-t/0-9/;
12435: $txt=~tr/U-Z/0-5/;
12436: $txt=~tr/u-z/0-5/;
12437: $txt=~s/\D//g;
1.564 albertel 12438: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 12439: return int($txt);
1.368 albertel 12440: }
12441:
1.484 albertel 12442: sub numval2 {
12443: my $txt=shift;
12444: $txt=~tr/A-J/0-9/;
12445: $txt=~tr/a-j/0-9/;
12446: $txt=~tr/K-T/0-9/;
12447: $txt=~tr/k-t/0-9/;
12448: $txt=~tr/U-Z/0-5/;
12449: $txt=~tr/u-z/0-5/;
12450: $txt=~s/\D//g;
12451: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12452: my $total;
12453: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 12454: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 12455: return int($total);
12456: }
12457:
1.575 albertel 12458: sub numval3 {
12459: use integer;
12460: my $txt=shift;
12461: $txt=~tr/A-J/0-9/;
12462: $txt=~tr/a-j/0-9/;
12463: $txt=~tr/K-T/0-9/;
12464: $txt=~tr/k-t/0-9/;
12465: $txt=~tr/U-Z/0-5/;
12466: $txt=~tr/u-z/0-5/;
12467: $txt=~s/\D//g;
12468: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12469: my $total;
12470: foreach my $val (@txts) { $total+=$val; }
12471: if ($_64bit) { $total=(($total<<32)>>32); }
12472: return $total;
12473: }
12474:
1.675 albertel 12475: sub digest {
12476: my ($data)=@_;
12477: my $digest=&Digest::MD5::md5($data);
12478: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12479: my ($e,$f);
12480: {
12481: use integer;
12482: $e=($a+$b);
12483: $f=($c+$d);
12484: if ($_64bit) {
12485: $e=(($e<<32)>>32);
12486: $f=(($f<<32)>>32);
12487: }
12488: }
12489: if (wantarray) {
12490: return ($e,$f);
12491: } else {
12492: my $g;
12493: {
12494: use integer;
12495: $g=($e+$f);
12496: if ($_64bit) {
12497: $g=(($g<<32)>>32);
12498: }
12499: }
12500: return $g;
12501: }
12502: }
12503:
1.368 albertel 12504: sub latest_rnd_algorithm_id {
1.675 albertel 12505: return '64bit5';
1.366 albertel 12506: }
1.32 www 12507:
1.503 albertel 12508: sub get_rand_alg {
12509: my ($courseid)=@_;
1.790 albertel 12510: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12511: if ($courseid) {
1.620 albertel 12512: return $env{"course.$courseid.rndseed"};
1.503 albertel 12513: }
12514: return &latest_rnd_algorithm_id();
12515: }
12516:
1.562 albertel 12517: sub validCODE {
12518: my ($CODE)=@_;
12519: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12520: return 0;
12521: }
12522:
1.491 albertel 12523: sub getCODE {
1.620 albertel 12524: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12525: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12526: defined($Apache::lonhomework::parsing_a_task) ) &&
12527: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12528: return $Apache::lonhomework::history{'resource.CODE'};
12529: }
12530: return undef;
12531: }
1.1133 foxr 12532: #
12533: # Determines the random seed for a specific context:
12534: #
12535: # parameters:
12536: # symb - in course context the symb for the seed.
12537: # course_id - The course id of the form domain_coursenum.
12538: # domain - Domain for the user.
12539: # course - Course for the user.
12540: # cenv - environment of the course.
12541: #
12542: # NOTE:
12543: # All parameters are picked out of the environment if missing
12544: # or not defined.
12545: # If a symb cannot be determined the current time is used instead.
12546: #
12547: # For a given well defined symb, courside, domain, username,
12548: # and course environment, the seed is reproducible.
12549: #
1.31 www 12550: sub rndseed {
1.1133 foxr 12551: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12552: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12553: if (!defined($symb)) {
1.366 albertel 12554: unless ($symb=$wsymb) { return time; }
12555: }
1.1146 foxr 12556: if (!defined $courseid) {
12557: $courseid=$wcourseid;
12558: }
12559: if (!defined $domain) { $domain=$wdomain; }
12560: if (!defined $username) { $username=$wusername }
1.1133 foxr 12561:
12562: my $which;
12563: if (defined($cenv->{'rndseed'})) {
12564: $which = $cenv->{'rndseed'};
12565: } else {
12566: $which =&get_rand_alg($courseid);
12567: }
1.491 albertel 12568: if (defined(&getCODE())) {
1.1133 foxr 12569:
1.675 albertel 12570: if ($which eq '64bit5') {
12571: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12572: } elsif ($which eq '64bit4') {
1.575 albertel 12573: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12574: } else {
12575: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12576: }
1.675 albertel 12577: } elsif ($which eq '64bit5') {
12578: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12579: } elsif ($which eq '64bit4') {
12580: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12581: } elsif ($which eq '64bit3') {
12582: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12583: } elsif ($which eq '64bit2') {
12584: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12585: } elsif ($which eq '64bit') {
12586: return &rndseed_64bit($symb,$courseid,$domain,$username);
12587: }
12588: return &rndseed_32bit($symb,$courseid,$domain,$username);
12589: }
12590:
12591: sub rndseed_32bit {
12592: my ($symb,$courseid,$domain,$username)=@_;
12593: {
12594: use integer;
12595: my $symbchck=unpack("%32C*",$symb) << 27;
12596: my $symbseed=numval($symb) << 22;
12597: my $namechck=unpack("%32C*",$username) << 17;
12598: my $nameseed=numval($username) << 12;
12599: my $domainseed=unpack("%32C*",$domain) << 7;
12600: my $courseseed=unpack("%32C*",$courseid);
12601: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12602: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12603: #&logthis("rndseed :$num:$symb");
1.564 albertel 12604: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 12605: return $num;
12606: }
12607: }
12608:
12609: sub rndseed_64bit {
12610: my ($symb,$courseid,$domain,$username)=@_;
12611: {
12612: use integer;
12613: my $symbchck=unpack("%32S*",$symb) << 21;
12614: my $symbseed=numval($symb) << 10;
12615: my $namechck=unpack("%32S*",$username);
12616:
12617: my $nameseed=numval($username) << 21;
12618: my $domainseed=unpack("%32S*",$domain) << 10;
12619: my $courseseed=unpack("%32S*",$courseid);
12620:
12621: my $num1=$symbchck+$symbseed+$namechck;
12622: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12623: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12624: #&logthis("rndseed :$num:$symb");
1.564 albertel 12625: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 12626: return "$num1,$num2";
1.155 albertel 12627: }
1.366 albertel 12628: }
12629:
1.443 albertel 12630: sub rndseed_64bit2 {
12631: my ($symb,$courseid,$domain,$username)=@_;
12632: {
12633: use integer;
12634: # strings need to be an even # of cahracters long, it it is odd the
12635: # last characters gets thrown away
12636: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12637: my $symbseed=numval($symb) << 10;
12638: my $namechck=unpack("%32S*",$username.' ');
12639:
12640: my $nameseed=numval($username) << 21;
1.501 albertel 12641: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12642: my $courseseed=unpack("%32S*",$courseid.' ');
12643:
12644: my $num1=$symbchck+$symbseed+$namechck;
12645: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12646: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12647: #&logthis("rndseed :$num:$symb");
1.803 albertel 12648: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 12649: return "$num1,$num2";
12650: }
12651: }
12652:
12653: sub rndseed_64bit3 {
12654: my ($symb,$courseid,$domain,$username)=@_;
12655: {
12656: use integer;
12657: # strings need to be an even # of cahracters long, it it is odd the
12658: # last characters gets thrown away
12659: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12660: my $symbseed=numval2($symb) << 10;
12661: my $namechck=unpack("%32S*",$username.' ');
12662:
12663: my $nameseed=numval2($username) << 21;
1.443 albertel 12664: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12665: my $courseseed=unpack("%32S*",$courseid.' ');
12666:
12667: my $num1=$symbchck+$symbseed+$namechck;
12668: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12669: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12670: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 12671: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12672:
1.503 albertel 12673: return "$num1:$num2";
1.443 albertel 12674: }
12675: }
12676:
1.575 albertel 12677: sub rndseed_64bit4 {
12678: my ($symb,$courseid,$domain,$username)=@_;
12679: {
12680: use integer;
12681: # strings need to be an even # of cahracters long, it it is odd the
12682: # last characters gets thrown away
12683: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12684: my $symbseed=numval3($symb) << 10;
12685: my $namechck=unpack("%32S*",$username.' ');
12686:
12687: my $nameseed=numval3($username) << 21;
12688: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12689: my $courseseed=unpack("%32S*",$courseid.' ');
12690:
12691: my $num1=$symbchck+$symbseed+$namechck;
12692: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12693: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12694: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 12695: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12696:
1.575 albertel 12697: return "$num1:$num2";
12698: }
12699: }
12700:
1.675 albertel 12701: sub rndseed_64bit5 {
12702: my ($symb,$courseid,$domain,$username)=@_;
12703: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12704: return "$num1:$num2";
12705: }
12706:
1.366 albertel 12707: sub rndseed_CODE_64bit {
12708: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 12709: {
1.366 albertel 12710: use integer;
1.443 albertel 12711: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 12712: my $symbseed=numval2($symb);
1.491 albertel 12713: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12714: my $CODEseed=numval(&getCODE());
1.443 albertel 12715: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 12716: my $num1=$symbseed+$CODEchck;
12717: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12718: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12719: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 12720: if ($_64bit) { $num1=(($num1<<32)>>32); }
12721: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 12722: return "$num1:$num2";
1.366 albertel 12723: }
12724: }
12725:
1.575 albertel 12726: sub rndseed_CODE_64bit4 {
12727: my ($symb,$courseid,$domain,$username)=@_;
12728: {
12729: use integer;
12730: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12731: my $symbseed=numval3($symb);
12732: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12733: my $CODEseed=numval3(&getCODE());
12734: my $courseseed=unpack("%32S*",$courseid.' ');
12735: my $num1=$symbseed+$CODEchck;
12736: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12737: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12738: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 12739: if ($_64bit) { $num1=(($num1<<32)>>32); }
12740: if ($_64bit) { $num2=(($num2<<32)>>32); }
12741: return "$num1:$num2";
12742: }
12743: }
12744:
1.675 albertel 12745: sub rndseed_CODE_64bit5 {
12746: my ($symb,$courseid,$domain,$username)=@_;
12747: my $code = &getCODE();
12748: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12749: return "$num1:$num2";
12750: }
12751:
1.366 albertel 12752: sub setup_random_from_rndseed {
12753: my ($rndseed)=@_;
1.503 albertel 12754: if ($rndseed =~/([,:])/) {
1.1262 raeburn 12755: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12756: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12757: &Math::Random::random_set_seed_from_phrase($rndseed);
12758: } else {
12759: &Math::Random::random_set_seed($num1,$num2);
12760: }
1.366 albertel 12761: } else {
12762: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12763: }
1.36 albertel 12764: }
12765:
1.474 albertel 12766: sub latest_receipt_algorithm_id {
1.835 albertel 12767: return 'receipt3';
1.474 albertel 12768: }
12769:
1.480 www 12770: sub recunique {
12771: my $fucourseid=shift;
12772: my $unique;
1.835 albertel 12773: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12774: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12775: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12776: } else {
12777: $unique=$perlvar{'lonReceipt'};
12778: }
12779: return unpack("%32C*",$unique);
12780: }
12781:
12782: sub recprefix {
12783: my $fucourseid=shift;
12784: my $prefix;
1.835 albertel 12785: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12786: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12787: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12788: } else {
12789: $prefix=$perlvar{'lonHostID'};
12790: }
12791: return unpack("%32C*",$prefix);
12792: }
12793:
1.76 www 12794: sub ireceipt {
1.474 albertel 12795: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12796:
12797: my $return =&recprefix($fucourseid).'-';
12798:
12799: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12800: $env{'request.state'} eq 'construct') {
12801: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12802: return $return;
12803: }
12804:
1.76 www 12805: my $cuname=unpack("%32C*",$funame);
12806: my $cudom=unpack("%32C*",$fudom);
12807: my $cucourseid=unpack("%32C*",$fucourseid);
12808: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12809: my $cunique=&recunique($fucourseid);
1.474 albertel 12810: my $cpart=unpack("%32S*",$part);
1.835 albertel 12811: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12812:
1.790 albertel 12813: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12814:
12815: $return.= ($cunique%$cuname+
12816: $cunique%$cudom+
12817: $cusymb%$cuname+
12818: $cusymb%$cudom+
12819: $cucourseid%$cuname+
12820: $cucourseid%$cudom+
12821: $cpart%$cuname+
12822: $cpart%$cudom);
12823: } else {
12824: $return.= ($cunique%$cuname+
12825: $cunique%$cudom+
12826: $cusymb%$cuname+
12827: $cusymb%$cudom+
12828: $cucourseid%$cuname+
12829: $cucourseid%$cudom);
12830: }
12831: return $return;
1.76 www 12832: }
12833:
12834: sub receipt {
1.474 albertel 12835: my ($part)=@_;
1.790 albertel 12836: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 12837: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 12838: }
1.260 ng 12839:
1.790 albertel 12840: sub whichuser {
12841: my ($passedsymb)=@_;
12842: my ($symb,$courseid,$domain,$name,$publicuser);
12843: if (defined($env{'form.grade_symb'})) {
12844: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12845: my $allowed=&allowed('vgr',$tmp_courseid);
12846: if (!$allowed &&
12847: exists($env{'request.course.sec'}) &&
12848: $env{'request.course.sec'} !~ /^\s*$/) {
12849: $allowed=&allowed('vgr',$tmp_courseid.
12850: '/'.$env{'request.course.sec'});
12851: }
12852: if ($allowed) {
12853: ($symb)=&get_env_multiple('form.grade_symb');
12854: $courseid=$tmp_courseid;
12855: ($domain)=&get_env_multiple('form.grade_domain');
12856: ($name)=&get_env_multiple('form.grade_username');
12857: return ($symb,$courseid,$domain,$name,$publicuser);
12858: }
12859: }
12860: if (!$passedsymb) {
12861: $symb=&symbread();
12862: } else {
12863: $symb=$passedsymb;
12864: }
12865: $courseid=$env{'request.course.id'};
12866: $domain=$env{'user.domain'};
12867: $name=$env{'user.name'};
12868: if ($name eq 'public' && $domain eq 'public') {
12869: if (!defined($env{'form.username'})) {
12870: $env{'form.username'}.=time.rand(10000000);
12871: }
12872: $name.=$env{'form.username'};
12873: }
12874: return ($symb,$courseid,$domain,$name,$publicuser);
12875:
12876: }
12877:
1.36 albertel 12878: # ------------------------------------------------------------ Serves up a file
1.472 albertel 12879: # returns either the contents of the file or
12880: # -1 if the file doesn't exist
1.481 raeburn 12881: #
12882: # if the target is a file that was uploaded via DOCS,
12883: # a check will be made to see if a current copy exists on the local server,
12884: # if it does this will be served, otherwise a copy will be retrieved from
12885: # the home server for the course and stored in /home/httpd/html/userfiles on
12886: # the local server.
1.472 albertel 12887:
1.36 albertel 12888: sub getfile {
1.538 albertel 12889: my ($file) = @_;
1.609 banghart 12890: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 12891: &repcopy($file);
12892: return &readfile($file);
12893: }
12894:
12895: sub repcopy_userfile {
12896: my ($file)=@_;
1.1142 raeburn 12897: my $londocroot = $perlvar{'lonDocRoot'};
12898: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 12899: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 12900: my ($cdom,$cnum,$filename) =
1.811 albertel 12901: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 12902: my $uri="/uploaded/$cdom/$cnum/$filename";
12903: if (-e "$file") {
1.828 www 12904: # we already have a local copy, check it out
1.538 albertel 12905: my @fileinfo = stat($file);
1.828 www 12906: my $rtncode;
12907: my $info;
1.538 albertel 12908: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 12909: if ($lwpresp ne 'ok') {
1.828 www 12910: # there is no such file anymore, even though we had a local copy
1.482 albertel 12911: if ($rtncode eq '404') {
1.538 albertel 12912: unlink($file);
1.482 albertel 12913: }
12914: return -1;
12915: }
12916: if ($info < $fileinfo[9]) {
1.828 www 12917: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 12918: return 'ok';
1.828 www 12919: } else {
12920: # the file is outdated, get rid of it
12921: unlink($file);
1.482 albertel 12922: }
1.828 www 12923: }
12924: # one way or the other, at this point, we don't have the file
12925: # construct the correct path for the file
12926: my @parts = ($cdom,$cnum);
12927: if ($filename =~ m|^(.+)/[^/]+$|) {
12928: push @parts, split(/\//,$1);
12929: }
12930: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12931: foreach my $part (@parts) {
12932: $path .= '/'.$part;
12933: if (!-e $path) {
12934: mkdir($path,0770);
1.482 albertel 12935: }
12936: }
1.828 www 12937: # now the path exists for sure
12938: # get a user agent
12939: my $transferfile=$file.'.in.transfer';
12940: # FIXME: this should flock
12941: if (-e $transferfile) { return 'ok'; }
12942: my $request;
12943: $uri=~s/^\///;
1.980 raeburn 12944: my $homeserver = &homeserver($cnum,$cdom);
12945: my $protocol = $protocol{$homeserver};
12946: $protocol = 'http' if ($protocol ne 'https');
12947: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.1345 raeburn 12948: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828 www 12949: # did it work?
12950: if ($response->is_error()) {
12951: unlink($transferfile);
12952: &logthis("Userfile repcopy failed for $uri");
12953: return -1;
12954: }
12955: # worked, rename the transfer file
12956: rename($transferfile,$file);
1.607 raeburn 12957: return 'ok';
1.481 raeburn 12958: }
12959:
1.517 albertel 12960: sub tokenwrapper {
12961: my $uri=shift;
1.980 raeburn 12962: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 12963: $uri=~s|^/||;
1.620 albertel 12964: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 12965: my $token=$1;
1.552 albertel 12966: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12967: if ($udom && $uname && $file) {
12968: $file=~s|(\?\.*)*$||;
1.949 raeburn 12969: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 12970: my $homeserver = &homeserver($uname,$udom);
12971: my $protocol = $protocol{$homeserver};
12972: $protocol = 'http' if ($protocol ne 'https');
12973: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 12974: (($uri=~/\?/)?'&':'?').'token='.$token.
12975: '&tokenissued='.$perlvar{'lonHostID'};
12976: } else {
12977: return '/adm/notfound.html';
12978: }
12979: }
12980:
1.828 www 12981: # call with reqtype HEAD: get last modification time
12982: # call with reqtype GET: get the file contents
12983: # Do not call this with reqtype GET for large files! It loads everything into memory
12984: #
1.481 raeburn 12985: sub getuploaded {
12986: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12987: $uri=~s/^\///;
1.980 raeburn 12988: my $homeserver = &homeserver($cnum,$cdom);
12989: my $protocol = $protocol{$homeserver};
12990: $protocol = 'http' if ($protocol ne 'https');
12991: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 12992: my $request=new HTTP::Request($reqtype,$uri);
1.1345 raeburn 12993: my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481 raeburn 12994: $$rtncode = $response->code;
1.482 albertel 12995: if (! $response->is_success()) {
12996: return 'failed';
12997: }
12998: if ($reqtype eq 'HEAD') {
1.486 www 12999: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 13000: } elsif ($reqtype eq 'GET') {
13001: $$info = $response->content;
1.472 albertel 13002: }
1.482 albertel 13003: return 'ok';
1.36 albertel 13004: }
13005:
1.481 raeburn 13006: sub readfile {
13007: my $file = shift;
13008: if ( (! -e $file ) || ($file eq '') ) { return -1; };
13009: my $fh;
13010: open($fh,"<$file");
13011: my $a='';
1.800 albertel 13012: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 13013: return $a;
13014: }
13015:
1.36 albertel 13016: sub filelocation {
1.590 banghart 13017: my ($dir,$file) = @_;
13018: my $location;
13019: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 13020:
13021: if ($file =~ m-^/adm/-) {
13022: $file=~s-^/adm/wrapper/-/-;
13023: $file=~s-^/adm/coursedocs/showdoc/-/-;
13024: }
1.882 albertel 13025:
1.1139 www 13026: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 13027: $location = $file;
1.609 banghart 13028: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 13029: my ($udom,$uname,$filename)=
1.811 albertel 13030: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 13031: my $home=&homeserver($uname,$udom);
13032: my $is_me=0;
13033: my @ids=¤t_machine_ids();
13034: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13035: if ($is_me) {
1.1117 foxr 13036: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 13037: } else {
13038: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13039: $udom.'/'.$uname.'/'.$filename;
13040: }
1.882 albertel 13041: } elsif ($file =~ m-^/adm/-) {
13042: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 13043: } else {
13044: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 13045: $file=~s:^/(res|priv)/:/:;
13046: my $space=$1;
1.590 banghart 13047: if ( !( $file =~ m:^/:) ) {
13048: $location = $dir. '/'.$file;
13049: } else {
1.1142 raeburn 13050: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 13051: }
1.59 albertel 13052: }
1.590 banghart 13053: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 13054: while ($location=~m{/\.\./}) {
13055: if ($location =~ m{/[^/]+/\.\./}) {
13056: $location=~ s{/[^/]+/\.\./}{/}g;
13057: } else {
13058: $location=~ s{/\.\./}{/}g;
13059: }
13060: } #remove dir/..
1.590 banghart 13061: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13062: return $location;
1.46 www 13063: }
1.36 albertel 13064:
1.46 www 13065: sub hreflocation {
13066: my ($dir,$file)=@_;
1.980 raeburn 13067: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 13068: $file=filelocation($dir,$file);
1.700 albertel 13069: } elsif ($file=~m-^/adm/-) {
13070: $file=~s-^/adm/wrapper/-/-;
13071: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 13072: }
13073: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13074: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13075: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 13076: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13077: {/uploaded/$1/$2/}x;
1.46 www 13078: }
1.913 albertel 13079: if ($file=~ m{^/userfiles/}) {
13080: $file =~ s{^/userfiles/}{/uploaded/};
13081: }
1.462 albertel 13082: return $file;
1.465 albertel 13083: }
13084:
1.1139 www 13085:
13086:
13087:
13088:
1.465 albertel 13089: sub current_machine_domains {
1.853 albertel 13090: return &machine_domains(&hostname($perlvar{'lonHostID'}));
13091: }
13092:
13093: sub machine_domains {
13094: my ($hostname) = @_;
1.465 albertel 13095: my @domains;
1.838 albertel 13096: my %hostname = &all_hostnames();
1.465 albertel 13097: while( my($id, $name) = each(%hostname)) {
1.467 matthew 13098: # &logthis("-$id-$name-$hostname-");
1.465 albertel 13099: if ($hostname eq $name) {
1.844 albertel 13100: push(@domains,&host_domain($id));
1.465 albertel 13101: }
13102: }
13103: return @domains;
13104: }
13105:
13106: sub current_machine_ids {
1.853 albertel 13107: return &machine_ids(&hostname($perlvar{'lonHostID'}));
13108: }
13109:
13110: sub machine_ids {
13111: my ($hostname) = @_;
13112: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 13113: my @ids;
1.888 albertel 13114: my %name_to_host = &all_names();
1.889 albertel 13115: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13116: return @{ $name_to_host{$hostname} };
13117: }
13118: return;
1.31 www 13119: }
13120:
1.824 raeburn 13121: sub additional_machine_domains {
13122: my @domains;
13123: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
13124: while( my $line = <$fh>) {
13125: $line =~ s/\s//g;
13126: push(@domains,$line);
13127: }
13128: return @domains;
13129: }
13130:
13131: sub default_login_domain {
13132: my $domain = $perlvar{'lonDefDomain'};
13133: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13134: foreach my $posdom (¤t_machine_domains(),
13135: &additional_machine_domains()) {
13136: if (lc($posdom) eq lc($testdomain)) {
13137: $domain=$posdom;
13138: last;
13139: }
13140: }
13141: return $domain;
13142: }
13143:
1.31 www 13144: # ------------------------------------------------------------- Declutters URLs
13145:
13146: sub declutter {
13147: my $thisfn=shift;
1.569 albertel 13148: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 13149: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13150: $thisfn=~s{^/home/httpd/html}{};
13151: }
1.31 www 13152: $thisfn=~s/^\///;
1.697 albertel 13153: $thisfn=~s|^adm/wrapper/||;
13154: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 13155: $thisfn=~s/^res\///;
1.1172 bisitz 13156: $thisfn=~s/^priv\///;
1.1032 raeburn 13157: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13158: $thisfn=~s/\?.+$//;
13159: }
1.268 www 13160: return $thisfn;
13161: }
13162:
13163: # ------------------------------------------------------------- Clutter up URLs
13164:
13165: sub clutter {
13166: my $thisfn='/'.&declutter(shift);
1.887 albertel 13167: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 13168: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 13169: $thisfn='/res'.$thisfn;
13170: }
1.1031 raeburn 13171: if ($thisfn !~m|^/adm|) {
13172: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 13173: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 13174: } else {
13175: my ($ext) = ($thisfn =~ /\.(\w+)$/);
13176: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 13177: if ($embstyle eq 'ssi'
13178: || ($embstyle eq 'hdn')
13179: || ($embstyle eq 'rat')
13180: || ($embstyle eq 'prv')
13181: || ($embstyle eq 'ign')) {
13182: #do nothing with these
13183: } elsif (($embstyle eq 'img')
1.695 albertel 13184: || ($embstyle eq 'emb')
13185: || ($embstyle eq 'wrp')) {
13186: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 13187: } elsif ($embstyle eq 'unk'
13188: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 13189: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 13190: } else {
1.718 www 13191: # &logthis("Got a blank emb style");
1.695 albertel 13192: }
1.694 albertel 13193: }
1.1343 raeburn 13194: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298 raeburn 13195: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 13196: }
1.31 www 13197: return $thisfn;
1.12 www 13198: }
13199:
1.787 albertel 13200: sub clutter_with_no_wrapper {
13201: my $uri = &clutter(shift);
13202: if ($uri =~ m-^/adm/-) {
13203: $uri =~ s-^/adm/wrapper/-/-;
13204: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
13205: }
13206: return $uri;
13207: }
13208:
1.557 albertel 13209: sub freeze_escape {
13210: my ($value)=@_;
13211: if (ref($value)) {
13212: $value=&nfreeze($value);
13213: return '__FROZEN__'.&escape($value);
13214: }
13215: return &escape($value);
13216: }
13217:
1.11 www 13218:
1.557 albertel 13219: sub thaw_unescape {
13220: my ($value)=@_;
13221: if ($value =~ /^__FROZEN__/) {
13222: substr($value,0,10,undef);
13223: $value=&unescape($value);
13224: return &thaw($value);
13225: }
13226: return &unescape($value);
13227: }
13228:
1.436 albertel 13229: sub correct_line_ends {
13230: my ($result)=@_;
13231: $$result =~s/\r\n/\n/mg;
13232: $$result =~s/\r/\n/mg;
1.415 albertel 13233: }
1.1 albertel 13234: # ================================================================ Main Program
13235:
1.184 www 13236: sub goodbye {
1.204 albertel 13237: &logthis("Starting Shut down");
1.443 albertel 13238: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 13239: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 13240: #converted
1.599 albertel 13241: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 13242: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13243: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13244: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 13245: #1.1 only
1.870 albertel 13246: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13247: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13248: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13249: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13250: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 13251: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13252: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 13253: &flushcourselogs();
13254: &logthis("Shutting down");
13255: }
13256:
1.852 albertel 13257: sub get_dns {
1.1210 raeburn 13258: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 13259: if (!$ignore_cache) {
13260: my ($content,$cached)=
13261: &Apache::lonnet::is_cached_new('dns',$url);
13262: if ($cached) {
1.1210 raeburn 13263: &$func($content,$hashref);
1.869 albertel 13264: return;
13265: }
13266: }
13267:
13268: my %alldns;
1.852 albertel 13269: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13270: foreach my $dns (<$config>) {
13271: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 13272: my $line = $1;
13273: my ($host,$protocol) = split(/:/,$line);
13274: if ($protocol ne 'https') {
13275: $protocol = 'http';
13276: }
13277: $alldns{$host} = $protocol;
1.869 albertel 13278: }
13279: while (%alldns) {
1.1263 raeburn 13280: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979 raeburn 13281: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345 raeburn 13282: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979 raeburn 13283: delete($alldns{$dns});
1.852 albertel 13284: next if ($response->is_error());
13285: my @content = split("\n",$response->content);
1.1210 raeburn 13286: unless ($nocache) {
1.1219 raeburn 13287: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 13288: }
13289: &$func(\@content,$hashref);
1.869 albertel 13290: return;
1.852 albertel 13291: }
13292: close($config);
1.871 albertel 13293: my $which = (split('/',$url))[3];
13294: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13295: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 13296: my @content = <$config>;
1.1210 raeburn 13297: &$func(\@content,$hashref);
13298: return;
13299: }
13300:
13301: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 13302: sub parse_dns_checksums_tab {
1.1210 raeburn 13303: my ($lines,$hashref) = @_;
1.1264 raeburn 13304: my $lonhost = $perlvar{'lonHostID'};
13305: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 13306: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 13307: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13308: my $webconfdir = '/etc/httpd/conf';
13309: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13310: $webconfdir = '/etc/apache2';
13311: } elsif ($distro =~ /^sles(\d+)$/) {
13312: if ($1 >= 10) {
13313: $webconfdir = '/etc/apache2';
13314: }
13315: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13316: if ($1 >= 10.0) {
13317: $webconfdir = '/etc/apache2';
13318: }
13319: }
1.1210 raeburn 13320: my ($release,$timestamp) = split(/\-/,$loncaparev);
13321: my (%chksum,%revnum);
13322: if (ref($lines) eq 'ARRAY') {
13323: chomp(@{$lines});
1.1238 raeburn 13324: my $version = shift(@{$lines});
13325: if ($version eq $release) {
1.1210 raeburn 13326: foreach my $line (@{$lines}) {
1.1238 raeburn 13327: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 13328: if ($file =~ m{^/etc/httpd/conf}) {
13329: if ($webconfdir eq '/etc/apache2') {
13330: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13331: }
13332: }
1.1238 raeburn 13333: $chksum{$file} = $shasum;
13334: $revnum{$file} = $version;
1.1210 raeburn 13335: }
13336: if (ref($hashref) eq 'HASH') {
13337: %{$hashref} = (
13338: sums => \%chksum,
13339: versions => \%revnum,
13340: );
13341: }
13342: }
13343: }
1.869 albertel 13344: return;
1.852 albertel 13345: }
1.1210 raeburn 13346:
13347: sub fetch_dns_checksums {
1.1238 raeburn 13348: my %checksums;
13349: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 13350: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 13351: my ($release,$timestamp) = split(/\-/,$loncaparev);
13352: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 13353: \%checksums);
1.1210 raeburn 13354: return \%checksums;
13355: }
13356:
1.327 albertel 13357: # ------------------------------------------------------------ Read domain file
13358: {
1.852 albertel 13359: my $loaded;
1.846 albertel 13360: my %domain;
13361:
1.852 albertel 13362: sub parse_domain_tab {
13363: my ($lines) = @_;
13364: foreach my $line (@$lines) {
13365: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 13366:
1.846 albertel 13367: chomp($line);
1.852 albertel 13368: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 13369: my %this_domain;
13370: foreach my $field ('description', 'auth_def', 'auth_arg_def',
13371: 'lang_def', 'city', 'longi', 'lati',
13372: 'primary') {
13373: $this_domain{$field} = shift(@elements);
13374: }
13375: $domain{$name} = \%this_domain;
1.852 albertel 13376: }
13377: }
1.864 albertel 13378:
13379: sub reset_domain_info {
13380: undef($loaded);
13381: undef(%domain);
13382: }
13383:
1.852 albertel 13384: sub load_domain_tab {
1.1293 raeburn 13385: my ($ignore_cache,$nocache) = @_;
13386: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 13387: my $fh;
13388: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
13389: my @lines = <$fh>;
13390: &parse_domain_tab(\@lines);
1.448 albertel 13391: }
1.852 albertel 13392: close($fh);
13393: $loaded = 1;
1.327 albertel 13394: }
1.846 albertel 13395:
13396: sub domain {
1.852 albertel 13397: &load_domain_tab() if (!$loaded);
13398:
1.846 albertel 13399: my ($name,$what) = @_;
13400: return if ( !exists($domain{$name}) );
13401:
13402: if (!$what) {
13403: return $domain{$name}{'description'};
13404: }
13405: return $domain{$name}{$what};
13406: }
1.974 raeburn 13407:
13408: sub domain_info {
13409: &load_domain_tab() if (!$loaded);
13410: return %domain;
13411: }
13412:
1.327 albertel 13413: }
13414:
13415:
1.1 albertel 13416: # ------------------------------------------------------------- Read hosts file
13417: {
1.838 albertel 13418: my %hostname;
1.844 albertel 13419: my %hostdom;
1.845 albertel 13420: my %libserv;
1.852 albertel 13421: my $loaded;
1.888 albertel 13422: my %name_to_host;
1.1074 raeburn 13423: my %internetdom;
1.1107 raeburn 13424: my %LC_dns_serv;
1.852 albertel 13425:
13426: sub parse_hosts_tab {
13427: my ($file) = @_;
13428: foreach my $configline (@$file) {
13429: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 13430: chomp($configline);
13431: if ($configline =~ /^\^/) {
13432: if ($configline =~ /^\^([\w.\-]+)/) {
13433: $LC_dns_serv{$1} = 1;
13434: }
13435: next;
13436: }
1.1074 raeburn 13437: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 13438: $name=~s/\s//g;
13439: if ($id && $domain && $role && $name) {
1.1351 raeburn 13440: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13441: my $curr = $hostname{$id};
13442: my $skip;
13443: if (ref($name_to_host{$curr}) eq 'ARRAY') {
13444: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13445: $skip = 1;
13446: } else {
13447: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13448: }
13449: }
13450: unless ($skip) {
13451: push(@{$name_to_host{$name}},$id);
13452: }
13453: } else {
13454: push(@{$name_to_host{$name}},$id);
13455: }
1.852 albertel 13456: $hostname{$id}=$name;
13457: $hostdom{$id}=$domain;
13458: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 13459: if (defined($protocol)) {
13460: if ($protocol eq 'https') {
13461: $protocol{$id} = $protocol;
13462: } else {
13463: $protocol{$id} = 'http';
13464: }
1.968 raeburn 13465: } else {
1.969 raeburn 13466: $protocol{$id} = 'http';
1.968 raeburn 13467: }
1.1074 raeburn 13468: if (defined($intdom)) {
13469: $internetdom{$id} = $intdom;
13470: }
1.852 albertel 13471: }
13472: }
13473: }
1.864 albertel 13474:
13475: sub reset_hosts_info {
1.897 albertel 13476: &purge_remembered();
1.864 albertel 13477: &reset_domain_info();
13478: &reset_hosts_ip_info();
1.1339 raeburn 13479: undef(%internetdom);
1.892 albertel 13480: undef(%name_to_host);
1.864 albertel 13481: undef(%hostname);
13482: undef(%hostdom);
13483: undef(%libserv);
13484: undef($loaded);
13485: }
1.1 albertel 13486:
1.852 albertel 13487: sub load_hosts_tab {
1.1293 raeburn 13488: my ($ignore_cache,$nocache) = @_;
13489: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852 albertel 13490: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13491: my @config = <$config>;
13492: &parse_hosts_tab(\@config);
13493: close($config);
13494: $loaded=1;
1.1 albertel 13495: }
1.852 albertel 13496:
1.838 albertel 13497: sub hostname {
1.852 albertel 13498: &load_hosts_tab() if (!$loaded);
13499:
1.838 albertel 13500: my ($lonid) = @_;
13501: return $hostname{$lonid};
13502: }
1.845 albertel 13503:
1.838 albertel 13504: sub all_hostnames {
1.852 albertel 13505: &load_hosts_tab() if (!$loaded);
13506:
1.838 albertel 13507: return %hostname;
13508: }
1.845 albertel 13509:
1.888 albertel 13510: sub all_names {
1.1293 raeburn 13511: my ($ignore_cache,$nocache) = @_;
13512: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 13513:
13514: return %name_to_host;
13515: }
13516:
1.974 raeburn 13517: sub all_host_domain {
13518: &load_hosts_tab() if (!$loaded);
13519: return %hostdom;
13520: }
13521:
1.1339 raeburn 13522: sub all_host_intdom {
13523: &load_hosts_tab() if (!$loaded);
13524: return %internetdom;
13525: }
13526:
1.845 albertel 13527: sub is_library {
1.852 albertel 13528: &load_hosts_tab() if (!$loaded);
13529:
1.845 albertel 13530: return exists($libserv{$_[0]});
13531: }
13532:
13533: sub all_library {
1.852 albertel 13534: &load_hosts_tab() if (!$loaded);
13535:
1.845 albertel 13536: return %libserv;
13537: }
13538:
1.1062 droeschl 13539: sub unique_library {
13540: #2x reverse removes all hostnames that appear more than once
13541: my %unique = reverse &all_library();
13542: return reverse %unique;
13543: }
13544:
1.841 albertel 13545: sub get_servers {
1.852 albertel 13546: &load_hosts_tab() if (!$loaded);
13547:
1.841 albertel 13548: my ($domain,$type) = @_;
13549: my %possible_hosts = ($type eq 'library') ? %libserv
13550: : %hostname;
13551: my %result;
1.842 albertel 13552: if (ref($domain) eq 'ARRAY') {
13553: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 13554: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 13555: $result{$host} = $hostname;
13556: }
13557: }
13558: } else {
13559: while ( my ($host,$hostname) = each(%possible_hosts)) {
13560: if ($hostdom{$host} eq $domain) {
13561: $result{$host} = $hostname;
13562: }
1.841 albertel 13563: }
13564: }
13565: return %result;
13566: }
1.845 albertel 13567:
1.1062 droeschl 13568: sub get_unique_servers {
13569: my %unique = reverse &get_servers(@_);
13570: return reverse %unique;
13571: }
13572:
1.844 albertel 13573: sub host_domain {
1.852 albertel 13574: &load_hosts_tab() if (!$loaded);
13575:
1.844 albertel 13576: my ($lonid) = @_;
13577: return $hostdom{$lonid};
13578: }
13579:
1.841 albertel 13580: sub all_domains {
1.852 albertel 13581: &load_hosts_tab() if (!$loaded);
13582:
1.841 albertel 13583: my %seen;
13584: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13585: return @uniq;
13586: }
1.1074 raeburn 13587:
13588: sub internet_dom {
13589: &load_hosts_tab() if (!$loaded);
13590:
13591: my ($lonid) = @_;
13592: return $internetdom{$lonid};
13593: }
1.1107 raeburn 13594:
13595: sub is_LC_dns {
13596: &load_hosts_tab() if (!$loaded);
13597:
13598: my ($hostname) = @_;
13599: return exists($LC_dns_serv{$hostname});
13600: }
13601:
1.1 albertel 13602: }
13603:
1.847 albertel 13604: {
13605: my %iphost;
1.856 albertel 13606: my %name_to_ip;
13607: my %lonid_to_ip;
1.869 albertel 13608:
1.847 albertel 13609: sub get_hosts_from_ip {
13610: my ($ip) = @_;
13611: my %iphosts = &get_iphost();
13612: if (ref($iphosts{$ip})) {
13613: return @{$iphosts{$ip}};
13614: }
13615: return;
1.839 albertel 13616: }
1.864 albertel 13617:
13618: sub reset_hosts_ip_info {
13619: undef(%iphost);
13620: undef(%name_to_ip);
13621: undef(%lonid_to_ip);
13622: }
1.856 albertel 13623:
13624: sub get_host_ip {
13625: my ($lonid) = @_;
13626: if (exists($lonid_to_ip{$lonid})) {
13627: return $lonid_to_ip{$lonid};
13628: }
13629: my $name=&hostname($lonid);
13630: my $ip = gethostbyname($name);
13631: return if (!$ip || length($ip) ne 4);
13632: $ip=inet_ntoa($ip);
13633: $name_to_ip{$name} = $ip;
13634: $lonid_to_ip{$lonid} = $ip;
13635: return $ip;
13636: }
1.847 albertel 13637:
13638: sub get_iphost {
1.1293 raeburn 13639: my ($ignore_cache,$nocache) = @_;
1.894 albertel 13640:
1.869 albertel 13641: if (!$ignore_cache) {
13642: if (%iphost) {
13643: return %iphost;
13644: }
13645: my ($ip_info,$cached)=
13646: &Apache::lonnet::is_cached_new('iphost','iphost');
13647: if ($cached) {
13648: %iphost = %{$ip_info->[0]};
13649: %name_to_ip = %{$ip_info->[1]};
13650: %lonid_to_ip = %{$ip_info->[2]};
13651: return %iphost;
13652: }
13653: }
1.894 albertel 13654:
13655: # get yesterday's info for fallback
13656: my %old_name_to_ip;
13657: my ($ip_info,$cached)=
13658: &Apache::lonnet::is_cached_new('iphost','iphost');
13659: if ($cached) {
13660: %old_name_to_ip = %{$ip_info->[1]};
13661: }
13662:
1.1293 raeburn 13663: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 13664: foreach my $name (keys(%name_to_host)) {
1.847 albertel 13665: my $ip;
13666: if (!exists($name_to_ip{$name})) {
13667: $ip = gethostbyname($name);
13668: if (!$ip || length($ip) ne 4) {
1.894 albertel 13669: if (defined($old_name_to_ip{$name})) {
13670: $ip = $old_name_to_ip{$name};
13671: &logthis("Can't find $name defaulting to old $ip");
13672: } else {
13673: &logthis("Name $name no IP found");
13674: next;
13675: }
13676: } else {
13677: $ip=inet_ntoa($ip);
1.847 albertel 13678: }
13679: $name_to_ip{$name} = $ip;
13680: } else {
13681: $ip = $name_to_ip{$name};
1.653 albertel 13682: }
1.888 albertel 13683: foreach my $id (@{ $name_to_host{$name} }) {
13684: $lonid_to_ip{$id} = $ip;
13685: }
13686: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 13687: }
1.1293 raeburn 13688: unless ($nocache) {
13689: &do_cache_new('iphost','iphost',
13690: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13691: 48*60*60);
13692: }
1.869 albertel 13693:
1.847 albertel 13694: return %iphost;
1.598 albertel 13695: }
13696:
1.992 raeburn 13697: #
13698: # Given a DNS returns the loncapa host name for that DNS
13699: #
13700: sub host_from_dns {
13701: my ($dns) = @_;
13702: my @hosts;
13703: my $ip;
13704:
1.993 raeburn 13705: if (exists($name_to_ip{$dns})) {
1.992 raeburn 13706: $ip = $name_to_ip{$dns};
13707: }
13708: if (!$ip) {
13709: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13710: if (length($ip) == 4) {
13711: $ip = &IO::Socket::inet_ntoa($ip);
13712: }
13713: }
13714: if ($ip) {
13715: @hosts = get_hosts_from_ip($ip);
13716: return $hosts[0];
13717: }
13718: return undef;
1.986 foxr 13719: }
1.992 raeburn 13720:
1.1074 raeburn 13721: sub get_internet_names {
13722: my ($lonid) = @_;
13723: return if ($lonid eq '');
13724: my ($idnref,$cached)=
13725: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13726: if ($cached) {
13727: return $idnref;
13728: }
13729: my $ip = &get_host_ip($lonid);
13730: my @hosts = &get_hosts_from_ip($ip);
13731: my %iphost = &get_iphost();
13732: my (@idns,%seen);
13733: foreach my $id (@hosts) {
13734: my $dom = &host_domain($id);
13735: my $prim_id = &domain($dom,'primary');
13736: my $prim_ip = &get_host_ip($prim_id);
13737: next if ($seen{$prim_ip});
13738: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13739: foreach my $id (@{$iphost{$prim_ip}}) {
13740: my $intdom = &internet_dom($id);
13741: unless (grep(/^\Q$intdom\E$/,@idns)) {
13742: push(@idns,$intdom);
13743: }
13744: }
13745: }
13746: $seen{$prim_ip} = 1;
13747: }
1.1219 raeburn 13748: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 13749: }
13750:
1.986 foxr 13751: }
13752:
1.1079 raeburn 13753: sub all_loncaparevs {
1.1249 raeburn 13754: 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 13755: }
13756:
1.1227 raeburn 13757: # ---------------------------------------------------------- Read loncaparev table
13758: {
13759: sub load_loncaparevs {
13760: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13761: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13762: while (my $configline=<$config>) {
13763: chomp($configline);
13764: my ($hostid,$loncaparev)=split(/:/,$configline);
13765: $loncaparevs{$hostid}=$loncaparev;
13766: }
13767: close($config);
13768: }
13769: }
13770: }
13771: }
13772:
13773: # ---------------------------------------------------------- Read serverhostID table
13774: {
13775: sub load_serverhomeIDs {
13776: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13777: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13778: while (my $configline=<$config>) {
13779: chomp($configline);
13780: my ($name,$id)=split(/:/,$configline);
13781: $serverhomeIDs{$name}=$id;
13782: }
13783: close($config);
13784: }
13785: }
13786: }
13787: }
13788:
13789:
1.862 albertel 13790: BEGIN {
13791:
13792: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13793: unless ($readit) {
13794: {
13795: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13796: %perlvar = (%perlvar,%{$configvars});
13797: }
13798:
13799:
1.1 albertel 13800: # ------------------------------------------------------ Read spare server file
13801: {
1.448 albertel 13802: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 13803:
13804: while (my $configline=<$config>) {
13805: chomp($configline);
1.284 matthew 13806: if ($configline) {
1.784 albertel 13807: my ($host,$type) = split(':',$configline,2);
1.785 albertel 13808: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 13809: push(@{ $spareid{$type} }, $host);
1.1 albertel 13810: }
13811: }
1.448 albertel 13812: close($config);
1.1 albertel 13813: }
1.11 www 13814: # ------------------------------------------------------------ Read permissions
13815: {
1.448 albertel 13816: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 13817:
13818: while (my $configline=<$config>) {
1.448 albertel 13819: chomp($configline);
13820: if ($configline) {
13821: my ($role,$perm)=split(/ /,$configline);
13822: if ($perm ne '') { $pr{$role}=$perm; }
13823: }
1.11 www 13824: }
1.448 albertel 13825: close($config);
1.11 www 13826: }
13827:
13828: # -------------------------------------------- Read plain texts for permissions
13829: {
1.448 albertel 13830: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 13831:
13832: while (my $configline=<$config>) {
1.448 albertel 13833: chomp($configline);
13834: if ($configline) {
1.742 raeburn 13835: my ($short,@plain)=split(/:/,$configline);
13836: %{$prp{$short}} = ();
13837: if (@plain > 0) {
13838: $prp{$short}{'std'} = $plain[0];
13839: for (my $i=1; $i<@plain; $i++) {
13840: $prp{$short}{'alt'.$i} = $plain[$i];
13841: }
13842: }
1.448 albertel 13843: }
1.135 www 13844: }
1.448 albertel 13845: close($config);
1.135 www 13846: }
13847:
13848: # ---------------------------------------------------------- Read package table
13849: {
1.448 albertel 13850: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 13851:
13852: while (my $configline=<$config>) {
1.483 albertel 13853: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 13854: chomp($configline);
13855: my ($short,$plain)=split(/:/,$configline);
13856: my ($pack,$name)=split(/\&/,$short);
13857: if ($plain ne '') {
13858: $packagetab{$pack.'&'.$name.'&name'}=$name;
13859: $packagetab{$short}=$plain;
13860: }
1.11 www 13861: }
1.448 albertel 13862: close($config);
1.329 matthew 13863: }
13864:
1.1073 raeburn 13865: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 13866:
13867: &load_loncaparevs();
1.1073 raeburn 13868:
1.1074 raeburn 13869: # ---------------------------------------------------------- Read serverhostID table
13870:
1.1227 raeburn 13871: &load_serverhomeIDs();
13872:
13873: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 13874: {
13875: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13876: if (-e $file) {
13877: my $parser = HTML::LCParser->new($file);
13878: while (my $token = $parser->get_token()) {
13879: if ($token->[0] eq 'S') {
13880: my $item = $token->[1];
13881: my $name = $token->[2]{'name'};
13882: my $value = $token->[2]{'value'};
1.1285 raeburn 13883: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 13884: my $namematch = $token->[2]{'namematch'};
13885: if ($item eq 'parameter') {
13886: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
13887: my $release = $parser->get_text();
13888: $release =~ s/(^\s*|\s*$ )//gx;
13889: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
13890: }
13891: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 13892: my $release = $parser->get_text();
13893: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 13894: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 13895: }
13896: }
13897: }
13898: }
1.1073 raeburn 13899: }
13900:
1.1138 raeburn 13901: # ---------------------------------------------------------- Read managers table
13902: {
13903: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13904: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
13905: while (my $configline=<$config>) {
13906: chomp($configline);
13907: next if ($configline =~ /^\#/);
13908: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13909: $managerstab{$configline} = 1;
13910: }
13911: }
13912: close($config);
13913: }
13914: }
13915: }
13916:
1.329 matthew 13917: # ------------- set up temporary directory
13918: {
1.1117 foxr 13919: $tmpdir = LONCAPA::tempdir();
1.329 matthew 13920:
1.11 www 13921: }
13922:
1.794 albertel 13923: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13924: 'compress_threshold'=> 20_000,
13925: });
1.185 www 13926:
1.281 www 13927: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 13928: $dumpcount=0;
1.958 www 13929: $locknum=0;
1.22 www 13930:
1.163 harris41 13931: &logtouch();
1.672 albertel 13932: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 13933: $readit=1;
1.564 albertel 13934: {
13935: use integer;
13936: my $test=(2**32)+1;
1.568 albertel 13937: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 13938: &logthis(" Detected 64bit platform ($_64bit)");
13939: }
1.195 www 13940: }
1.1 albertel 13941: }
1.179 www 13942:
1.1 albertel 13943: 1;
1.191 harris41 13944: __END__
13945:
1.243 albertel 13946: =pod
13947:
1.191 harris41 13948: =head1 NAME
13949:
1.243 albertel 13950: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 13951:
13952: =head1 SYNOPSIS
13953:
1.243 albertel 13954: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 13955:
13956: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13957:
1.243 albertel 13958: Common parameters:
13959:
13960: =over 4
13961:
13962: =item *
13963:
13964: $uname : an internal username (if $cname expecting a course Id specifically)
13965:
13966: =item *
13967:
13968: $udom : a domain (if $cdom expecting a course's domain specifically)
13969:
13970: =item *
13971:
13972: $symb : a resource instance identifier
13973:
13974: =item *
13975:
13976: $namespace : the name of a .db file that contains the data needed or
13977: being set.
13978:
13979: =back
13980:
1.394 bowersj2 13981: =head1 OVERVIEW
1.191 harris41 13982:
1.394 bowersj2 13983: lonnet provides subroutines which interact with the
13984: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13985: about classes, users, and resources.
1.243 albertel 13986:
13987: For many of these objects you can also use this to store data about
13988: them or modify them in various ways.
1.191 harris41 13989:
1.394 bowersj2 13990: =head2 Symbs
1.191 harris41 13991:
1.394 bowersj2 13992: To identify a specific instance of a resource, LON-CAPA uses symbols
13993: or "symbs"X<symb>. These identifiers are built from the URL of the
13994: map, the resource number of the resource in the map, and the URL of
13995: the resource itself. The latter is somewhat redundant, but might help
13996: if maps change.
13997:
13998: An example is
13999:
14000: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14001:
14002: The respective map entry is
14003:
14004: <resource id="19" src="/res/msu/korte/tests/part12.problem"
14005: title="Problem 2">
14006: </resource>
14007:
14008: Symbs are used by the random number generator, as well as to store and
14009: restore data specific to a certain instance of for example a problem.
14010:
14011: =head2 Storing And Retrieving Data
14012:
14013: X<store()>X<cstore()>X<restore()>Three of the most important functions
14014: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14015: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14016: is is the non-critical message twin of cstore. These functions are for
14017: handlers to store a perl hash to a user's permanent data space in an
14018: easy manner, and to retrieve it again on another call. It is expected
14019: that a handler would use this once at the beginning to retrieve data,
14020: and then again once at the end to send only the new data back.
14021:
14022: The data is stored in the user's data directory on the user's
14023: homeserver under the ID of the course.
14024:
14025: The hash that is returned by restore will have all of the previous
14026: value for all of the elements of the hash.
14027:
14028: Example:
14029:
14030: #creating a hash
14031: my %hash;
14032: $hash{'foo'}='bar';
14033:
14034: #storing it
14035: &Apache::lonnet::cstore(\%hash);
14036:
14037: #changing a value
14038: $hash{'foo'}='notbar';
14039:
14040: #adding a new value
14041: $hash{'bar'}='foo';
14042: &Apache::lonnet::cstore(\%hash);
14043:
14044: #retrieving the hash
14045: my %history=&Apache::lonnet::restore();
14046:
14047: #print the hash
14048: foreach my $key (sort(keys(%history))) {
14049: print("\%history{$key} = $history{$key}");
14050: }
14051:
14052: Will print out:
1.191 harris41 14053:
1.394 bowersj2 14054: %history{1:foo} = bar
14055: %history{1:keys} = foo:timestamp
14056: %history{1:timestamp} = 990455579
14057: %history{2:bar} = foo
14058: %history{2:foo} = notbar
14059: %history{2:keys} = foo:bar:timestamp
14060: %history{2:timestamp} = 990455580
14061: %history{bar} = foo
14062: %history{foo} = notbar
14063: %history{timestamp} = 990455580
14064: %history{version} = 2
14065:
14066: Note that the special hash entries C<keys>, C<version> and
14067: C<timestamp> were added to the hash. C<version> will be equal to the
14068: total number of versions of the data that have been stored. The
14069: C<timestamp> attribute will be the UNIX time the hash was
14070: stored. C<keys> is available in every historical section to list which
14071: keys were added or changed at a specific historical revision of a
14072: hash.
14073:
14074: B<Warning>: do not store the hash that restore returns directly. This
14075: will cause a mess since it will restore the historical keys as if the
14076: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 14077:
1.394 bowersj2 14078: Calling convention:
1.191 harris41 14079:
1.1225 raeburn 14080: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 14081: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 14082:
1.394 bowersj2 14083: For more detailed information, see lonnet specific documentation.
1.191 harris41 14084:
1.394 bowersj2 14085: =head1 RETURN MESSAGES
1.191 harris41 14086:
1.394 bowersj2 14087: =over 4
1.191 harris41 14088:
1.394 bowersj2 14089: =item * B<con_lost>: unable to contact remote host
1.191 harris41 14090:
1.394 bowersj2 14091: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14092: when the connection is brought back up
1.191 harris41 14093:
1.394 bowersj2 14094: =item * B<con_failed>: unable to contact remote host and unable to save message
14095: for later delivery
1.191 harris41 14096:
1.967 bisitz 14097: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 14098:
1.394 bowersj2 14099: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 14100: that was requested
1.191 harris41 14101:
1.243 albertel 14102: =back
1.191 harris41 14103:
1.243 albertel 14104: =head1 PUBLIC SUBROUTINES
1.191 harris41 14105:
1.243 albertel 14106: =head2 Session Environment Functions
1.191 harris41 14107:
1.243 albertel 14108: =over 4
1.191 harris41 14109:
1.394 bowersj2 14110: =item *
14111: X<appenv()>
1.949 raeburn 14112: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 14113: the user envirnoment file, and will be restored for each access this
1.620 albertel 14114: user makes during this session, also modifies the %env for the current
1.949 raeburn 14115: process. Optional rolesarrayref - if defined contains a reference to an array
14116: of roles which are exempt from the restriction on modifying user.role entries
14117: in the user's environment.db and in %env.
1.191 harris41 14118:
14119: =item *
1.394 bowersj2 14120: X<delenv()>
1.987 raeburn 14121: B<delenv($delthis,$regexp)>: removes all items from the session
14122: environment file that begin with $delthis. If the
14123: optional second arg - $regexp - is true, $delthis is treated as a
14124: regular expression, otherwise \Q$delthis\E is used.
14125: The values are also deleted from the current processes %env.
1.191 harris41 14126:
1.795 albertel 14127: =item * get_env_multiple($name)
14128:
14129: gets $name from the %env hash, it seemlessly handles the cases where multiple
14130: values may be defined and end up as an array ref.
14131:
14132: returns an array of values
14133:
1.243 albertel 14134: =back
14135:
14136: =head2 User Information
1.191 harris41 14137:
1.243 albertel 14138: =over 4
1.191 harris41 14139:
14140: =item *
1.394 bowersj2 14141: X<queryauthenticate()>
14142: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 14143: authentication scheme
14144:
14145: =item *
1.394 bowersj2 14146: X<authenticate()>
1.1073 raeburn 14147: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 14148: authenticate user from domain's lib servers (first use the current
14149: one). C<$upass> should be the users password.
1.1073 raeburn 14150: $checkdefauth is optional (value is 1 if a check should be made to
14151: authenticate user using default authentication method, and allow
14152: account creation if username does not have account in the domain).
14153: $clientcancheckhost is optional (value is 1 if checking whether the
14154: server can host will occur on the client side in lonauth.pm).
1.191 harris41 14155:
14156: =item *
1.394 bowersj2 14157: X<homeserver()>
14158: B<homeserver($uname,$udom)>: find the server which has
14159: the user's directory and files (there must be only one), this caches
14160: the answer, and also caches if there is a borken connection.
1.191 harris41 14161:
14162: =item *
1.394 bowersj2 14163: X<idget()>
1.1300 raeburn 14164: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
14165: a list of student/employee IDs or clicker IDs
14166: (student/employee IDs are a unique resource in a domain, there must be
14167: only 1 ID per username, and only 1 username per ID in a specific domain).
14168: clickerIDs are not necessarily unique, as students might share clickers.
14169: (returns hash: id=>name,id=>name)
1.191 harris41 14170:
14171: =item *
1.394 bowersj2 14172: X<idrget()>
14173: B<idrget($udom,@unames)>: find the IDs behind a list of
14174: usernames (returns hash: name=>id,name=>id)
1.191 harris41 14175:
14176: =item *
1.394 bowersj2 14177: X<idput()>
1.1300 raeburn 14178: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
14179: names and associated student/employee IDs or clicker IDs.
14180:
14181: =item *
14182: X<iddel()>
14183: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
14184: student/employee ID or clicker ID username look-ups from domain.
14185: The homeserver ($uhome) and namespace ($namespace) are optional.
14186: If no $uhome is provided, it will be determined usig &homeserver()
14187: for each user. If no $namespace is provided, the default is ids.
14188:
14189: =item *
14190: X<updateclickers()>
14191: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
14192: clicker ID-to-username look-ups in clickers.db on library server.
14193: Permitted actions are add or del (i.e., add or delete). The
14194: clickers.db contains clickerID as keys (escaped), and each corresponding
14195: value is an escaped comma-separated list of usernames (for whom the
14196: library server is the homeserver), who registered that particular ID.
14197: If $critical is true, the update will be sent via &critical, otherwise
14198: &reply() will be used.
1.191 harris41 14199:
14200: =item *
1.394 bowersj2 14201: X<rolesinit()>
1.1169 droeschl 14202: B<rolesinit($udom,$username)>: get user privileges.
14203: returns user role, first access and timer interval hashes
1.243 albertel 14204:
14205: =item *
1.1171 droeschl 14206: X<privileged()>
14207: B<privileged($username,$domain)>: returns a true if user has a
14208: privileged and active role (i.e. su or dc), false otherwise.
14209:
14210: =item *
1.551 albertel 14211: X<getsection()>
14212: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 14213: course $cname, return section name/number or '' for "not in course"
14214: and '-1' for "no section"
14215:
14216: =item *
1.394 bowersj2 14217: X<userenvironment()>
14218: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 14219: passed in @what from the requested user's environment, returns a hash
14220:
1.858 raeburn 14221: =item *
14222: X<userlog_query()>
1.859 albertel 14223: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14224: activity.log file. %filters defines filters applied when parsing the
14225: log file. These can be start or end timestamps, or the type of action
14226: - log to look for Login or Logout events, check for Checkin or
14227: Checkout, role for role selection. The response is in the form
14228: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
14229: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 14230:
1.243 albertel 14231: =back
14232:
14233: =head2 User Roles
14234:
14235: =over 4
14236:
14237: =item *
14238:
1.1284 raeburn 14239: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14240: returns codes for allowed actions.
14241:
14242: The first argument is required, all others are optional.
14243:
14244: $priv is the privilege being checked.
14245: $uri contains additional information about what is being checked for access (e.g.,
14246: URL, course ID etc.).
14247: $symb is the unique resource instance identifier in a course; if needed,
14248: but not provided, it will be retrieved via a call to &symbread().
14249: $role is the role for which a priv is being checked (only used if priv is evb).
14250: $clientip is the user's IP address (only used when checking for access to portfolio
14251: files).
14252: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14253: prevents recursive calls to &allowed.
14254:
1.243 albertel 14255: F: full access
14256: U,I,K: authentication modes (cxx only)
14257: '': forbidden
14258: 1: user needs to choose course
14259: 2: browse allowed
1.766 albertel 14260: A: passphrase authentication needed
1.1284 raeburn 14261: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 14262:
14263: =item *
14264:
1.1192 raeburn 14265: constructaccess($url,$setpriv) : check for access to construction space URL
14266:
14267: See if the owner domain and name in the URL match those in the
14268: expected environment. If so, return three element list
14269: ($ownername,$ownerdomain,$ownerhome).
14270:
14271: Otherwise return the null string.
14272:
14273: If second argument 'setpriv' is true, it assigns the privileges,
14274: and returns the same three element list, unless the owner has
14275: blocked "ad hoc" Domain Coordinator access to the Author Space,
14276: in which case the null string is returned.
14277:
14278: =item *
14279:
1.1326 raeburn 14280: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14281: define a custom role rolename set privileges in format of lonTabs/roles.tab
14282: for system, domain, and course level. $uname and $udom are optional (current
14283: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 14284:
14285: =item *
14286:
1.988 raeburn 14287: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
14288: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 14289: $type is Course (default) or Community.
1.988 raeburn 14290: If $forcedefault evaluates to true, text returned will be default
14291: text for $type. Otherwise, if this is a course, the text returned
14292: will be a custom name for the role (if defined in the course's
14293: environment). If no custom name is defined the default is returned.
14294:
1.832 raeburn 14295: =item *
14296:
1.1219 raeburn 14297: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 14298: All arguments are optional. Returns a hash of a roles, either for
14299: co-author/assistant author roles for a user's Construction Space
1.906 albertel 14300: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 14301: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14302: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14303: For each key, value is set to colon-separated start and end times for
14304: the role. If no username and domain are specified, will default to
1.934 raeburn 14305: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 14306: of role statuses (active, future or previous), roles
14307: (e.g., cc,in, st etc.) and domains of the roles which can be used
14308: to restrict the list of roles reported. If no array ref is
14309: provided for types, will default to return only active roles.
1.834 albertel 14310:
1.1195 raeburn 14311: =item *
14312:
14313: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 14314: user: $uname:$udom has a role in the course: $cdom_$cnum.
14315:
14316: Additional optional arguments are: $type (if role checking is to be restricted
14317: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 14318: available roles) or future (roles available in the future), and
14319: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 14320: have active Domain Coordinator role in course's domain or in additional
14321: domains (specified in 'Domains to check for privileged users' in course
14322: environment -- set via: Course Settings -> Classlists and staff listing).
14323:
14324: =item *
14325:
14326: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14327: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14328: $possdomains and $possroles are optional array refs -- to domains to check and
14329: roles to check. If $possdomains is not specified, a dump will be done of the
14330: users' roles.db to check for a dc or su role in any domain. This can be
14331: time consuming if &privileged is called repeatedly (e.g., when displaying a
14332: classlist), so in such cases, supplying a $possdomains array is preferred, as
14333: this then allows &privileged_by_domain() to be used, which caches the identity
14334: of privileged users, eliminating the need for repeated calls to &dump().
14335:
14336: =item *
14337:
14338: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14339: where the outer hash keys are domains specified in the $possdomains array ref,
14340: next inner hash keys are privileged roles specified in the $roles array ref,
14341: and the innermost hash contains key = value pairs for username:domain = end:start
14342: for active or future "privileged" users with that role in that domain. To avoid
14343: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14344: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 14345:
1.243 albertel 14346: =back
14347:
14348: =head2 User Modification
14349:
14350: =over 4
14351:
14352: =item *
14353:
1.957 raeburn 14354: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 14355: user for the level given by URL. Optional start and end dates (leave empty
14356: string or zero for "no date")
1.191 harris41 14357:
14358: =item *
14359:
1.243 albertel 14360: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14361: change a users, password, possible return values are: ok,
14362: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14363: refused
1.191 harris41 14364:
14365: =item *
14366:
1.243 albertel 14367: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 14368:
14369: =item *
14370:
1.1058 raeburn 14371: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14372: $forceid,$desiredhome,$email,$inststatus,$candelete) :
14373:
14374: will update user information (firstname,middlename,lastname,generation,
14375: permanentemail), and if forceid is true, student/employee ID also.
14376: A user's institutional affiliation(s) can also be updated.
14377: User information fields will not be overwritten with empty entries
14378: unless the field is included in the $candelete array reference.
14379: This array is included when a single user is modified via "Manage Users",
14380: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 14381:
14382: =item *
14383:
1.286 matthew 14384: modifystudent
14385:
1.957 raeburn 14386: modify a student's enrollment and identification information.
1.1235 raeburn 14387: The course id is resolved based on the current user's environment.
14388: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 14389: associated with a course.
14390:
1.297 matthew 14391: This call is essentially a wrapper for lonnet::modifyuser and
14392: lonnet::modify_student_enrollment
1.286 matthew 14393:
14394: Inputs:
14395:
14396: =over 4
14397:
1.957 raeburn 14398: =item B<$udom> Student's loncapa domain
1.286 matthew 14399:
1.957 raeburn 14400: =item B<$uname> Student's loncapa login name
1.286 matthew 14401:
1.964 bisitz 14402: =item B<$uid> Student/Employee ID
1.286 matthew 14403:
1.957 raeburn 14404: =item B<$umode> Student's authentication mode
1.286 matthew 14405:
1.957 raeburn 14406: =item B<$upass> Student's password
1.286 matthew 14407:
1.957 raeburn 14408: =item B<$first> Student's first name
1.286 matthew 14409:
1.957 raeburn 14410: =item B<$middle> Student's middle name
1.286 matthew 14411:
1.957 raeburn 14412: =item B<$last> Student's last name
1.286 matthew 14413:
1.957 raeburn 14414: =item B<$gene> Student's generation
1.286 matthew 14415:
1.957 raeburn 14416: =item B<$usec> Student's section in course
1.286 matthew 14417:
14418: =item B<$end> Unix time of the roles expiration
14419:
14420: =item B<$start> Unix time of the roles start date
14421:
14422: =item B<$forceid> If defined, allow $uid to be changed
14423:
14424: =item B<$desiredhome> server to use as home server for student
14425:
1.957 raeburn 14426: =item B<$email> Student's permanent e-mail address
14427:
14428: =item B<$type> Type of enrollment (auto or manual)
14429:
1.963 raeburn 14430: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
14431:
14432: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 14433:
1.963 raeburn 14434: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 14435:
1.963 raeburn 14436: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 14437:
1.1216 raeburn 14438: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14439:
14440: =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 14441:
1.286 matthew 14442: =back
1.297 matthew 14443:
14444: =item *
14445:
14446: modify_student_enrollment
14447:
1.1235 raeburn 14448: Change a student's enrollment status in a class. The environment variable
1.297 matthew 14449: 'role.request.course' must be defined for this function to proceed.
14450:
14451: Inputs:
14452:
14453: =over 4
14454:
1.1235 raeburn 14455: =item $udom, student's domain
1.297 matthew 14456:
1.1235 raeburn 14457: =item $uname, student's name
1.297 matthew 14458:
1.1235 raeburn 14459: =item $uid, student's user id
1.297 matthew 14460:
1.1235 raeburn 14461: =item $first, student's first name
1.297 matthew 14462:
14463: =item $middle
14464:
14465: =item $last
14466:
14467: =item $gene
14468:
14469: =item $usec
14470:
14471: =item $end
14472:
14473: =item $start
14474:
1.957 raeburn 14475: =item $type
14476:
14477: =item $locktype
14478:
14479: =item $cid
14480:
14481: =item $selfenroll
14482:
14483: =item $context
14484:
1.1216 raeburn 14485: =item $credits, number of credits student will earn from this class
14486:
1.1314 raeburn 14487: =item $instsec, institutional course section code for student
14488:
1.297 matthew 14489: =back
14490:
1.191 harris41 14491:
14492: =item *
14493:
1.243 albertel 14494: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14495: custom role; give a custom role to a user for the level given by URL. Specify
14496: name and domain of role author, and role name
1.191 harris41 14497:
14498: =item *
14499:
1.243 albertel 14500: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 14501:
14502: =item *
14503:
1.243 albertel 14504: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14505:
14506: =back
14507:
14508: =head2 Course Infomation
14509:
14510: =over 4
1.191 harris41 14511:
14512: =item *
14513:
1.1118 foxr 14514: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 14515: specified course id, including all environment settings for the
14516: course, the description of the course will be in the hash under the
14517: key 'description'
1.191 harris41 14518:
1.1118 foxr 14519: $options is an optional parameter that if supplied is a hash reference that controls
14520: what how this function works. It has the following key/values:
14521:
14522: =over 4
14523:
14524: =item freshen_cache
14525:
14526: If defined, and the environment cache for the course is valid, it is
14527: returned in the returned hash.
14528:
14529: =item one_time
14530:
14531: If defined, the last cache time is set to _now_
14532:
14533: =item user
14534:
14535: If defined, the supplied username is used instead of the current user.
14536:
14537:
14538: =back
14539:
1.191 harris41 14540: =item *
14541:
1.624 albertel 14542: resdata($name,$domain,$type,@which) : request for current parameter
14543: setting for a specific $type, where $type is either 'course' or 'user',
14544: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 14545: answers for 10 minutes.
1.243 albertel 14546:
1.877 foxr 14547: =item *
14548:
14549: get_courseresdata($courseid, $domain) : dump the entire course resource
14550: data base, returning a hash that is keyed by the resource name and has
14551: values that are the resource value. I believe that the timestamps and
14552: versions are also returned.
14553:
1.1236 raeburn 14554: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14555: supplemental content area. This routine caches the number of files for
14556: 10 minutes.
14557:
1.243 albertel 14558: =back
14559:
14560: =head2 Course Modification
14561:
14562: =over 4
1.191 harris41 14563:
14564: =item *
14565:
1.243 albertel 14566: writecoursepref($courseid,%prefs) : write preferences (environment
14567: database) for a course
1.191 harris41 14568:
14569: =item *
14570:
1.1011 raeburn 14571: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14572:
14573: =item *
14574:
1.1038 raeburn 14575: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 14576:
1.1167 droeschl 14577: =item *
14578:
14579: is_course($courseid), is_course($cdom, $cnum)
14580:
14581: Accepts either a combined $courseid (in the form of domain_courseid) or the
14582: two component version $cdom, $cnum. It checks if the specified course exists.
14583:
14584: Returns:
14585: undef if the course doesn't exist, otherwise
14586: in scalar context the combined courseid.
14587: in list context the two components of the course identifier, domain and
14588: courseid.
14589:
1.243 albertel 14590: =back
14591:
14592: =head2 Resource Subroutines
14593:
14594: =over 4
1.191 harris41 14595:
14596: =item *
14597:
1.243 albertel 14598: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 14599:
14600: =item *
14601:
1.243 albertel 14602: repcopy($filename) : subscribes to the requested file, and attempts to
14603: replicate from the owning library server, Might return
1.607 raeburn 14604: 'unavailable', 'not_found', 'forbidden', 'ok', or
14605: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 14606: resource. Expects the local filesystem pathname
14607: (/home/httpd/html/res/....)
14608:
14609: =back
14610:
14611: =head2 Resource Information
14612:
14613: =over 4
1.191 harris41 14614:
14615: =item *
14616:
1.1228 raeburn 14617: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
14618: and returns the value of a variety of different possible values,
14619: $varname should be a request string, and the other parameters can be
14620: used to specify who and what one is asking about. Ordinarily, $cid
14621: does not need to be specified, as it is retrived from
14622: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14623: within lonuserstate::loadmap() when initializing a course, before
14624: $env{'request.course.id'} has been set, so it needs to be provided
14625: in that one case.
1.243 albertel 14626:
14627: Possible values for $varname are environment.lastname (or other item
14628: from the envirnment hash), user.name (or someother aspect about the
14629: user), resource.0.maxtries (or some other part and parameter of a
14630: resource)
1.204 albertel 14631:
14632: =item *
14633:
1.243 albertel 14634: directcondval($number) : get current value of a condition; reads from a state
14635: string
1.204 albertel 14636:
14637: =item *
14638:
1.243 albertel 14639: condval($condidx) : value of condition index based on state
1.204 albertel 14640:
14641: =item *
14642:
1.243 albertel 14643: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14644: resource's metadata, $what should be either a specific key, or either
14645: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14646: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14647:
14648: this function automatically caches all requests
1.191 harris41 14649:
14650: =item *
14651:
1.243 albertel 14652: metadata_query($query,$custom,$customshow) : make a metadata query against the
14653: network of library servers; returns file handle of where SQL and regex results
14654: will be stored for query
1.191 harris41 14655:
14656: =item *
14657:
1.1282 raeburn 14658: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14659: return symbolic list entry (all arguments optional).
14660:
14661: Args: filename is the filename (including path) for the file for which a symb
14662: is required; donotrecurse, if true will prevent calls to allowed() being made
14663: to check access status if more than one resource was found in the bighash
14664: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14665: a randompick); ignorecachednull, if true will prevent a symb of '' being
14666: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14667: cause possible symbs to be checked to determine if they are subject to content
14668: blocking, if so they will not be included as possible symbs; possibles is a
14669: ref to a hash, which, as a side effect, will be populated with all possible
14670: symbs (content blocking not tested).
14671:
1.243 albertel 14672: returns the data handle
1.191 harris41 14673:
14674: =item *
14675:
1.1190 raeburn 14676: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
14677: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 14678: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 14679: on failure, user must be in a course, as it assumes the existence of
14680: the course initial hash, and uses $env('request.course.id'}. The third
14681: arg is an optional reference to a scalar. If this arg is passed in the
14682: call to symbverify, it will be set to 1 if the symb has been set to be
14683: encrypted; otherwise it will be null.
1.191 harris41 14684:
14685: =item *
14686:
1.243 albertel 14687: symbclean($symb) : removes versions numbers from a symb, returns the
14688: cleaned symb
1.191 harris41 14689:
14690: =item *
14691:
1.243 albertel 14692: is_on_map($uri) : checks if the $uri is somewhere on the current
14693: course map, user must be in a course for it to work.
1.191 harris41 14694:
14695: =item *
14696:
1.243 albertel 14697: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 14698:
14699: =item *
14700:
1.243 albertel 14701: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14702: a random seed, all arguments are optional, if they aren't sent it uses the
14703: environment to derive them. Note: if symb isn't sent and it can't get one
14704: from &symbread it will use the current time as its return value
1.191 harris41 14705:
14706: =item *
14707:
1.243 albertel 14708: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14709: unfakeable, receipt
1.191 harris41 14710:
14711: =item *
14712:
1.620 albertel 14713: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 14714:
14715: =item *
14716:
1.243 albertel 14717: countacc($url) : count the number of accesses to a given URL
1.191 harris41 14718:
14719: =item *
14720:
1.243 albertel 14721: 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 14722:
14723: =item *
14724:
1.243 albertel 14725: 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 14726:
14727: =item *
14728:
1.243 albertel 14729: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 14730:
14731: =item *
14732:
1.243 albertel 14733: devalidate($symb) : devalidate temporary spreadsheet calculations,
14734: forcing spreadsheet to reevaluate the resource scores next time.
14735:
1.1195 raeburn 14736: =item *
14737:
1.1196 raeburn 14738: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14739: when viewing in course context.
1.1195 raeburn 14740:
1.1196 raeburn 14741: input: six args -- filename (decluttered), course number, course domain,
14742: url, symb (if registered) and group (if this is a
14743: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 14744:
1.1196 raeburn 14745: output: array of five scalars --
1.1195 raeburn 14746: $cfile -- url for file editing if editable on current server
14747: $home -- homeserver of resource (i.e., for author if published,
14748: or course if uploaded.).
14749: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 14750: $forceedit -- 1 if icon/link should be to go to edit mode
14751: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 14752:
14753: =item *
14754:
14755: is_course_upload($file,$cnum,$cdom)
14756:
14757: Used in course context to determine if current file was uploaded to
14758: the course (i.e., would be found in /userfiles/docs on the course's
14759: homeserver.
14760:
14761: input: 3 args -- filename (decluttered), course number and course domain.
14762: output: boolean -- 1 if file was uploaded.
14763:
1.243 albertel 14764: =back
14765:
14766: =head2 Storing/Retreiving Data
14767:
14768: =over 4
1.191 harris41 14769:
14770: =item *
14771:
1.1269 raeburn 14772: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14773: permanently for this url; hashref needs to be given and should be a \%hashname;
14774: the remaining args aren't required and if they aren't passed or are '' they will
14775: be derived from the env (with the exception of $laststore, which is an
14776: optional arg used when a user's submission is stored in grading).
14777: $laststore is $version=$timestamp, where $version is the most recent version
14778: number retrieved for the corresponding $symb in the $namespace db file, and
14779: $timestamp is the timestamp for that transaction (UNIX time).
14780: $laststore is currently only passed when cstore() is called by
14781: structuretags::finalize_storage().
1.191 harris41 14782:
14783: =item *
14784:
1.1269 raeburn 14785: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14786: but uses critical subroutine
1.191 harris41 14787:
14788: =item *
14789:
1.243 albertel 14790: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14791: all args are optional
1.191 harris41 14792:
14793: =item *
14794:
1.717 albertel 14795: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14796: dumps the complete (or key matching regexp) namespace into a hash
14797: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14798: normally &store()ed into
14799:
14800: $range should be either an integer '100' (give me the first 100
14801: matching records)
14802: or be two integers sperated by a - with no spaces
14803: '30-50' (give me the 30th through the 50th matching
14804: records)
14805:
14806:
14807: =item *
14808:
1.1269 raeburn 14809: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 14810: replaces a &store() version of data with a replacement set of data
14811: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 14812: reference. If $tolog is true, the transaction is logged in the courselog
14813: with an action=PUTSTORE.
1.717 albertel 14814:
14815: =item *
14816:
1.243 albertel 14817: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14818: works very similar to store/cstore, but all data is stored in a
14819: temporary location and can be reset using tmpreset, $storehash should
14820: be a hash reference, returns nothing on success
1.191 harris41 14821:
14822: =item *
14823:
1.243 albertel 14824: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14825: similar to restore, but all data is stored in a temporary location and
14826: can be reset using tmpreset. Returns a hash of values on success,
14827: error string otherwise.
1.191 harris41 14828:
14829: =item *
14830:
1.243 albertel 14831: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14832: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 14833:
14834: =item *
14835:
1.243 albertel 14836: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14837: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 14838:
14839: =item *
14840:
1.243 albertel 14841: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14842: namesp ($udom and $uname are optional)
1.191 harris41 14843:
14844: =item *
14845:
1.702 albertel 14846: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 14847: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 14848: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 14849:
1.702 albertel 14850: $range should be either an integer '100' (give me the first 100
14851: matching records)
14852: or be two integers sperated by a - with no spaces
14853: '30-50' (give me the 30th through the 50th matching
14854: records)
1.449 matthew 14855: =item *
14856:
14857: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14858: $store can be a scalar, an array reference, or if the amount to be
14859: incremented is > 1, a hash reference.
14860:
14861: ($udom and $uname are optional)
1.191 harris41 14862:
14863: =item *
14864:
1.243 albertel 14865: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14866: ($udom and $uname are optional)
1.191 harris41 14867:
14868: =item *
14869:
1.243 albertel 14870: cput($namespace,$storehash,$udom,$uname) : critical put
14871: ($udom and $uname are optional)
1.191 harris41 14872:
14873: =item *
14874:
1.748 albertel 14875: newput($namespace,$storehash,$udom,$uname) :
14876:
14877: Attempts to store the items in the $storehash, but only if they don't
14878: currently exist, if this succeeds you can be certain that you have
14879: successfully created a new key value pair in the $namespace db.
14880:
14881:
14882: Args:
14883: $namespace: name of database to store values to
14884: $storehash: hashref to store to the db
14885: $udom: (optional) domain of user containing the db
14886: $uname: (optional) name of user caontaining the db
14887:
14888: Returns:
14889: 'ok' -> succeeded in storing all keys of $storehash
14890: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14891: least <key> already existed in the db (other
14892: requested keys may also already exist)
1.967 bisitz 14893: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 14894: 'con_lost' -> unable to contact request server
14895: 'refused' -> action was not allowed by remote machine
14896:
14897:
14898: =item *
14899:
1.243 albertel 14900: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14901: reference filled in from namesp (encrypts the return communication)
14902: ($udom and $uname are optional)
1.191 harris41 14903:
14904: =item *
14905:
1.243 albertel 14906: log($udom,$name,$home,$message) : write to permanent log for user; use
14907: critical subroutine
14908:
1.806 raeburn 14909: =item *
14910:
1.860 raeburn 14911: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14912: array reference filled in from namespace found in domain level on either
14913: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 14914:
14915: =item *
14916:
1.860 raeburn 14917: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14918: domain level either on specified domain server ($uhome) or primary domain
14919: server ($udom and $uhome are optional)
1.806 raeburn 14920:
1.943 raeburn 14921: =item *
14922:
1.1240 raeburn 14923: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14924: for: authentication, language, quotas, timezone, date locale, and portal URL in
14925: the target domain.
14926:
14927: May also include additional key => value pairs for the following groups:
14928:
14929: =over
14930:
14931: =item
14932: disk quotas (MB allocated by default to portfolios and authoring spaces).
14933:
14934: =over
14935:
14936: =item defaultquota, authorquota
14937:
14938: =back
14939:
14940: =item
14941: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14942: portfolio for users).
14943:
14944: =over
14945:
14946: =item
14947: aboutme, blog, webdav, portfolio
14948:
14949: =back
14950:
14951: =item
14952: requestcourses: ability to request courses, and how requests are processed.
14953:
14954: =over
14955:
14956: =item
1.1305 raeburn 14957: official, unofficial, community, textbook, placement
1.1240 raeburn 14958:
14959: =back
14960:
14961: =item
14962: inststatus: types of institutional affiliation, and order in which they are displayed.
14963:
14964: =over
14965:
14966: =item
1.1256 raeburn 14967: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 14968:
14969: =back
14970:
14971: =item
14972: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14973: for course's uploaded content.
14974:
14975: =over
14976:
14977: =item
1.1246 raeburn 14978: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 14979: communityquota, textbookquota, placementquota
1.1240 raeburn 14980:
14981: =back
14982:
14983: =item
14984: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14985: on your servers.
14986:
14987: =over
14988:
14989: =item
14990: remotesessions, hostedsessions
14991:
14992: =back
14993:
14994: =back
14995:
14996: In cases where a domain coordinator has never used the "Set Domain Configuration"
14997: utility to create a configuration.db file on a domain's primary library server
14998: only the following domain defaults: auth_def, auth_arg_def, lang_def
14999: -- corresponding values are authentication type (internal, krb4, krb5,
15000: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
15001: will be available. Values are retrieved from cache (if current), unless the
15002: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15003: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15004:
15005: Typical usage:
1.943 raeburn 15006:
1.1240 raeburn 15007: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 15008:
1.243 albertel 15009: =back
15010:
15011: =head2 Network Status Functions
15012:
15013: =over 4
1.191 harris41 15014:
15015: =item *
15016:
1.1137 raeburn 15017: dirlist() : return directory list based on URI (first arg).
15018:
15019: Inputs: 1 required, 5 optional.
15020:
15021: =over
15022:
15023: =item
15024: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15025:
15026: =item
15027: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
15028:
15029: =item
15030: $username - username of user/course to be listed. Extracted from $uri if absent.
15031:
15032: =item
15033: $getpropath - boolean: 1 if prepend path using &propath().
15034:
15035: =item
15036: $getuserdir - boolean: 1 if prepend path for "userfiles".
15037:
15038: =item
15039: $alternateRoot - path to prepend in place of path from $uri.
15040:
15041: =back
15042:
15043: Returns: Array of up to two items.
15044:
15045: =over
15046:
15047: a reference to an array of files/subdirectories
15048:
15049: =over
15050:
15051: Each element in the array of files/subdirectories is a & separated list of
15052: item name and the result of running stat on the item. If dirlist was requested
15053: for a file instead of a directory, the item name will be ''. For a directory
15054: listing, if the item is a metadata file, the element will end &N&M
15055: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15056: default copyright set (1).
15057:
15058: =back
15059:
15060: a scalar containing error condition (if encountered).
15061:
15062: =over
15063:
15064: =item
15065: no_host (no homeserver identified for $username:$domain).
15066:
15067: =item
15068: no_such_host (server contacted for listing not identified as valid host).
15069:
15070: =item
15071: con_lost (connection to remote server failed).
15072:
15073: =item
15074: refused (invalid $username:$domain received on lond side).
15075:
15076: =item
15077: no_such_dir (directory at specified path on lond side does not exist).
15078:
15079: =item
15080: empty (directory at specified path on lond side is empty).
15081:
15082: =over
15083:
15084: This is currently not encountered because the &ls3, &ls2,
15085: &ls (_handler) routines on the lond side do not filter out
15086: . and .. from a directory listing.
15087:
15088: =back
15089:
15090: =back
15091:
15092: =back
1.191 harris41 15093:
15094: =item *
15095:
1.243 albertel 15096: spareserver() : find server with least workload from spare.tab
15097:
1.986 foxr 15098:
15099: =item *
15100:
15101: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15102: if there is no corresponding loncapa host.
15103:
1.243 albertel 15104: =back
15105:
1.986 foxr 15106:
1.243 albertel 15107: =head2 Apache Request
15108:
15109: =over 4
1.191 harris41 15110:
15111: =item *
15112:
1.243 albertel 15113: ssi($url,%hash) : server side include, does a complete request cycle on url to
15114: localhost, posts hash
15115:
15116: =back
15117:
15118: =head2 Data to String to Data
15119:
15120: =over 4
1.191 harris41 15121:
15122: =item *
15123:
1.243 albertel 15124: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15125: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 15126:
15127: =item *
15128:
1.243 albertel 15129: hashref2str($hashref) : convert a hashref into a string complete with
15130: escaping and '=' and '&' separators, supports elements that are
15131: arrayrefs and hashrefs
1.191 harris41 15132:
15133: =item *
15134:
1.243 albertel 15135: arrayref2str($arrayref) : convert an arrayref into a string complete
15136: with escaping and '&' separators, supports elements that are arrayrefs
15137: and hashrefs
1.191 harris41 15138:
15139: =item *
15140:
1.243 albertel 15141: str2hash($string) : convert string to hash using unescaping and
15142: splitting on '=' and '&', supports elements that are arrayrefs and
15143: hashrefs
1.191 harris41 15144:
15145: =item *
15146:
1.243 albertel 15147: str2array($string) : convert string to hash using unescaping and
15148: splitting on '&', supports elements that are arrayrefs and hashrefs
15149:
15150: =back
15151:
15152: =head2 Logging Routines
15153:
15154:
15155: These routines allow one to make log messages in the lonnet.log and
15156: lonnet.perm logfiles.
1.191 harris41 15157:
1.1119 foxr 15158: =over 4
15159:
1.191 harris41 15160: =item *
15161:
1.243 albertel 15162: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 15163:
15164: =item *
15165:
1.243 albertel 15166: logthis() : append message to the normal lonnet.log file, it gets
15167: preiodically rolled over and deleted.
1.191 harris41 15168:
15169: =item *
15170:
1.243 albertel 15171: logperm() : append a permanent message to lonnet.perm.log, this log
15172: file never gets deleted by any automated portion of the system, only
15173: messages of critical importance should go in here.
15174:
1.1119 foxr 15175:
1.243 albertel 15176: =back
15177:
15178: =head2 General File Helper Routines
15179:
15180: =over 4
1.191 harris41 15181:
15182: =item *
15183:
1.481 raeburn 15184: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15185: (a) files in /uploaded
15186: (i) If a local copy of the file exists -
15187: compares modification date of local copy with last-modified date for
15188: definitive version stored on home server for course. If local copy is
15189: stale, requests a new version from the home server and stores it.
15190: If the original has been removed from the home server, then local copy
15191: is unlinked.
15192: (ii) If local copy does not exist -
15193: requests the file from the home server and stores it.
15194:
15195: If $caller is 'uploadrep':
15196: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15197: for request for files originally uploaded via DOCS.
15198: - returns 'ok' if fresh local copy now available, -1 otherwise.
15199:
15200: Otherwise:
15201: This indicates a call from the content generation phase of the request.
15202: - returns the entire contents of the file or -1.
15203:
15204: (b) files in /res
15205: - returns the entire contents of a file or -1;
15206: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 15207:
1.712 albertel 15208:
15209: =item *
15210:
15211: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15212: reference
15213:
15214: returns either a stat() list of data about the file or an empty list
15215: if the file doesn't exist or couldn't find out about it (connection
15216: problems or user unknown)
15217:
1.191 harris41 15218: =item *
15219:
1.243 albertel 15220: filelocation($dir,$file) : returns file system location of a file
15221: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15222: directory that relative $file lookups are to looked in ($dir of /a/dir
15223: and a file of ../bob will become /a/bob)
1.191 harris41 15224:
15225: =item *
15226:
15227: hreflocation($dir,$file) : returns file system location or a URL; same as
15228: filelocation except for hrefs
15229:
15230: =item *
15231:
1.1261 raeburn 15232: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15233: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 15234:
1.243 albertel 15235: =back
15236:
1.608 albertel 15237: =head2 Usererfile file routines (/uploaded*)
15238:
15239: =over 4
15240:
15241: =item *
15242:
15243: userfileupload(): main rotine for putting a file in a user or course's
15244: filespace, arguments are,
15245:
1.620 albertel 15246: formname - required - this is the name of the element in $env where the
1.608 albertel 15247: filename, and the contents of the file to create/modifed exist
1.620 albertel 15248: the filename is in $env{'form.'.$formname.'.filename'} and the
15249: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 15250: context - if coursedoc, store the file in the course of the active role
15251: of the current user;
15252: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15253: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 15254: subdir - required - subdirectory to put the file in under ../userfiles/
15255: if undefined, it will be placed in "unknown"
15256:
15257: (This routine calls clean_filename() to remove any dangerous
15258: characters from the filename, and then calls finuserfileupload() to
15259: complete the transaction)
15260:
15261: returns either the url of the uploaded file (/uploaded/....) if successful
15262: and /adm/notfound.html if unsuccessful
15263:
15264: =item *
15265:
15266: clean_filename(): routine for cleaing a filename up for storage in
15267: userfile space, argument is:
15268:
15269: filename - proposed filename
15270:
15271: returns: the new clean filename
15272:
15273: =item *
15274:
1.1090 raeburn 15275: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 15276: userspace, probably shouldn't be called directly
15277:
15278: docuname: username or courseid of destination for the file
15279: docudom: domain of user/course of destination for the file
15280: formname: same as for userfileupload()
1.1090 raeburn 15281: fname: filename (including subdirectories) for the file
15282: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15283: allfiles: reference to hash used to store objects found by parser
15284: codebase: reference to hash used for codebases of java objects found by parser
15285: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15286: thumbheight: height (pixels) of thumbnail to be created for uploaded image
15287: resizewidth: width to be used to resize image using resizeImage from ImageMagick
15288: resizeheight: height to be used to resize image using resizeImage from ImageMagick
15289: context: if 'overwrite', will move the uploaded file from its temporary location to
15290: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 15291: mimetype: reference to scalar to accommodate mime type determined
15292: from File::MMagic if $parser = parse.
1.608 albertel 15293:
15294: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 15295: and /adm/notfound.html if unsuccessful (or an error message if context
15296: was 'overwrite').
15297:
1.608 albertel 15298:
15299: =item *
15300:
15301: renameuserfile(): renames an existing userfile to a new name
15302:
15303: Args:
15304: docuname: username or courseid of destination for the file
15305: docudom: domain of user/course of destination for the file
15306: old: current file name (including any subdirs under userfiles)
15307: new: desired file name (including any subdirs under userfiles)
15308:
15309: =item *
15310:
15311: mkdiruserfile(): creates a directory is a userfiles dir
15312:
15313: Args:
15314: docuname: username or courseid of destination for the file
15315: docudom: domain of user/course of destination for the file
15316: dir: dir to create (including any subdirs under userfiles)
15317:
15318: =item *
15319:
15320: removeuserfile(): removes a file that exists in userfiles
15321:
15322: Args:
15323: docuname: username or courseid of destination for the file
15324: docudom: domain of user/course of destination for the file
15325: fname: filname to delete (including any subdirs under userfiles)
15326:
15327: =item *
15328:
15329: removeuploadedurl(): convience function for removeuserfile()
15330:
15331: Args:
15332: url: a full /uploaded/... url to delete
15333:
1.747 albertel 15334: =item *
15335:
15336: get_portfile_permissions():
15337: Args:
15338: domain: domain of user or course contain the portfolio files
15339: user: name of user or num of course contain the portfolio files
15340: Returns:
15341: hashref of a dump of the proper file_permissions.db
15342:
15343:
15344: =item *
15345:
15346: get_access_controls():
15347:
15348: Args:
15349: current_permissions: the hash ref returned from get_portfile_permissions()
15350: group: (optional) the group you want the files associated with
15351: file: (optional) the file you want access info on
15352:
15353: Returns:
1.749 raeburn 15354: a hash (keys are file names) of hashes containing
15355: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15356: values are XML containing access control settings (see below)
1.747 albertel 15357:
15358: Internal notes:
15359:
1.749 raeburn 15360: access controls are stored in file_permissions.db as key=value pairs.
15361: key -> path to file/file_name\0uniqueID:scope_end_start
15362: where scope -> public,guest,course,group,domains or users.
15363: end -> UNIX time for end of access (0 -> no end date)
15364: start -> UNIX time for start of access
15365:
15366: value -> XML description of access control
15367: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15368: <start></start>
15369: <end></end>
15370:
15371: <password></password> for scope type = guest
15372:
15373: <domain></domain> for scope type = course or group
15374: <number></number>
15375: <roles id="">
15376: <role></role>
15377: <access></access>
15378: <section></section>
15379: <group></group>
15380: </roles>
15381:
15382: <dom></dom> for scope type = domains
15383:
15384: <users> for scope type = users
15385: <user>
15386: <uname></uname>
15387: <udom></udom>
15388: </user>
15389: </users>
15390: </scope>
15391:
15392: Access data is also aggregated for each file in an additional key=value pair:
15393: key -> path to file/file_name\0accesscontrol
15394: value -> reference to hash
15395: hash contains key = value pairs
15396: where key = uniqueID:scope_end_start
15397: value = UNIX time record was last updated
15398:
15399: Used to improve speed of look-ups of access controls for each file.
15400:
15401: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15402:
1.1198 raeburn 15403: =item *
15404:
1.749 raeburn 15405: modify_access_controls():
15406:
15407: Modifies access controls for a portfolio file
15408: Args
15409: 1. file name
15410: 2. reference to hash of required changes,
15411: 3. domain
15412: 4. username
15413: where domain,username are the domain of the portfolio owner
15414: (either a user or a course)
15415:
15416: Returns:
15417: 1. result of additions or updates ('ok' or 'error', with error message).
15418: 2. result of deletions ('ok' or 'error', with error message).
15419: 3. reference to hash of any new or updated access controls.
15420: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15421: key = integer (inbound ID)
1.1198 raeburn 15422: value = uniqueID
15423:
15424: =item *
15425:
15426: get_timebased_id():
15427:
15428: Attempts to get a unique timestamp-based suffix for use with items added to a
15429: course via the Course Editor (e.g., folders, composite pages,
15430: group bulletin boards).
15431:
15432: Args: (first three required; six others optional)
15433:
15434: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15435: docssequence, or name of group
15436:
15437: 2. keyid (alphanumeric): name of temporary locking key in hash,
15438: e.g., num, boardids
15439:
15440: 3. namespace: name of gdbm file used to store suffixes already assigned;
15441: file will be named nohist_namespace.db
15442:
15443: 4. cdom: domain of course; default is current course domain from %env
15444:
15445: 5. cnum: course number; default is current course number from %env
15446:
15447: 6. idtype: set to concat if an additional digit is to be appended to the
15448: unix timestamp to form the suffix, if the plain timestamp is already
15449: in use. Default is to not do this, but simply increment the unix
15450: timestamp by 1 until a unique key is obtained.
15451:
15452: 7. who: holder of locking key; defaults to user:domain for user.
15453:
15454: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15455: retrying); default is 3.
15456:
15457: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15458:
15459: Returns:
15460:
15461: 1. suffix obtained (numeric)
15462:
15463: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15464:
15465: 3. error: contains (localized) error message if an error occurred.
15466:
1.747 albertel 15467:
1.608 albertel 15468: =back
15469:
1.243 albertel 15470: =head2 HTTP Helper Routines
15471:
15472: =over 4
15473:
1.191 harris41 15474: =item *
15475:
15476: escape() : unpack non-word characters into CGI-compatible hex codes
15477:
15478: =item *
15479:
15480: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15481:
1.243 albertel 15482: =back
15483:
15484: =head1 PRIVATE SUBROUTINES
15485:
15486: =head2 Underlying communication routines (Shouldn't call)
15487:
15488: =over 4
15489:
15490: =item *
15491:
15492: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15493:
15494: =item *
15495:
15496: reply() : uses subreply to send a message to remote machine, logs all failures
15497:
15498: =item *
15499:
15500: critical() : passes a critical message to another server; if cannot
15501: get through then place message in connection buffer directory and
15502: returns con_delayed, if incapable of saving message, returns
15503: con_failed
15504:
15505: =item *
15506:
15507: reconlonc() : tries to reconnect lonc client processes.
15508:
15509: =back
15510:
15511: =head2 Resource Access Logging
15512:
15513: =over 4
15514:
15515: =item *
15516:
15517: flushcourselogs() : flush (save) buffer logs and access logs
15518:
15519: =item *
15520:
15521: courselog($what) : save message for course in hash
15522:
15523: =item *
15524:
15525: courseacclog($what) : save message for course using &courselog(). Perform
15526: special processing for specific resource types (problems, exams, quizzes, etc).
15527:
1.191 harris41 15528: =item *
15529:
15530: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15531: as a PerlChildExitHandler
1.243 albertel 15532:
15533: =back
15534:
15535: =head2 Other
15536:
15537: =over 4
15538:
15539: =item *
15540:
15541: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 15542:
15543: =back
15544:
15545: =cut
1.877 foxr 15546:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>