Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1354
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1354 ! raeburn 4: # $Id: lonnet.pm,v 1.1353 2017/08/27 13:48:52 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.486 www 74: use HTTP::Date;
1.977 amueller 75: use Image::Magick;
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.1245 raeburn 653: my ($r,$name,$userhashref) = @_;
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.916 albertel 681: return undef if (!-e "$lonidsdir/$handle.id");
682:
1.917 albertel 683: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
684: return undef if (!$opened);
1.916 albertel 685:
686: flock($idf,LOCK_SH);
687: my %disk_env;
688: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
689: &GDBM_READER(),0640)) {
690: return undef;
691: }
692:
693: if (!defined($disk_env{'user.name'})
694: || !defined($disk_env{'user.domain'})) {
695: return undef;
696: }
1.1245 raeburn 697:
698: if (ref($userhashref) eq 'HASH') {
699: $userhashref->{'name'} = $disk_env{'user.name'};
700: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212 raeburn 701: }
1.1245 raeburn 702:
1.916 albertel 703: return $handle;
704: }
705:
1.830 albertel 706: sub timed_flock {
707: my ($file,$lock_type) = @_;
708: my $failed=0;
709: eval {
710: local $SIG{__DIE__}='DEFAULT';
711: local $SIG{ALRM}=sub {
712: $failed=1;
713: die("failed lock");
714: };
715: alarm(13);
716: flock($file,$lock_type);
717: alarm(0);
718: };
719: if ($failed) {
720: return undef;
721: } else {
722: return 1;
723: }
724: }
725:
1.5 www 726: # ---------------------------------------------------------- Append Environment
727:
728: sub appenv {
1.949 raeburn 729: my ($newenv,$roles) = @_;
730: if (ref($newenv) eq 'HASH') {
731: foreach my $key (keys(%{$newenv})) {
732: my $refused = 0;
733: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
734: $refused = 1;
735: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 736: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 737: if (grep(/^\Q$role\E$/,@{$roles})) {
738: $refused = 0;
739: }
740: }
741: }
742: if ($refused) {
743: &logthis("<font color=\"blue\">WARNING: ".
744: "Attempt to modify environment ".$key." to ".$newenv->{$key}
745: .'</font>');
746: delete($newenv->{$key});
747: } else {
748: $env{$key}=$newenv->{$key};
749: }
750: }
751: my $opened = open(my $env_file,'+<',$env{'user.environment'});
752: if ($opened
753: && &timed_flock($env_file,LOCK_EX)
754: &&
755: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
756: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
757: while (my ($key,$value) = each(%{$newenv})) {
758: $disk_env{$key} = $value;
759: }
760: untie(%disk_env);
1.35 www 761: }
1.191 harris41 762: }
1.56 www 763: return 'ok';
764: }
765: # ----------------------------------------------------- Delete from Environment
766:
767: sub delenv {
1.1104 raeburn 768: my ($delthis,$regexp,$roles) = @_;
769: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
770: my $refused = 1;
771: if (ref($roles) eq 'ARRAY') {
772: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
773: if (grep(/^\Q$role\E$/,@{$roles})) {
774: $refused = 0;
775: }
776: }
777: if ($refused) {
778: &logthis("<font color=\"blue\">WARNING: ".
779: "Attempt to delete from environment ".$delthis);
780: return 'error';
781: }
1.56 www 782: }
1.917 albertel 783: my $opened = open(my $env_file,'+<',$env{'user.environment'});
784: if ($opened
1.915 albertel 785: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 786: &&
787: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
788: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 789: foreach my $key (keys(%disk_env)) {
1.987 raeburn 790: if ($regexp) {
791: if ($key=~/^$delthis/) {
792: delete($env{$key});
793: delete($disk_env{$key});
794: }
795: } else {
796: if ($key=~/^\Q$delthis\E/) {
797: delete($env{$key});
798: delete($disk_env{$key});
799: }
800: }
1.448 albertel 801: }
1.783 albertel 802: untie(%disk_env);
1.5 www 803: }
804: return 'ok';
1.369 albertel 805: }
806:
1.790 albertel 807: sub get_env_multiple {
808: my ($name) = @_;
809: my @values;
810: if (defined($env{$name})) {
811: # exists is it an array
812: if (ref($env{$name})) {
813: @values=@{ $env{$name} };
814: } else {
815: $values[0]=$env{$name};
816: }
817: }
818: return(@values);
819: }
820:
1.958 www 821: # ------------------------------------------------------------------- Locking
822:
823: sub set_lock {
824: my ($text)=@_;
825: $locknum++;
826: my $id=$$.'-'.$locknum;
827: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
828: 'session.lock.'.$id => $text});
829: return $id;
830: }
831:
832: sub get_locks {
833: my $num=0;
834: my %texts=();
835: foreach my $lock (split(/\,/,$env{'session.locks'})) {
836: if ($lock=~/\w/) {
837: $num++;
838: $texts{$lock}=$env{'session.lock.'.$lock};
839: }
840: }
841: return ($num,%texts);
842: }
843:
844: sub remove_lock {
845: my ($id)=@_;
846: my $newlocks='';
847: foreach my $lock (split(/\,/,$env{'session.locks'})) {
848: if (($lock=~/\w/) && ($lock ne $id)) {
849: $newlocks.=','.$lock;
850: }
851: }
852: &appenv({'session.locks' => $newlocks});
853: &delenv('session.lock.'.$id);
854: }
855:
856: sub remove_all_locks {
857: my $activelocks=$env{'session.locks'};
858: foreach my $lock (split(/\,/,$env{'session.locks'})) {
859: if ($lock=~/\w/) {
860: &remove_lock($lock);
861: }
862: }
863: }
864:
865:
1.369 albertel 866: # ------------------------------------------ Find out current server userload
867: sub userload {
868: my $numusers=0;
869: {
870: opendir(LONIDS,$perlvar{'lonIDsDir'});
871: my $filename;
872: my $curtime=time;
873: while ($filename=readdir(LONIDS)) {
1.925 albertel 874: next if ($filename eq '.' || $filename eq '..');
875: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 876: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 877: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 878: }
879: closedir(LONIDS);
880: }
881: my $userloadpercent=0;
882: my $maxuserload=$perlvar{'lonUserLoadLim'};
883: if ($maxuserload) {
1.371 albertel 884: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 885: }
1.372 albertel 886: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 887: return $userloadpercent;
1.283 www 888: }
889:
1.1 albertel 890: # ------------------------------ Find server with least workload from spare.tab
1.11 www 891:
1.1 albertel 892: sub spareserver {
1.1083 raeburn 893: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 894: my $spare_server;
1.370 albertel 895: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 896: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
897: : $userloadpercent;
1.1083 raeburn 898: my ($uint_dom,$remotesessions);
899: if (($udom ne '') && (&domain($udom) ne '')) {
900: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
901: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
902: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
903: $remotesessions = $udomdefaults{'remotesessions'};
904: }
1.1123 raeburn 905: my $spareshash = &this_host_spares($udom);
906: if (ref($spareshash) eq 'HASH') {
907: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
908: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279 raeburn 909: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
910: $try_server));
1.1123 raeburn 911: ($spare_server, $lowest_load) =
912: &compare_server_load($try_server, $spare_server, $lowest_load);
913: }
1.1083 raeburn 914: }
1.784 albertel 915:
1.1123 raeburn 916: my $found_server = ($spare_server ne '' && $lowest_load < 100);
917:
918: if (!$found_server) {
919: if (ref($spareshash->{'default'}) eq 'ARRAY') {
920: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279 raeburn 921: next unless (&spare_can_host($udom,$uint_dom,
922: $remotesessions,$try_server));
1.1123 raeburn 923: ($spare_server, $lowest_load) =
924: &compare_server_load($try_server, $spare_server, $lowest_load);
925: }
926: }
927: }
1.784 albertel 928: }
929:
930: if (!$want_server_name) {
1.968 raeburn 931: my $protocol = 'http';
932: if ($protocol{$spare_server} eq 'https') {
933: $protocol = $protocol{$spare_server};
934: }
1.1001 raeburn 935: if (defined($spare_server)) {
936: my $hostname = &hostname($spare_server);
1.1083 raeburn 937: if (defined($hostname)) {
1.1001 raeburn 938: $spare_server = $protocol.'://'.$hostname;
939: }
940: }
1.784 albertel 941: }
942: return $spare_server;
943: }
944:
945: sub compare_server_load {
1.1253 raeburn 946: my ($try_server, $spare_server, $lowest_load, $required) = @_;
947:
948: if ($required) {
949: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
950: my $remoterev = &get_server_loncaparev(undef,$try_server);
951: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
952: if (($major eq '' && $minor eq '') ||
953: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
954: return ($spare_server,$lowest_load);
955: }
956: }
1.784 albertel 957:
958: my $loadans = &reply('load', $try_server);
959: my $userloadans = &reply('userload',$try_server);
960:
961: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 962: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 963: }
964:
965: my $load;
966: if ($loadans =~ /\d/) {
967: if ($userloadans =~ /\d/) {
968: #both are numbers, pick the bigger one
969: $load = ($loadans > $userloadans) ? $loadans
970: : $userloadans;
1.411 albertel 971: } else {
1.784 albertel 972: $load = $loadans;
1.411 albertel 973: }
1.784 albertel 974: } else {
975: $load = $userloadans;
976: }
977:
978: if (($load =~ /\d/) && ($load < $lowest_load)) {
979: $spare_server = $try_server;
980: $lowest_load = $load;
1.370 albertel 981: }
1.784 albertel 982: return ($spare_server,$lowest_load);
1.202 matthew 983: }
1.914 albertel 984:
985: # --------------------------- ask offload servers if user already has a session
986: sub find_existing_session {
987: my ($udom,$uname) = @_;
1.1123 raeburn 988: my $spareshash = &this_host_spares($udom);
989: if (ref($spareshash) eq 'HASH') {
990: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
991: foreach my $try_server (@{ $spareshash->{'primary'} }) {
992: return $try_server if (&has_user_session($try_server, $udom, $uname));
993: }
994: }
995: if (ref($spareshash->{'default'}) eq 'ARRAY') {
996: foreach my $try_server (@{ $spareshash->{'default'} }) {
997: return $try_server if (&has_user_session($try_server, $udom, $uname));
998: }
999: }
1.914 albertel 1000: }
1001: return;
1002: }
1003:
1004: # -------------------------------- ask if server already has a session for user
1005: sub has_user_session {
1006: my ($lonid,$udom,$uname) = @_;
1007: my $result = &reply(join(':','userhassession',
1008: map {&escape($_)} ($udom,$uname)),$lonid);
1009: return 1 if ($result eq 'ok');
1010:
1011: return 0;
1012: }
1013:
1.1076 raeburn 1014: # --------- determine least loaded server in a user's domain which allows login
1015:
1016: sub choose_server {
1.1259 raeburn 1017: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1018: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1019: my %servers = &get_servers($udom);
1.1076 raeburn 1020: my $lowest_load = 30000;
1.1259 raeburn 1021: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1022: if ($skiploadbal) {
1023: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1024: unless (defined($cached)) {
1025: my $cachetime = 60*60*24;
1026: my %domconfig =
1027: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1028: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1029: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1030: $cachetime);
1031: }
1032: }
1033: }
1.1076 raeburn 1034: foreach my $lonhost (keys(%servers)) {
1.1259 raeburn 1035: if ($skiploadbal) {
1036: if (ref($balancers) eq 'HASH') {
1037: next if (exists($balancers->{$lonhost}));
1038: }
1039: }
1.1115 raeburn 1040: my $loginvia;
1041: if ($checkloginvia) {
1042: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1043: if ($loginvia) {
1044: my ($server,$path) = split(/:/,$loginvia);
1045: ($login_host, $lowest_load) =
1.1253 raeburn 1046: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1047: if ($login_host eq $server) {
1048: $portal_path = $path;
1.1151 raeburn 1049: $isredirect = 1;
1.1116 raeburn 1050: }
1051: } else {
1052: ($login_host, $lowest_load) =
1.1253 raeburn 1053: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1054: if ($login_host eq $lonhost) {
1055: $portal_path = '';
1.1151 raeburn 1056: $isredirect = '';
1.1116 raeburn 1057: }
1058: }
1059: } else {
1.1076 raeburn 1060: ($login_host, $lowest_load) =
1.1253 raeburn 1061: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1062: }
1063: }
1064: if ($login_host ne '') {
1.1116 raeburn 1065: $hostname = &hostname($login_host);
1.1076 raeburn 1066: }
1.1331 raeburn 1067: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1068: }
1069:
1.202 matthew 1070: # --------------------------------------------- Try to change a user's password
1071:
1072: sub changepass {
1.799 raeburn 1073: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1074: $currentpass = &escape($currentpass);
1075: $newpass = &escape($newpass);
1.1030 raeburn 1076: my $lonhost = $perlvar{'lonHostID'};
1077: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1078: $server);
1079: if (! $answer) {
1080: &logthis("No reply on password change request to $server ".
1081: "by $uname in domain $udom.");
1082: } elsif ($answer =~ "^ok") {
1083: &logthis("$uname in $udom successfully changed their password ".
1084: "on $server.");
1085: } elsif ($answer =~ "^pwchange_failure") {
1086: &logthis("$uname in $udom was unable to change their password ".
1087: "on $server. The action was blocked by either lcpasswd ".
1088: "or pwchange");
1089: } elsif ($answer =~ "^non_authorized") {
1090: &logthis("$uname in $udom did not get their password correct when ".
1091: "attempting to change it on $server.");
1092: } elsif ($answer =~ "^auth_mode_error") {
1093: &logthis("$uname in $udom attempted to change their password despite ".
1094: "not being locally or internally authenticated on $server.");
1095: } elsif ($answer =~ "^unknown_user") {
1096: &logthis("$uname in $udom attempted to change their password ".
1097: "on $server but were unable to because $server is not ".
1098: "their home server.");
1099: } elsif ($answer =~ "^refused") {
1100: &logthis("$server refused to change $uname in $udom password because ".
1101: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1102: } elsif ($answer =~ "invalid_client") {
1103: &logthis("$server refused to change $uname in $udom password because ".
1104: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1105: }
1106: return $answer;
1.1 albertel 1107: }
1108:
1.169 harris41 1109: # ----------------------- Try to determine user's current authentication scheme
1110:
1111: sub queryauthenticate {
1112: my ($uname,$udom)=@_;
1.456 albertel 1113: my $uhome=&homeserver($uname,$udom);
1114: if (!$uhome) {
1115: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1116: return 'no_host';
1117: }
1118: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1119: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1120: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1121: }
1.456 albertel 1122: return $answer;
1.169 harris41 1123: }
1124:
1.1 albertel 1125: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1126:
1.1 albertel 1127: sub authenticate {
1.1073 raeburn 1128: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1129: $upass=&escape($upass);
1130: $uname= &LONCAPA::clean_username($uname);
1.836 www 1131: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1132: my $newhome;
1.836 www 1133: if ((!$uhome) || ($uhome eq 'no_host')) {
1134: # Maybe the machine was offline and only re-appeared again recently?
1135: &reconlonc();
1136: # One more
1.952 raeburn 1137: $uhome=&homeserver($uname,$udom,1);
1138: if (($uhome eq 'no_host') && $checkdefauth) {
1139: if (defined(&domain($udom,'primary'))) {
1140: $newhome=&domain($udom,'primary');
1141: }
1142: if ($newhome ne '') {
1143: $uhome = $newhome;
1144: }
1145: }
1.836 www 1146: if ((!$uhome) || ($uhome eq 'no_host')) {
1147: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1148: return 'no_host';
1149: }
1.1 albertel 1150: }
1.1073 raeburn 1151: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1152: if ($answer eq 'authorized') {
1.952 raeburn 1153: if ($newhome) {
1154: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1155: return 'no_account_on_host';
1156: } else {
1157: &logthis("User $uname at $udom authorized by $uhome");
1158: return $uhome;
1159: }
1.471 albertel 1160: }
1161: if ($answer eq 'non_authorized') {
1162: &logthis("User $uname at $udom rejected by $uhome");
1163: return 'no_host';
1.9 www 1164: }
1.471 albertel 1165: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1166: return 'no_host';
1167: }
1168:
1.1073 raeburn 1169: sub can_host_session {
1.1074 raeburn 1170: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1171: my $canhost = 1;
1.1074 raeburn 1172: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1173: if (ref($remotesessions) eq 'HASH') {
1174: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1175: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1176: $canhost = 0;
1177: } else {
1178: $canhost = 1;
1179: }
1180: }
1181: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1182: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1183: $canhost = 1;
1184: } else {
1185: $canhost = 0;
1186: }
1187: }
1188: if ($canhost) {
1189: if ($remotesessions->{'version'} ne '') {
1190: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1191: if ($reqmajor ne '' && $reqminor ne '') {
1192: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1193: my $major = $1;
1194: my $minor = $2;
1195: if (($major < $reqmajor ) ||
1196: (($major == $reqmajor) && ($minor < $reqminor))) {
1197: $canhost = 0;
1198: }
1199: } else {
1200: $canhost = 0;
1201: }
1202: }
1203: }
1204: }
1205: }
1206: if ($canhost) {
1207: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1208: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1209: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1210: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1211: if (($uint_dom ne '') &&
1212: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1213: $canhost = 0;
1214: } else {
1215: $canhost = 1;
1216: }
1217: }
1218: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1219: if (($uint_dom ne '') &&
1220: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1221: $canhost = 1;
1222: } else {
1223: $canhost = 0;
1224: }
1225: }
1226: }
1227: }
1228: return $canhost;
1229: }
1230:
1.1083 raeburn 1231: sub spare_can_host {
1232: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1233: my $canhost=1;
1.1279 raeburn 1234: my $try_server_hostname = &hostname($try_server);
1235: my $serverhomeID = &get_server_homeID($try_server_hostname);
1236: my $serverhomedom = &host_domain($serverhomeID);
1237: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1238: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1239: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1240: $canhost = 0;
1241: }
1242: }
1243: if (($canhost) && ($uint_dom)) {
1244: my @intdoms;
1245: my $internet_names = &get_internet_names($try_server);
1246: if (ref($internet_names) eq 'ARRAY') {
1247: @intdoms = @{$internet_names};
1248: }
1249: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1250: my $remoterev = &get_server_loncaparev(undef,$try_server);
1251: $canhost = &can_host_session($udom,$try_server,$remoterev,
1252: $remotesessions,
1253: $defdomdefaults{'hostedsessions'});
1254: }
1.1083 raeburn 1255: }
1256: return $canhost;
1257: }
1258:
1.1123 raeburn 1259: sub this_host_spares {
1260: my ($dom) = @_;
1.1126 raeburn 1261: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1262: my @hosts = ¤t_machine_ids();
1263: foreach my $lonhost (@hosts) {
1264: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1265: $dom_in_use = $dom;
1266: $lonhost_in_use = $lonhost;
1.1123 raeburn 1267: last;
1268: }
1269: }
1.1126 raeburn 1270: if ($dom_in_use ne '') {
1271: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1272: }
1273: if (ref($result) ne 'HASH') {
1274: $lonhost_in_use = $perlvar{'lonHostID'};
1275: $dom_in_use = &host_domain($lonhost_in_use);
1276: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1277: if (ref($result) ne 'HASH') {
1278: $result = \%spareid;
1279: }
1280: }
1281: return $result;
1282: }
1283:
1284: sub spares_for_offload {
1285: my ($dom_in_use,$lonhost_in_use) = @_;
1286: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1287: if (defined($cached)) {
1288: return $result;
1289: } else {
1.1126 raeburn 1290: my $cachetime = 60*60*24;
1291: my %domconfig =
1292: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1293: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1294: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1295: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1296: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1297: }
1298: }
1299: }
1300: }
1.1126 raeburn 1301: return;
1.1123 raeburn 1302: }
1303:
1.1129 raeburn 1304: sub get_lonbalancer_config {
1305: my ($servers) = @_;
1306: my ($currbalancer,$currtargets);
1307: if (ref($servers) eq 'HASH') {
1308: foreach my $server (keys(%{$servers})) {
1309: my %what = (
1310: spareid => 1,
1311: perlvar => 1,
1312: );
1313: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1314: if ($result eq 'ok') {
1315: if (ref($returnhash) eq 'HASH') {
1316: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1317: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1318: $currbalancer = $server;
1319: $currtargets = {};
1320: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1321: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1322: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1323: }
1324: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1325: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1326: }
1327: }
1328: last;
1329: }
1330: }
1331: }
1332: }
1333: }
1334: }
1335: return ($currbalancer,$currtargets);
1336: }
1337:
1338: sub check_loadbalancing {
1.1331 raeburn 1339: my ($uname,$udom,$caller) = @_;
1.1191 raeburn 1340: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1341: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1342: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1343: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1344: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1345: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1346: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1347: my $serverhomedom = &host_domain($lonhost);
1.1307 raeburn 1348: my $domneedscache;
1.1129 raeburn 1349: my $cachetime = 60*60*24;
1350:
1351: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1352: $dom_in_use = $udom;
1353: $homeintdom = 1;
1354: } else {
1355: $dom_in_use = $serverhomedom;
1356: }
1357: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1358: unless (defined($cached)) {
1359: my %domconfig =
1360: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1361: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1362: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307 raeburn 1363: } else {
1364: $domneedscache = $dom_in_use;
1.1129 raeburn 1365: }
1366: }
1367: if (ref($result) eq 'HASH') {
1.1191 raeburn 1368: ($is_balancer,$currtargets,$currrules) =
1369: &check_balancer_result($result,@hosts);
1.1129 raeburn 1370: if ($is_balancer) {
1371: if (ref($currrules) eq 'HASH') {
1372: if ($homeintdom) {
1373: if ($uname ne '') {
1374: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1375: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1376: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1377: $rule_in_effect = $currrules->{'_LC_author'};
1378: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1379: $rule_in_effect = $currrules->{'_LC_adv'}
1380: }
1381: }
1382: if ($rule_in_effect eq '') {
1383: my %userenv = &userenvironment($udom,$uname,'inststatus');
1384: if ($userenv{'inststatus'} ne '') {
1385: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1386: my ($othertitle,$usertypes,$types) =
1387: &Apache::loncommon::sorted_inst_types($udom);
1388: if (ref($types) eq 'ARRAY') {
1389: foreach my $type (@{$types}) {
1390: if (grep(/^\Q$type\E$/,@statuses)) {
1391: if (exists($currrules->{$type})) {
1392: $rule_in_effect = $currrules->{$type};
1393: }
1394: }
1395: }
1396: }
1397: } else {
1398: if (exists($currrules->{'default'})) {
1399: $rule_in_effect = $currrules->{'default'};
1400: }
1401: }
1402: }
1403: } else {
1404: if (exists($currrules->{'default'})) {
1405: $rule_in_effect = $currrules->{'default'};
1406: }
1407: }
1408: } else {
1409: if ($currrules->{'_LC_external'} ne '') {
1410: $rule_in_effect = $currrules->{'_LC_external'};
1411: }
1412: }
1413: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1414: $uname,$udom);
1415: }
1416: }
1417: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1418: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1419: unless (defined($cached)) {
1420: my %domconfig =
1421: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1422: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307 raeburn 1423: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1424: } else {
1425: $domneedscache = $serverhomedom;
1.1129 raeburn 1426: }
1427: }
1428: if (ref($result) eq 'HASH') {
1.1191 raeburn 1429: ($is_balancer,$currtargets,$currrules) =
1430: &check_balancer_result($result,@hosts);
1431: if ($is_balancer) {
1.1129 raeburn 1432: if (ref($currrules) eq 'HASH') {
1433: if ($currrules->{'_LC_internetdom'} ne '') {
1434: $rule_in_effect = $currrules->{'_LC_internetdom'};
1435: }
1436: }
1437: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1438: $uname,$udom);
1439: }
1440: } else {
1441: if ($perlvar{'lonBalancer'} eq 'yes') {
1442: $is_balancer = 1;
1443: $offloadto = &this_host_spares($dom_in_use);
1444: }
1.1307 raeburn 1445: unless (defined($cached)) {
1446: $domneedscache = $serverhomedom;
1447: }
1.1129 raeburn 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: }
1457: }
1458: if ($domneedscache) {
1459: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1460: }
1.1176 raeburn 1461: if ($is_balancer) {
1462: my $lowest_load = 30000;
1463: if (ref($offloadto) eq 'HASH') {
1464: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1465: foreach my $try_server (@{$offloadto->{'primary'}}) {
1466: ($otherserver,$lowest_load) =
1467: &compare_server_load($try_server,$otherserver,$lowest_load);
1468: }
1.1129 raeburn 1469: }
1.1176 raeburn 1470: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1471:
1.1176 raeburn 1472: if (!$found_server) {
1473: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1474: foreach my $try_server (@{$offloadto->{'default'}}) {
1475: ($otherserver,$lowest_load) =
1476: &compare_server_load($try_server,$otherserver,$lowest_load);
1477: }
1478: }
1479: }
1480: } elsif (ref($offloadto) eq 'ARRAY') {
1481: if (@{$offloadto} == 1) {
1482: $otherserver = $offloadto->[0];
1483: } elsif (@{$offloadto} > 1) {
1484: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1485: ($otherserver,$lowest_load) =
1486: &compare_server_load($try_server,$otherserver,$lowest_load);
1487: }
1488: }
1489: }
1.1331 raeburn 1490: unless ($caller eq 'login') {
1491: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1492: $is_balancer = 0;
1493: if ($uname ne '' && $udom ne '') {
1494: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1176 raeburn 1495:
1.1331 raeburn 1496: &appenv({'user.loadbalexempt' => $lonhost,
1497: 'user.loadbalcheck.time' => time});
1498: }
1.1176 raeburn 1499: }
1.1129 raeburn 1500: }
1501: }
1502: }
1503: return ($is_balancer,$otherserver);
1504: }
1505:
1.1191 raeburn 1506: sub check_balancer_result {
1507: my ($result,@hosts) = @_;
1508: my ($is_balancer,$currtargets,$currrules);
1509: if (ref($result) eq 'HASH') {
1510: if ($result->{'lonhost'} ne '') {
1511: my $currbalancer = $result->{'lonhost'};
1512: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1513: $is_balancer = 1;
1514: $currtargets = $result->{'targets'};
1515: $currrules = $result->{'rules'};
1516: }
1517: } else {
1518: foreach my $key (keys(%{$result})) {
1519: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1520: (ref($result->{$key}) eq 'HASH')) {
1521: $is_balancer = 1;
1522: $currrules = $result->{$key}{'rules'};
1523: $currtargets = $result->{$key}{'targets'};
1524: last;
1525: }
1526: }
1527: }
1528: }
1529: return ($is_balancer,$currtargets,$currrules);
1530: }
1531:
1.1129 raeburn 1532: sub get_loadbalancer_targets {
1533: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1534: my $offloadto;
1.1175 raeburn 1535: if ($rule_in_effect eq 'none') {
1536: return [$perlvar{'lonHostID'}];
1537: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1538: $offloadto = $currtargets;
1539: } else {
1540: if ($rule_in_effect eq 'homeserver') {
1541: my $homeserver = &homeserver($uname,$udom);
1542: if ($homeserver ne 'no_host') {
1543: $offloadto = [$homeserver];
1544: }
1545: } elsif ($rule_in_effect eq 'externalbalancer') {
1546: my %domconfig =
1547: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1548: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1549: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1550: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1551: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1552: }
1553: }
1554: } else {
1.1178 raeburn 1555: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1556: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1557: if (&hostname($remotebalancer) ne '') {
1558: $offloadto = [$remotebalancer];
1559: }
1560: }
1561: } elsif (&hostname($rule_in_effect) ne '') {
1562: $offloadto = [$rule_in_effect];
1563: }
1564: }
1565: return $offloadto;
1566: }
1567:
1.1127 raeburn 1568: sub internet_dom_servers {
1569: my ($dom) = @_;
1570: my (%uniqservers,%servers);
1571: my $primaryserver = &hostname(&domain($dom,'primary'));
1572: my @machinedoms = &machine_domains($primaryserver);
1573: foreach my $mdom (@machinedoms) {
1574: my %currservers = %servers;
1575: my %server = &get_servers($mdom);
1576: %servers = (%currservers,%server);
1577: }
1578: my %by_hostname;
1579: foreach my $id (keys(%servers)) {
1580: push(@{$by_hostname{$servers{$id}}},$id);
1581: }
1582: foreach my $hostname (sort(keys(%by_hostname))) {
1583: if (@{$by_hostname{$hostname}} > 1) {
1584: my $match = 0;
1585: foreach my $id (@{$by_hostname{$hostname}}) {
1586: if (&host_domain($id) eq $dom) {
1587: $uniqservers{$id} = $hostname;
1588: $match = 1;
1589: }
1590: }
1591: unless ($match) {
1592: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1593: }
1594: } else {
1595: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1596: }
1597: }
1598: return %uniqservers;
1599: }
1600:
1.1347 raeburn 1601: sub trusted_domains {
1602: my ($cmdtype,$calldom) = @_;
1.1349 raeburn 1603: my ($trusted,$untrusted);
1.1347 raeburn 1604: if (&domain($calldom) eq '') {
1.1349 raeburn 1605: return ($trusted,$untrusted);
1.1347 raeburn 1606: }
1607: unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
1.1349 raeburn 1608: return ($trusted,$untrusted);
1.1347 raeburn 1609: }
1610: my $callprimary = &domain($calldom,'primary');
1611: my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
1612: if ($intcalldom eq '') {
1.1349 raeburn 1613: return ($trusted,$untrusted);
1.1347 raeburn 1614: }
1615:
1616: my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
1617: unless (defined($cached)) {
1618: my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
1619: &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
1620: $trustconfig = $domconfig{'trust'};
1621: }
1622: if (ref($trustconfig)) {
1623: my (%possexc,%possinc,@allexc,@allinc);
1624: if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
1625: if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
1626: map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}};
1627: }
1628: if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1629: map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
1630: }
1631: }
1632: if (keys(%possexc)) {
1633: if (keys(%possinc)) {
1634: foreach my $key (sort(keys(%possexc))) {
1635: next if ($key eq $intcalldom);
1636: unless ($possinc{$key}) {
1637: push(@allexc,$key);
1638: }
1639: }
1640: } else {
1641: @allexc = sort(keys(%possexc));
1642: }
1643: }
1644: if (keys(%possinc)) {
1645: $possinc{$intcalldom} = 1;
1646: @allinc = sort(keys(%possinc));
1647: }
1648: if ((@allexc > 0) || (@allinc > 0)) {
1649: my %doms_by_intdom;
1650: my %allintdoms = &all_host_intdom();
1651: my %alldoms = &all_host_domain();
1652: foreach my $key (%allintdoms) {
1653: if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
1654: unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
1655: push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
1656: }
1657: } else {
1658: $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}];
1659: }
1660: }
1661: foreach my $exc (@allexc) {
1662: if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1349 raeburn 1663: $untrusted = $doms_by_intdom{$exc};
1.1347 raeburn 1664: }
1665: }
1666: foreach my $inc (@allinc) {
1667: if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1349 raeburn 1668: $trusted = $doms_by_intdom{$inc};
1.1347 raeburn 1669: }
1670: }
1671: }
1672: }
1.1349 raeburn 1673: return ($trusted,$untrusted);
1.1347 raeburn 1674: }
1675:
1676: sub will_trust {
1677: my ($cmdtype,$domain,$possdom) = @_;
1678: return 1 if ($domain eq $possdom);
1679: my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
1680: my $willtrust;
1681: if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
1682: if (grep(/^\Q$domain\E$/,@{$trustedref})) {
1683: $willtrust = 1;
1684: }
1685: } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
1686: unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
1687: $willtrust = 1;
1688: }
1689: } else {
1690: $willtrust = 1;
1691: }
1692: return $willtrust;
1693: }
1694:
1.1 albertel 1695: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1696:
1.599 albertel 1697: my %homecache;
1.1 albertel 1698: sub homeserver {
1.230 stredwic 1699: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1700: my $index="$uname:$udom";
1.426 albertel 1701:
1.599 albertel 1702: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1703:
1704: my %servers = &get_servers($udom,'library');
1705: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1706: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1707: exists($badServerCache{$tryserver}));
1.841 albertel 1708:
1709: my $answer=reply("home:$udom:$uname",$tryserver);
1710: if ($answer eq 'found') {
1711: delete($badServerCache{$tryserver});
1712: return $homecache{$index}=$tryserver;
1713: } elsif ($answer eq 'no_host') {
1714: $badServerCache{$tryserver}=1;
1715: }
1.1 albertel 1716: }
1717: return 'no_host';
1.70 www 1718: }
1719:
1.1300 raeburn 1720: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70 www 1721:
1722: sub idget {
1.1300 raeburn 1723: my ($udom,$idsref,$namespace)=@_;
1.70 www 1724: my %returnhash=();
1.1300 raeburn 1725: my @ids=();
1726: if (ref($idsref) eq 'ARRAY') {
1727: @ids = @{$idsref};
1728: } else {
1729: return %returnhash;
1730: }
1731: if ($namespace eq '') {
1732: $namespace = 'ids';
1733: }
1.70 www 1734:
1.841 albertel 1735: my %servers = &get_servers($udom,'library');
1736: foreach my $tryserver (keys(%servers)) {
1.1299 raeburn 1737: my $idlist=join('&', map { &escape($_); } @ids);
1.1300 raeburn 1738: if ($namespace eq 'ids') {
1739: $idlist=~tr/A-Z/a-z/;
1740: }
1741: my $reply;
1742: if ($namespace eq 'ids') {
1743: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1744: } else {
1745: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1746: }
1.841 albertel 1747: my @answer=();
1748: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1749: @answer=split(/\&/,$reply);
1750: } ;
1751: my $i;
1752: for ($i=0;$i<=$#ids;$i++) {
1753: if ($answer[$i]) {
1.1299 raeburn 1754: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300 raeburn 1755: }
1.841 albertel 1756: }
1.1300 raeburn 1757: }
1.70 www 1758: return %returnhash;
1759: }
1760:
1761: # ------------------------------------- Find the IDs behind a list of usernames
1762:
1763: sub idrget {
1764: my ($udom,@unames)=@_;
1765: my %returnhash=();
1.800 albertel 1766: foreach my $uname (@unames) {
1767: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1768: }
1.70 www 1769: return %returnhash;
1770: }
1771:
1.1300 raeburn 1772: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70 www 1773:
1774: sub idput {
1.1300 raeburn 1775: my ($udom,$idsref,$uhom,$namespace)=@_;
1.70 www 1776: my %servers=();
1.1300 raeburn 1777: my %ids=();
1778: my %byid = ();
1779: if (ref($idsref) eq 'HASH') {
1780: %ids=%{$idsref};
1781: }
1782: if ($namespace eq '') {
1783: $namespace = 'ids';
1784: }
1.800 albertel 1785: foreach my $uname (keys(%ids)) {
1786: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300 raeburn 1787: if ($uhom eq '') {
1788: $uhom=&homeserver($uname,$udom);
1789: }
1.70 www 1790: if ($uhom ne 'no_host') {
1.800 albertel 1791: my $esc_unam=&escape($uname);
1.1300 raeburn 1792: if ($namespace eq 'ids') {
1793: my $id=&escape($ids{$uname});
1794: $id=~tr/A-Z/a-z/;
1795: my $esc_unam=&escape($uname);
1796: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70 www 1797: } else {
1.1300 raeburn 1798: my @currids = split(/,/,$ids{$uname});
1799: foreach my $id (@currids) {
1800: $byid{$uhom}{$id} .= $uname.',';
1801: }
1802: }
1803: }
1804: }
1805: if ($namespace eq 'clickers') {
1806: foreach my $server (keys(%byid)) {
1807: if (ref($byid{$server}) eq 'HASH') {
1808: foreach my $id (keys(%{$byid{$server}})) {
1809: $byid{$server} =~ s/,$//;
1810: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
1811: }
1.70 www 1812: }
1813: }
1.191 harris41 1814: }
1.800 albertel 1815: foreach my $server (keys(%servers)) {
1.1300 raeburn 1816: $servers{$server} =~ s/\&$//;
1817: if ($namespace eq 'ids') {
1818: &critical('idput:'.$udom.':'.$servers{$server},$server);
1819: } else {
1820: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
1821: }
1.191 harris41 1822: }
1.344 www 1823: }
1824:
1.1300 raeburn 1825: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231 raeburn 1826:
1827: sub iddel {
1.1300 raeburn 1828: my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231 raeburn 1829: my %result=();
1.1300 raeburn 1830: my %ids=();
1831: my %byid = ();
1832: if (ref($idshashref) eq 'HASH') {
1833: %ids=%{$idshashref};
1834: } else {
1.1231 raeburn 1835: return %result;
1836: }
1.1300 raeburn 1837: if ($namespace eq '') {
1838: $namespace = 'ids';
1839: }
1.1231 raeburn 1840: my %servers=();
1.1300 raeburn 1841: while (my ($id,$unamestr) = each(%ids)) {
1842: if ($namespace eq 'ids') {
1843: my $uhom = $uhome;
1844: if ($uhom eq '') {
1845: $uhom=&homeserver($unamestr,$udom);
1846: }
1847: if ($uhom ne 'no_host') {
1848: $servers{$uhom}.='&'.&escape($id);
1849: }
1850: } else {
1851: my @curritems = split(/,/,$ids{$id});
1852: foreach my $uname (@curritems) {
1853: my $uhom = $uhome;
1854: if ($uhom eq '') {
1855: $uhom=&homeserver($uname,$udom);
1856: }
1857: if ($uhom ne 'no_host') {
1858: $byid{$uhom}{$id} .= $uname.',';
1859: }
1860: }
1.1231 raeburn 1861: }
1.1300 raeburn 1862: }
1863: if ($namespace eq 'clickers') {
1864: foreach my $server (keys(%byid)) {
1865: if (ref($byid{$server}) eq 'HASH') {
1866: foreach my $id (keys(%{$byid{$server}})) {
1867: $byid{$server}{$id} =~ s/,$//;
1868: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
1869: }
1.1231 raeburn 1870: }
1871: }
1872: }
1873: foreach my $server (keys(%servers)) {
1.1300 raeburn 1874: $servers{$server} =~ s/\&$//;
1875: if ($namespace eq 'ids') {
1876: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1877: } elsif ($namespace eq 'clickers') {
1878: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
1879: }
1.1231 raeburn 1880: }
1881: return %result;
1882: }
1883:
1.1300 raeburn 1884: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
1885:
1886: sub updateclickers {
1887: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
1888: my %clickers;
1889: if (ref($idshashref) eq 'HASH') {
1890: %clickers=%{$idshashref};
1891: } else {
1892: return;
1893: }
1894: my $items='';
1895: foreach my $item (keys(%clickers)) {
1896: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
1897: }
1898: $items=~s/\&$//;
1899: my $request = "updateclickers:$udom:$action:$items";
1900: if ($critical) {
1901: return &critical($request,$uhome);
1902: } else {
1903: return &reply($request,$uhome);
1904: }
1905: }
1906:
1.1023 raeburn 1907: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1908: sub dump_dom {
1.1165 droeschl 1909: my ($namespace, $udom, $regexp) = @_;
1910:
1911: $udom ||= $env{'user.domain'};
1912:
1913: return () unless $udom;
1914:
1915: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1916: }
1917:
1.1023 raeburn 1918: # ------------------------------------------ get items from domain db files
1.806 raeburn 1919:
1920: sub get_dom {
1.860 raeburn 1921: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267 raeburn 1922: return if ($udom eq 'public');
1.806 raeburn 1923: my $items='';
1924: foreach my $item (@$storearr) {
1925: $items.=&escape($item).'&';
1926: }
1927: $items=~s/\&$//;
1.860 raeburn 1928: if (!$udom) {
1929: $udom=$env{'user.domain'};
1.1267 raeburn 1930: return if ($udom eq 'public');
1.860 raeburn 1931: if (defined(&domain($udom,'primary'))) {
1932: $uhome=&domain($udom,'primary');
1933: } else {
1.874 albertel 1934: undef($uhome);
1.860 raeburn 1935: }
1936: } else {
1937: if (!$uhome) {
1938: if (defined(&domain($udom,'primary'))) {
1939: $uhome=&domain($udom,'primary');
1940: }
1941: }
1942: }
1943: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344 raeburn 1944: my $rep;
1945: if ($namespace =~ /^enc/) {
1946: $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
1947: } else {
1948: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1949: }
1.866 raeburn 1950: my %returnhash;
1.875 albertel 1951: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1952: return %returnhash;
1953: }
1.806 raeburn 1954: my @pairs=split(/\&/,$rep);
1955: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1956: return @pairs;
1957: }
1958: my $i=0;
1959: foreach my $item (@$storearr) {
1960: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1961: $i++;
1962: }
1963: return %returnhash;
1964: } else {
1.880 banghart 1965: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1966: }
1967: }
1968:
1969: # -------------------------------------------- put items in domain db files
1970:
1971: sub put_dom {
1.860 raeburn 1972: my ($namespace,$storehash,$udom,$uhome)=@_;
1973: if (!$udom) {
1974: $udom=$env{'user.domain'};
1975: if (defined(&domain($udom,'primary'))) {
1976: $uhome=&domain($udom,'primary');
1977: } else {
1.874 albertel 1978: undef($uhome);
1.860 raeburn 1979: }
1980: } else {
1981: if (!$uhome) {
1982: if (defined(&domain($udom,'primary'))) {
1983: $uhome=&domain($udom,'primary');
1984: }
1985: }
1986: }
1987: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1988: my $items='';
1989: foreach my $item (keys(%$storehash)) {
1990: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1991: }
1992: $items=~s/\&$//;
1.1344 raeburn 1993: if ($namespace =~ /^enc/) {
1994: return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
1995: } else {
1996: return &reply("putdom:$udom:$namespace:$items",$uhome);
1997: }
1.806 raeburn 1998: } else {
1.860 raeburn 1999: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 2000: }
2001: }
2002:
1.1023 raeburn 2003: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 2004: sub newput_dom {
1.1023 raeburn 2005: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 2006: my $result;
2007: if (!$udom) {
2008: $udom=$env{'user.domain'};
2009: }
1.1023 raeburn 2010: if ($udom) {
2011: my $uname = &get_domainconfiguser($udom);
2012: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 2013: }
2014: return $result;
2015: }
2016:
1.1023 raeburn 2017: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 2018: sub del_dom {
1.1023 raeburn 2019: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 2020: if (ref($storearr) eq 'ARRAY') {
2021: if (!$udom) {
2022: $udom=$env{'user.domain'};
2023: }
1.1023 raeburn 2024: if ($udom) {
2025: my $uname = &get_domainconfiguser($udom);
2026: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 2027: }
2028: }
2029: }
2030:
1.1023 raeburn 2031: # ----------------------------------construct domainconfig user for a domain
2032: sub get_domainconfiguser {
2033: my ($udom) = @_;
2034: return $udom.'-domainconfig';
2035: }
2036:
1.837 raeburn 2037: sub retrieve_inst_usertypes {
2038: my ($udom) = @_;
2039: my (%returnhash,@order);
1.989 raeburn 2040: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
2041: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
2042: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 2043: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 2044: } else {
2045: if (defined(&domain($udom,'primary'))) {
2046: my $uhome=&domain($udom,'primary');
2047: my $rep=&reply("inst_usertypes:$udom",$uhome);
2048: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 2049: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 2050: return (\%returnhash,\@order);
2051: }
2052: my ($hashitems,$orderitems) = split(/:/,$rep);
2053: my @pairs=split(/\&/,$hashitems);
2054: foreach my $item (@pairs) {
2055: my ($key,$value)=split(/=/,$item,2);
2056: $key = &unescape($key);
2057: next if ($key =~ /^error: 2 /);
2058: $returnhash{$key}=&thaw_unescape($value);
2059: }
2060: my @esc_order = split(/\&/,$orderitems);
2061: foreach my $item (@esc_order) {
2062: push(@order,&unescape($item));
2063: }
2064: } else {
1.1256 raeburn 2065: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 2066: }
1.1256 raeburn 2067: return (\%returnhash,\@order);
1.837 raeburn 2068: }
2069: }
2070:
1.868 raeburn 2071: sub is_domainimage {
2072: my ($url) = @_;
1.1306 raeburn 2073: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 2074: if (&domain($1) ne '') {
2075: return '1';
2076: }
2077: }
2078: return;
2079: }
2080:
1.899 raeburn 2081: sub inst_directory_query {
2082: my ($srch) = @_;
2083: my $udom = $srch->{'srchdomain'};
2084: my %results;
2085: my $homeserver = &domain($udom,'primary');
1.909 raeburn 2086: my $outcome;
1.899 raeburn 2087: if ($homeserver ne '') {
1.904 albertel 2088: my $queryid=&reply("querysend:instdirsearch:".
2089: &escape($srch->{'srchby'}).':'.
2090: &escape($srch->{'srchterm'}).':'.
2091: &escape($srch->{'srchtype'}),$homeserver);
2092: my $host=&hostname($homeserver);
2093: if ($queryid !~/^\Q$host\E\_/) {
1.1343 raeburn 2094: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 2095: return;
2096: }
2097: my $response = &get_query_reply($queryid);
2098: my $maxtries = 5;
2099: my $tries = 1;
2100: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2101: $response = &get_query_reply($queryid);
2102: $tries ++;
2103: }
2104:
2105: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2106: if ($response eq 'unavailable') {
2107: $outcome = $response;
2108: } else {
2109: $outcome = 'ok';
2110: my @matches = split(/\n/,$response);
2111: foreach my $match (@matches) {
2112: my ($key,$value) = split(/=/,$match);
2113: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2114: }
1.899 raeburn 2115: }
2116: }
2117: }
1.909 raeburn 2118: return ($outcome,%results);
1.899 raeburn 2119: }
2120:
2121: sub usersearch {
2122: my ($srch) = @_;
2123: my $dom = $srch->{'srchdomain'};
2124: my %results;
2125: my %libserv = &all_library();
2126: my $query = 'usersearch';
2127: foreach my $tryserver (keys(%libserv)) {
2128: if (&host_domain($tryserver) eq $dom) {
2129: my $host=&hostname($tryserver);
2130: my $queryid=
1.911 raeburn 2131: &reply("querysend:".&escape($query).':'.
2132: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2133: &escape($srch->{'srchtype'}).':'.
2134: &escape($srch->{'srchterm'}),$tryserver);
2135: if ($queryid !~/^\Q$host\E\_/) {
2136: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2137: next;
1.899 raeburn 2138: }
2139: my $reply = &get_query_reply($queryid);
2140: my $maxtries = 1;
2141: my $tries = 1;
2142: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2143: $reply = &get_query_reply($queryid);
2144: $tries ++;
2145: }
2146: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2147: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2148: } else {
1.911 raeburn 2149: my @matches;
2150: if ($reply =~ /\n/) {
2151: @matches = split(/\n/,$reply);
2152: } else {
2153: @matches = split(/\&/,$reply);
2154: }
1.899 raeburn 2155: foreach my $match (@matches) {
2156: my ($uname,$udom,%userhash);
1.911 raeburn 2157: foreach my $entry (split(/:/,$match)) {
2158: my ($key,$value) =
2159: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2160: $userhash{$key} = $value;
2161: if ($key eq 'username') {
2162: $uname = $value;
2163: } elsif ($key eq 'domain') {
2164: $udom = $value;
1.911 raeburn 2165: }
1.899 raeburn 2166: }
2167: $results{$uname.':'.$udom} = \%userhash;
2168: }
2169: }
2170: }
2171: }
2172: return %results;
2173: }
2174:
1.912 raeburn 2175: sub get_instuser {
2176: my ($udom,$uname,$id) = @_;
2177: my $homeserver = &domain($udom,'primary');
2178: my ($outcome,%results);
2179: if ($homeserver ne '') {
2180: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2181: &escape($id).':'.&escape($udom),$homeserver);
2182: my $host=&hostname($homeserver);
2183: if ($queryid !~/^\Q$host\E\_/) {
2184: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2185: return;
2186: }
2187: my $response = &get_query_reply($queryid);
2188: my $maxtries = 5;
2189: my $tries = 1;
2190: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2191: $response = &get_query_reply($queryid);
2192: $tries ++;
2193: }
2194: if (!&error($response) && $response ne 'refused') {
2195: if ($response eq 'unavailable') {
2196: $outcome = $response;
2197: } else {
2198: $outcome = 'ok';
2199: my @matches = split(/\n/,$response);
2200: foreach my $match (@matches) {
2201: my ($key,$value) = split(/=/,$match);
2202: $results{&unescape($key)} = &thaw_unescape($value);
2203: }
2204: }
2205: }
2206: }
2207: my %userinfo;
2208: if (ref($results{$uname}) eq 'HASH') {
2209: %userinfo = %{$results{$uname}};
2210: }
2211: return ($outcome,%userinfo);
2212: }
2213:
1.1290 raeburn 2214: sub get_multiple_instusers {
2215: my ($udom,$users,$caller) = @_;
2216: my ($outcome,$results);
2217: if (ref($users) eq 'HASH') {
2218: my $count = keys(%{$users});
2219: my $requested = &freeze_escape($users);
2220: my $homeserver = &domain($udom,'primary');
2221: if ($homeserver ne '') {
2222: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2223: my $host=&hostname($homeserver);
2224: if ($queryid !~/^\Q$host\E\_/) {
2225: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2226: ' for host: '.$homeserver.'in domain '.$udom);
2227: return ($outcome,$results);
2228: }
2229: my $response = &get_query_reply($queryid);
2230: my $maxtries = 5;
2231: if ($count > 100) {
2232: $maxtries = 1+int($count/20);
2233: }
2234: my $tries = 1;
2235: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2236: $response = &get_query_reply($queryid);
2237: $tries ++;
2238: }
2239: if ($response eq '') {
2240: $results = {};
2241: foreach my $key (keys(%{$users})) {
2242: my ($uname,$id);
2243: if ($caller eq 'id') {
2244: $id = $key;
2245: } else {
2246: $uname = $key;
2247: }
2248: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291 raeburn 2249: $outcome = $resp;
1.1290 raeburn 2250: if ($resp eq 'ok') {
2251: %{$results} = (%{$results}, %info);
2252: } else {
2253: last;
2254: }
2255: }
2256: } elsif(!&error($response) && ($response ne 'refused')) {
2257: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2258: $outcome = $response;
2259: } else {
1.1291 raeburn 2260: ($outcome,my $userdata) = split(/=/,$response,2);
1.1290 raeburn 2261: if ($outcome eq 'ok') {
2262: $results = &thaw_unescape($userdata);
2263: }
2264: }
2265: }
2266: }
2267: }
2268: return ($outcome,$results);
2269: }
2270:
1.912 raeburn 2271: sub inst_rulecheck {
1.923 raeburn 2272: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2273: my %returnhash;
2274: if ($udom ne '') {
2275: if (ref($rules) eq 'ARRAY') {
2276: @{$rules} = map {&escape($_);} (@{$rules});
2277: my $rulestr = join(':',@{$rules});
2278: my $homeserver=&domain($udom,'primary');
2279: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2280: my $response;
2281: if ($item eq 'username') {
2282: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2283: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2284: $homeserver));
1.923 raeburn 2285: } elsif ($item eq 'id') {
2286: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2287: ':'.&escape($id).':'.$rulestr,
2288: $homeserver));
1.945 raeburn 2289: } elsif ($item eq 'selfcreate') {
2290: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2291: &escape($udom).':'.&escape($uname).
2292: ':'.$rulestr,$homeserver));
1.923 raeburn 2293: }
1.912 raeburn 2294: if ($response ne 'refused') {
2295: my @pairs=split(/\&/,$response);
2296: foreach my $item (@pairs) {
2297: my ($key,$value)=split(/=/,$item,2);
2298: $key = &unescape($key);
2299: next if ($key =~ /^error: 2 /);
2300: $returnhash{$key}=&thaw_unescape($value);
2301: }
2302: }
2303: }
2304: }
2305: }
2306: return %returnhash;
2307: }
2308:
2309: sub inst_userrules {
1.923 raeburn 2310: my ($udom,$check) = @_;
1.912 raeburn 2311: my (%ruleshash,@ruleorder);
2312: if ($udom ne '') {
2313: my $homeserver=&domain($udom,'primary');
2314: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2315: my $response;
2316: if ($check eq 'id') {
2317: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2318: $homeserver);
1.943 raeburn 2319: } elsif ($check eq 'email') {
2320: $response=&reply('instemailrules:'.&escape($udom),
2321: $homeserver);
1.923 raeburn 2322: } else {
2323: $response=&reply('instuserrules:'.&escape($udom),
2324: $homeserver);
2325: }
1.912 raeburn 2326: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2327: ($response ne 'unknown_cmd') &&
1.912 raeburn 2328: ($response ne 'no_such_host')) {
2329: my ($hashitems,$orderitems) = split(/:/,$response);
2330: my @pairs=split(/\&/,$hashitems);
2331: foreach my $item (@pairs) {
2332: my ($key,$value)=split(/=/,$item,2);
2333: $key = &unescape($key);
2334: next if ($key =~ /^error: 2 /);
2335: $ruleshash{$key}=&thaw_unescape($value);
2336: }
2337: my @esc_order = split(/\&/,$orderitems);
2338: foreach my $item (@esc_order) {
2339: push(@ruleorder,&unescape($item));
2340: }
2341: }
2342: }
2343: }
2344: return (\%ruleshash,\@ruleorder);
2345: }
2346:
1.976 raeburn 2347: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2348:
2349: sub get_domain_defaults {
1.1240 raeburn 2350: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2351: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2352: my $cachetime = 60*60*24;
1.1240 raeburn 2353: unless ($ignore_cache) {
2354: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2355: if (defined($cached)) {
2356: if (ref($result) eq 'HASH') {
2357: return %{$result};
2358: }
1.943 raeburn 2359: }
2360: }
2361: my %domdefaults;
2362: my %domconfig =
1.989 raeburn 2363: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2364: 'requestcourses','inststatus',
1.1183 raeburn 2365: 'coursedefaults','usersessions',
1.1258 raeburn 2366: 'requestauthor','selfenrollment',
1.1320 raeburn 2367: 'coursecategories','ssl','autoenroll',
1.1332 raeburn 2368: 'trust','helpsettings'],$domain);
1.1305 raeburn 2369: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2370: if (ref($domconfig{'defaults'}) eq 'HASH') {
2371: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2372: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2373: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2374: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2375: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2376: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340 raeburn 2377: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2378: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2379: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943 raeburn 2380: } else {
2381: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2382: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2383: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2384: }
1.976 raeburn 2385: if (ref($domconfig{'quotas'}) eq 'HASH') {
2386: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2387: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2388: } else {
2389: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2390: }
1.1177 raeburn 2391: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2392: foreach my $item (@usertools) {
2393: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2394: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2395: }
2396: }
1.1229 raeburn 2397: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2398: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2399: }
1.976 raeburn 2400: }
1.985 raeburn 2401: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 raeburn 2402: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2403: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2404: }
2405: }
1.1183 raeburn 2406: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2407: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2408: }
1.989 raeburn 2409: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2410: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2411: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2412: }
2413: }
1.1047 raeburn 2414: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2415: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2416: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2417: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2418: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2419: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2420: }
1.1254 raeburn 2421: foreach my $type (@coursetypes) {
2422: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2423: unless ($type eq 'community') {
2424: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2425: }
2426: }
2427: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2428: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2429: }
1.1277 raeburn 2430: if ($domdefaults{'postsubmit'} eq 'on') {
2431: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2432: $domdefaults{$type.'postsubtimeout'} =
2433: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2434: }
2435: }
1.1230 raeburn 2436: }
1.1286 raeburn 2437: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2438: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2439: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2440: if (@clonecodes) {
2441: $domdefaults{'canclone'} = join('+',@clonecodes);
2442: }
2443: }
2444: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2445: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2446: }
1.1047 raeburn 2447: }
1.1073 raeburn 2448: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2449: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2450: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2451: }
2452: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2453: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2454: }
1.1279 raeburn 2455: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2456: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2457: }
1.1073 raeburn 2458: }
1.1254 raeburn 2459: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2460: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2461: my @settings = ('types','registered','enroll_dates','access_dates','section',
2462: 'approval','limit');
2463: foreach my $type (@coursetypes) {
2464: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2465: my @mgrdc = ();
2466: foreach my $item (@settings) {
2467: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2468: push(@mgrdc,$item);
2469: }
2470: }
2471: if (@mgrdc) {
2472: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2473: }
2474: }
2475: }
2476: }
2477: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2478: foreach my $type (@coursetypes) {
2479: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2480: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2481: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2482: }
2483: }
2484: }
2485: }
2486: }
1.1258 raeburn 2487: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2488: $domdefaults{'catauth'} = 'std';
2489: $domdefaults{'catunauth'} = 'std';
2490: if ($domconfig{'coursecategories'}{'auth'}) {
2491: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2492: }
2493: if ($domconfig{'coursecategories'}{'unauth'}) {
2494: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2495: }
2496: }
1.1315 raeburn 2497: if (ref($domconfig{'ssl'}) eq 'HASH') {
2498: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2499: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2500: }
1.1338 raeburn 2501: if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
2502: $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
2503: }
2504: if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
2505: $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315 raeburn 2506: }
2507: }
1.1320 raeburn 2508: if (ref($domconfig{'trust'}) eq 'HASH') {
2509: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2510: foreach my $prefix (@prefixes) {
2511: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2512: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2513: }
2514: }
2515: }
1.1314 raeburn 2516: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2517: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2518: }
1.1332 raeburn 2519: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2520: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2521: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2522: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2523: }
2524: }
1.1219 raeburn 2525: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2526: return %domdefaults;
2527: }
2528:
1.1311 raeburn 2529: sub course_portal_url {
2530: my ($cnum,$cdom) = @_;
2531: my $chome = &homeserver($cnum,$cdom);
2532: my $hostname = &hostname($chome);
2533: my $protocol = $protocol{$chome};
2534: $protocol = 'http' if ($protocol ne 'https');
2535: my %domdefaults = &get_domain_defaults($cdom);
2536: my $firsturl;
2537: if ($domdefaults{'portal_def'}) {
2538: $firsturl = $domdefaults{'portal_def'};
2539: } else {
2540: $firsturl = $protocol.'://'.$hostname;
2541: }
2542: return $firsturl;
2543: }
2544:
1.344 www 2545: # --------------------------------------------------- Assign a key to a student
2546:
2547: sub assign_access_key {
1.364 www 2548: #
2549: # a valid key looks like uname:udom#comments
2550: # comments are being appended
2551: #
1.498 www 2552: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2553: $kdom=
1.620 albertel 2554: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2555: $knum=
1.620 albertel 2556: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2557: $cdom=
1.620 albertel 2558: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2559: $cnum=
1.620 albertel 2560: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2561: $udom=$env{'user.name'} unless (defined($udom));
2562: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2563: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2564: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2565: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2566: # assigned to this person
2567: # - this should not happen,
1.345 www 2568: # unless something went wrong
2569: # the first time around
2570: # ready to assign
1.364 www 2571: $logentry=$1.'; '.$logentry;
1.496 www 2572: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2573: $kdom,$knum) eq 'ok') {
1.345 www 2574: # key now belongs to user
1.346 www 2575: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2576: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2577: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2578: return 'ok';
2579: } else {
2580: return
2581: 'error: Count not permanently assign key, will need to be re-entered later.';
2582: }
2583: } else {
2584: return 'error: Could not assign key, try again later.';
2585: }
1.364 www 2586: } elsif (!$existing{$ckey}) {
1.345 www 2587: # the key does not exist
2588: return 'error: The key does not exist';
2589: } else {
2590: # the key is somebody else's
2591: return 'error: The key is already in use';
2592: }
1.344 www 2593: }
2594:
1.364 www 2595: # ------------------------------------------ put an additional comment on a key
2596:
2597: sub comment_access_key {
2598: #
2599: # a valid key looks like uname:udom#comments
2600: # comments are being appended
2601: #
2602: my ($ckey,$cdom,$cnum,$logentry)=@_;
2603: $cdom=
1.620 albertel 2604: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2605: $cnum=
1.620 albertel 2606: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2607: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2608: if ($existing{$ckey}) {
2609: $existing{$ckey}.='; '.$logentry;
2610: # ready to assign
1.367 www 2611: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2612: $cdom,$cnum) eq 'ok') {
2613: return 'ok';
2614: } else {
2615: return 'error: Count not store comment.';
2616: }
2617: } else {
2618: # the key does not exist
2619: return 'error: The key does not exist';
2620: }
2621: }
2622:
1.344 www 2623: # ------------------------------------------------------ Generate a set of keys
2624:
2625: sub generate_access_keys {
1.364 www 2626: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2627: $cdom=
1.620 albertel 2628: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2629: $cnum=
1.620 albertel 2630: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2631: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2632: unless (($cdom) && ($cnum)) { return 0; }
2633: if ($number>10000) { return 0; }
2634: sleep(2); # make sure don't get same seed twice
2635: srand(time()^($$+($$<<15))); # from "Programming Perl"
2636: my $total=0;
2637: for (my $i=1;$i<=$number;$i++) {
2638: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2639: sprintf("%lx",int(100000*rand)).'-'.
2640: sprintf("%lx",int(100000*rand));
2641: $newkey=~s/1/g/g; # folks mix up 1 and l
2642: $newkey=~s/0/h/g; # and also 0 and O
2643: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2644: if ($existing{$newkey}) {
2645: $i--;
2646: } else {
1.364 www 2647: if (&put('accesskeys',
2648: { $newkey => '# generated '.localtime().
1.620 albertel 2649: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2650: '; '.$logentry },
2651: $cdom,$cnum) eq 'ok') {
1.344 www 2652: $total++;
2653: }
2654: }
2655: }
1.620 albertel 2656: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2657: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2658: return $total;
2659: }
2660:
2661: # ------------------------------------------------------- Validate an accesskey
2662:
2663: sub validate_access_key {
2664: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2665: $cdom=
1.620 albertel 2666: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2667: $cnum=
1.620 albertel 2668: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2669: $udom=$env{'user.domain'} unless (defined($udom));
2670: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2671: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2672: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2673: }
2674:
2675: # ------------------------------------- Find the section of student in a course
1.652 albertel 2676: sub devalidate_getsection_cache {
2677: my ($udom,$unam,$courseid)=@_;
2678: my $hashid="$udom:$unam:$courseid";
2679: &devalidate_cache_new('getsection',$hashid);
2680: }
1.298 matthew 2681:
1.815 albertel 2682: sub courseid_to_courseurl {
2683: my ($courseid) = @_;
2684: #already url style courseid
2685: return $courseid if ($courseid =~ m{^/});
2686:
2687: if (exists($env{'course.'.$courseid.'.num'})) {
2688: my $cnum = $env{'course.'.$courseid.'.num'};
2689: my $cdom = $env{'course.'.$courseid.'.domain'};
2690: return "/$cdom/$cnum";
2691: }
2692:
2693: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2694: if (exists($courseinfo{'num'})) {
2695: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2696: }
2697:
2698: return undef;
2699: }
2700:
1.298 matthew 2701: sub getsection {
2702: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2703: my $cachetime=1800;
1.551 albertel 2704:
2705: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2706: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2707: if (defined($cached)) { return $result; }
2708:
1.298 matthew 2709: my %Pending;
2710: my %Expired;
2711: #
2712: # Each role can either have not started yet (pending), be active,
2713: # or have expired.
2714: #
2715: # If there is an active role, we are done.
2716: #
2717: # If there is more than one role which has not started yet,
2718: # choose the one which will start sooner
2719: # If there is one role which has not started yet, return it.
2720: #
2721: # If there is more than one expired role, choose the one which ended last.
2722: # If there is a role which has expired, return it.
2723: #
1.815 albertel 2724: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2725: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2726: foreach my $key (keys(%roleshash)) {
1.479 albertel 2727: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2728: my $section=$1;
2729: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2730: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2731: my $now=time;
1.548 albertel 2732: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2733: $Expired{$end}=$section;
2734: next;
2735: }
1.548 albertel 2736: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2737: $Pending{$start}=$section;
2738: next;
2739: }
1.599 albertel 2740: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2741: }
2742: #
2743: # Presumedly there will be few matching roles from the above
2744: # loop and the sorting time will be negligible.
2745: if (scalar(keys(%Pending))) {
2746: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2747: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2748: }
2749: if (scalar(keys(%Expired))) {
2750: my @sorted = sort {$a <=> $b} keys(%Expired);
2751: my $time = pop(@sorted);
1.599 albertel 2752: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2753: }
1.599 albertel 2754: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2755: }
1.70 www 2756:
1.599 albertel 2757: sub save_cache {
2758: &purge_remembered();
1.722 albertel 2759: #&Apache::loncommon::validate_page();
1.620 albertel 2760: undef(%env);
1.780 albertel 2761: undef($env_loaded);
1.599 albertel 2762: }
1.452 albertel 2763:
1.599 albertel 2764: my $to_remember=-1;
2765: my %remembered;
2766: my %accessed;
2767: my $kicks=0;
2768: my $hits=0;
1.849 albertel 2769: sub make_key {
2770: my ($name,$id) = @_;
1.872 albertel 2771: if (length($id) > 65
2772: && length(&escape($id)) > 200) {
2773: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2774: }
1.849 albertel 2775: return &escape($name.':'.$id);
2776: }
2777:
1.599 albertel 2778: sub devalidate_cache_new {
2779: my ($name,$id,$debug) = @_;
2780: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319 damieng 2781: my $remembered_id=$name.':'.$id;
1.849 albertel 2782: $id=&make_key($name,$id);
1.599 albertel 2783: $memcache->delete($id);
1.1319 damieng 2784: delete($remembered{$remembered_id});
2785: delete($accessed{$remembered_id});
1.599 albertel 2786: }
2787:
2788: sub is_cached_new {
2789: my ($name,$id,$debug) = @_;
1.1319 damieng 2790: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
2791: if (exists($remembered{$remembered_id})) {
2792: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2793: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2794: $hits++;
1.1319 damieng 2795: return ($remembered{$remembered_id},1);
1.599 albertel 2796: }
1.1319 damieng 2797: $id=&make_key($name,$id);
1.599 albertel 2798: my $value = $memcache->get($id);
2799: if (!(defined($value))) {
2800: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2801: return (undef,undef);
1.416 albertel 2802: }
1.599 albertel 2803: if ($value eq '__undef__') {
2804: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2805: $value=undef;
2806: }
1.1319 damieng 2807: &make_room($remembered_id,$value,$debug);
1.599 albertel 2808: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2809: return ($value,1);
2810: }
2811:
2812: sub do_cache_new {
2813: my ($name,$id,$value,$time,$debug) = @_;
1.1319 damieng 2814: my $remembered_id=$name.':'.$id;
1.849 albertel 2815: $id=&make_key($name,$id);
1.599 albertel 2816: my $setvalue=$value;
2817: if (!defined($setvalue)) {
2818: $setvalue='__undef__';
2819: }
1.623 albertel 2820: if (!defined($time) ) {
2821: $time=600;
2822: }
1.599 albertel 2823: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2824: my $result = $memcache->set($id,$setvalue,$time);
2825: if (! $result) {
1.872 albertel 2826: &logthis("caching of id -> $id failed");
1.910 albertel 2827: $memcache->disconnect_all();
1.872 albertel 2828: }
1.600 albertel 2829: # need to make a copy of $value
1.1319 damieng 2830: &make_room($remembered_id,$value,$debug);
1.599 albertel 2831: return $value;
2832: }
2833:
2834: sub make_room {
1.1319 damieng 2835: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2836:
1.1319 damieng 2837: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2838: : $value;
1.599 albertel 2839: if ($to_remember<0) { return; }
1.1319 damieng 2840: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2841: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2842: my $to_kick;
2843: my $max_time=0;
2844: foreach my $other (keys(%accessed)) {
2845: if (&tv_interval($accessed{$other}) > $max_time) {
2846: $to_kick=$other;
2847: $max_time=&tv_interval($accessed{$other});
2848: }
2849: }
2850: delete($remembered{$to_kick});
2851: delete($accessed{$to_kick});
2852: $kicks++;
2853: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2854: return;
2855: }
2856:
1.599 albertel 2857: sub purge_remembered {
1.604 albertel 2858: #&logthis("Tossing ".scalar(keys(%remembered)));
2859: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2860: undef(%remembered);
2861: undef(%accessed);
1.428 albertel 2862: }
1.70 www 2863: # ------------------------------------- Read an entry from a user's environment
2864:
2865: sub userenvironment {
2866: my ($udom,$unam,@what)=@_;
1.976 raeburn 2867: my $items;
2868: foreach my $item (@what) {
2869: $items.=&escape($item).'&';
2870: }
2871: $items=~s/\&$//;
1.70 www 2872: my %returnhash=();
1.1009 raeburn 2873: my $uhome = &homeserver($unam,$udom);
2874: unless ($uhome eq 'no_host') {
2875: my @answer=split(/\&/,
2876: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2877: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2878: return %returnhash;
2879: }
1.1009 raeburn 2880: my $i;
2881: for ($i=0;$i<=$#what;$i++) {
2882: $returnhash{$what[$i]}=&unescape($answer[$i]);
2883: }
1.70 www 2884: }
2885: return %returnhash;
1.1 albertel 2886: }
2887:
1.617 albertel 2888: # ---------------------------------------------------------- Get a studentphoto
2889: sub studentphoto {
2890: my ($udom,$unam,$ext) = @_;
2891: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2892: if (defined($env{'request.course.id'})) {
1.708 raeburn 2893: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2894: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2895: return(&retrievestudentphoto($udom,$unam,$ext));
2896: } else {
2897: my ($result,$perm_reqd)=
1.707 albertel 2898: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2899: if ($result eq 'ok') {
2900: if (!($perm_reqd eq 'yes')) {
2901: return(&retrievestudentphoto($udom,$unam,$ext));
2902: }
2903: }
2904: }
2905: }
2906: } else {
2907: my ($result,$perm_reqd) =
1.707 albertel 2908: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2909: if ($result eq 'ok') {
2910: if (!($perm_reqd eq 'yes')) {
2911: return(&retrievestudentphoto($udom,$unam,$ext));
2912: }
2913: }
2914: }
2915: return '/adm/lonKaputt/lonlogo_broken.gif';
2916: }
2917:
2918: sub retrievestudentphoto {
2919: my ($udom,$unam,$ext,$type) = @_;
2920: my $home=&Apache::lonnet::homeserver($unam,$udom);
2921: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2922: if ($ret eq 'ok') {
2923: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2924: if ($type eq 'thumbnail') {
2925: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2926: }
2927: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2928: return $tokenurl;
2929: } else {
2930: if ($type eq 'thumbnail') {
2931: return '/adm/lonKaputt/genericstudent_tn.gif';
2932: } else {
2933: return '/adm/lonKaputt/lonlogo_broken.gif';
2934: }
1.617 albertel 2935: }
2936: }
2937:
1.263 www 2938: # -------------------------------------------------------------------- New chat
2939:
2940: sub chatsend {
1.724 raeburn 2941: my ($newentry,$anon,$group)=@_;
1.620 albertel 2942: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2943: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2944: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2945: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2946: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2947: &escape($newentry)).':'.$group,$chome);
1.292 www 2948: }
2949:
2950: # ------------------------------------------ Find current version of a resource
2951:
2952: sub getversion {
2953: my $fname=&clutter(shift);
1.1189 raeburn 2954: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2955: return ¤tversion(&filelocation('',$fname));
2956: }
2957:
2958: sub currentversion {
2959: my $fname=shift;
2960: my $author=$fname;
2961: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2962: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2963: my $home=&homeserver($uname,$udom);
1.292 www 2964: if ($home eq 'no_host') {
2965: return -1;
2966: }
1.1112 www 2967: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2968: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2969: return -1;
2970: }
1.1112 www 2971: return $answer;
1.263 www 2972: }
2973:
1.1111 www 2974: #
2975: # Return special version number of resource if set by override, empty otherwise
2976: #
2977: sub usedversion {
2978: my $fname=shift;
2979: unless ($fname) { $fname=$env{'request.uri'}; }
2980: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2981: if ($urlversion) { return $urlversion; }
2982: return '';
2983: }
2984:
1.1 albertel 2985: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2986:
1.1 albertel 2987: sub subscribe {
2988: my $fname=shift;
1.761 raeburn 2989: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2990: $fname=~s/[\n\r]//g;
1.1 albertel 2991: my $author=$fname;
2992: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2993: my ($udom,$uname)=split(/\//,$author);
2994: my $home=homeserver($uname,$udom);
1.335 albertel 2995: if ($home eq 'no_host') {
2996: return 'not_found';
1.1 albertel 2997: }
2998: my $answer=reply("sub:$fname",$home);
1.64 www 2999: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3000: $answer.=' by '.$home;
3001: }
1.1 albertel 3002: return $answer;
3003: }
3004:
1.8 www 3005: # -------------------------------------------------------------- Replicate file
3006:
3007: sub repcopy {
3008: my $filename=shift;
1.23 www 3009: $filename=~s/\/+/\//g;
1.1142 raeburn 3010: my $londocroot = $perlvar{'lonDocRoot'};
3011: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 3012: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 3013: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3014: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 3015: return &repcopy_userfile($filename);
3016: }
1.532 albertel 3017: $filename=~s/[\n\r]//g;
1.8 www 3018: my $transname="$filename.in.transfer";
1.828 www 3019: # FIXME: this should flock
1.607 raeburn 3020: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 3021: my $remoteurl=subscribe($filename);
1.64 www 3022: if ($remoteurl =~ /^con_lost by/) {
3023: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3024: return 'unavailable';
1.8 www 3025: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 3026: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 3027: return 'not_found';
1.64 www 3028: } elsif ($remoteurl =~ /^rejected by/) {
3029: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 3030: return 'forbidden';
1.20 www 3031: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 3032: return 'ok';
1.8 www 3033: } else {
1.290 www 3034: my $author=$filename;
3035: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3036: my ($udom,$uname)=split(/\//,$author);
3037: my $home=homeserver($uname,$udom);
3038: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 3039: my @parts=split(/\//,$filename);
3040: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 3041: if ($path ne "$londocroot/res") {
1.8 www 3042: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 3043: return 'bad_request';
1.8 www 3044: }
3045: my $count;
3046: for ($count=5;$count<$#parts;$count++) {
3047: $path.="/$parts[$count]";
3048: if ((-e $path)!=1) {
3049: mkdir($path,0777);
3050: }
3051: }
3052: my $request=new HTTP::Request('GET',"$remoteurl");
1.1345 raeburn 3053: my $response;
3054: if ($remoteurl =~ m{/raw/}) {
3055: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
3056: } else {
3057: $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
3058: }
1.8 www 3059: if ($response->is_error()) {
3060: unlink($transname);
3061: my $message=$response->status_line;
1.672 albertel 3062: &logthis("<font color=\"blue\">WARNING:"
1.12 www 3063: ." LWP get: $message: $filename</font>");
1.607 raeburn 3064: return 'unavailable';
1.8 www 3065: } else {
1.16 www 3066: if ($remoteurl!~/\.meta$/) {
3067: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345 raeburn 3068: my $mresponse;
3069: if ($remoteurl =~ m{/raw/}) {
3070: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
3071: } else {
3072: $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
3073: }
1.16 www 3074: if ($mresponse->is_error()) {
3075: unlink($filename.'.meta');
3076: &logthis(
1.672 albertel 3077: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 3078: }
3079: }
1.8 www 3080: rename($transname,$filename);
1.607 raeburn 3081: return 'ok';
1.8 www 3082: }
1.290 www 3083: }
1.8 www 3084: }
1.330 www 3085: }
3086:
3087: # ------------------------------------------------ Get server side include body
3088: sub ssi_body {
1.381 albertel 3089: my ($filelink,%form)=@_;
1.606 matthew 3090: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3091: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3092: }
1.953 www 3093: my $output='';
3094: my $response;
1.980 raeburn 3095: if ($filelink=~/^https?\:/) {
1.954 raeburn 3096: ($output,$response)=&externalssi($filelink);
1.953 www 3097: } else {
1.1004 droeschl 3098: $filelink .= $filelink=~/\?/ ? '&' : '?';
3099: $filelink .= 'inhibitmenu=yes';
1.953 www 3100: ($output,$response)=&ssi($filelink,%form);
3101: }
1.778 albertel 3102: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 3103: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 3104: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3105: if (wantarray) {
3106: return ($output, $response);
3107: } else {
3108: return $output;
3109: }
1.8 www 3110: }
3111:
1.15 www 3112: # --------------------------------------------------------- Server Side Include
3113:
1.782 albertel 3114: sub absolute_url {
3115: my ($host_name) = @_;
3116: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3117: if ($host_name eq '') {
3118: $host_name = $ENV{'SERVER_NAME'};
3119: }
3120: return $protocol.$host_name;
3121: }
3122:
1.942 foxr 3123: #
3124: # Server side include.
3125: # Parameters:
3126: # fn Possibly encrypted resource name/id.
3127: # form Hash that describes how the rendering should be done
3128: # and other things.
1.944 foxr 3129: # Returns:
1.950 raeburn 3130: # Scalar context: The content of the response.
3131: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3132: #
1.15 www 3133: sub ssi {
3134:
1.944 foxr 3135: my ($fn,%form)=@_;
1.23 www 3136: my $request;
1.711 albertel 3137:
3138: $form{'no_update_last_known'}=1;
1.895 albertel 3139: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3140: if (%form) {
1.782 albertel 3141: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272 droeschl 3142: $request->content(join('&',map {
3143: my $name = escape($_);
3144: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3145: ? join("&$name=", map {escape($_) } @{$form{$_}})
3146: : &escape($form{$_}) );
3147: } keys(%form)));
1.23 www 3148: } else {
1.782 albertel 3149: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 3150: }
3151:
1.15 www 3152: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345 raeburn 3153: my $lonhost = $perlvar{'lonHostID'};
3154: my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar);
1.1182 foxr 3155:
1.944 foxr 3156: if (wantarray) {
1.1345 raeburn 3157: return ($response->content, $response);
1.944 foxr 3158: } else {
1.1345 raeburn 3159: return $response->content;
1.942 foxr 3160: }
1.324 www 3161: }
3162:
3163: sub externalssi {
3164: my ($url)=@_;
3165: my $request=new HTTP::Request('GET',$url);
1.1345 raeburn 3166: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954 raeburn 3167: if (wantarray) {
3168: return ($response->content, $response);
3169: } else {
3170: return $response->content;
3171: }
1.15 www 3172: }
1.254 www 3173:
1.1354 ! raeburn 3174:
! 3175: # If the local copy of a replicated resource is outdated, trigger a
! 3176: # connection from the homeserver to flush the delayed queue. If no update
! 3177: # happens, remove local copies of outdated resource (and corresponding
! 3178: # metadata file).
! 3179:
1.1352 raeburn 3180: sub remove_stale_resfile {
3181: my ($url) = @_;
1.1354 ! raeburn 3182: my $removed;
1.1352 raeburn 3183: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3184: my $audom = $1;
3185: my $auname = $2;
1.1353 raeburn 3186: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352 raeburn 3187: my $homeserver = &homeserver($auname,$audom);
3188: unless (($homeserver eq 'no_host') ||
3189: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3190: my $fname = &filelocation('',$url);
3191: if (-e $fname) {
3192: my $protocol = $protocol{$homeserver};
3193: $protocol = 'http' if ($protocol ne 'https');
3194: my $hostname = &hostname($homeserver);
3195: if ($hostname) {
3196: my $uri = &declutter($url);
3197: my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
3198: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
3199: if ($response->is_success()) {
3200: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3201: my $locmodtime = (stat($fname))[9];
3202: if ($locmodtime < $remmodtime) {
1.1354 ! raeburn 3203: my $stale;
! 3204: my $answer = &reply('pong',$homeserver);
! 3205: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
! 3206: sleep(0.2);
! 3207: $locmodtime = (stat($fname))[9];
! 3208: if ($locmodtime < $remmodtime) {
! 3209: my $posstransfer = $fname.'.in.transfer';
! 3210: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
! 3211: $removed = 1;
! 3212: } else {
! 3213: $stale = 1;
! 3214: }
! 3215: } else {
! 3216: $removed = 1;
! 3217: }
! 3218: } else {
! 3219: $stale = 1;
! 3220: }
! 3221: if ($stale) {
! 3222: unlink($fname);
! 3223: if ($uri!~/\.meta$/) {
! 3224: unlink($fname.'.meta');
! 3225: }
! 3226: &reply("unsub:$fname",$homeserver);
! 3227: $removed = 1;
1.1352 raeburn 3228: }
3229: }
3230: }
3231: }
3232: }
3233: }
3234: }
3235: }
1.1354 ! raeburn 3236: return $removed;
1.1352 raeburn 3237: }
3238:
1.492 albertel 3239: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3240:
3241: sub allowuploaded {
3242: my ($srcurl,$url)=@_;
3243: $url=&clutter(&declutter($url));
3244: my $dir=$url;
3245: $dir=~s/\/[^\/]+$//;
3246: my %httpref=();
3247: my $httpurl=&hreflocation('',$url);
3248: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3249: &Apache::lonnet::appenv(\%httpref);
1.254 www 3250: }
1.477 raeburn 3251:
1.1193 raeburn 3252: #
3253: # Determine if the current user should be able to edit a particular resource,
3254: # when viewing in course context.
3255: # (a) When viewing resource used to determine if "Edit" item is included in
3256: # Functions.
3257: # (b) When displaying folder contents in course editor, used to determine if
3258: # "Edit" link will be displayed alongside resource.
3259: #
1.1196 raeburn 3260: # input: six args -- filename (decluttered), course number, course domain,
3261: # url, symb (if registered) and group (if this is a group
3262: # item -- e.g., bulletin board, group page etc.).
3263: # output: array of five scalars --
1.1193 raeburn 3264: # $cfile -- url for file editing if editable on current server
3265: # $home -- homeserver of resource (i.e., for author if published,
3266: # or course if uploaded.).
3267: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 3268: # $forceedit -- 1 if icon/link should be to go to edit mode
3269: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 3270: #
3271:
3272: sub can_edit_resource {
1.1194 raeburn 3273: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3274: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3275: #
3276: # For aboutme pages user can only edit his/her own.
3277: #
1.1199 raeburn 3278: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 3279: my ($sdom,$sname) = ($1,$2);
3280: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3281: $home = $env{'user.home'};
3282: $cfile = $resurl;
3283: if ($env{'form.forceedit'}) {
3284: $forceview = 1;
3285: } else {
3286: $forceedit = 1;
3287: }
3288: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3289: } else {
3290: return;
3291: }
3292: }
3293:
3294: if ($env{'request.course.id'}) {
3295: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3296: if ($group ne '') {
3297: # if this is a group homepage or group bulletin board, check group privs
3298: my $allowed = 0;
1.1197 raeburn 3299: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3300: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3301: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3302: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3303: $allowed = 1;
3304: }
1.1197 raeburn 3305: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3306: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3307: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3308: $allowed = 1;
3309: }
3310: }
3311: if ($allowed) {
3312: $home=&homeserver($cnum,$cdom);
3313: if ($env{'form.forceedit'}) {
3314: $forceview = 1;
3315: } else {
3316: $forceedit = 1;
3317: }
3318: $cfile = $resurl;
3319: } else {
3320: return;
3321: }
3322: } else {
1.1208 raeburn 3323: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3324: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3325: return;
3326: }
3327: } elsif (!$crsedit) {
1.1194 raeburn 3328: #
3329: # No edit allowed where CC has switched to student role.
3330: #
3331: return;
3332: }
3333: }
3334: }
3335:
1.1193 raeburn 3336: if ($file ne '') {
3337: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3338: if (&is_course_upload($file,$cnum,$cdom)) {
3339: $uploaded = 1;
3340: $incourse = 1;
1.1193 raeburn 3341: if ($file =~/\.(htm|html|css|js|txt)$/) {
3342: $cfile = &hreflocation('',$file);
1.1201 raeburn 3343: if ($env{'form.forceedit'}) {
3344: $forceview = 1;
3345: } else {
3346: $forceedit = 1;
3347: }
1.1194 raeburn 3348: }
3349: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3350: $incourse = 1;
3351: if ($env{'form.forceedit'}) {
3352: $forceview = 1;
3353: } else {
3354: $forceedit = 1;
3355: }
3356: $cfile = $resurl;
3357: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3358: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3359: $incourse = 1;
3360: if ($env{'form.forceedit'}) {
3361: $forceview = 1;
3362: } else {
3363: $forceedit = 1;
3364: }
3365: $cfile = $resurl;
1.1199 raeburn 3366: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3367: $incourse = 1;
3368: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3369: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3370: $incourse = 1;
1.1199 raeburn 3371: if ($env{'form.forceedit'}) {
3372: $forceview = 1;
3373: } else {
3374: $forceedit = 1;
3375: }
3376: $cfile = $resurl;
1.1343 raeburn 3377: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3378: $incourse = 1;
3379: if ($env{'form.forceedit'}) {
3380: $forceview = 1;
3381: } else {
3382: $forceedit = 1;
3383: }
3384: $cfile = $resurl;
1.1208 raeburn 3385: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3386: $incourse = 1;
3387: if ($env{'form.forceedit'}) {
3388: $forceview = 1;
3389: } else {
3390: $forceedit = 1;
3391: }
3392: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3393: }
3394: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3395: my $template = '/res/lib/templates/simpleproblem.problem';
3396: if (&is_on_map($template)) {
3397: $incourse = 1;
3398: $forceview = 1;
3399: $cfile = $template;
1.1193 raeburn 3400: }
1.1199 raeburn 3401: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3402: $incourse = 1;
3403: if ($env{'form.forceedit'}) {
3404: $forceview = 1;
3405: } else {
3406: $forceedit = 1;
3407: }
3408: $cfile = $resurl;
1.1343 raeburn 3409: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298 raeburn 3410: $incourse = 1;
3411: if ($env{'form.forceedit'}) {
3412: $forceview = 1;
3413: } else {
3414: $forceedit = 1;
3415: }
3416: $cfile = $resurl;
1.1199 raeburn 3417: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3418: $incourse = 1;
3419: $forceview = 1;
3420: if ($symb) {
3421: my ($map,$id,$res)=&decode_symb($symb);
3422: $env{'request.symb'} = $symb;
3423: $cfile = &clutter($res);
3424: } else {
3425: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3426: my $escfile = &unescape($cfile);
1.1343 raeburn 3427: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3428: $cfile = '/adm/wrapper'.$escfile;
3429: } else {
3430: $escfile =~ s{^http://}{};
3431: $cfile = &escape("/adm/wrapper/ext/$escfile");
3432: }
1.1199 raeburn 3433: }
1.1234 raeburn 3434: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3435: if ($env{'form.forceedit'}) {
3436: $forceview = 1;
3437: } else {
3438: $forceedit = 1;
3439: }
3440: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 3441: }
3442: }
1.1194 raeburn 3443: if ($uploaded || $incourse) {
3444: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 3445: } elsif ($file !~ m{/$}) {
1.1193 raeburn 3446: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3447: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3448: # Check that the user has permission to edit this resource
3449: my $setpriv = 1;
3450: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3451: if (defined($cfudom)) {
3452: $home=&homeserver($cfuname,$cfudom);
3453: $cfile=$file;
3454: }
3455: }
1.1194 raeburn 3456: if (($cfile ne '') && (!$incourse || $uploaded) &&
3457: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 3458: my @ids=¤t_machine_ids();
3459: unless (grep(/^\Q$home\E$/,@ids)) {
3460: $switchserver=1;
3461: }
3462: }
3463: }
1.1194 raeburn 3464: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 3465: }
3466:
3467: sub is_course_upload {
3468: my ($file,$cnum,$cdom) = @_;
3469: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3470: $uploadpath =~ s{^\/}{};
1.1201 raeburn 3471: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3472: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 3473: return 1;
3474: }
3475: return;
3476: }
3477:
1.1194 raeburn 3478: sub in_course {
1.1195 raeburn 3479: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3480: if ($hideprivileged) {
3481: my $skipuser;
1.1219 raeburn 3482: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3483: my @possdoms = ($cdom);
3484: if ($coursehash{'checkforpriv'}) {
3485: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3486: }
3487: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3488: $skipuser = 1;
3489: if ($coursehash{'nothideprivileged'}) {
3490: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3491: my $user;
3492: if ($item =~ /:/) {
3493: $user = $item;
3494: } else {
3495: $user = join(':',split(/[\@]/,$item));
3496: }
3497: if ($user eq $uname.':'.$udom) {
3498: undef($skipuser);
3499: last;
3500: }
3501: }
3502: }
3503: if ($skipuser) {
3504: return 0;
3505: }
3506: }
3507: }
1.1194 raeburn 3508: $type ||= 'any';
3509: if (!defined($cdom) || !defined($cnum)) {
3510: my $cid = $env{'request.course.id'};
3511: $cdom = $env{'course.'.$cid.'.domain'};
3512: $cnum = $env{'course.'.$cid.'.num'};
3513: }
3514: my $typesref;
1.1195 raeburn 3515: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3516: $typesref = ['active','previous','future'];
3517: } elsif ($type eq 'previous' || $type eq 'future') {
3518: $typesref = [$type];
3519: }
3520: my %roles = &get_my_roles($uname,$udom,'userroles',
3521: $typesref,undef,[$cdom]);
3522: my ($tmp) = keys(%roles);
3523: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3524: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3525: if (@course_roles > 0) {
3526: return 1;
3527: }
3528: return 0;
3529: }
3530:
1.478 albertel 3531: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3532: # input: action, courseID, current domain, intended
1.637 raeburn 3533: # path to file, source of file, instruction to parse file for objects,
3534: # ref to hash for embedded objects,
3535: # ref to hash for codebase of java objects.
1.1095 raeburn 3536: # reference to scalar to accommodate mime type determined
3537: # from File::MMagic if $parser = parse.
1.637 raeburn 3538: #
1.485 raeburn 3539: # output: url to file (if action was uploaddoc),
3540: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3541: #
1.478 albertel 3542: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3543: # course.
1.477 raeburn 3544: #
1.478 albertel 3545: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3546: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3547: # course's home server.
1.477 raeburn 3548: #
1.478 albertel 3549: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3550: # be copied from $source (current location) to
3551: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3552: # and will then be copied to
3553: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3554: # course's home server.
1.485 raeburn 3555: #
1.481 raeburn 3556: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3557: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3558: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3559: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3560: # in course's home server.
1.637 raeburn 3561: #
1.477 raeburn 3562:
3563: sub process_coursefile {
1.1095 raeburn 3564: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3565: $mimetype)=@_;
1.477 raeburn 3566: my $fetchresult;
1.638 albertel 3567: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3568: if ($action eq 'propagate') {
1.638 albertel 3569: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3570: $home);
1.481 raeburn 3571: } else {
1.477 raeburn 3572: my $fpath = '';
3573: my $fname = $file;
1.478 albertel 3574: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3575: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3576: my $filepath = &build_filepath($fpath);
1.481 raeburn 3577: if ($action eq 'copy') {
3578: if ($source eq '') {
3579: $fetchresult = 'no source file';
3580: return $fetchresult;
3581: } else {
3582: my $destination = $filepath.'/'.$fname;
3583: rename($source,$destination);
3584: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3585: $home);
1.481 raeburn 3586: }
3587: } elsif ($action eq 'uploaddoc') {
3588: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3589: print $fh $env{'form.'.$source};
1.481 raeburn 3590: close($fh);
1.637 raeburn 3591: if ($parser eq 'parse') {
1.1024 raeburn 3592: my $mm = new File::MMagic;
1.1095 raeburn 3593: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3594: if ($type eq 'text/html') {
1.1024 raeburn 3595: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3596: unless ($parse_result eq 'ok') {
3597: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3598: }
1.637 raeburn 3599: }
1.1095 raeburn 3600: if (ref($mimetype)) {
3601: $$mimetype = $type;
3602: }
1.637 raeburn 3603: }
1.477 raeburn 3604: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3605: $home);
1.481 raeburn 3606: if ($fetchresult eq 'ok') {
3607: return '/uploaded/'.$fpath.'/'.$fname;
3608: } else {
3609: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3610: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3611: return '/adm/notfound.html';
3612: }
1.477 raeburn 3613: }
3614: }
1.485 raeburn 3615: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3616: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3617: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3618: }
3619: return $fetchresult;
3620: }
3621:
1.637 raeburn 3622: sub build_filepath {
3623: my ($fpath) = @_;
3624: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3625: unless ($fpath eq '') {
3626: my @parts=split('/',$fpath);
3627: foreach my $part (@parts) {
3628: $filepath.= '/'.$part;
3629: if ((-e $filepath)!=1) {
3630: mkdir($filepath,0777);
3631: }
3632: }
3633: }
3634: return $filepath;
3635: }
3636:
3637: sub store_edited_file {
1.638 albertel 3638: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3639: my $file = $primary_url;
3640: $file =~ s#^/uploaded/$docudom/$docuname/##;
3641: my $fpath = '';
3642: my $fname = $file;
3643: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3644: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3645: my $filepath = &build_filepath($fpath);
3646: open(my $fh,'>'.$filepath.'/'.$fname);
3647: print $fh $content;
3648: close($fh);
1.638 albertel 3649: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3650: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3651: $home);
1.637 raeburn 3652: if ($$fetchresult eq 'ok') {
3653: return '/uploaded/'.$fpath.'/'.$fname;
3654: } else {
1.638 albertel 3655: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3656: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3657: return '/adm/notfound.html';
3658: }
3659: }
3660:
1.531 albertel 3661: sub clean_filename {
1.831 albertel 3662: my ($fname,$args)=@_;
1.315 www 3663: # Replace Windows backslashes by forward slashes
1.257 www 3664: $fname=~s/\\/\//g;
1.831 albertel 3665: if (!$args->{'keep_path'}) {
3666: # Get rid of everything but the actual filename
3667: $fname=~s/^.*\/([^\/]+)$/$1/;
3668: }
1.315 www 3669: # Replace spaces by underscores
3670: $fname=~s/\s+/\_/g;
3671: # Replace all other weird characters by nothing
1.831 albertel 3672: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3673: # Replace all .\d. sequences with _\d. so they no longer look like version
3674: # numbers
3675: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3676: return $fname;
3677: }
1.1051 raeburn 3678: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3679: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3680: # image with the same aspect ratio as the original, but with dimensions which do
3681: # not exceed $resizewidth and $resizeheight.
3682:
1.984 neumanie 3683: sub resizeImage {
1.1051 raeburn 3684: my ($img_path,$resizewidth,$resizeheight) = @_;
3685: my $ima = Image::Magick->new;
3686: my $resized;
3687: if (-e $img_path) {
3688: $ima->Read($img_path);
3689: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3690: my $width = $ima->Get('width');
3691: my $height = $ima->Get('height');
3692: if ($width > $resizewidth) {
3693: my $factor = $width/$resizewidth;
3694: my $newheight = $height/$factor;
3695: $ima->Scale(width=>$resizewidth,height=>$newheight);
3696: $resized = 1;
3697: }
3698: }
3699: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3700: my $width = $ima->Get('width');
3701: my $height = $ima->Get('height');
3702: if ($height > $resizeheight) {
3703: my $factor = $height/$resizeheight;
3704: my $newwidth = $width/$factor;
3705: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3706: $resized = 1;
3707: }
3708: }
3709: if ($resized) {
3710: $ima->Write($img_path);
3711: }
3712: }
3713: return;
1.977 amueller 3714: }
3715:
1.608 albertel 3716: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3717: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3718: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3719: # $context - possible values: coursedoc, existingfile, overwrite,
3720: # canceloverwrite, or ''.
3721: # if 'coursedoc': upload to the current course
3722: # if 'existingfile': write file to tmp/overwrites directory
3723: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3724: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3725: # $subdir - directory in userfile to store the file into
1.858 raeburn 3726: # $parser - instruction to parse file for objects ($parser = parse)
3727: # $allfiles - reference to hash for embedded objects
3728: # $codebase - reference to hash for codebase of java objects
3729: # $desuname - username for permanent storage of uploaded file
3730: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3731: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3732: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3733: # $resizewidth - width (pixels) to which to resize uploaded image
3734: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3735: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3736: # from File::MMagic.
1.858 raeburn 3737: #
1.686 albertel 3738: # output: url of file in userspace, or error: <message>
3739: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3740:
1.531 albertel 3741: sub userfileupload {
1.1090 raeburn 3742: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3743: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3744: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3745: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3746: $fname=&clean_filename($fname);
1.1090 raeburn 3747: # See if there is anything left
1.257 www 3748: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3749: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3750: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3751: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3752: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3753: my $now = time;
1.1090 raeburn 3754: my $filepath;
1.1095 raeburn 3755: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3756: $filepath = 'tmp/helprequests/'.$now;
3757: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3758: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3759: '_'.$env{'user.domain'}.'/pending';
3760: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3761: my ($docuname,$docudom);
1.1350 raeburn 3762: if ($destudom =~ /^$match_domain$/) {
1.1090 raeburn 3763: $docudom = $destudom;
3764: } else {
3765: $docudom = $env{'user.domain'};
3766: }
1.1350 raeburn 3767: if ($destuname =~ /^$match_username$/) {
1.1090 raeburn 3768: $docuname = $destuname;
3769: } else {
3770: $docuname = $env{'user.name'};
3771: }
3772: if (exists($env{'form.group'})) {
3773: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3774: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3775: }
3776: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3777: if ($context eq 'canceloverwrite') {
3778: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3779: if (-e $tempfile) {
3780: my @info = stat($tempfile);
3781: if ($info[9] eq $env{'form.timestamp'}) {
3782: unlink($tempfile);
3783: }
3784: }
3785: return;
1.523 raeburn 3786: }
3787: }
1.1090 raeburn 3788: # Create the directory if not present
1.741 raeburn 3789: my @parts=split(/\//,$filepath);
3790: my $fullpath = $perlvar{'lonDaemons'};
3791: for (my $i=0;$i<@parts;$i++) {
3792: $fullpath .= '/'.$parts[$i];
3793: if ((-e $fullpath)!=1) {
3794: mkdir($fullpath,0777);
3795: }
3796: }
3797: open(my $fh,'>'.$fullpath.'/'.$fname);
3798: print $fh $env{'form.'.$formname};
3799: close($fh);
1.1090 raeburn 3800: if ($context eq 'existingfile') {
3801: my @info = stat($fullpath.'/'.$fname);
3802: return ($fullpath.'/'.$fname,$info[9]);
3803: } else {
3804: return $fullpath.'/'.$fname;
3805: }
1.523 raeburn 3806: }
1.995 raeburn 3807: if ($subdir eq 'scantron') {
3808: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3809: } else {
1.995 raeburn 3810: $fname="$subdir/$fname";
3811: }
1.1090 raeburn 3812: if ($context eq 'coursedoc') {
1.638 albertel 3813: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3814: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3815: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3816: return &finishuserfileupload($docuname,$docudom,
3817: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3818: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3819: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3820: } else {
1.1218 raeburn 3821: if ($env{'form.folder'}) {
3822: $fname=$env{'form.folder'}.'/'.$fname;
3823: }
1.638 albertel 3824: return &process_coursefile('uploaddoc',$docuname,$docudom,
3825: $fname,$formname,$parser,
1.1095 raeburn 3826: $allfiles,$codebase,$mimetype);
1.481 raeburn 3827: }
1.719 banghart 3828: } elsif (defined($destuname)) {
3829: my $docuname=$destuname;
3830: my $docudom=$destudom;
1.860 raeburn 3831: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3832: $parser,$allfiles,$codebase,
1.1051 raeburn 3833: $thumbwidth,$thumbheight,
1.1095 raeburn 3834: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3835: } else {
1.638 albertel 3836: my $docuname=$env{'user.name'};
3837: my $docudom=$env{'user.domain'};
1.1220 raeburn 3838: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3839: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3840: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3841: }
1.860 raeburn 3842: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3843: $parser,$allfiles,$codebase,
1.1051 raeburn 3844: $thumbwidth,$thumbheight,
1.1095 raeburn 3845: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3846: }
1.271 www 3847: }
3848:
3849: sub finishuserfileupload {
1.860 raeburn 3850: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3851: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3852: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3853: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3854:
1.860 raeburn 3855: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3856: $file=$fname;
3857: if ($fname=~m|/|) {
3858: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3859: $path.=$fnamepath.'/';
3860: }
1.259 www 3861: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3862: my $count;
3863: for ($count=4;$count<=$#parts;$count++) {
3864: $filepath.="/$parts[$count]";
3865: if ((-e $filepath)!=1) {
3866: mkdir($filepath,0777);
3867: }
3868: }
1.984 neumanie 3869:
1.258 www 3870: # Save the file
3871: {
1.701 albertel 3872: if (!open(FH,'>'.$filepath.'/'.$file)) {
3873: &logthis('Failed to create '.$filepath.'/'.$file);
3874: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3875: return '/adm/notfound.html';
3876: }
1.1090 raeburn 3877: if ($context eq 'overwrite') {
1.1117 foxr 3878: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3879: my $target = $filepath.'/'.$file;
3880: if (-e $source) {
3881: my @info = stat($source);
3882: if ($info[9] eq $env{'form.timestamp'}) {
3883: unless (&File::Copy::move($source,$target)) {
3884: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3885: return "Moving from $source failed";
3886: }
3887: } else {
3888: return "Temporary file: $source had unexpected date/time for last modification";
3889: }
3890: } else {
3891: return "Temporary file: $source missing";
3892: }
3893: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3894: &logthis('Failed to write to '.$filepath.'/'.$file);
3895: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3896: return '/adm/notfound.html';
3897: }
1.570 albertel 3898: close(FH);
1.1051 raeburn 3899: if ($resizewidth && $resizeheight) {
3900: my $mm = new File::MMagic;
3901: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3902: if ($mime_type =~ m{^image/}) {
3903: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3904: }
1.977 amueller 3905: }
1.258 www 3906: }
1.1152 raeburn 3907: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3908: if (ref($mimetype)) {
3909: if ($$mimetype eq '') {
3910: my $mm = new File::MMagic;
3911: my $type = $mm->checktype_filename($filepath.'/'.$file);
3912: $$mimetype = $type;
3913: }
3914: }
3915: }
1.637 raeburn 3916: if ($parser eq 'parse') {
1.1152 raeburn 3917: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3918: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3919: $allfiles,$codebase);
3920: unless ($parse_result eq 'ok') {
3921: &logthis('Failed to parse '.$filepath.$file.
3922: ' for embedded media: '.$parse_result);
3923: }
1.637 raeburn 3924: }
3925: }
1.860 raeburn 3926: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3927: my $input = $filepath.'/'.$file;
3928: my $output = $filepath.'/'.'tn-'.$file;
3929: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3930: system("convert -sample $thumbsize $input $output");
3931: if (-e $filepath.'/'.'tn-'.$file) {
3932: $fetchthumb = 1;
3933: }
3934: }
1.858 raeburn 3935:
1.259 www 3936: # Notify homeserver to grep it
3937: #
1.984 neumanie 3938: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3939: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3940: if ($fetchresult eq 'ok') {
1.860 raeburn 3941: if ($fetchthumb) {
3942: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3943: if ($thumbresult ne 'ok') {
3944: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3945: $docuhome.': '.$thumbresult);
3946: }
3947: }
1.259 www 3948: #
1.258 www 3949: # Return the URL to it
1.494 albertel 3950: return '/uploaded/'.$path.$file;
1.263 www 3951: } else {
1.494 albertel 3952: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3953: ': '.$fetchresult);
1.263 www 3954: return '/adm/notfound.html';
1.858 raeburn 3955: }
1.493 albertel 3956: }
3957:
1.637 raeburn 3958: sub extract_embedded_items {
1.961 raeburn 3959: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3960: my @state = ();
1.1164 raeburn 3961: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3962: my %javafiles = (
3963: codebase => '',
3964: code => '',
3965: archive => ''
3966: );
3967: my %mediafiles = (
3968: src => '',
3969: movie => '',
3970: );
1.648 raeburn 3971: my $p;
3972: if ($content) {
3973: $p = HTML::LCParser->new($content);
3974: } else {
1.961 raeburn 3975: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3976: }
1.641 albertel 3977: while (my $t=$p->get_token()) {
1.640 albertel 3978: if ($t->[0] eq 'S') {
3979: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3980: push(@state, $tagname);
1.648 raeburn 3981: if (lc($tagname) eq 'allow') {
3982: &add_filetype($allfiles,$attr->{'src'},'src');
3983: }
1.640 albertel 3984: if (lc($tagname) eq 'img') {
3985: &add_filetype($allfiles,$attr->{'src'},'src');
3986: }
1.886 albertel 3987: if (lc($tagname) eq 'a') {
1.1222 raeburn 3988: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3989: &add_filetype($allfiles,$attr->{'href'},'href');
3990: }
1.886 albertel 3991: }
1.645 raeburn 3992: if (lc($tagname) eq 'script') {
1.1164 raeburn 3993: my $src;
1.645 raeburn 3994: if ($attr->{'archive'} =~ /\.jar$/i) {
3995: &add_filetype($allfiles,$attr->{'archive'},'archive');
3996: } else {
1.1164 raeburn 3997: if ($attr->{'src'} ne '') {
3998: $src = $attr->{'src'};
3999: &add_filetype($allfiles,$src,'src');
4000: }
4001: }
4002: my $text = $p->get_trimmed_text();
4003: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4004: my @swfargs = split(/,/,$1);
4005: foreach my $item (@swfargs) {
4006: $item =~ s/["']//g;
4007: $item =~ s/^\s+//;
4008: $item =~ s/\s+$//;
4009: }
4010: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4011: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4012: push(@{$related{$swfargs[0]}},$swfargs[2]);
4013: } else {
4014: $related{$swfargs[0]} = [$swfargs[2]];
4015: }
4016: }
1.645 raeburn 4017: }
4018: }
4019: if (lc($tagname) eq 'link') {
4020: if (lc($attr->{'rel'}) eq 'stylesheet') {
4021: &add_filetype($allfiles,$attr->{'href'},'href');
4022: }
4023: }
1.640 albertel 4024: if (lc($tagname) eq 'object' ||
4025: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4026: foreach my $item (keys(%javafiles)) {
4027: $javafiles{$item} = '';
4028: }
1.1164 raeburn 4029: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4030: $lastids{lc($tagname)} = $attr->{'id'};
4031: }
1.640 albertel 4032: }
4033: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4034: my $name = lc($attr->{'name'});
4035: foreach my $item (keys(%javafiles)) {
4036: if ($name eq $item) {
4037: $javafiles{$item} = $attr->{'value'};
4038: last;
4039: }
4040: }
1.1164 raeburn 4041: my $pathfrom;
1.640 albertel 4042: foreach my $item (keys(%mediafiles)) {
4043: if ($name eq $item) {
1.1164 raeburn 4044: $pathfrom = $attr->{'value'};
4045: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4046: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 4047: last;
4048: }
4049: }
1.1164 raeburn 4050: if ($name eq 'flashvars') {
4051: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4052: }
4053: if ($pathfrom ne '') {
4054: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4055: $pathfrom);
4056: }
1.640 albertel 4057: }
4058: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4059: foreach my $item (keys(%javafiles)) {
4060: if ($attr->{$item}) {
4061: $javafiles{$item} = $attr->{$item};
4062: last;
4063: }
4064: }
4065: foreach my $item (keys(%mediafiles)) {
4066: if ($attr->{$item}) {
4067: &add_filetype($allfiles,$attr->{$item},$item);
4068: last;
4069: }
4070: }
1.1164 raeburn 4071: if (lc($tagname) eq 'embed') {
4072: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4073: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4074: $attr->{'src'});
4075: }
4076: }
1.640 albertel 4077: }
1.1243 raeburn 4078: if (lc($tagname) eq 'iframe') {
4079: my $src = $attr->{'src'} ;
4080: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4081: &add_filetype($allfiles,$src,'src');
4082: } elsif ($src =~ m{^/}) {
4083: if ($env{'request.course.id'}) {
4084: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4085: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4086: my $url = &hreflocation('',$fullpath);
4087: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4088: my $relpath = $1;
4089: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4090: &add_filetype($allfiles,$1,'src');
4091: }
4092: }
4093: }
4094: }
4095: }
1.1164 raeburn 4096: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 4097: pop(@state);
1.1164 raeburn 4098: }
1.640 albertel 4099: } elsif ($t->[0] eq 'E') {
4100: my ($tagname) = ($t->[1]);
4101: if ($javafiles{'codebase'} ne '') {
4102: $javafiles{'codebase'} .= '/';
4103: }
4104: if (lc($tagname) eq 'applet' ||
4105: lc($tagname) eq 'object' ||
4106: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4107: ) {
4108: foreach my $item (keys(%javafiles)) {
4109: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4110: my $file=$javafiles{'codebase'}.$javafiles{$item};
4111: &add_filetype($allfiles,$file,$item);
4112: }
4113: }
4114: }
4115: pop @state;
4116: }
4117: }
1.1164 raeburn 4118: foreach my $id (sort(keys(%flashvars))) {
4119: if ($shockwave{$id} ne '') {
4120: my @pairs = split(/\&/,$flashvars{$id});
4121: foreach my $pair (@pairs) {
4122: my ($key,$value) = split(/\=/,$pair);
4123: if ($key eq 'thumb') {
4124: &add_filetype($allfiles,$value,$key);
4125: } elsif ($key eq 'content') {
4126: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4127: my ($ext) = ($value =~ /\.([^.]+)$/);
4128: if ($ext ne '') {
4129: &add_filetype($allfiles,$path.$value,$ext);
4130: }
4131: }
4132: }
4133: }
4134: }
1.637 raeburn 4135: return 'ok';
4136: }
4137:
1.639 albertel 4138: sub add_filetype {
4139: my ($allfiles,$file,$type)=@_;
4140: if (exists($allfiles->{$file})) {
4141: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4142: push(@{$allfiles->{$file}}, &escape($type));
4143: }
4144: } else {
4145: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 4146: }
4147: }
4148:
1.1164 raeburn 4149: sub embedded_dependency {
4150: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4151: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4152: if (($identifier ne '') &&
4153: (ref($related->{$identifier}) eq 'ARRAY') &&
4154: ($pathfrom ne '')) {
4155: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4156: foreach my $dep (@{$related->{$identifier}}) {
4157: &add_filetype($allfiles,$path.$dep,'object');
4158: }
4159: }
4160: }
4161: return;
4162: }
4163:
1.493 albertel 4164: sub removeuploadedurl {
1.984 neumanie 4165: my ($url)=@_;
4166: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4167: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4168: }
4169:
4170: sub removeuserfile {
4171: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4172: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4173: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4174: if ($result eq 'ok') {
1.798 raeburn 4175: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4176: my $metafile = $fname.'.meta';
4177: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4178: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4179: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4180: my $sqlresult =
1.823 albertel 4181: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4182: 'portfolio_metadata',$group,
4183: 'delete');
1.798 raeburn 4184: }
4185: }
4186: return $result;
1.257 www 4187: }
1.15 www 4188:
1.530 albertel 4189: sub mkdiruserfile {
4190: my ($docuname,$docudom,$dir)=@_;
4191: my $home=&homeserver($docuname,$docudom);
4192: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4193: }
4194:
1.531 albertel 4195: sub renameuserfile {
4196: my ($docuname,$docudom,$old,$new)=@_;
4197: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4198: my $result = &reply("renameuserfile:$docudom:$docuname:".
4199: &escape("$old").':'.&escape("$new"),$home);
4200: if ($result eq 'ok') {
4201: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4202: my $oldmeta = $old.'.meta';
4203: my $newmeta = $new.'.meta';
4204: my $metaresult =
4205: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4206: my $url = "/uploaded/$docudom/$docuname/$old";
4207: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4208: my $sqlresult =
1.823 albertel 4209: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4210: 'portfolio_metadata',$group,
4211: 'delete');
1.798 raeburn 4212: }
4213: }
4214: return $result;
1.531 albertel 4215: }
4216:
1.14 www 4217: # ------------------------------------------------------------------------- Log
4218:
4219: sub log {
4220: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4221: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4222: }
4223:
4224: # ------------------------------------------------------------------ Course Log
1.352 www 4225: #
4226: # This routine flushes several buffers of non-mission-critical nature
4227: #
1.157 www 4228:
4229: sub flushcourselogs {
1.352 www 4230: &logthis('Flushing log buffers');
4231: #
4232: # course logs
4233: # This is a log of all transactions in a course, which can be used
4234: # for data mining purposes
4235: #
4236: # It also collects the courseid database, which lists last transaction
4237: # times and course titles for all courseids
4238: #
4239: my %courseidbuffer=();
1.921 raeburn 4240: foreach my $crsid (keys(%courselogs)) {
1.352 www 4241: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4242: &escape($courselogs{$crsid}),
4243: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4244: delete $courselogs{$crsid};
4245: } else {
4246: &logthis('Failed to flush log buffer for '.$crsid);
4247: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4248: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4249: " exceeded maximum size, deleting.</font>");
4250: delete $courselogs{$crsid};
4251: }
1.352 www 4252: }
1.920 raeburn 4253: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4254: 'description' => $coursedescrbuf{$crsid},
4255: 'inst_code' => $courseinstcodebuf{$crsid},
4256: 'type' => $coursetypebuf{$crsid},
4257: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4258: };
1.191 harris41 4259: }
1.352 www 4260: #
4261: # Write course id database (reverse lookup) to homeserver of courses
4262: # Is used in pickcourse
4263: #
1.840 albertel 4264: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4265: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4266: $courseidbuffer{$crs_home},
4267: $crs_home,'timeonly');
1.352 www 4268: }
4269: #
4270: # File accesses
4271: # Writes to the dynamic metadata of resources to get hit counts, etc.
4272: #
1.449 matthew 4273: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4274: if ($entry =~ /___count$/) {
4275: my ($dom,$name);
1.807 albertel 4276: ($dom,$name,undef)=
1.811 albertel 4277: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4278: if (! defined($dom) || $dom eq '' ||
4279: ! defined($name) || $name eq '') {
1.620 albertel 4280: my $cid = $env{'request.course.id'};
4281: $dom = $env{'request.'.$cid.'.domain'};
4282: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4283: }
1.450 matthew 4284: my $value = $accesshash{$entry};
4285: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4286: my %temphash=($url => $value);
1.449 matthew 4287: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4288: if ($result eq 'ok') {
4289: delete $accesshash{$entry};
4290: }
4291: } else {
1.811 albertel 4292: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4293: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4294: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4295: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4296: delete $accesshash{$entry};
4297: }
1.185 www 4298: }
1.191 harris41 4299: }
1.352 www 4300: #
4301: # Roles
4302: # Reverse lookup of user roles for course faculty/staff and co-authorship
4303: #
1.800 albertel 4304: foreach my $entry (keys(%userrolehash)) {
1.351 www 4305: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4306: split(/\:/,$entry);
4307: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4308: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4309: $rudom,$runame) eq 'ok') {
4310: delete $userrolehash{$entry};
4311: }
4312: }
1.662 raeburn 4313: #
1.1334 raeburn 4314: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4315: #
4316: my %domrolebuffer = ();
1.1000 raeburn 4317: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4318: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4319: if ($domrolebuffer{$rudom}) {
4320: $domrolebuffer{$rudom}.='&'.&escape($entry).
4321: '='.&escape($domainrolehash{$entry});
4322: } else {
4323: $domrolebuffer{$rudom}.=&escape($entry).
4324: '='.&escape($domainrolehash{$entry});
4325: }
4326: delete $domainrolehash{$entry};
4327: }
4328: foreach my $dom (keys(%domrolebuffer)) {
1.1324 raeburn 4329: my %servers;
4330: if (defined(&domain($dom,'primary'))) {
4331: my $primary=&domain($dom,'primary');
4332: my $hostname=&hostname($primary);
4333: $servers{$primary} = $hostname;
4334: } else {
4335: %servers = &get_servers($dom,'library');
4336: }
1.841 albertel 4337: foreach my $tryserver (keys(%servers)) {
1.1324 raeburn 4338: if (&reply('domroleput:'.$dom.':'.
4339: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4340: last;
4341: } else {
1.841 albertel 4342: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4343: }
1.662 raeburn 4344: }
4345: }
1.186 www 4346: $dumpcount++;
1.157 www 4347: }
4348:
4349: sub courselog {
4350: my $what=shift;
1.158 www 4351: $what=time.':'.$what;
1.620 albertel 4352: unless ($env{'request.course.id'}) { return ''; }
4353: $coursedombuf{$env{'request.course.id'}}=
4354: $env{'course.'.$env{'request.course.id'}.'.domain'};
4355: $coursenumbuf{$env{'request.course.id'}}=
4356: $env{'course.'.$env{'request.course.id'}.'.num'};
4357: $coursehombuf{$env{'request.course.id'}}=
4358: $env{'course.'.$env{'request.course.id'}.'.home'};
4359: $coursedescrbuf{$env{'request.course.id'}}=
4360: $env{'course.'.$env{'request.course.id'}.'.description'};
4361: $courseinstcodebuf{$env{'request.course.id'}}=
4362: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4363: $courseownerbuf{$env{'request.course.id'}}=
4364: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4365: $coursetypebuf{$env{'request.course.id'}}=
4366: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4367: if (defined $courselogs{$env{'request.course.id'}}) {
4368: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4369: } else {
1.620 albertel 4370: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4371: }
1.620 albertel 4372: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4373: &flushcourselogs();
4374: }
1.158 www 4375: }
4376:
4377: sub courseacclog {
4378: my $fnsymb=shift;
1.620 albertel 4379: unless ($env{'request.course.id'}) { return ''; }
4380: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4381: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4382: $what.=':POST';
1.583 matthew 4383: # FIXME: Probably ought to escape things....
1.800 albertel 4384: foreach my $key (keys(%env)) {
4385: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4386: my $formitem = $1;
4387: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4388: $what.=':'.$formitem.'='.$env{$key};
4389: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4390: $what.=':'.$formitem.'='.$env{$key};
4391: }
1.158 www 4392: }
1.191 harris41 4393: }
1.583 matthew 4394: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4395: # FIXME: We should not be depending on a form parameter that someone
4396: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4397: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4398: $what.= ':POST';
4399: # FIXME: Probably ought to escape things....
4400: foreach my $element ('courseexp','crsfulltext','crsrelated',
4401: 'crsdiscuss') {
1.620 albertel 4402: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4403: }
4404: }
1.158 www 4405: }
4406: &courselog($what);
1.149 www 4407: }
4408:
1.185 www 4409: sub countacc {
4410: my $url=&declutter(shift);
1.458 matthew 4411: return if (! defined($url) || $url eq '');
1.620 albertel 4412: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4413: #
4414: # Mark that this url was used in this course
4415: #
1.620 albertel 4416: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4417: #
4418: # Increase the access count for this resource in this child process
4419: #
1.281 www 4420: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4421: $accesshash{$key}++;
1.185 www 4422: }
1.349 www 4423:
1.361 www 4424: sub linklog {
4425: my ($from,$to)=@_;
4426: $from=&declutter($from);
4427: $to=&declutter($to);
4428: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4429: $accesshash{$to.'___'.$from.'___goto'}=1;
4430: }
1.1160 www 4431:
4432: sub statslog {
4433: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4434: if ($users<2) { return; }
4435: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4436: 'course' => $env{'request.course.id'},
4437: 'sections' => '"all"',
4438: 'num_students' => $users,
4439: 'part' => $part,
4440: 'symb' => $symb,
4441: 'mean_tries' => $av_attempts,
4442: 'deg_of_diff' => $degdiff});
4443: foreach my $key (keys(%dynstore)) {
4444: $accesshash{$key}=$dynstore{$key};
4445: }
4446: }
1.361 www 4447:
1.349 www 4448: sub userrolelog {
4449: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4450: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4451: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4452: $userrolehash
4453: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4454: =$tend.':'.$tstart;
1.662 raeburn 4455: }
1.1169 droeschl 4456: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4457: $userrolehash
4458: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4459: =$tend.':'.$tstart;
4460: }
1.1334 raeburn 4461: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4462: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4463: $domainrolehash
4464: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4465: = $tend.':'.$tstart;
4466: }
1.351 www 4467: }
4468:
1.957 raeburn 4469: sub courserolelog {
4470: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 4471: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4472: my $cdom = $1;
4473: my $cnum = $2;
4474: my $sec = $3;
4475: my $namespace = 'rolelog';
4476: my %storehash = (
4477: role => $trole,
4478: start => $tstart,
4479: end => $tend,
4480: selfenroll => $selfenroll,
4481: context => $context,
4482: );
4483: if ($trole eq 'gr') {
4484: $namespace = 'groupslog';
4485: $storehash{'group'} = $sec;
4486: } else {
4487: $storehash{'section'} = $sec;
4488: }
1.1188 raeburn 4489: &write_log('course',$namespace,\%storehash,$delflag,$username,
4490: $domain,$cnum,$cdom);
1.1184 raeburn 4491: if (($trole ne 'st') || ($sec ne '')) {
4492: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4493: }
4494: }
4495: return;
4496: }
4497:
1.1184 raeburn 4498: sub domainrolelog {
4499: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4500: if ($area =~ m{^/($match_domain)/$}) {
4501: my $cdom = $1;
4502: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4503: my $namespace = 'rolelog';
4504: my %storehash = (
4505: role => $trole,
4506: start => $tstart,
4507: end => $tend,
4508: context => $context,
4509: );
1.1188 raeburn 4510: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4511: $domain,$domconfiguser,$cdom);
1.1184 raeburn 4512: }
4513: return;
4514:
4515: }
4516:
4517: sub coauthorrolelog {
4518: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4519: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4520: my $audom = $1;
4521: my $auname = $2;
4522: my $namespace = 'rolelog';
4523: my %storehash = (
4524: role => $trole,
4525: start => $tstart,
4526: end => $tend,
4527: context => $context,
4528: );
1.1188 raeburn 4529: &write_log('author',$namespace,\%storehash,$delflag,$username,
4530: $domain,$auname,$audom);
1.1184 raeburn 4531: }
4532: return;
4533: }
4534:
1.351 www 4535: sub get_course_adv_roles {
1.948 raeburn 4536: my ($cid,$codes) = @_;
1.620 albertel 4537: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4538: my %coursehash=&coursedescription($cid);
1.988 raeburn 4539: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4540: my %nothide=();
1.800 albertel 4541: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4542: if ($user !~ /:/) {
4543: $nothide{join(':',split(/[\@]/,$user))}=1;
4544: } else {
4545: $nothide{$user}=1;
4546: }
1.470 www 4547: }
1.1219 raeburn 4548: my @possdoms = ($coursehash{'domain'});
4549: if ($coursehash{'checkforpriv'}) {
4550: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4551: }
1.351 www 4552: my %returnhash=();
4553: my %dumphash=
4554: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4555: my $now=time;
1.997 raeburn 4556: my %privileged;
1.1000 raeburn 4557: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4558: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4559: if (($tstart) && ($tstart<0)) { next; }
4560: if (($tend) && ($tend<$now)) { next; }
4561: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4562: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4563: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 4564: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4565: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4566: if ($role eq 'cr') { next; }
1.948 raeburn 4567: if ($codes) {
4568: if ($section) { $role .= ':'.$section; }
4569: if ($returnhash{$role}) {
4570: $returnhash{$role}.=','.$username.':'.$domain;
4571: } else {
4572: $returnhash{$role}=$username.':'.$domain;
4573: }
1.351 www 4574: } else {
1.988 raeburn 4575: my $key=&plaintext($role,$crstype);
1.973 bisitz 4576: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4577: if ($returnhash{$key}) {
4578: $returnhash{$key}.=','.$username.':'.$domain;
4579: } else {
4580: $returnhash{$key}=$username.':'.$domain;
4581: }
1.351 www 4582: }
1.948 raeburn 4583: }
1.400 www 4584: return %returnhash;
4585: }
4586:
4587: sub get_my_roles {
1.937 raeburn 4588: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4589: unless (defined($uname)) { $uname=$env{'user.name'}; }
4590: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4591: my (%dumphash,%nothide);
1.1086 raeburn 4592: if ($context eq 'userroles') {
1.1166 raeburn 4593: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4594: } else {
1.1219 raeburn 4595: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4596: if ($hidepriv) {
4597: my %coursehash=&coursedescription($udom.'_'.$uname);
4598: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4599: if ($user !~ /:/) {
4600: $nothide{join(':',split(/[\@]/,$user))} = 1;
4601: } else {
4602: $nothide{$user} = 1;
4603: }
4604: }
4605: }
1.858 raeburn 4606: }
1.400 www 4607: my %returnhash=();
4608: my $now=time;
1.999 raeburn 4609: my %privileged;
1.800 albertel 4610: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4611: my ($role,$tend,$tstart);
4612: if ($context eq 'userroles') {
1.1149 raeburn 4613: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4614: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4615: } else {
4616: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4617: }
1.400 www 4618: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4619: my $status = 'active';
1.939 raeburn 4620: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4621: $status = 'previous';
4622: }
4623: if (($tstart) && ($now<$tstart)) {
4624: $status = 'future';
4625: }
4626: if (ref($types) eq 'ARRAY') {
4627: if (!grep(/^\Q$status\E$/,@{$types})) {
4628: next;
4629: }
4630: } else {
4631: if ($status ne 'active') {
4632: next;
4633: }
4634: }
1.867 raeburn 4635: my ($rolecode,$username,$domain,$section,$area);
4636: if ($context eq 'userroles') {
1.1186 raeburn 4637: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4638: (undef,$domain,$username,$section) = split(/\//,$area);
4639: } else {
4640: ($role,$username,$domain,$section) = split(/\:/,$entry);
4641: }
1.832 raeburn 4642: if (ref($roledoms) eq 'ARRAY') {
4643: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4644: next;
4645: }
4646: }
4647: if (ref($roles) eq 'ARRAY') {
4648: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4649: if ($role =~ /^cr\//) {
4650: if (!grep(/^cr$/,@{$roles})) {
4651: next;
4652: }
1.1104 raeburn 4653: } elsif ($role =~ /^gr\//) {
4654: if (!grep(/^gr$/,@{$roles})) {
4655: next;
4656: }
1.922 raeburn 4657: } else {
4658: next;
4659: }
1.832 raeburn 4660: }
1.867 raeburn 4661: }
1.937 raeburn 4662: if ($hidepriv) {
1.1219 raeburn 4663: my @privroles = ('dc','su');
1.999 raeburn 4664: if ($context eq 'userroles') {
1.1219 raeburn 4665: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4666: } else {
1.1219 raeburn 4667: my $possdoms = [$domain];
4668: if (ref($roledoms) eq 'ARRAY') {
4669: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4670: }
1.1219 raeburn 4671: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4672: if (!$nothide{$username.':'.$domain}) {
4673: next;
4674: }
4675: }
1.937 raeburn 4676: }
4677: }
1.933 raeburn 4678: if ($withsec) {
4679: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4680: $tstart.':'.$tend;
4681: } else {
4682: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4683: }
1.832 raeburn 4684: }
1.373 www 4685: return %returnhash;
1.399 www 4686: }
4687:
1.1333 raeburn 4688: sub get_all_adhocroles {
4689: my ($dom) = @_;
4690: my @roles_by_num = ();
4691: my %domdefaults = &get_domain_defaults($dom);
4692: my (%description,%access_in_dom,%access_info);
4693: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
4694: my $count = 0;
4695: my %domcurrent = %{$domdefaults{'adhocroles'}};
4696: my %ordered;
4697: foreach my $role (sort(keys(%domcurrent))) {
4698: my ($order,$desc,$access_in_dom);
4699: if (ref($domcurrent{$role}) eq 'HASH') {
4700: $order = $domcurrent{$role}{'order'};
4701: $desc = $domcurrent{$role}{'desc'};
4702: $access_in_dom{$role} = $domcurrent{$role}{'access'};
4703: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
4704: }
4705: if ($order eq '') {
4706: $order = $count;
4707: }
4708: $ordered{$order} = $role;
4709: if ($desc ne '') {
4710: $description{$role} = $desc;
4711: } else {
4712: $description{$role}= $role;
4713: }
4714: $count++;
4715: }
4716: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
4717: push(@roles_by_num,$ordered{$item});
4718: }
4719: }
4720: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
4721: }
4722:
1.1332 raeburn 4723: sub get_my_adhocroles {
1.1333 raeburn 4724: my ($cid,$checkreg) = @_;
4725: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
4726: if ($env{'request.course.id'} eq $cid) {
4727: $cdom = $env{'course.'.$cid.'.domain'};
4728: $cnum = $env{'course.'.$cid.'.num'};
4729: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
4730: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
4731: $cdom = $1;
4732: $cnum = $2;
4733: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
4734: $cdom,$cnum);
4735: }
4736: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
4737: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4738: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
4739: if ($rosterhash{$user} ne '') {
4740: my $type = (split(/:/,$rosterhash{$user}))[5];
4741: return ([],{}) if ($type eq 'auto');
4742: }
4743: }
4744: if (($cdom ne '') && ($cnum ne '')) {
1.1334 raeburn 4745: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332 raeburn 4746: my $then=$env{'user.login.time'};
4747: my $update=$env{'user.update.time'};
1.1335 raeburn 4748: if (!$update) {
4749: $update = $then;
4750: }
4751: my @liveroles;
1.1334 raeburn 4752: foreach my $role ('dh','da') {
4753: if ($env{"user.role.$role./$cdom/"}) {
1.1335 raeburn 4754: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334 raeburn 4755: my $limit = $update;
4756: if ($env{'request.role'} eq "$role./$cdom/") {
4757: $limit = $then;
4758: }
1.1335 raeburn 4759: my $activerole = 1;
4760: if ($tstart && $tstart>$limit) { $activerole = 0; }
4761: if ($tend && $tend <$limit) { $activerole = 0; }
4762: if ($activerole) {
4763: push(@liveroles,$role);
4764: }
1.1334 raeburn 4765: }
1.1332 raeburn 4766: }
1.1335 raeburn 4767: if (@liveroles) {
1.1332 raeburn 4768: if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333 raeburn 4769: my ($accessref,$accessinfo,%access_in_dom);
4770: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
4771: if (ref($roles_by_num) eq 'ARRAY') {
4772: if (@{$roles_by_num}) {
1.1332 raeburn 4773: my %settings;
4774: if ($env{'request.course.id'} eq $cid) {
4775: foreach my $envkey (keys(%env)) {
4776: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
4777: $settings{$1} = $env{$envkey};
4778: }
4779: }
4780: } else {
4781: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
4782: }
4783: my %setincrs;
4784: if ($settings{'internal.adhocaccess'}) {
4785: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
4786: }
4787: my @statuses;
4788: if ($env{'environment.inststatus'}) {
4789: @statuses = split(/,/,$env{'environment.inststatus'});
4790: }
4791: my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333 raeburn 4792: if (ref($accessref) eq 'HASH') {
4793: %access_in_dom = %{$accessref};
4794: }
4795: foreach my $role (@{$roles_by_num}) {
1.1332 raeburn 4796: my ($curraccess,@okstatus,@personnel);
4797: if ($setincrs{$role}) {
4798: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
4799: if ($curraccess eq 'status') {
4800: @okstatus = split(/\&/,$rest);
4801: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4802: @personnel = split(/\&/,$rest);
4803: }
4804: } else {
4805: $curraccess = $access_in_dom{$role};
1.1333 raeburn 4806: if (ref($accessinfo) eq 'HASH') {
4807: if ($curraccess eq 'status') {
4808: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4809: @okstatus = @{$accessinfo->{$role}};
4810: }
4811: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4812: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4813: @personnel = @{$accessinfo->{$role}};
4814: }
1.1332 raeburn 4815: }
4816: }
4817: }
4818: if ($curraccess eq 'none') {
4819: next;
4820: } elsif ($curraccess eq 'all') {
4821: push(@possroles,$role);
1.1336 raeburn 4822: } elsif ($curraccess eq 'dh') {
1.1335 raeburn 4823: if (grep(/^dh$/,@liveroles)) {
4824: push(@possroles,$role);
4825: } else {
4826: next;
4827: }
1.1336 raeburn 4828: } elsif ($curraccess eq 'da') {
1.1335 raeburn 4829: if (grep(/^da$/,@liveroles)) {
4830: push(@possroles,$role);
4831: } else {
4832: next;
4833: }
1.1332 raeburn 4834: } elsif ($curraccess eq 'status') {
4835: if (@okstatus) {
4836: if (!@statuses) {
4837: if (grep(/^default$/,@okstatus)) {
4838: push(@possroles,$role);
4839: }
4840: } else {
4841: foreach my $status (@okstatus) {
4842: if (grep(/^\Q$status\E$/,@statuses)) {
4843: push(@possroles,$role);
4844: last;
4845: }
4846: }
4847: }
4848: }
4849: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4850: if (grep(/^\Q$user\E$/,@personnel)) {
4851: if ($curraccess eq 'exc') {
4852: push(@possroles,$role);
4853: }
4854: } elsif ($curraccess eq 'inc') {
4855: push(@possroles,$role);
4856: }
4857: }
4858: }
4859: }
4860: }
4861: }
4862: }
4863: }
4864: }
1.1333 raeburn 4865: unless (ref($description) eq 'HASH') {
4866: if (ref($roles_by_num) eq 'ARRAY') {
4867: my %desc;
4868: map { $desc{$_} = $_; } (@{$roles_by_num});
4869: $description = \%desc;
4870: } else {
4871: $description = {};
4872: }
4873: }
4874: return (\@possroles,$description);
1.1332 raeburn 4875: }
4876:
1.399 www 4877: # ----------------------------------------------------- Frontpage Announcements
4878: #
4879: #
4880:
4881: sub postannounce {
4882: my ($server,$text)=@_;
1.844 albertel 4883: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4884: unless ($text=~/\w/) { $text=''; }
4885: return &reply('setannounce:'.&escape($text),$server);
4886: }
4887:
4888: sub getannounce {
1.448 albertel 4889:
4890: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4891: my $announcement='';
1.800 albertel 4892: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4893: close($fh);
1.399 www 4894: if ($announcement=~/\w/) {
4895: return
4896: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4897: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4898: } else {
4899: return '';
4900: }
4901: } else {
4902: return '';
4903: }
1.351 www 4904: }
1.353 www 4905:
4906: # ---------------------------------------------------------- Course ID routines
4907: # Deal with domain's nohist_courseid.db files
4908: #
4909:
4910: sub courseidput {
1.921 raeburn 4911: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4912: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4913: my $outcome;
4914: if ($caller eq 'timeonly') {
4915: my $cids = '';
4916: foreach my $item (keys(%$storehash)) {
4917: $cids.=&escape($item).'&';
4918: }
4919: $cids=~s/\&$//;
4920: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4921: $coursehome);
4922: } else {
4923: my $items = '';
4924: foreach my $item (keys(%$storehash)) {
4925: $items.= &escape($item).'='.
4926: &freeze_escape($$storehash{$item}).'&';
4927: }
4928: $items=~s/\&$//;
4929: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4930: $coursehome);
1.918 raeburn 4931: }
4932: if ($outcome eq 'unknown_cmd') {
4933: my $what;
4934: foreach my $cid (keys(%$storehash)) {
4935: $what .= &escape($cid).'=';
1.921 raeburn 4936: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4937: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4938: }
4939: $what =~ s/\:$/&/;
4940: }
4941: $what =~ s/\&$//;
4942: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4943: } else {
4944: return $outcome;
4945: }
1.353 www 4946: }
4947:
4948: sub courseiddump {
1.921 raeburn 4949: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4950: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4951: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4952: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 4953: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4954: my $as_hash = 1;
4955: my %returnhash;
4956: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4957: my %libserv = &all_library();
4958: foreach my $tryserver (keys(%libserv)) {
4959: if ( ( $hostidflag == 1
4960: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4961: || (!defined($hostidflag)) ) {
4962:
1.918 raeburn 4963: if (($domfilter eq '') ||
4964: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4965: my $rep;
4966: if (grep { $_ eq $tryserver } current_machine_ids()) {
4967: $rep = LONCAPA::Lond::dump_course_id_handler(
4968: join(":", (&host_domain($tryserver), $sincefilter,
4969: &escape($descfilter), &escape($instcodefilter),
4970: &escape($ownerfilter), &escape($coursefilter),
4971: &escape($typefilter), &escape($regexp_ok),
4972: $as_hash, &escape($selfenrollonly),
4973: &escape($catfilter), $showhidden, $caller,
4974: &escape($cloner), &escape($cc_clone), $cloneonly,
4975: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 4976: &escape($creationcontext),$domcloner,$hasuniquecode,
4977: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 4978: } else {
4979: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4980: $sincefilter.':'.&escape($descfilter).':'.
4981: &escape($instcodefilter).':'.&escape($ownerfilter).
4982: ':'.&escape($coursefilter).':'.&escape($typefilter).
4983: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4984: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4985: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4986: &escape($cc_clone).':'.$cloneonly.':'.
4987: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 4988: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4989: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 4990: }
4991:
1.918 raeburn 4992: my @pairs=split(/\&/,$rep);
4993: foreach my $item (@pairs) {
4994: my ($key,$value)=split(/\=/,$item,2);
4995: $key = &unescape($key);
4996: next if ($key =~ /^error: 2 /);
4997: my $result = &thaw_unescape($value);
4998: if (ref($result) eq 'HASH') {
4999: $returnhash{$key}=$result;
5000: } else {
1.921 raeburn 5001: my @responses = split(/:/,$value);
5002: my @items = ('description','inst_code','owner','type');
1.918 raeburn 5003: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 5004: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 5005: }
1.1008 raeburn 5006: }
1.353 www 5007: }
5008: }
5009: }
5010: }
5011: return %returnhash;
5012: }
5013:
1.1055 raeburn 5014: sub courselastaccess {
5015: my ($cdom,$cnum,$hostidref) = @_;
5016: my %returnhash;
5017: if ($cdom && $cnum) {
5018: my $chome = &homeserver($cnum,$cdom);
5019: if ($chome ne 'no_host') {
5020: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5021: &extract_lastaccess(\%returnhash,$rep);
5022: }
5023: } else {
5024: if (!$cdom) { $cdom=''; }
5025: my %libserv = &all_library();
5026: foreach my $tryserver (keys(%libserv)) {
5027: if (ref($hostidref) eq 'ARRAY') {
5028: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5029: }
5030: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5031: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5032: &extract_lastaccess(\%returnhash,$rep);
5033: }
5034: }
5035: }
5036: return %returnhash;
5037: }
5038:
5039: sub extract_lastaccess {
5040: my ($returnhash,$rep) = @_;
5041: if (ref($returnhash) eq 'HASH') {
5042: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5043: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5044: $rep eq '') {
5045: my @pairs=split(/\&/,$rep);
5046: foreach my $item (@pairs) {
5047: my ($key,$value)=split(/\=/,$item,2);
5048: $key = &unescape($key);
5049: next if ($key =~ /^error: 2 /);
5050: $returnhash->{$key} = &thaw_unescape($value);
5051: }
5052: }
5053: }
5054: return;
5055: }
5056:
1.658 raeburn 5057: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 5058:
5059: sub dcmailput {
1.685 raeburn 5060: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 5061: my $status = &Apache::lonnet::critical(
1.740 www 5062: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5063: &escape($message),$server);
1.662 raeburn 5064: return $status;
5065: }
5066:
1.658 raeburn 5067: sub dcmaildump {
5068: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 5069: my %returnhash=();
1.846 albertel 5070:
5071: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 5072: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5073: &escape($enddate).':';
5074: my @esc_senders=map { &escape($_)} @$senders;
5075: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 5076: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 5077: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 5078: if (($key) && ($value)) {
5079: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 5080: }
5081: }
5082: }
5083: return %returnhash;
5084: }
1.662 raeburn 5085: # ---------------------------------------------------------- Domain roles
5086:
5087: sub get_domain_roles {
5088: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 5089: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 5090: $startdate = '.';
5091: }
1.1018 raeburn 5092: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 5093: $enddate = '.';
5094: }
1.922 raeburn 5095: my $rolelist;
5096: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 5097: $rolelist = join('&',@{$roles});
1.922 raeburn 5098: }
1.662 raeburn 5099: my %personnel = ();
1.841 albertel 5100:
5101: my %servers = &get_servers($dom,'library');
5102: foreach my $tryserver (keys(%servers)) {
5103: %{$personnel{$tryserver}}=();
5104: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5105: &escape($startdate).':'.
5106: &escape($enddate).':'.
5107: &escape($rolelist), $tryserver))) {
5108: my ($key,$value) = split(/\=/,$line,2);
5109: if (($key) && ($value)) {
5110: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5111: }
5112: }
1.662 raeburn 5113: }
5114: return %personnel;
5115: }
1.658 raeburn 5116:
1.1332 raeburn 5117: sub get_active_domroles {
5118: my ($dom,$roles) = @_;
5119: return () unless (ref($roles) eq 'ARRAY');
5120: my $now = time;
5121: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5122: my %domroles;
5123: foreach my $server (keys(%dompersonnel)) {
5124: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5125: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5126: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5127: }
5128: }
5129: return %domroles;
5130: }
5131:
1.1057 www 5132: # ----------------------------------------------------------- Interval timing
1.149 www 5133:
1.1153 www 5134: {
5135: # Caches needed for speedup of navmaps
5136: # We don't want to cache this for very long at all (5 seconds at most)
5137: #
5138: # The user for whom we cache
5139: my $cachedkey='';
5140: # The cached times for this user
5141: my %cachedtimes=();
5142: # When this was last done
1.1282 raeburn 5143: my $cachedtime='';
1.1153 www 5144:
5145: sub load_all_first_access {
1.1308 raeburn 5146: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 5147: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 raeburn 5148: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5149: (!$ignorecache)) {
1.1154 raeburn 5150: return;
5151: }
5152: $cachedtime=time;
5153: $cachedkey=$uname.':'.$udom;
5154: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 5155: }
5156:
1.504 albertel 5157: sub get_first_access {
1.1308 raeburn 5158: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 5159: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5160: if ($argsymb) { $symb=$argsymb; }
5161: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 5162: if ($argmap) { $map = $argmap; }
1.926 albertel 5163: if ($type eq 'course') {
5164: $res='course';
5165: } elsif ($type eq 'map') {
1.588 albertel 5166: $res=&symbread($map);
5167: } else {
5168: $res=$symb;
5169: }
1.1308 raeburn 5170: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 5171: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5172: }
5173:
5174: sub set_first_access {
1.1162 raeburn 5175: my ($type,$interval)=@_;
1.790 albertel 5176: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5177: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5178: if ($type eq 'course') {
5179: $res='course';
5180: } elsif ($type eq 'map') {
1.588 albertel 5181: $res=&symbread($map);
5182: } else {
5183: $res=$symb;
5184: }
1.1153 www 5185: $cachedkey='';
1.1162 raeburn 5186: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 5187: if (!$firstaccess) {
1.1162 raeburn 5188: my $start = time;
5189: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5190: $udom,$uname);
5191: if ($putres eq 'ok') {
5192: &put('timerinterval',{"$courseid\0$res"=>$interval},
5193: $udom,$uname);
5194: &appenv(
5195: {
5196: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5197: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5198: }
5199: );
5200: }
5201: return $putres;
1.505 albertel 5202: }
5203: return 'already_set';
1.504 albertel 5204: }
1.1153 www 5205: }
1.1282 raeburn 5206:
1.110 www 5207: # --------------------------------------------- Set Expire Date for Spreadsheet
5208:
5209: sub expirespread {
5210: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5211: my $cid=$env{'request.course.id'};
1.110 www 5212: if ($cid) {
5213: my $now=time;
5214: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5215: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5216: $env{'course.'.$cid.'.num'}.
1.110 www 5217: ':nohist_expirationdates:'.
5218: &escape($key).'='.$now,
1.620 albertel 5219: $env{'course.'.$cid.'.home'})
1.110 www 5220: }
5221: return 'ok';
1.14 www 5222: }
5223:
1.109 www 5224: # ----------------------------------------------------- Devalidate Spreadsheets
5225:
5226: sub devalidate {
1.325 www 5227: my ($symb,$uname,$udom)=@_;
1.620 albertel 5228: my $cid=$env{'request.course.id'};
1.109 www 5229: if ($cid) {
1.391 matthew 5230: # delete the stored spreadsheets for
5231: # - the student level sheet of this user in course's homespace
5232: # - the assessment level sheet for this resource
5233: # for this user in user's homespace
1.553 albertel 5234: # - current conditional state info
1.325 www 5235: my $key=$uname.':'.$udom.':';
1.109 www 5236: my $status=
1.299 matthew 5237: &del('nohist_calculatedsheets',
1.391 matthew 5238: [$key.'studentcalc:'],
1.620 albertel 5239: $env{'course.'.$cid.'.domain'},
5240: $env{'course.'.$cid.'.num'})
1.133 albertel 5241: .' '.
5242: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5243: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5244: unless ($status eq 'ok ok') {
5245: &logthis('Could not devalidate spreadsheet '.
1.325 www 5246: $uname.' at '.$udom.' for '.
1.109 www 5247: $symb.': '.$status);
1.133 albertel 5248: }
1.553 albertel 5249: &delenv('user.state.'.$cid);
1.109 www 5250: }
5251: }
5252:
1.265 albertel 5253: sub get_scalar {
5254: my ($string,$end) = @_;
5255: my $value;
5256: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5257: $value = $1;
5258: } elsif ($$string =~ s/^([^&]*?)&//) {
5259: $value = $1;
5260: }
5261: return &unescape($value);
5262: }
5263:
5264: sub array2str {
5265: my (@array) = @_;
5266: my $result=&arrayref2str(\@array);
5267: $result=~s/^__ARRAY_REF__//;
5268: $result=~s/__END_ARRAY_REF__$//;
5269: return $result;
5270: }
5271:
1.204 albertel 5272: sub arrayref2str {
5273: my ($arrayref) = @_;
1.265 albertel 5274: my $result='__ARRAY_REF__';
1.204 albertel 5275: foreach my $elem (@$arrayref) {
1.265 albertel 5276: if(ref($elem) eq 'ARRAY') {
5277: $result.=&arrayref2str($elem).'&';
5278: } elsif(ref($elem) eq 'HASH') {
5279: $result.=&hashref2str($elem).'&';
5280: } elsif(ref($elem)) {
5281: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5282: } else {
5283: $result.=&escape($elem).'&';
5284: }
5285: }
5286: $result=~s/\&$//;
1.265 albertel 5287: $result .= '__END_ARRAY_REF__';
1.204 albertel 5288: return $result;
5289: }
5290:
1.168 albertel 5291: sub hash2str {
1.204 albertel 5292: my (%hash) = @_;
5293: my $result=&hashref2str(\%hash);
1.265 albertel 5294: $result=~s/^__HASH_REF__//;
5295: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5296: return $result;
5297: }
5298:
5299: sub hashref2str {
5300: my ($hashref)=@_;
1.265 albertel 5301: my $result='__HASH_REF__';
1.800 albertel 5302: foreach my $key (sort(keys(%$hashref))) {
5303: if (ref($key) eq 'ARRAY') {
5304: $result.=&arrayref2str($key).'=';
5305: } elsif (ref($key) eq 'HASH') {
5306: $result.=&hashref2str($key).'=';
5307: } elsif (ref($key)) {
1.265 albertel 5308: $result.='=';
1.800 albertel 5309: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5310: } else {
1.1132 raeburn 5311: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5312: }
5313:
1.800 albertel 5314: if(ref($hashref->{$key}) eq 'ARRAY') {
5315: $result.=&arrayref2str($hashref->{$key}).'&';
5316: } elsif(ref($hashref->{$key}) eq 'HASH') {
5317: $result.=&hashref2str($hashref->{$key}).'&';
5318: } elsif(ref($hashref->{$key})) {
1.265 albertel 5319: $result.='&';
1.800 albertel 5320: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5321: } else {
1.800 albertel 5322: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5323: }
5324: }
1.168 albertel 5325: $result=~s/\&$//;
1.265 albertel 5326: $result .= '__END_HASH_REF__';
1.168 albertel 5327: return $result;
5328: }
5329:
5330: sub str2hash {
1.265 albertel 5331: my ($string)=@_;
5332: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5333: return %$hash;
5334: }
5335:
5336: sub str2hashref {
1.168 albertel 5337: my ($string) = @_;
1.265 albertel 5338:
5339: my %hash;
5340:
5341: if($string !~ /^__HASH_REF__/) {
5342: if (! ($string eq '' || !defined($string))) {
5343: $hash{'error'}='Not hash reference';
5344: }
5345: return (\%hash, $string);
5346: }
5347:
5348: $string =~ s/^__HASH_REF__//;
5349:
5350: while($string !~ /^__END_HASH_REF__/) {
5351: #key
5352: my $key='';
5353: if($string =~ /^__HASH_REF__/) {
5354: ($key, $string)=&str2hashref($string);
5355: if(defined($key->{'error'})) {
5356: $hash{'error'}='Bad data';
5357: return (\%hash, $string);
5358: }
5359: } elsif($string =~ /^__ARRAY_REF__/) {
5360: ($key, $string)=&str2arrayref($string);
5361: if($key->[0] eq 'Array reference error') {
5362: $hash{'error'}='Bad data';
5363: return (\%hash, $string);
5364: }
5365: } else {
5366: $string =~ s/^(.*?)=//;
1.267 albertel 5367: $key=&unescape($1);
1.265 albertel 5368: }
5369: $string =~ s/^=//;
5370:
5371: #value
5372: my $value='';
5373: if($string =~ /^__HASH_REF__/) {
5374: ($value, $string)=&str2hashref($string);
5375: if(defined($value->{'error'})) {
5376: $hash{'error'}='Bad data';
5377: return (\%hash, $string);
5378: }
5379: } elsif($string =~ /^__ARRAY_REF__/) {
5380: ($value, $string)=&str2arrayref($string);
5381: if($value->[0] eq 'Array reference error') {
5382: $hash{'error'}='Bad data';
5383: return (\%hash, $string);
5384: }
5385: } else {
5386: $value=&get_scalar(\$string,'__END_HASH_REF__');
5387: }
5388: $string =~ s/^&//;
5389:
5390: $hash{$key}=$value;
1.204 albertel 5391: }
1.265 albertel 5392:
5393: $string =~ s/^__END_HASH_REF__//;
5394:
5395: return (\%hash, $string);
1.204 albertel 5396: }
5397:
5398: sub str2array {
1.265 albertel 5399: my ($string)=@_;
5400: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5401: return @$array;
5402: }
5403:
5404: sub str2arrayref {
1.204 albertel 5405: my ($string) = @_;
1.265 albertel 5406: my @array;
5407:
5408: if($string !~ /^__ARRAY_REF__/) {
5409: if (! ($string eq '' || !defined($string))) {
5410: $array[0]='Array reference error';
5411: }
5412: return (\@array, $string);
5413: }
5414:
5415: $string =~ s/^__ARRAY_REF__//;
5416:
5417: while($string !~ /^__END_ARRAY_REF__/) {
5418: my $value='';
5419: if($string =~ /^__HASH_REF__/) {
5420: ($value, $string)=&str2hashref($string);
5421: if(defined($value->{'error'})) {
5422: $array[0] ='Array reference error';
5423: return (\@array, $string);
5424: }
5425: } elsif($string =~ /^__ARRAY_REF__/) {
5426: ($value, $string)=&str2arrayref($string);
5427: if($value->[0] eq 'Array reference error') {
5428: $array[0] ='Array reference error';
5429: return (\@array, $string);
5430: }
5431: } else {
5432: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5433: }
5434: $string =~ s/^&//;
5435:
5436: push(@array, $value);
1.191 harris41 5437: }
1.265 albertel 5438:
5439: $string =~ s/^__END_ARRAY_REF__//;
5440:
5441: return (\@array, $string);
1.168 albertel 5442: }
5443:
1.167 albertel 5444: # -------------------------------------------------------------------Temp Store
5445:
1.168 albertel 5446: sub tmpreset {
5447: my ($symb,$namespace,$domain,$stuname) = @_;
5448: if (!$symb) {
5449: $symb=&symbread();
1.620 albertel 5450: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5451: }
5452: $symb=escape($symb);
5453:
1.620 albertel 5454: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5455: $namespace=~s/\//\_/g;
5456: $namespace=~s/\W//g;
5457:
1.620 albertel 5458: if (!$domain) { $domain=$env{'user.domain'}; }
5459: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5460: if ($domain eq 'public' && $stuname eq 'public') {
5461: $stuname=$ENV{'REMOTE_ADDR'};
5462: }
1.1117 foxr 5463: my $path=LONCAPA::tempdir();
1.168 albertel 5464: my %hash;
5465: if (tie(%hash,'GDBM_File',
5466: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5467: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5468: foreach my $key (keys(%hash)) {
1.180 albertel 5469: if ($key=~ /:$symb/) {
1.168 albertel 5470: delete($hash{$key});
5471: }
5472: }
5473: }
5474: }
5475:
1.167 albertel 5476: sub tmpstore {
1.168 albertel 5477: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5478:
5479: if (!$symb) {
5480: $symb=&symbread();
1.620 albertel 5481: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5482: }
5483: $symb=escape($symb);
5484:
5485: if (!$namespace) {
5486: # I don't think we would ever want to store this for a course.
5487: # it seems this will only be used if we don't have a course.
1.620 albertel 5488: #$namespace=$env{'request.course.id'};
1.168 albertel 5489: #if (!$namespace) {
1.620 albertel 5490: $namespace=$env{'request.state'};
1.168 albertel 5491: #}
5492: }
5493: $namespace=~s/\//\_/g;
5494: $namespace=~s/\W//g;
1.620 albertel 5495: if (!$domain) { $domain=$env{'user.domain'}; }
5496: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5497: if ($domain eq 'public' && $stuname eq 'public') {
5498: $stuname=$ENV{'REMOTE_ADDR'};
5499: }
1.168 albertel 5500: my $now=time;
5501: my %hash;
1.1117 foxr 5502: my $path=LONCAPA::tempdir();
1.168 albertel 5503: if (tie(%hash,'GDBM_File',
5504: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5505: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5506: $hash{"version:$symb"}++;
5507: my $version=$hash{"version:$symb"};
5508: my $allkeys='';
5509: foreach my $key (keys(%$storehash)) {
5510: $allkeys.=$key.':';
1.591 albertel 5511: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5512: }
5513: $hash{"$version:$symb:timestamp"}=$now;
5514: $allkeys.='timestamp';
5515: $hash{"$version:keys:$symb"}=$allkeys;
5516: if (untie(%hash)) {
5517: return 'ok';
5518: } else {
5519: return "error:$!";
5520: }
5521: } else {
5522: return "error:$!";
5523: }
5524: }
1.167 albertel 5525:
1.168 albertel 5526: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5527:
1.168 albertel 5528: sub tmprestore {
5529: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5530:
1.168 albertel 5531: if (!$symb) {
5532: $symb=&symbread();
1.620 albertel 5533: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5534: }
5535: $symb=escape($symb);
5536:
1.620 albertel 5537: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5538:
1.620 albertel 5539: if (!$domain) { $domain=$env{'user.domain'}; }
5540: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5541: if ($domain eq 'public' && $stuname eq 'public') {
5542: $stuname=$ENV{'REMOTE_ADDR'};
5543: }
1.168 albertel 5544: my %returnhash;
5545: $namespace=~s/\//\_/g;
5546: $namespace=~s/\W//g;
5547: my %hash;
1.1117 foxr 5548: my $path=LONCAPA::tempdir();
1.168 albertel 5549: if (tie(%hash,'GDBM_File',
5550: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5551: &GDBM_READER(),0640)) {
1.168 albertel 5552: my $version=$hash{"version:$symb"};
5553: $returnhash{'version'}=$version;
5554: my $scope;
5555: for ($scope=1;$scope<=$version;$scope++) {
5556: my $vkeys=$hash{"$scope:keys:$symb"};
5557: my @keys=split(/:/,$vkeys);
5558: my $key;
5559: $returnhash{"$scope:keys"}=$vkeys;
5560: foreach $key (@keys) {
1.591 albertel 5561: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5562: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5563: }
5564: }
1.168 albertel 5565: if (!(untie(%hash))) {
5566: return "error:$!";
5567: }
5568: } else {
5569: return "error:$!";
5570: }
5571: return %returnhash;
1.167 albertel 5572: }
5573:
1.9 www 5574: # ----------------------------------------------------------------------- Store
5575:
5576: sub store {
1.1269 raeburn 5577: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5578: my $home='';
5579:
1.168 albertel 5580: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5581:
1.213 www 5582: $symb=&symbclean($symb);
1.122 albertel 5583: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5584:
1.620 albertel 5585: if (!$domain) { $domain=$env{'user.domain'}; }
5586: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5587:
5588: &devalidate($symb,$stuname,$domain);
1.109 www 5589:
5590: $symb=escape($symb);
1.187 www 5591: if (!$namespace) {
1.620 albertel 5592: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5593: return '';
5594: }
5595: }
1.620 albertel 5596: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5597:
5598: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5599: $$storehash{'host'}=$perlvar{'lonHostID'};
5600:
1.12 www 5601: my $namevalue='';
1.800 albertel 5602: foreach my $key (keys(%$storehash)) {
5603: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5604: }
1.12 www 5605: $namevalue=~s/\&$//;
1.187 www 5606: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 5607: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5608: }
5609:
1.47 www 5610: # -------------------------------------------------------------- Critical Store
5611:
5612: sub cstore {
1.1269 raeburn 5613: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5614: my $home='';
5615:
1.168 albertel 5616: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5617:
1.213 www 5618: $symb=&symbclean($symb);
1.122 albertel 5619: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5620:
1.620 albertel 5621: if (!$domain) { $domain=$env{'user.domain'}; }
5622: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5623:
5624: &devalidate($symb,$stuname,$domain);
1.109 www 5625:
5626: $symb=escape($symb);
1.187 www 5627: if (!$namespace) {
1.620 albertel 5628: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5629: return '';
5630: }
5631: }
1.620 albertel 5632: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5633:
5634: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5635: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5636:
1.47 www 5637: my $namevalue='';
1.800 albertel 5638: foreach my $key (keys(%$storehash)) {
5639: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5640: }
1.47 www 5641: $namevalue=~s/\&$//;
1.187 www 5642: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5643: return critical
1.1269 raeburn 5644: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5645: }
5646:
1.9 www 5647: # --------------------------------------------------------------------- Restore
5648:
5649: sub restore {
1.124 www 5650: my ($symb,$namespace,$domain,$stuname) = @_;
5651: my $home='';
5652:
1.168 albertel 5653: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5654:
1.122 albertel 5655: if (!$symb) {
1.1224 raeburn 5656: return if ($namespace eq 'courserequests');
5657: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5658: } else {
1.1224 raeburn 5659: unless ($namespace eq 'courserequests') {
5660: $symb=&escape(&symbclean($symb));
5661: }
1.122 albertel 5662: }
1.188 www 5663: if (!$namespace) {
1.620 albertel 5664: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5665: return '';
5666: }
5667: }
1.620 albertel 5668: if (!$domain) { $domain=$env{'user.domain'}; }
5669: if (!$stuname) { $stuname=$env{'user.name'}; }
5670: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5671: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5672:
1.12 www 5673: my %returnhash=();
1.800 albertel 5674: foreach my $line (split(/\&/,$answer)) {
5675: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5676: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5677: }
1.75 www 5678: my $version;
5679: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5680: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5681: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5682: }
1.75 www 5683: }
1.13 www 5684: return %returnhash;
1.34 www 5685: }
5686:
5687: # ---------------------------------------------------------- Course Description
1.1118 foxr 5688: #
5689: #
1.34 www 5690:
5691: sub coursedescription {
1.731 albertel 5692: my ($courseid,$args)=@_;
1.34 www 5693: $courseid=~s/^\///;
1.49 www 5694: $courseid=~s/\_/\//g;
1.34 www 5695: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5696: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5697: my $normalid=$cdomain.'_'.$cnum;
5698: # need to always cache even if we get errors otherwise we keep
5699: # trying and trying and trying to get the course description.
5700: my %envhash=();
5701: my %returnhash=();
1.731 albertel 5702:
5703: my $expiretime=600;
5704: if ($env{'request.course.id'} eq $normalid) {
5705: $expiretime=120;
5706: }
5707:
5708: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5709: if (!$args->{'freshen_cache'}
5710: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5711: foreach my $key (keys(%env)) {
5712: next if ($key !~ /^\Q$prefix\E(.*)/);
5713: my ($setting) = $1;
5714: $returnhash{$setting} = $env{$key};
5715: }
5716: return %returnhash;
5717: }
5718:
1.1118 foxr 5719: # get the data again
5720:
1.731 albertel 5721: if (!$args->{'one_time'}) {
5722: $envhash{'course.'.$normalid.'.last_cache'}=time;
5723: }
1.811 albertel 5724:
1.34 www 5725: if ($chome ne 'no_host') {
1.302 albertel 5726: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5727: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5728: my $username = $env{'user.name'}; # Defult username
5729: if(defined $args->{'user'}) {
5730: $username = $args->{'user'};
5731: }
1.129 albertel 5732: $returnhash{'home'}= $chome;
5733: $returnhash{'domain'} = $cdomain;
5734: $returnhash{'num'} = $cnum;
1.741 raeburn 5735: if (!defined($returnhash{'type'})) {
5736: $returnhash{'type'} = 'Course';
5737: }
1.130 albertel 5738: while (my ($name,$value) = each %returnhash) {
1.53 www 5739: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5740: }
1.270 www 5741: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5742: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5743: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5744: $envhash{'course.'.$normalid.'.home'}=$chome;
5745: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5746: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5747: }
5748: }
1.731 albertel 5749: if (!$args->{'one_time'}) {
1.949 raeburn 5750: &appenv(\%envhash);
1.731 albertel 5751: }
1.302 albertel 5752: return %returnhash;
1.461 www 5753: }
5754:
1.1080 raeburn 5755: sub update_released_required {
5756: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5757: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5758: $cid = $env{'request.course.id'};
5759: $cdom = $env{'course.'.$cid.'.domain'};
5760: $cnum = $env{'course.'.$cid.'.num'};
5761: $chome = $env{'course.'.$cid.'.home'};
5762: }
5763: if ($needsrelease) {
5764: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5765: my $needsupdate;
5766: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5767: $needsupdate = 1;
5768: } else {
5769: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5770: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5771: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5772: $needsupdate = 1;
5773: }
5774: }
5775: if ($needsupdate) {
5776: my %needshash = (
5777: 'internal.releaserequired' => $needsrelease,
5778: );
5779: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5780: if ($putresult eq 'ok') {
5781: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5782: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5783: if (ref($crsinfo{$cid}) eq 'HASH') {
5784: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5785: &courseidput($cdom,\%crsinfo,$chome,'notime');
5786: }
5787: }
5788: }
5789: }
5790: return;
5791: }
5792:
1.461 www 5793: # -------------------------------------------------See if a user is privileged
5794:
5795: sub privileged {
1.1219 raeburn 5796: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5797: my $now = time;
1.1219 raeburn 5798: my $roles;
5799: if (ref($possroles) eq 'ARRAY') {
5800: $roles = $possroles;
5801: } else {
5802: $roles = ['dc','su'];
5803: }
5804: if (ref($possdomains) eq 'ARRAY') {
5805: my %privileged = &privileged_by_domain($possdomains,$roles);
5806: foreach my $dom (@{$possdomains}) {
5807: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5808: (ref($privileged{$dom}) eq 'HASH')) {
5809: foreach my $role (@{$roles}) {
5810: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5811: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5812: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5813: return 1 unless (($end && $end < $now) ||
5814: ($start && $start > $now));
5815: }
5816: }
5817: }
5818: }
5819: }
5820: } else {
5821: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5822: my $now = time;
1.1170 droeschl 5823:
1.1275 musolffc 5824: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5825: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5826: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5827: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5828: or ($tstart && $tstart > $now);
1.1170 droeschl 5829: }
1.1219 raeburn 5830: }
5831: }
5832: return 0;
5833: }
1.1170 droeschl 5834:
1.1219 raeburn 5835: sub privileged_by_domain {
5836: my ($domains,$roles) = @_;
5837: my %privileged = ();
5838: my $cachetime = 60*60*24;
5839: my $now = time;
5840: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5841: return %privileged;
5842: }
5843: foreach my $dom (@{$domains}) {
5844: next if (ref($privileged{$dom}) eq 'HASH');
5845: my $needroles;
5846: foreach my $role (@{$roles}) {
5847: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5848: if (defined($cached)) {
5849: if (ref($result) eq 'HASH') {
5850: $privileged{$dom}{$role} = $result;
5851: }
5852: } else {
5853: $needroles = 1;
5854: }
5855: }
5856: if ($needroles) {
5857: my %dompersonnel = &get_domain_roles($dom,$roles);
5858: $privileged{$dom} = {};
5859: foreach my $server (keys(%dompersonnel)) {
5860: if (ref($dompersonnel{$server}) eq 'HASH') {
5861: foreach my $item (keys(%{$dompersonnel{$server}})) {
5862: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5863: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5864: next if ($end && $end < $now);
5865: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5866: $dompersonnel{$server}{$item};
5867: }
5868: }
5869: }
5870: if (ref($privileged{$dom}) eq 'HASH') {
5871: foreach my $role (@{$roles}) {
5872: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5873: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5874: } else {
5875: my %hash = ();
5876: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5877: }
5878: }
5879: }
5880: }
5881: }
5882: return %privileged;
1.9 www 5883: }
1.1 albertel 5884:
1.103 harris41 5885: # -------------------------------------------------------- Get user privileges
1.11 www 5886:
5887: sub rolesinit {
1.1169 droeschl 5888: my ($domain, $username) = @_;
5889: my %userroles = ('user.login.time' => time);
5890: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5891:
5892: # firstaccess and timerinterval are related to timed maps/resources.
5893: # also, blocking can be triggered by an activating timer
5894: # it's saved in the user's %env.
5895: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5896: my %timerinterval = &dump('timerinterval', $domain, $username);
5897: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5898: %timerintchk, %timerintenv);
5899:
1.1162 raeburn 5900: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5901: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5902: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5903: }
1.1169 droeschl 5904:
1.1162 raeburn 5905: foreach my $key (keys(%timerinterval)) {
5906: my ($cid,$rest) = split(/\0/,$key);
5907: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5908: }
1.1169 droeschl 5909:
1.11 www 5910: my %allroles=();
1.1162 raeburn 5911: my %allgroups=();
1.11 www 5912:
1.1274 raeburn 5913: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5914: my $role = $rolesdump{$area};
5915: $area =~ s/\_\w\w$//;
5916:
5917: my ($trole, $tend, $tstart, $group_privs);
5918:
5919: if ($role =~ /^cr/) {
5920: # Custom role, defined by a user
5921: # e.g., user.role.cr/msu/smith/mynewrole
5922: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5923: $trole = $1;
5924: ($tend, $tstart) = split('_', $2);
5925: } else {
5926: $trole = $role;
5927: }
5928: } elsif ($role =~ m|^gr/|) {
5929: # Role of member in a group, defined within a course/community
5930: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5931: ($trole, $tend, $tstart) = split(/_/, $role);
5932: next if $tstart eq '-1';
5933: ($trole, $group_privs) = split(/\//, $trole);
5934: $group_privs = &unescape($group_privs);
5935: } else {
5936: # Just a normal role, defined in roles.tab
5937: ($trole, $tend, $tstart) = split(/_/,$role);
5938: }
5939:
5940: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5941: $username);
5942: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5943:
5944: # role expired or not available yet?
5945: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5946: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5947:
5948: next if $area eq '' or $trole eq '';
5949:
5950: my $spec = "$trole.$area";
5951: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5952:
5953: if ($trole =~ /^cr\//) {
5954: # Custom role, defined by a user
5955: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5956: } elsif ($trole eq 'gr') {
5957: # Role of a member in a group, defined within a course/community
5958: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5959: next;
5960: } else {
5961: # Normal role, defined in roles.tab
5962: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5963: }
5964:
5965: my $cid = $tdomain.'_'.$trest;
5966: unless ($firstaccchk{$cid}) {
5967: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5968: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5969: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5970: $coursetimerstarts{$cid}{$item};
5971: }
5972: }
5973: $firstaccchk{$cid} = 1;
5974: }
5975: unless ($timerintchk{$cid}) {
5976: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5977: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5978: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5979: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5980: }
1.12 www 5981: }
1.1169 droeschl 5982: $timerintchk{$cid} = 1;
1.191 harris41 5983: }
1.11 www 5984: }
1.1169 droeschl 5985:
1.1341 raeburn 5986: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
5987: \%allroles, \%allgroups);
1.1169 droeschl 5988: $env{'user.adv'} = $userroles{'user.adv'};
1.1341 raeburn 5989: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 5990:
1.1162 raeburn 5991: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5992: }
5993:
1.567 raeburn 5994: sub set_arearole {
1.1215 raeburn 5995: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5996: unless ($nolog) {
1.567 raeburn 5997: # log the associated role with the area
1.1215 raeburn 5998: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5999: }
1.743 albertel 6000: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 6001: }
6002:
6003: sub custom_roleprivs {
6004: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6005: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 6006: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 6007: if (&hostname($homsvr) ne '') {
1.567 raeburn 6008: my ($rdummy,$roledef)=
6009: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6010: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6011: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6012: if (defined($syspriv)) {
1.1043 raeburn 6013: if ($trest =~ /^$match_community$/) {
6014: $syspriv =~ s/bre\&S//;
6015: }
1.567 raeburn 6016: $$allroles{'cm./'}.=':'.$syspriv;
6017: $$allroles{$spec.'./'}.=':'.$syspriv;
6018: }
6019: if ($tdomain ne '') {
6020: if (defined($dompriv)) {
6021: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6022: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6023: }
6024: if (($trest ne '') && (defined($coursepriv))) {
1.1332 raeburn 6025: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6026: my $rolename = $1;
6027: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6028: }
1.567 raeburn 6029: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6030: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6031: }
6032: }
6033: }
6034: }
6035: }
6036:
1.1332 raeburn 6037: sub course_adhocrole_privs {
6038: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6039: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6040: if ($overrides{"internal.adhocpriv.$rolename"}) {
6041: my (%currprivs,%storeprivs);
6042: foreach my $item (split(/:/,$coursepriv)) {
6043: my ($priv,$restrict) = split(/\&/,$item);
6044: $currprivs{$priv} = $restrict;
6045: }
6046: my (%possadd,%possremove,%full);
6047: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6048: my ($priv,$restrict)=split(/\&/,$item);
6049: $full{$priv} = $restrict;
6050: }
6051: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6052: next if ($item eq '');
6053: my ($rule,$rest) = split(/=/,$item);
6054: next unless (($rule eq 'off') || ($rule eq 'on'));
6055: foreach my $priv (split(/:/,$rest)) {
6056: if ($priv ne '') {
6057: if ($rule eq 'off') {
6058: $possremove{$priv} = 1;
6059: } else {
6060: $possadd{$priv} = 1;
6061: }
6062: }
6063: }
6064: }
6065: foreach my $priv (sort(keys(%full))) {
6066: if (exists($currprivs{$priv})) {
6067: unless (exists($possremove{$priv})) {
6068: $storeprivs{$priv} = $currprivs{$priv};
6069: }
6070: } elsif (exists($possadd{$priv})) {
6071: $storeprivs{$priv} = $full{$priv};
6072: }
6073: }
6074: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6075: }
6076: return $coursepriv;
6077: }
6078:
1.678 raeburn 6079: sub group_roleprivs {
6080: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6081: my $access = 1;
6082: my $now = time;
6083: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6084: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6085: if ($access) {
1.811 albertel 6086: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 6087: $$allgroups{$course}{$group} .=':'.$group_privs;
6088: }
6089: }
1.567 raeburn 6090:
6091: sub standard_roleprivs {
6092: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6093: if (defined($pr{$trole.':s'})) {
6094: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6095: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6096: }
6097: if ($tdomain ne '') {
6098: if (defined($pr{$trole.':d'})) {
6099: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6100: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6101: }
6102: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6103: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6104: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6105: }
6106: }
6107: }
6108:
6109: sub set_userprivs {
1.1064 raeburn 6110: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 6111: my $author=0;
6112: my $adv=0;
1.1341 raeburn 6113: my $rar=0;
1.678 raeburn 6114: my %grouproles = ();
6115: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 6116: my @groupkeys;
1.1000 raeburn 6117: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 6118: push(@groupkeys,$role);
6119: }
6120: if (ref($groups_roles) eq 'HASH') {
6121: foreach my $key (keys(%{$groups_roles})) {
6122: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6123: push(@groupkeys,$key);
6124: }
6125: }
6126: }
6127: if (@groupkeys > 0) {
6128: foreach my $role (@groupkeys) {
6129: my ($trole,$area,$sec,$extendedarea);
6130: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6131: $trole = $1;
6132: $area = $2;
6133: $sec = $3;
6134: $extendedarea = $area.$sec;
6135: if (exists($$allgroups{$area})) {
6136: foreach my $group (keys(%{$$allgroups{$area}})) {
6137: my $spec = $trole.'.'.$extendedarea;
6138: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 6139: $$allgroups{$area}{$group};
1.1064 raeburn 6140: }
1.678 raeburn 6141: }
6142: }
6143: }
6144: }
6145: }
1.800 albertel 6146: foreach my $group (keys(%grouproles)) {
6147: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 6148: }
1.800 albertel 6149: foreach my $role (keys(%{$allroles})) {
6150: my %thesepriv;
1.941 raeburn 6151: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 6152: foreach my $item (split(/:/,$$allroles{$role})) {
6153: if ($item ne '') {
6154: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 6155: if ($restrictions eq '') {
6156: $thesepriv{$privilege}='F';
6157: } elsif ($thesepriv{$privilege} ne 'F') {
6158: $thesepriv{$privilege}.=$restrictions;
6159: }
6160: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341 raeburn 6161: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 6162: }
6163: }
6164: my $thesestr='';
1.1104 raeburn 6165: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 6166: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6167: }
6168: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 6169: }
1.1341 raeburn 6170: return ($author,$adv,$rar);
1.567 raeburn 6171: }
6172:
1.994 raeburn 6173: sub role_status {
1.1104 raeburn 6174: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 6175: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 6176: my ($one,$two) = split(m{\./},$rolekey,2);
6177: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 6178: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 6179: $$where = '/'.$two;
1.994 raeburn 6180: $$trolecode=$$role.'.'.$$where;
6181: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6182: $$tstatus='is';
1.1104 raeburn 6183: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6184: $$tstatus='future';
1.1034 raeburn 6185: if ($$tstart<$now) {
6186: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6187: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6188: my (%allroles,%allgroups,$group_privs,
6189: %groups_roles,@rolecodes);
1.1002 raeburn 6190: my %userroles = (
6191: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6192: );
1.1064 raeburn 6193: @rolecodes = ('cm');
1.1002 raeburn 6194: my $spec=$$role.'.'.$$where;
6195: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6196: if ($$role =~ /^cr\//) {
6197: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6198: push(@rolecodes,'cr');
1.1002 raeburn 6199: } elsif ($$role eq 'gr') {
1.1064 raeburn 6200: push(@rolecodes,$$role);
1.1002 raeburn 6201: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6202: $env{'user.name'});
1.1064 raeburn 6203: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6204: (undef,my $group_privs) = split(/\//,$trole);
6205: $group_privs = &unescape($group_privs);
6206: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6207: 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 6208: &get_groups_roles($tdomain,$trest,
6209: \%course_roles,\@rolecodes,
6210: \%groups_roles);
1.1002 raeburn 6211: } else {
1.1064 raeburn 6212: push(@rolecodes,$$role);
1.1002 raeburn 6213: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6214: }
1.1341 raeburn 6215: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6216: \%groups_roles);
1.1064 raeburn 6217: &appenv(\%userroles,\@rolecodes);
1.1342 raeburn 6218: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 6219: }
6220: }
1.1034 raeburn 6221: $$tstatus = 'is';
1.1002 raeburn 6222: }
1.994 raeburn 6223: }
6224: if ($$tend) {
1.1104 raeburn 6225: if ($$tend<$update) {
1.994 raeburn 6226: $$tstatus='expired';
6227: } elsif ($$tend<$now) {
6228: $$tstatus='will_not';
6229: }
6230: }
6231: }
6232: }
6233: }
6234:
1.1104 raeburn 6235: sub get_groups_roles {
6236: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6237: return unless((ref($cdom_courseroles) eq 'HASH') &&
6238: (ref($rolecodes) eq 'ARRAY') &&
6239: (ref($groups_roles) eq 'HASH'));
6240: if (keys(%{$cdom_courseroles}) > 0) {
6241: my ($cnum) = ($rest =~ /^($match_courseid)/);
6242: if ($cdom ne '' && $cnum ne '') {
6243: foreach my $key (keys(%{$cdom_courseroles})) {
6244: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6245: my $crsrole = $1;
6246: my $crssec = $2;
6247: if ($crsrole =~ /^cr/) {
6248: unless (grep(/^cr$/,@{$rolecodes})) {
6249: push(@{$rolecodes},'cr');
6250: }
6251: } else {
6252: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6253: push(@{$rolecodes},$crsrole);
6254: }
6255: }
6256: my $rolekey = "$crsrole./$cdom/$cnum";
6257: if ($crssec ne '') {
6258: $rolekey .= "/$crssec";
6259: }
6260: $rolekey .= './';
6261: $groups_roles->{$rolekey} = $rolecodes;
6262: }
6263: }
6264: }
6265: }
6266: return;
6267: }
6268:
6269: sub delete_env_groupprivs {
6270: my ($where,$courseroles,$possroles) = @_;
6271: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6272: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6273: unless (ref($courseroles->{$udom}) eq 'HASH') {
6274: %{$courseroles->{$udom}} =
6275: &get_my_roles('','','userroles',['active'],
6276: $possroles,[$udom],1);
6277: }
6278: if (ref($courseroles->{$udom}) eq 'HASH') {
6279: foreach my $item (keys(%{$courseroles->{$udom}})) {
6280: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6281: my $area = '/'.$cdom.'/'.$cnum;
6282: my $privkey = "user.priv.$crsrole.$area";
6283: if ($crssec ne '') {
6284: $privkey .= '/'.$crssec;
6285: }
6286: $privkey .= ".$area/$group";
6287: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6288: }
6289: }
6290: return;
6291: }
6292:
1.994 raeburn 6293: sub check_adhoc_privs {
1.1329 raeburn 6294: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6295: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329 raeburn 6296: if ($sec) {
6297: $cckey .= '/'.$sec;
6298: }
1.1185 raeburn 6299: my $setprivs;
1.994 raeburn 6300: if ($env{$cckey}) {
6301: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6302: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6303: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329 raeburn 6304: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 6305: $setprivs = 1;
1.994 raeburn 6306: }
6307: } else {
1.1330 raeburn 6308: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 6309: $setprivs = 1;
1.994 raeburn 6310: }
1.1185 raeburn 6311: return $setprivs;
1.994 raeburn 6312: }
6313:
6314: sub set_adhoc_privileges {
1.1326 raeburn 6315: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329 raeburn 6316: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6317: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329 raeburn 6318: if ($sec ne '') {
6319: $area .= '/'.$sec;
6320: }
1.994 raeburn 6321: my $spec = $role.'.'.$area;
6322: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 6323: $env{'user.name'},1);
1.1326 raeburn 6324: my %rolehash = ();
1.1332 raeburn 6325: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6326: my $rolename = $1;
1.1326 raeburn 6327: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332 raeburn 6328: my %domdef = &get_domain_defaults($dcdom);
6329: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6330: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6331: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6332: }
6333: }
1.1326 raeburn 6334: } else {
6335: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6336: }
1.1341 raeburn 6337: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6338: &appenv(\%userroles,[$role,'cm']);
1.1342 raeburn 6339: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088 raeburn 6340: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6341: &appenv( {'request.role' => $spec,
6342: 'request.role.domain' => $dcdom,
1.1332 raeburn 6343: 'request.course.sec' => $sec,
1.1088 raeburn 6344: }
6345: );
6346: my $tadv=0;
6347: if (&allowed('adv') eq 'F') { $tadv=1; }
6348: &appenv({'request.role.adv' => $tadv});
6349: }
1.994 raeburn 6350: }
6351:
1.12 www 6352: # --------------------------------------------------------------- get interface
6353:
6354: sub get {
1.131 albertel 6355: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6356: my $items='';
1.800 albertel 6357: foreach my $item (@$storearr) {
6358: $items.=&escape($item).'&';
1.191 harris41 6359: }
1.12 www 6360: $items=~s/\&$//;
1.620 albertel 6361: if (!$udomain) { $udomain=$env{'user.domain'}; }
6362: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6363: my $uhome=&homeserver($uname,$udomain);
6364:
1.133 albertel 6365: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6366: my @pairs=split(/\&/,$rep);
1.273 albertel 6367: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6368: return @pairs;
6369: }
1.15 www 6370: my %returnhash=();
1.42 www 6371: my $i=0;
1.800 albertel 6372: foreach my $item (@$storearr) {
6373: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6374: $i++;
1.191 harris41 6375: }
1.15 www 6376: return %returnhash;
1.27 www 6377: }
6378:
6379: # --------------------------------------------------------------- del interface
6380:
6381: sub del {
1.133 albertel 6382: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6383: my $items='';
1.800 albertel 6384: foreach my $item (@$storearr) {
6385: $items.=&escape($item).'&';
1.191 harris41 6386: }
1.984 neumanie 6387:
1.27 www 6388: $items=~s/\&$//;
1.620 albertel 6389: if (!$udomain) { $udomain=$env{'user.domain'}; }
6390: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6391: my $uhome=&homeserver($uname,$udomain);
6392: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6393: }
6394:
6395: # -------------------------------------------------------------- dump interface
6396:
1.1180 droeschl 6397: sub unserialize {
6398: my ($rep, $escapedkeys) = @_;
6399:
6400: return {} if $rep =~ /^error/;
6401:
6402: my %returnhash=();
1.1252 raeburn 6403: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 6404: my ($key, $value) = split(/=/, $item, 2);
6405: $key = unescape($key) unless $escapedkeys;
6406: next if $key =~ /^error: 2 /;
1.1252 raeburn 6407: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 6408: }
6409: #return %returnhash;
6410: return \%returnhash;
6411: }
6412:
6413: # see Lond::dump_with_regexp
6414: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6415: sub dump {
1.1180 droeschl 6416: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6417: if (!$udomain) { $udomain=$env{'user.domain'}; }
6418: if (!$uname) { $uname=$env{'user.name'}; }
6419: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6420:
1.1266 raeburn 6421: if ($regexp) {
6422: $regexp=&escape($regexp);
6423: } else {
6424: $regexp='.';
6425: }
1.1180 droeschl 6426: if (grep { $_ eq $uhome } current_machine_ids()) {
6427: # user is hosted on this machine
1.1266 raeburn 6428: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 6429: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 6430: return %{unserialize($reply, $escapedkeys)};
6431: }
1.1166 raeburn 6432: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6433: my @pairs=split(/\&/,$rep);
6434: my %returnhash=();
1.1098 foxr 6435: if (!($rep =~ /^error/ )) {
6436: foreach my $item (@pairs) {
6437: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 6438: $key = unescape($key) unless $escapedkeys;
6439: #$key = &unescape($key);
1.1098 foxr 6440: next if ($key =~ /^error: 2 /);
6441: $returnhash{$key}=&thaw_unescape($value);
6442: }
1.755 albertel 6443: }
6444: return %returnhash;
1.407 www 6445: }
6446:
1.1098 foxr 6447:
1.717 albertel 6448: # --------------------------------------------------------- dumpstore interface
6449:
6450: sub dumpstore {
6451: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 6452: # same as dump but keys must be escaped. They may contain colon separated
6453: # lists of values that may themself contain colons (e.g. symbs).
6454: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6455: }
6456:
1.407 www 6457: # -------------------------------------------------------------- keys interface
6458:
6459: sub getkeys {
6460: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6461: if (!$udomain) { $udomain=$env{'user.domain'}; }
6462: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6463: my $uhome=&homeserver($uname,$udomain);
6464: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6465: my @keyarray=();
1.800 albertel 6466: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6467: next if ($key =~ /^error: 2 /);
1.800 albertel 6468: push(@keyarray,&unescape($key));
1.407 www 6469: }
6470: return @keyarray;
1.318 matthew 6471: }
6472:
1.319 matthew 6473: # --------------------------------------------------------------- currentdump
6474: sub currentdump {
1.328 matthew 6475: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6476: $courseid = $env{'request.course.id'} if (! defined($courseid));
6477: $sdom = $env{'user.domain'} if (! defined($sdom));
6478: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6479: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 6480: my $rep;
6481:
6482: if (grep { $_ eq $uhome } current_machine_ids()) {
6483: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6484: $courseid)));
6485: } else {
6486: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6487: }
6488:
1.318 matthew 6489: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6490: #
1.318 matthew 6491: my %returnhash=();
1.319 matthew 6492: #
1.1343 raeburn 6493: if ($rep eq 'unknown_cmd') {
1.319 matthew 6494: # an old lond will not know currentdump
6495: # Do a dump and make it look like a currentdump
1.822 albertel 6496: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6497: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6498: my %hash = @tmp;
6499: @tmp=();
1.424 matthew 6500: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6501: } else {
6502: my @pairs=split(/\&/,$rep);
1.800 albertel 6503: foreach my $pair (@pairs) {
6504: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6505: my ($symb,$param) = split(/:/,$key);
6506: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6507: &thaw_unescape($value);
1.319 matthew 6508: }
1.191 harris41 6509: }
1.12 www 6510: return %returnhash;
1.424 matthew 6511: }
6512:
6513: sub convert_dump_to_currentdump{
6514: my %hash = %{shift()};
6515: my %returnhash;
6516: # Code ripped from lond, essentially. The only difference
6517: # here is the unescaping done by lonnet::dump(). Conceivably
6518: # we might run in to problems with parameter names =~ /^v\./
6519: while (my ($key,$value) = each(%hash)) {
6520: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 6521: $symb = &unescape($symb);
6522: $param = &unescape($param);
1.424 matthew 6523: next if ($v eq 'version' || $symb eq 'keys');
6524: next if (exists($returnhash{$symb}) &&
6525: exists($returnhash{$symb}->{$param}) &&
6526: $returnhash{$symb}->{'v.'.$param} > $v);
6527: $returnhash{$symb}->{$param}=$value;
6528: $returnhash{$symb}->{'v.'.$param}=$v;
6529: }
6530: #
6531: # Remove all of the keys in the hashes which keep track of
6532: # the version of the parameter.
6533: while (my ($symb,$param_hash) = each(%returnhash)) {
6534: # use a foreach because we are going to delete from the hash.
6535: foreach my $key (keys(%$param_hash)) {
6536: delete($param_hash->{$key}) if ($key =~ /^v\./);
6537: }
6538: }
6539: return \%returnhash;
1.12 www 6540: }
6541:
1.627 albertel 6542: # ------------------------------------------------------ critical inc interface
6543:
6544: sub cinc {
6545: return &inc(@_,'critical');
6546: }
6547:
1.449 matthew 6548: # --------------------------------------------------------------- inc interface
6549:
6550: sub inc {
1.627 albertel 6551: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 6552: if (!$udomain) { $udomain=$env{'user.domain'}; }
6553: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 6554: my $uhome=&homeserver($uname,$udomain);
6555: my $items='';
6556: if (! ref($store)) {
6557: # got a single value, so use that instead
6558: $items = &escape($store).'=&';
6559: } elsif (ref($store) eq 'SCALAR') {
6560: $items = &escape($$store).'=&';
6561: } elsif (ref($store) eq 'ARRAY') {
6562: $items = join('=&',map {&escape($_);} @{$store});
6563: } elsif (ref($store) eq 'HASH') {
6564: while (my($key,$value) = each(%{$store})) {
6565: $items.= &escape($key).'='.&escape($value).'&';
6566: }
6567: }
6568: $items=~s/\&$//;
1.627 albertel 6569: if ($critical) {
6570: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6571: } else {
6572: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6573: }
1.449 matthew 6574: }
6575:
1.12 www 6576: # --------------------------------------------------------------- put interface
6577:
6578: sub put {
1.134 albertel 6579: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6580: if (!$udomain) { $udomain=$env{'user.domain'}; }
6581: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6582: my $uhome=&homeserver($uname,$udomain);
1.12 www 6583: my $items='';
1.800 albertel 6584: foreach my $item (keys(%$storehash)) {
6585: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6586: }
1.12 www 6587: $items=~s/\&$//;
1.134 albertel 6588: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6589: }
6590:
1.631 albertel 6591: # ------------------------------------------------------------ newput interface
6592:
6593: sub newput {
6594: my ($namespace,$storehash,$udomain,$uname)=@_;
6595: if (!$udomain) { $udomain=$env{'user.domain'}; }
6596: if (!$uname) { $uname=$env{'user.name'}; }
6597: my $uhome=&homeserver($uname,$udomain);
6598: my $items='';
6599: foreach my $key (keys(%$storehash)) {
6600: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6601: }
6602: $items=~s/\&$//;
6603: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6604: }
6605:
6606: # --------------------------------------------------------- putstore interface
6607:
1.524 raeburn 6608: sub putstore {
1.1269 raeburn 6609: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6610: if (!$udomain) { $udomain=$env{'user.domain'}; }
6611: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6612: my $uhome=&homeserver($uname,$udomain);
6613: my $items='';
1.715 albertel 6614: foreach my $key (keys(%$storehash)) {
6615: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6616: }
1.715 albertel 6617: $items=~s/\&$//;
1.716 albertel 6618: my $esc_symb=&escape($symb);
6619: my $esc_v=&escape($version);
1.715 albertel 6620: my $reply =
1.716 albertel 6621: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6622: $uhome);
1.1269 raeburn 6623: if (($tolog) && ($reply eq 'ok')) {
6624: my $namevalue='';
6625: foreach my $key (keys(%{$storehash})) {
6626: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6627: }
6628: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6629: '&host='.&escape($perlvar{'lonHostID'}).
6630: '&version='.$esc_v.
6631: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6632: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6633: }
1.715 albertel 6634: if ($reply eq 'unknown_cmd') {
1.716 albertel 6635: # gfall back to way things use to be done
1.715 albertel 6636: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6637: $uname);
1.524 raeburn 6638: }
1.715 albertel 6639: return $reply;
6640: }
6641:
6642: sub old_putstore {
1.716 albertel 6643: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6644: if (!$udomain) { $udomain=$env{'user.domain'}; }
6645: if (!$uname) { $uname=$env{'user.name'}; }
6646: my $uhome=&homeserver($uname,$udomain);
6647: my %newstorehash;
1.800 albertel 6648: foreach my $item (keys(%$storehash)) {
6649: my $key = $version.':'.&escape($symb).':'.$item;
6650: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6651: }
6652: my $items='';
6653: my %allitems = ();
1.800 albertel 6654: foreach my $item (keys(%newstorehash)) {
6655: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6656: my $key = $1.':keys:'.$2;
6657: $allitems{$key} .= $3.':';
6658: }
1.800 albertel 6659: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6660: }
1.800 albertel 6661: foreach my $item (keys(%allitems)) {
6662: $allitems{$item} =~ s/\:$//;
6663: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6664: }
6665: $items=~s/\&$//;
6666: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6667: }
6668:
1.47 www 6669: # ------------------------------------------------------ critical put interface
6670:
6671: sub cput {
1.134 albertel 6672: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6673: if (!$udomain) { $udomain=$env{'user.domain'}; }
6674: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6675: my $uhome=&homeserver($uname,$udomain);
1.47 www 6676: my $items='';
1.800 albertel 6677: foreach my $item (keys(%$storehash)) {
6678: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6679: }
1.47 www 6680: $items=~s/\&$//;
1.134 albertel 6681: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6682: }
6683:
6684: # -------------------------------------------------------------- eget interface
6685:
6686: sub eget {
1.133 albertel 6687: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6688: my $items='';
1.800 albertel 6689: foreach my $item (@$storearr) {
6690: $items.=&escape($item).'&';
1.191 harris41 6691: }
1.12 www 6692: $items=~s/\&$//;
1.620 albertel 6693: if (!$udomain) { $udomain=$env{'user.domain'}; }
6694: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6695: my $uhome=&homeserver($uname,$udomain);
6696: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6697: my @pairs=split(/\&/,$rep);
6698: my %returnhash=();
1.42 www 6699: my $i=0;
1.800 albertel 6700: foreach my $item (@$storearr) {
6701: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6702: $i++;
1.191 harris41 6703: }
1.12 www 6704: return %returnhash;
6705: }
6706:
1.667 albertel 6707: # ------------------------------------------------------------ tmpput interface
6708: sub tmpput {
1.802 raeburn 6709: my ($storehash,$server,$context)=@_;
1.667 albertel 6710: my $items='';
1.800 albertel 6711: foreach my $item (keys(%$storehash)) {
6712: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6713: }
6714: $items=~s/\&$//;
1.802 raeburn 6715: if (defined($context)) {
6716: $items .= ':'.&escape($context);
6717: }
1.667 albertel 6718: return &reply("tmpput:$items",$server);
6719: }
6720:
6721: # ------------------------------------------------------------ tmpget interface
6722: sub tmpget {
1.688 albertel 6723: my ($token,$server)=@_;
6724: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6725: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6726: my %returnhash;
1.1328 raeburn 6727: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
6728: return %returnhash;
6729: }
1.667 albertel 6730: foreach my $item (split(/\&/,$rep)) {
6731: my ($key,$value)=split(/=/,$item);
6732: $returnhash{&unescape($key)}=&thaw_unescape($value);
6733: }
6734: return %returnhash;
6735: }
6736:
1.1113 raeburn 6737: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6738: sub tmpdel {
6739: my ($token,$server)=@_;
6740: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6741: return &reply("tmpdel:$token",$server);
6742: }
6743:
1.1198 raeburn 6744: # ------------------------------------------------------------ get_timebased_id
6745:
6746: sub get_timebased_id {
6747: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6748: $maxtries) = @_;
6749: my ($newid,$error,$dellock);
6750: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6751: return ('','ok','invalid call to get suffix');
6752: }
6753:
6754: # set defaults for any optional args for which values were not supplied
6755: if ($who eq '') {
6756: $who = $env{'user.name'}.':'.$env{'user.domain'};
6757: }
6758: if (!$locktries) {
6759: $locktries = 3;
6760: }
6761: if (!$maxtries) {
6762: $maxtries = 10;
6763: }
6764:
6765: if (($cdom eq '') || ($cnum eq '')) {
6766: if ($env{'request.course.id'}) {
6767: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6768: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6769: }
6770: if (($cdom eq '') || ($cnum eq '')) {
6771: return ('','ok','call to get suffix not in course context');
6772: }
6773: }
6774:
6775: # construct locking item
6776: my $lockhash = {
6777: $prefix."\0".'locked_'.$keyid => $who,
6778: };
6779: my $tries = 0;
6780:
6781: # attempt to get lock on nohist_$namespace file
6782: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6783: while (($gotlock ne 'ok') && $tries <$locktries) {
6784: $tries ++;
6785: sleep 1;
6786: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6787: }
6788:
6789: # attempt to get unique identifier, based on current timestamp
6790: if ($gotlock eq 'ok') {
6791: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6792: my $id = time;
6793: $newid = $id;
1.1268 raeburn 6794: if ($idtype eq 'addcode') {
6795: $newid .= &sixnum_code();
6796: }
1.1198 raeburn 6797: my $idtries = 0;
6798: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6799: if ($idtype eq 'concat') {
6800: $newid = $id.$idtries;
1.1268 raeburn 6801: } elsif ($idtype eq 'addcode') {
6802: $newid = $newid.&sixnum_code();
1.1198 raeburn 6803: } else {
6804: $newid ++;
6805: }
6806: $idtries ++;
6807: }
6808: if (!exists($inuse{$prefix."\0".$newid})) {
6809: my %new_item = (
6810: $prefix."\0".$newid => $who,
6811: );
6812: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6813: $cdom,$cnum);
6814: if ($putresult ne 'ok') {
6815: undef($newid);
6816: $error = 'error saving new item: '.$putresult;
6817: }
6818: } else {
1.1268 raeburn 6819: undef($newid);
1.1198 raeburn 6820: $error = ('error: no unique suffix available for the new item ');
6821: }
6822: # remove lock
6823: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6824: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6825: } else {
6826: $error = "error: could not obtain lockfile\n";
6827: $dellock = 'ok';
1.1276 raeburn 6828: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6829: $dellock = 'nolock';
6830: }
1.1198 raeburn 6831: }
6832: return ($newid,$dellock,$error);
6833: }
6834:
1.1268 raeburn 6835: sub sixnum_code {
6836: my $code;
6837: for (0..6) {
6838: $code .= int( rand(9) );
6839: }
6840: return $code;
6841: }
6842:
1.765 albertel 6843: # -------------------------------------------------- portfolio access checking
6844:
6845: sub portfolio_access {
1.1270 raeburn 6846: my ($requrl,$clientip) = @_;
1.765 albertel 6847: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 6848: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6849: if ($result) {
6850: my %setters;
6851: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6852: my ($startblock,$endblock) =
6853: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6854: if ($startblock && $endblock) {
6855: return 'B';
6856: }
6857: } else {
6858: my ($startblock,$endblock) =
6859: &Apache::loncommon::blockcheck(\%setters,'port');
6860: if ($startblock && $endblock) {
6861: return 'B';
6862: }
6863: }
6864: }
1.765 albertel 6865: if ($result eq 'ok') {
1.766 albertel 6866: return 'F';
1.765 albertel 6867: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6868: return 'A';
1.765 albertel 6869: }
1.766 albertel 6870: return '';
1.765 albertel 6871: }
6872:
6873: sub get_portfolio_access {
1.1270 raeburn 6874: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6875:
6876: if (!ref($access_hash)) {
6877: my $current_perms = &get_portfile_permissions($udom,$unum);
6878: my %access_controls = &get_access_controls($current_perms,$group,
6879: $file_name);
6880: $access_hash = $access_controls{$file_name};
6881: }
6882:
1.1270 raeburn 6883: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6884: my $now = time;
6885: if (ref($access_hash) eq 'HASH') {
6886: foreach my $key (keys(%{$access_hash})) {
6887: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6888: if ($start > $now) {
6889: next;
6890: }
6891: if ($end && $end<$now) {
6892: next;
6893: }
6894: if ($scope eq 'public') {
6895: $public = $key;
6896: last;
6897: } elsif ($scope eq 'guest') {
6898: $guest = $key;
6899: } elsif ($scope eq 'domains') {
6900: push(@domains,$key);
6901: } elsif ($scope eq 'users') {
6902: push(@users,$key);
6903: } elsif ($scope eq 'course') {
6904: push(@courses,$key);
6905: } elsif ($scope eq 'group') {
6906: push(@groups,$key);
1.1270 raeburn 6907: } elsif ($scope eq 'ip') {
6908: push(@ips,$key);
1.765 albertel 6909: }
6910: }
6911: if ($public) {
6912: return 'ok';
1.1270 raeburn 6913: } elsif (@ips > 0) {
6914: my $allowed;
6915: foreach my $ipkey (@ips) {
6916: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6917: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6918: $allowed = 1;
6919: last;
6920: }
6921: }
6922: }
6923: if ($allowed) {
6924: return 'ok';
6925: }
1.765 albertel 6926: }
6927: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6928: if ($guest) {
6929: return $guest;
6930: }
6931: } else {
6932: if (@domains > 0) {
6933: foreach my $domkey (@domains) {
6934: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6935: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6936: return 'ok';
6937: }
6938: }
6939: }
6940: }
6941: if (@users > 0) {
6942: foreach my $userkey (@users) {
1.865 raeburn 6943: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6944: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6945: if (ref($item) eq 'HASH') {
6946: if (($item->{'uname'} eq $env{'user.name'}) &&
6947: ($item->{'udom'} eq $env{'user.domain'})) {
6948: return 'ok';
6949: }
6950: }
6951: }
6952: }
1.765 albertel 6953: }
6954: }
6955: my %roleshash;
6956: my @courses_and_groups = @courses;
6957: push(@courses_and_groups,@groups);
6958: if (@courses_and_groups > 0) {
6959: my (%allgroups,%allroles);
6960: my ($start,$end,$role,$sec,$group);
6961: foreach my $envkey (%env) {
1.1060 raeburn 6962: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6963: my $cid = $2.'_'.$3;
6964: if ($1 eq 'gr') {
6965: $group = $4;
6966: $allgroups{$cid}{$group} = $env{$envkey};
6967: } else {
6968: if ($4 eq '') {
6969: $sec = 'none';
6970: } else {
6971: $sec = $4;
6972: }
6973: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6974: }
1.811 albertel 6975: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6976: my $cid = $2.'_'.$3;
6977: if ($4 eq '') {
6978: $sec = 'none';
6979: } else {
6980: $sec = $4;
6981: }
6982: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6983: }
6984: }
6985: if (keys(%allroles) == 0) {
6986: return;
6987: }
6988: foreach my $key (@courses_and_groups) {
6989: my %content = %{$$access_hash{$key}};
6990: my $cnum = $content{'number'};
6991: my $cdom = $content{'domain'};
6992: my $cid = $cdom.'_'.$cnum;
6993: if (!exists($allroles{$cid})) {
6994: next;
6995: }
6996: foreach my $role_id (keys(%{$content{'roles'}})) {
6997: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6998: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6999: my @status = @{$content{'roles'}{$role_id}{'access'}};
7000: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7001: foreach my $role (keys(%{$allroles{$cid}})) {
7002: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7003: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7004: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7005: if (grep/^all$/,@sections) {
7006: return 'ok';
7007: } else {
7008: if (grep/^$sec$/,@sections) {
7009: return 'ok';
7010: }
7011: }
7012: }
7013: }
7014: if (keys(%{$allgroups{$cid}}) == 0) {
7015: if (grep/^none$/,@groups) {
7016: return 'ok';
7017: }
7018: } else {
7019: if (grep/^all$/,@groups) {
7020: return 'ok';
7021: }
7022: foreach my $group (keys(%{$allgroups{$cid}})) {
7023: if (grep/^$group$/,@groups) {
7024: return 'ok';
7025: }
7026: }
7027: }
7028: }
7029: }
7030: }
7031: }
7032: }
7033: if ($guest) {
7034: return $guest;
7035: }
7036: }
7037: }
7038: return;
7039: }
7040:
7041: sub course_group_datechecker {
7042: my ($dates,$now,$status) = @_;
7043: my ($start,$end) = split(/\./,$dates);
7044: if (!$start && !$end) {
7045: return 'ok';
7046: }
7047: if (grep/^active$/,@{$status}) {
7048: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7049: return 'ok';
7050: }
7051: }
7052: if (grep/^previous$/,@{$status}) {
7053: if ($end > $now ) {
7054: return 'ok';
7055: }
7056: }
7057: if (grep/^future$/,@{$status}) {
7058: if ($start > $now) {
7059: return 'ok';
7060: }
7061: }
7062: return;
7063: }
7064:
7065: sub parse_portfolio_url {
7066: my ($url) = @_;
7067:
7068: my ($type,$udom,$unum,$group,$file_name);
7069:
1.823 albertel 7070: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 7071: $type = 1;
7072: $udom = $1;
7073: $unum = $2;
7074: $file_name = $3;
1.823 albertel 7075: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 7076: $type = 2;
7077: $udom = $1;
7078: $unum = $2;
7079: $group = $3;
7080: $file_name = $3.'/'.$4;
7081: }
7082: if (wantarray) {
7083: return ($type,$udom,$unum,$file_name,$group);
7084: }
7085: return $type;
7086: }
7087:
7088: sub is_portfolio_url {
7089: my ($url) = @_;
7090: return scalar(&parse_portfolio_url($url));
7091: }
7092:
1.798 raeburn 7093: sub is_portfolio_file {
7094: my ($file) = @_;
1.820 raeburn 7095: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 7096: return 1;
7097: }
7098: return;
7099: }
7100:
1.976 raeburn 7101: sub usertools_access {
1.1084 raeburn 7102: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 7103: my ($access,%tools);
7104: if ($context eq '') {
7105: $context = 'tools';
7106: }
7107: if ($context eq 'requestcourses') {
7108: %tools = (
7109: official => 1,
7110: unofficial => 1,
1.1006 raeburn 7111: community => 1,
1.1246 raeburn 7112: textbook => 1,
1.1305 raeburn 7113: placement => 1,
1.985 raeburn 7114: );
1.1183 raeburn 7115: } elsif ($context eq 'requestauthor') {
7116: %tools = (
7117: requestauthor => 1,
7118: );
1.985 raeburn 7119: } else {
7120: %tools = (
7121: aboutme => 1,
7122: blog => 1,
1.1177 raeburn 7123: webdav => 1,
1.985 raeburn 7124: portfolio => 1,
7125: );
7126: }
1.976 raeburn 7127: return if (!defined($tools{$tool}));
7128:
1.1242 raeburn 7129: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 7130: $udom = $env{'user.domain'};
7131: $uname = $env{'user.name'};
7132: }
7133:
1.978 raeburn 7134: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7135: if ($action ne 'reload') {
1.985 raeburn 7136: if ($context eq 'requestcourses') {
7137: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 7138: } elsif ($context eq 'requestauthor') {
7139: return $env{'environment.canrequest.author'};
1.985 raeburn 7140: } else {
7141: return $env{'environment.availabletools.'.$tool};
7142: }
7143: }
1.976 raeburn 7144: }
7145:
1.1183 raeburn 7146: my ($toolstatus,$inststatus,$envkey);
7147: if ($context eq 'requestauthor') {
7148: $envkey = $context;
7149: } else {
7150: $envkey = $context.'.'.$tool;
7151: }
1.976 raeburn 7152:
1.985 raeburn 7153: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7154: ($action ne 'reload')) {
1.1183 raeburn 7155: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 7156: $inststatus = $env{'environment.inststatus'};
7157: } else {
1.1084 raeburn 7158: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 7159: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 7160: $inststatus = $userenvref->{'inststatus'};
7161: } else {
1.1183 raeburn 7162: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7163: $toolstatus = $userenv{$envkey};
1.1084 raeburn 7164: $inststatus = $userenv{'inststatus'};
7165: }
1.976 raeburn 7166: }
7167:
7168: if ($toolstatus ne '') {
7169: if ($toolstatus) {
7170: $access = 1;
7171: } else {
7172: $access = 0;
7173: }
7174: return $access;
7175: }
7176:
1.1084 raeburn 7177: my ($is_adv,%domdef);
7178: if (ref($is_advref) eq 'HASH') {
7179: $is_adv = $is_advref->{'is_adv'};
7180: } else {
7181: $is_adv = &is_advanced_user($udom,$uname);
7182: }
7183: if (ref($domdefref) eq 'HASH') {
7184: %domdef = %{$domdefref};
7185: } else {
7186: %domdef = &get_domain_defaults($udom);
7187: }
1.976 raeburn 7188: if (ref($domdef{$tool}) eq 'HASH') {
7189: if ($is_adv) {
7190: if ($domdef{$tool}{'_LC_adv'} ne '') {
7191: if ($domdef{$tool}{'_LC_adv'}) {
7192: $access = 1;
7193: } else {
7194: $access = 0;
7195: }
7196: return $access;
7197: }
7198: }
7199: if ($inststatus ne '') {
7200: my ($hasaccess,$hasnoaccess);
7201: foreach my $affiliation (split(/:/,$inststatus)) {
7202: if ($domdef{$tool}{$affiliation} ne '') {
7203: if ($domdef{$tool}{$affiliation}) {
7204: $hasaccess = 1;
7205: } else {
7206: $hasnoaccess = 1;
7207: }
7208: }
7209: }
7210: if ($hasaccess || $hasnoaccess) {
7211: if ($hasaccess) {
7212: $access = 1;
7213: } elsif ($hasnoaccess) {
7214: $access = 0;
7215: }
7216: return $access;
7217: }
7218: } else {
7219: if ($domdef{$tool}{'default'} ne '') {
7220: if ($domdef{$tool}{'default'}) {
7221: $access = 1;
7222: } elsif ($domdef{$tool}{'default'} == 0) {
7223: $access = 0;
7224: }
7225: return $access;
7226: }
7227: }
7228: } else {
1.1177 raeburn 7229: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7230: $access = 1;
7231: } else {
7232: $access = 0;
7233: }
1.976 raeburn 7234: return $access;
7235: }
7236: }
7237:
1.1050 raeburn 7238: sub is_course_owner {
7239: my ($cdom,$cnum,$udom,$uname) = @_;
7240: if (($udom eq '') || ($uname eq '')) {
7241: $udom = $env{'user.domain'};
7242: $uname = $env{'user.name'};
7243: }
7244: unless (($udom eq '') || ($uname eq '')) {
7245: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7246: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7247: return 1;
7248: } else {
7249: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7250: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7251: return 1;
7252: }
7253: }
7254: }
7255: }
7256: return;
7257: }
7258:
1.976 raeburn 7259: sub is_advanced_user {
7260: my ($udom,$uname) = @_;
1.1085 raeburn 7261: if ($udom ne '' && $uname ne '') {
7262: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7263: if (wantarray) {
7264: return ($env{'user.adv'},$env{'user.author'});
7265: } else {
7266: return $env{'user.adv'};
7267: }
1.1085 raeburn 7268: }
7269: }
1.976 raeburn 7270: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7271: my %allroles;
1.1128 raeburn 7272: my ($is_adv,$is_author);
1.976 raeburn 7273: foreach my $role (keys(%roleshash)) {
7274: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7275: my $area = '/'.$tdomain.'/'.$trest;
7276: if ($sec ne '') {
7277: $area .= '/'.$sec;
7278: }
7279: if (($area ne '') && ($trole ne '')) {
7280: my $spec=$trole.'.'.$area;
7281: if ($trole =~ /^cr\//) {
7282: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7283: } elsif ($trole ne 'gr') {
7284: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7285: }
1.1128 raeburn 7286: if ($trole eq 'au') {
7287: $is_author = 1;
7288: }
1.976 raeburn 7289: }
7290: }
7291: foreach my $role (keys(%allroles)) {
7292: last if ($is_adv);
7293: foreach my $item (split(/:/,$allroles{$role})) {
7294: if ($item ne '') {
7295: my ($privilege,$restrictions)=split(/&/,$item);
7296: if ($privilege eq 'adv') {
7297: $is_adv = 1;
7298: last;
7299: }
7300: }
7301: }
7302: }
1.1128 raeburn 7303: if (wantarray) {
7304: return ($is_adv,$is_author);
7305: }
1.976 raeburn 7306: return $is_adv;
7307: }
1.798 raeburn 7308:
1.1035 raeburn 7309: sub check_can_request {
1.1036 raeburn 7310: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7311: my $canreq = 0;
7312: my ($types,$typename) = &Apache::loncommon::course_types();
7313: my @options = ('approval','validate','autolimit');
7314: my $optregex = join('|',@options);
7315: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7316: foreach my $type (@{$types}) {
7317: if (&usertools_access($env{'user.name'},
7318: $env{'user.domain'},
7319: $type,undef,'requestcourses')) {
7320: $canreq ++;
1.1036 raeburn 7321: if (ref($request_domains) eq 'HASH') {
7322: push(@{$request_domains->{$type}},$env{'user.domain'});
7323: }
1.1035 raeburn 7324: if ($dom eq $env{'user.domain'}) {
7325: $can_request->{$type} = 1;
7326: }
7327: }
7328: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7329: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7330: if (@curr > 0) {
1.1036 raeburn 7331: foreach my $item (@curr) {
7332: if (ref($request_domains) eq 'HASH') {
7333: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7334: if ($otherdom ne '') {
7335: if (ref($request_domains->{$type}) eq 'ARRAY') {
7336: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7337: push(@{$request_domains->{$type}},$otherdom);
7338: }
7339: } else {
7340: push(@{$request_domains->{$type}},$otherdom);
7341: }
7342: }
7343: }
7344: }
7345: unless($dom eq $env{'user.domain'}) {
7346: $canreq ++;
1.1035 raeburn 7347: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7348: $can_request->{$type} = 1;
7349: }
7350: }
7351: }
7352: }
7353: }
7354: }
7355: return $canreq;
7356: }
7357:
1.341 www 7358: # ---------------------------------------------- Custom access rule evaluation
7359:
7360: sub customaccess {
7361: my ($priv,$uri)=@_;
1.807 albertel 7362: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7363: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7364: $udom = &LONCAPA::clean_domain($udom);
7365: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7366: my $access=0;
1.800 albertel 7367: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7368: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7369: if ($type eq 'user') {
7370: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7371: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7372: if ($tdom) {
7373: if ($tdom ne $env{'user.domain'}) { next; }
7374: }
1.896 albertel 7375: if ($tuname) {
7376: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7377: }
7378: $access=($effect eq 'allow');
7379: last;
7380: }
7381: } else {
7382: if ($role) {
7383: if ($role ne $urole) { next; }
7384: }
7385: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7386: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7387: if ($tdom) {
7388: if ($tdom ne $udom) { next; }
7389: }
7390: if ($tcrs) {
7391: if ($tcrs ne $ucrs) { next; }
7392: }
7393: if ($tsec) {
7394: if ($tsec ne $usec) { next; }
7395: }
7396: $access=($effect eq 'allow');
7397: last;
7398: }
7399: if ($realm eq '' && $role eq '') {
7400: $access=($effect eq 'allow');
7401: }
1.402 bowersj2 7402: }
1.341 www 7403: }
7404: return $access;
7405: }
7406:
1.103 harris41 7407: # ------------------------------------------------- Check for a user privilege
1.12 www 7408:
7409: sub allowed {
1.1281 raeburn 7410: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 7411: my $ver_orguri=$uri;
1.439 www 7412: $uri=&deversion($uri);
1.152 www 7413: my $orguri=$uri;
1.52 www 7414: $uri=&declutter($uri);
1.809 raeburn 7415:
1.810 raeburn 7416: if ($priv eq 'evb') {
7417: # Evade communication block restrictions for specified role in a course
7418: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7419: return $1;
7420: } else {
7421: return;
7422: }
7423: }
7424:
1.620 albertel 7425: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7426: # Free bre access to adm and meta resources
1.1343 raeburn 7427: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$}))
1.769 albertel 7428: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7429: && ($priv eq 'bre')) {
1.14 www 7430: return 'F';
1.159 www 7431: }
7432:
1.545 banghart 7433: # Free bre access to user's own portfolio contents
1.714 raeburn 7434: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7435: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7436: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7437: my %setters;
7438: my ($startblock,$endblock) =
7439: &Apache::loncommon::blockcheck(\%setters,'port');
7440: if ($startblock && $endblock) {
7441: return 'B';
7442: } else {
7443: return 'F';
7444: }
1.545 banghart 7445: }
7446:
1.762 raeburn 7447: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7448: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7449: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7450: if (exists($env{'request.course.id'})) {
7451: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7452: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7453: if (($domain eq $cdom) && ($name eq $cnum)) {
7454: my $courseprivid=$env{'request.course.id'};
7455: $courseprivid=~s/\_/\//;
7456: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7457: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7458: return $1;
1.762 raeburn 7459: } else {
7460: if ($env{'request.course.sec'}) {
7461: $courseprivid.='/'.$env{'request.course.sec'};
7462: }
7463: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7464: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7465: return $2;
7466: }
1.714 raeburn 7467: }
7468: }
7469: }
7470: }
7471:
1.159 www 7472: # Free bre to public access
7473:
7474: if ($priv eq 'bre') {
1.238 www 7475: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7476: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7477: return 'F';
7478: }
1.238 www 7479: if ($copyright eq 'priv') {
7480: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7481: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7482: return '';
7483: }
7484: }
7485: if ($copyright eq 'domain') {
7486: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7487: unless (($env{'user.domain'} eq $1) ||
7488: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7489: return '';
7490: }
1.262 matthew 7491: }
1.620 albertel 7492: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7493: # Library role, so allow browsing of resources in this domain.
7494: return 'F';
1.238 www 7495: }
1.341 www 7496: if ($copyright eq 'custom') {
7497: unless (&customaccess($priv,$uri)) { return ''; }
7498: }
1.14 www 7499: }
1.264 matthew 7500: # Domain coordinator is trying to create a course
1.620 albertel 7501: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7502: # uri is the requested domain in this case.
7503: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7504: # a role of dc for the domain in question.
1.620 albertel 7505: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7506: }
1.29 www 7507:
1.52 www 7508: my $thisallowed='';
7509: my $statecond=0;
7510: my $courseprivid='';
7511:
1.1039 raeburn 7512: my $ownaccess;
1.1043 raeburn 7513: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7514: if (($priv eq 'bro') && ($env{'user.author'})) {
7515: if ($uri eq '') {
7516: $ownaccess = 1;
7517: } else {
7518: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7519: my $udom = $env{'user.domain'};
7520: my $uname = $env{'user.name'};
7521: if ($uri =~ m{^\Q$udom\E/?$}) {
7522: $ownaccess = 1;
1.1040 raeburn 7523: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 7524: unless ($uri =~ m{\.\./}) {
7525: $ownaccess = 1;
7526: }
7527: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7528: my $now = time;
7529: if ($uri =~ m{^([^/]+)/?$}) {
7530: my $adom = $1;
7531: foreach my $key (keys(%env)) {
1.1042 raeburn 7532: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 7533: my ($start,$end) = split('.',$env{$key});
7534: if (($now >= $start) && (!$end || $end < $now)) {
7535: $ownaccess = 1;
7536: last;
7537: }
7538: }
7539: }
7540: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7541: my $adom = $1;
7542: my $aname = $2;
1.1042 raeburn 7543: foreach my $role ('ca','aa') {
7544: if ($env{"user.role.$role./$adom/$aname"}) {
7545: my ($start,$end) =
7546: split('.',$env{"user.role.$role./$adom/$aname"});
7547: if (($now >= $start) && (!$end || $end < $now)) {
7548: $ownaccess = 1;
7549: last;
7550: }
1.1039 raeburn 7551: }
7552: }
7553: }
7554: }
7555: }
7556: }
7557: }
7558:
1.52 www 7559: # Course
7560:
1.620 albertel 7561: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7562: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7563: $thisallowed.=$1;
7564: }
1.52 www 7565: }
1.29 www 7566:
1.52 www 7567: # Domain
7568:
1.620 albertel 7569: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7570: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7571: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7572: $thisallowed.=$1;
7573: }
1.12 www 7574: }
1.52 www 7575:
1.1141 raeburn 7576: # User who is not author or co-author might still be able to edit
7577: # resource of an author in the domain (e.g., if Domain Coordinator).
7578: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7579: (&allowed('mdc',$env{'request.course.id'}))) {
7580: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7581: $thisallowed.=$1;
7582: }
7583: }
7584:
1.52 www 7585: # Course: uri itself is a course
1.66 www 7586: my $courseuri=$uri;
7587: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 7588: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7589:
1.620 albertel 7590: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7591: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7592: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7593: $thisallowed.=$1;
7594: }
1.12 www 7595: }
1.29 www 7596:
1.665 albertel 7597: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7598: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7599: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7600: $thisallowed='';
1.671 raeburn 7601: my ($match)=&is_on_map($uri);
7602: if ($match) {
7603: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7604: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 7605: my $value = $1;
7606: if ($noblockcheck) {
7607: $thisallowed.=$value;
1.1162 raeburn 7608: } else {
1.1281 raeburn 7609: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7610: if (@blockers > 0) {
7611: $thisallowed = 'B';
7612: } else {
7613: $thisallowed.=$value;
7614: }
1.1162 raeburn 7615: }
1.671 raeburn 7616: }
7617: } else {
1.705 albertel 7618: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7619: if ($refuri) {
7620: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7621: $thisallowed='F';
1.671 raeburn 7622: } else {
7623: $refuri=&declutter($refuri);
7624: my ($match) = &is_on_map($refuri);
7625: if ($match) {
1.1281 raeburn 7626: if ($noblockcheck) {
7627: $thisallowed='F';
1.1162 raeburn 7628: } else {
1.1281 raeburn 7629: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7630: if (@blockers > 0) {
7631: $thisallowed = 'B';
7632: } else {
7633: $thisallowed='F';
7634: }
1.1162 raeburn 7635: }
1.671 raeburn 7636: }
1.669 raeburn 7637: }
1.671 raeburn 7638: }
7639: }
1.314 www 7640: }
1.492 albertel 7641:
1.766 albertel 7642: if ($priv eq 'bre'
7643: && $thisallowed ne 'F'
7644: && $thisallowed ne '2'
7645: && &is_portfolio_url($uri)) {
1.1270 raeburn 7646: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7647: }
1.1250 raeburn 7648:
1.52 www 7649: # Full access at system, domain or course-wide level? Exit.
1.29 www 7650: if ($thisallowed=~/F/) {
7651: return 'F';
7652: }
7653:
1.52 www 7654: # If this is generating or modifying users, exit with special codes
1.29 www 7655:
1.643 www 7656: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7657: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7658: my ($audom,$auname)=split('/',$uri);
1.643 www 7659: # no author name given, so this just checks on the general right to make a co-author in this domain
7660: unless ($auname) { return $thisallowed; }
7661: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7662: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7663: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7664: ($audom ne $env{'request.role.domain'}))) { return ''; }
7665: }
1.52 www 7666: return $thisallowed;
7667: }
7668: #
1.103 harris41 7669: # Gathered so far: system, domain and course wide privileges
1.52 www 7670: #
7671: # Course: See if uri or referer is an individual resource that is part of
7672: # the course
7673:
1.620 albertel 7674: if ($env{'request.course.id'}) {
1.232 www 7675:
1.620 albertel 7676: $courseprivid=$env{'request.course.id'};
7677: if ($env{'request.course.sec'}) {
7678: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7679: }
7680: $courseprivid=~s/\_/\//;
7681: my $checkreferer=1;
1.232 www 7682: my ($match,$cond)=&is_on_map($uri);
7683: if ($match) {
7684: $statecond=$cond;
1.620 albertel 7685: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7686: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7687: my $value = $1;
7688: if ($priv eq 'bre') {
1.1281 raeburn 7689: if ($noblockcheck) {
7690: $thisallowed.=$value;
1.1162 raeburn 7691: } else {
1.1281 raeburn 7692: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7693: if (@blockers > 0) {
7694: $thisallowed = 'B';
7695: } else {
7696: $thisallowed.=$value;
7697: }
1.1162 raeburn 7698: }
7699: } else {
7700: $thisallowed.=$value;
7701: }
1.52 www 7702: $checkreferer=0;
7703: }
1.29 www 7704: }
1.83 www 7705:
1.148 www 7706: if ($checkreferer) {
1.620 albertel 7707: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7708: unless ($refuri) {
1.800 albertel 7709: foreach my $key (keys(%env)) {
7710: if ($key=~/^httpref\..*\*/) {
7711: my $pattern=$key;
1.156 www 7712: $pattern=~s/^httpref\.\/res\///;
1.148 www 7713: $pattern=~s/\*/\[\^\/\]\+/g;
7714: $pattern=~s/\//\\\//g;
1.152 www 7715: if ($orguri=~/$pattern/) {
1.800 albertel 7716: $refuri=$env{$key};
1.148 www 7717: }
7718: }
1.191 harris41 7719: }
1.148 www 7720: }
1.232 www 7721:
1.148 www 7722: if ($refuri) {
1.152 www 7723: $refuri=&declutter($refuri);
1.232 www 7724: my ($match,$cond)=&is_on_map($refuri);
7725: if ($match) {
7726: my $refstatecond=$cond;
1.620 albertel 7727: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7728: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7729: my $value = $1;
7730: if ($priv eq 'bre') {
1.1281 raeburn 7731: if ($noblockcheck) {
7732: $thisallowed.=$value;
1.1162 raeburn 7733: } else {
1.1281 raeburn 7734: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7735: if (@blockers > 0) {
7736: $thisallowed = 'B';
7737: } else {
7738: $thisallowed.=$value;
7739: }
1.1162 raeburn 7740: }
7741: } else {
7742: $thisallowed.=$value;
7743: }
1.53 www 7744: $uri=$refuri;
7745: $statecond=$refstatecond;
1.52 www 7746: }
7747: }
1.148 www 7748: }
1.29 www 7749: }
1.52 www 7750: }
1.29 www 7751:
1.52 www 7752: #
1.103 harris41 7753: # Gathered now: all privileges that could apply, and condition number
1.52 www 7754: #
7755: #
7756: # Full or no access?
7757: #
1.29 www 7758:
1.52 www 7759: if ($thisallowed=~/F/) {
7760: return 'F';
7761: }
1.29 www 7762:
1.52 www 7763: unless ($thisallowed) {
7764: return '';
7765: }
1.29 www 7766:
1.52 www 7767: # Restrictions exist, deal with them
7768: #
7769: # C:according to course preferences
7770: # R:according to resource settings
7771: # L:unless locked
7772: # X:according to user session state
7773: #
7774:
7775: # Possibly locked functionality, check all courses
1.54 www 7776: # Locks might take effect only after 10 minutes cache expiration for other
7777: # courses, and 2 minutes for current course
1.52 www 7778:
7779: my $envkey;
7780: if ($thisallowed=~/L/) {
1.1000 raeburn 7781: foreach $envkey (keys(%env)) {
1.54 www 7782: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7783: my $courseid=$2;
7784: my $roleid=$1.'.'.$2;
1.92 www 7785: $courseid=~s/^\///;
1.54 www 7786: my $expiretime=600;
1.620 albertel 7787: if ($env{'request.role'} eq $roleid) {
1.54 www 7788: $expiretime=120;
7789: }
7790: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7791: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7792: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7793: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7794: }
1.620 albertel 7795: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7796: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7797: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7798: &log($env{'user.domain'},$env{'user.name'},
7799: $env{'user.home'},
1.57 www 7800: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7801: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7802: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7803: return '';
7804: }
7805: }
1.620 albertel 7806: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7807: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7808: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7809: &log($env{'user.domain'},$env{'user.name'},
7810: $env{'user.home'},
1.57 www 7811: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7812: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7813: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7814: return '';
7815: }
7816: }
7817: }
1.29 www 7818: }
1.52 www 7819: }
7820:
7821: #
7822: # Rest of the restrictions depend on selected course
7823: #
7824:
1.620 albertel 7825: unless ($env{'request.course.id'}) {
1.766 albertel 7826: if ($thisallowed eq 'A') {
7827: return 'A';
1.814 raeburn 7828: } elsif ($thisallowed eq 'B') {
7829: return 'B';
1.766 albertel 7830: } else {
7831: return '1';
7832: }
1.52 www 7833: }
1.29 www 7834:
1.52 www 7835: #
7836: # Now user is definitely in a course
7837: #
1.53 www 7838:
7839:
7840: # Course preferences
7841:
7842: if ($thisallowed=~/C/) {
1.620 albertel 7843: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7844: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7845: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7846: =~/\Q$rolecode\E/) {
1.1304 raeburn 7847: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7848: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7849: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7850: $env{'request.course.id'});
7851: }
1.237 www 7852: return '';
7853: }
7854:
1.620 albertel 7855: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7856: =~/\Q$unamedom\E/) {
1.1304 raeburn 7857: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7858: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7859: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7860: $env{'request.course.id'});
7861: }
1.54 www 7862: return '';
7863: }
1.53 www 7864: }
7865:
7866: # Resource preferences
7867:
7868: if ($thisallowed=~/R/) {
1.620 albertel 7869: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7870: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7871: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7872: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7873: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7874: }
7875: return '';
1.54 www 7876: }
1.53 www 7877: }
1.30 www 7878:
1.246 www 7879: # Restricted by state or randomout?
1.30 www 7880:
1.52 www 7881: if ($thisallowed=~/X/) {
1.620 albertel 7882: if ($env{'acc.randomout'}) {
1.579 albertel 7883: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7884: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7885: return '';
7886: }
1.247 www 7887: }
7888: if (&condval($statecond)) {
1.52 www 7889: return '2';
7890: } else {
7891: return '';
7892: }
7893: }
1.30 www 7894:
1.766 albertel 7895: if ($thisallowed eq 'A') {
7896: return 'A';
1.814 raeburn 7897: } elsif ($thisallowed eq 'B') {
7898: return 'B';
1.766 albertel 7899: }
1.52 www 7900: return 'F';
1.232 www 7901: }
1.1162 raeburn 7902:
1.1192 raeburn 7903: # ------------------------------------------- Check construction space access
7904:
7905: sub constructaccess {
7906: my ($url,$setpriv)=@_;
7907:
7908: # We do not allow editing of previous versions of files
7909: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7910:
7911: # Get username and domain from URL
7912: my ($ownername,$ownerdomain,$ownerhome);
7913:
7914: ($ownerdomain,$ownername) =
1.1325 raeburn 7915: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192 raeburn 7916:
7917: # The URL does not really point to any authorspace, forget it
7918: unless (($ownername) && ($ownerdomain)) { return ''; }
7919:
7920: # Now we need to see if the user has access to the authorspace of
7921: # $ownername at $ownerdomain
7922:
7923: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7924: # Real author for this?
7925: $ownerhome = $env{'user.home'};
7926: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7927: return ($ownername,$ownerdomain,$ownerhome);
7928: }
7929: } else {
7930: # Co-author for this?
7931: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7932: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7933: $ownerhome = &homeserver($ownername,$ownerdomain);
7934: return ($ownername,$ownerdomain,$ownerhome);
7935: }
1.1312 raeburn 7936: if ($env{'request.course.id'}) {
7937: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
7938: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
7939: if (&allowed('mdc',$env{'request.course.id'})) {
7940: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
7941: return ($ownername,$ownerdomain,$ownerhome);
7942: }
7943: }
7944: }
1.1192 raeburn 7945: }
7946:
7947: # We don't have any access right now. If we are not possibly going to do anything about this,
7948: # we might as well leave
7949: unless ($setpriv) { return ''; }
7950:
7951: # Backdoor access?
7952: my $allowed=&allowed('eco',$ownerdomain);
7953: # Nope
7954: unless ($allowed) { return ''; }
7955: # Looks like we may have access, but could be locked by the owner of the construction space
7956: if ($allowed eq 'U') {
7957: my %blocked=&get('environment',['domcoord.author'],
7958: $ownerdomain,$ownername);
7959: # Is blocked by owner
7960: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7961: }
7962: if (($allowed eq 'F') || ($allowed eq 'U')) {
7963: # Grant temporary access
7964: my $then=$env{'user.login.time'};
1.1209 raeburn 7965: my $update=$env{'user.update.time'};
1.1192 raeburn 7966: if (!$update) { $update = $then; }
7967: my $refresh=$env{'user.refresh.time'};
7968: if (!$refresh) { $refresh = $update; }
7969: my $now = time;
7970: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7971: $now,'ca','constructaccess');
7972: $ownerhome = &homeserver($ownername,$ownerdomain);
7973: return($ownername,$ownerdomain,$ownerhome);
7974: }
7975: # No business here
7976: return '';
7977: }
7978:
1.1282 raeburn 7979: # ----------------------------------------------------------- Content Blocking
7980:
7981: {
7982: # Caches for faster Course Contents display where content blocking
7983: # is in operation (i.e., interval param set) for timed quiz.
7984: #
7985: # User for whom data are being temporarily cached.
7986: my $cacheduser='';
7987: # Cached blockers for this user (a hash of blocking items).
7988: my %cachedblockers=();
7989: # When the data were last cached.
7990: my $cachedlast='';
7991:
7992: sub load_all_blockers {
7993: my ($uname,$udom,$blocks)=@_;
7994: if (($uname ne '') && ($udom ne '')) {
7995: if (($cacheduser eq $uname.':'.$udom) &&
7996: (abs($cachedlast-time)<5)) {
7997: return;
7998: }
7999: }
8000: $cachedlast=time;
8001: $cacheduser=$uname.':'.$udom;
8002: %cachedblockers = &get_commblock_resources($blocks);
8003: }
8004:
1.1162 raeburn 8005: sub get_comm_blocks {
8006: my ($cdom,$cnum) = @_;
8007: if ($cdom eq '' || $cnum eq '') {
8008: return unless ($env{'request.course.id'});
8009: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8010: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8011: }
8012: my %commblocks;
8013: my $hashid=$cdom.'_'.$cnum;
8014: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8015: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8016: %commblocks = %{$blocksref};
8017: } else {
8018: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8019: my $cachetime = 600;
8020: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8021: }
8022: return %commblocks;
8023: }
8024:
1.1282 raeburn 8025: sub get_commblock_resources {
8026: my ($blocks) = @_;
8027: my %blockers = ();
8028: return %blockers unless ($env{'request.course.id'});
8029: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 8030: my %commblocks;
8031: if (ref($blocks) eq 'HASH') {
8032: %commblocks = %{$blocks};
8033: } else {
8034: %commblocks = &get_comm_blocks();
8035: }
1.1282 raeburn 8036: return %blockers unless (keys(%commblocks) > 0);
8037: my $navmap = Apache::lonnavmaps::navmap->new();
8038: return %blockers unless (ref($navmap));
1.1162 raeburn 8039: my $now = time;
8040: foreach my $block (keys(%commblocks)) {
8041: if ($block =~ /^(\d+)____(\d+)$/) {
8042: my ($start,$end) = ($1,$2);
8043: if ($start <= $now && $end >= $now) {
8044: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8045: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8046: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 8047: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8048: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 8049: }
8050: }
8051: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 8052: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8053: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 8054: }
8055: }
8056: }
8057: }
8058: }
8059: } elsif ($block =~ /^firstaccess____(.+)$/) {
8060: my $item = $1;
1.1163 raeburn 8061: my @to_test;
1.1162 raeburn 8062: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8063: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282 raeburn 8064: my @interval;
8065: my $type = 'map';
8066: if ($item eq 'course') {
8067: $type = 'course';
8068: @interval=&EXT("resource.0.interval");
8069: } else {
8070: if ($item =~ /___\d+___/) {
8071: $type = 'resource';
8072: @interval=&EXT("resource.0.interval",$item);
8073: if (ref($navmap)) {
8074: my $res = $navmap->getBySymb($item);
8075: push(@to_test,$res);
8076: }
1.1162 raeburn 8077: } else {
1.1282 raeburn 8078: my $mapsymb = &symbread($item,1);
8079: if ($mapsymb) {
8080: if (ref($navmap)) {
8081: my $mapres = $navmap->getBySymb($mapsymb);
8082: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
8083: foreach my $res (@to_test) {
8084: my $symb = $res->symb();
8085: next if ($symb eq $mapsymb);
8086: if ($symb ne '') {
8087: @interval=&EXT("resource.0.interval",$symb);
8088: if ($interval[1] eq 'map') {
8089: last;
1.1162 raeburn 8090: }
8091: }
8092: }
8093: }
8094: }
8095: }
1.1282 raeburn 8096: }
1.1310 raeburn 8097: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 8098: my $timelimit = $1;
1.1282 raeburn 8099: my $first_access;
8100: if ($type eq 'resource') {
8101: $first_access=&get_first_access($interval[1],$item);
8102: } elsif ($type eq 'map') {
8103: $first_access=&get_first_access($interval[1],undef,$item);
8104: } else {
8105: $first_access=&get_first_access($interval[1]);
8106: }
8107: if ($first_access) {
1.1292 raeburn 8108: my $timesup = $first_access+$timelimit;
1.1282 raeburn 8109: if ($timesup > $now) {
8110: my $activeblock;
8111: foreach my $res (@to_test) {
1.1283 raeburn 8112: if ($res->answerable()) {
1.1282 raeburn 8113: $activeblock = 1;
8114: last;
8115: }
8116: }
8117: if ($activeblock) {
8118: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8119: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8120: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8121: }
8122: }
8123: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8124: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8125: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 8126: }
1.1162 raeburn 8127: }
8128: }
8129: }
8130: }
8131: }
8132: }
8133: }
8134: }
8135: }
1.1282 raeburn 8136: return %blockers;
1.1162 raeburn 8137: }
8138:
1.1282 raeburn 8139: sub has_comm_blocking {
8140: my ($priv,$symb,$uri,$blocks) = @_;
8141: my @blockers;
8142: return unless ($env{'request.course.id'});
8143: return unless ($priv eq 'bre');
8144: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8145: return if ($env{'request.state'} eq 'construct');
8146: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
8147: return unless (keys(%cachedblockers) > 0);
8148: my (%possibles,@symbs);
8149: if (!$symb) {
8150: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 8151: }
1.1282 raeburn 8152: if ($symb) {
8153: @symbs = ($symb);
8154: } elsif (keys(%possibles)) {
8155: @symbs = keys(%possibles);
8156: }
8157: my $noblock;
8158: foreach my $symb (@symbs) {
8159: last if ($noblock);
8160: my ($map,$resid,$resurl)=&decode_symb($symb);
8161: foreach my $block (keys(%cachedblockers)) {
8162: if ($block =~ /^firstaccess____(.+)$/) {
8163: my $item = $1;
8164: if (($item eq $map) || ($item eq $symb)) {
8165: $noblock = 1;
8166: last;
8167: }
8168: }
8169: if (ref($cachedblockers{$block}) eq 'HASH') {
8170: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
8171: if ($cachedblockers{$block}{'resources'}{$symb}) {
8172: unless (grep(/^\Q$block\E$/,@blockers)) {
8173: push(@blockers,$block);
8174: }
8175: }
8176: }
1.1162 raeburn 8177: }
1.1282 raeburn 8178: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
8179: if ($cachedblockers{$block}{'maps'}{$map}) {
8180: unless (grep(/^\Q$block\E$/,@blockers)) {
8181: push(@blockers,$block);
8182: }
8183: }
1.1162 raeburn 8184: }
8185: }
8186: }
1.1282 raeburn 8187: return if ($noblock);
8188: return @blockers;
8189: }
1.1162 raeburn 8190: }
8191:
1.1282 raeburn 8192: # -------------------------------- Deversion and split uri into path an filename
8193:
1.1133 foxr 8194: #
1.1282 raeburn 8195: # Removes the version from a URI and
1.1133 foxr 8196: # splits it in to its filename and path to the filename.
8197: # Seems like File::Basename could have done this more clearly.
8198: # Parameters:
8199: # $uri - input URI
8200: # Returns:
8201: # Two element list consisting of
8202: # $pathname - the URI up to and excluding the trailing /
8203: # $filename - The part of the URI following the last /
8204: # NOTE:
8205: # Another realization of this is simply:
8206: # use File::Basename;
8207: # ...
8208: # $uri = shift;
8209: # $filename = basename($uri);
8210: # $path = dirname($uri);
8211: # return ($filename, $path);
8212: #
8213: # The implementation below is probably faster however.
8214: #
1.710 albertel 8215: sub split_uri_for_cond {
8216: my $uri=&deversion(&declutter(shift));
8217: my @uriparts=split(/\//,$uri);
8218: my $filename=pop(@uriparts);
8219: my $pathname=join('/',@uriparts);
8220: return ($pathname,$filename);
8221: }
1.232 www 8222: # --------------------------------------------------- Is a resource on the map?
8223:
8224: sub is_on_map {
1.710 albertel 8225: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8226: #Trying to find the conditional for the file
1.620 albertel 8227: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8228: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8229: if ($match) {
1.289 bowersj2 8230: return (1,$1);
8231: } else {
1.434 www 8232: return (0,0);
1.289 bowersj2 8233: }
1.12 www 8234: }
8235:
1.427 www 8236: # --------------------------------------------------------- Get symb from alias
8237:
8238: sub get_symb_from_alias {
8239: my $symb=shift;
8240: my ($map,$resid,$url)=&decode_symb($symb);
8241: # Already is a symb
8242: if ($url) { return $symb; }
8243: # Must be an alias
8244: my $aliassymb='';
8245: my %bighash;
1.620 albertel 8246: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8247: &GDBM_READER(),0640)) {
8248: my $rid=$bighash{'mapalias_'.$symb};
8249: if ($rid) {
8250: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8251: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8252: $resid,$bighash{'src_'.$rid});
1.427 www 8253: }
8254: untie %bighash;
8255: }
8256: return $aliassymb;
8257: }
8258:
1.12 www 8259: # ----------------------------------------------------------------- Define Role
8260:
8261: sub definerole {
8262: if (allowed('mcr','/')) {
1.1326 raeburn 8263: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8264: foreach my $role (split(':',$sysrole)) {
8265: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8266: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8267: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8268: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8269: return "refused:s:$crole&$cqual";
8270: }
8271: }
1.191 harris41 8272: }
1.800 albertel 8273: foreach my $role (split(':',$domrole)) {
8274: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8275: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8276: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8277: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8278: return "refused:d:$crole&$cqual";
8279: }
8280: }
1.191 harris41 8281: }
1.800 albertel 8282: foreach my $role (split(':',$courole)) {
8283: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8284: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8285: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8286: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8287: return "refused:c:$crole&$cqual";
8288: }
8289: }
1.191 harris41 8290: }
1.1326 raeburn 8291: my $uhome;
8292: if (($uname ne '') && ($udom ne '')) {
8293: $uhome = &homeserver($uname,$udom);
8294: return $uhome if ($uhome eq 'no_host');
8295: } else {
8296: $uname = $env{'user.name'};
8297: $udom = $env{'user.domain'};
8298: $uhome = $env{'user.home'};
8299: }
1.620 albertel 8300: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326 raeburn 8301: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8302: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326 raeburn 8303: return reply($command,$uhome);
1.12 www 8304: } else {
8305: return 'refused';
8306: }
1.105 harris41 8307: }
8308:
8309: # ---------------- Make a metadata query against the network of library servers
8310:
8311: sub metadata_query {
1.1237 raeburn 8312: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8313: my %rhash;
1.845 albertel 8314: my %libserv = &all_library();
1.244 matthew 8315: my @server_list = (defined($server_array) ? @$server_array
8316: : keys(%libserv) );
8317: for my $server (@server_list) {
1.1237 raeburn 8318: my $domains = '';
8319: if (ref($domains_hash) eq 'HASH') {
8320: $domains = $domains_hash->{$server};
8321: }
1.118 harris41 8322: unless ($custom or $customshow) {
1.1237 raeburn 8323: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8324: $rhash{$server}=$reply;
8325: }
8326: else {
8327: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 8328: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8329: $server);
8330: $rhash{$server}=$reply;
8331: }
1.112 harris41 8332: }
1.118 harris41 8333: return \%rhash;
1.240 www 8334: }
8335:
8336: # ----------------------------------------- Send log queries and wait for reply
8337:
8338: sub log_query {
8339: my ($uname,$udom,$query,%filters)=@_;
8340: my $uhome=&homeserver($uname,$udom);
8341: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8342: my $uhost=&hostname($uhome);
1.800 albertel 8343: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8344: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8345: $uhome);
1.479 albertel 8346: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8347: return get_query_reply($queryid);
8348: }
8349:
1.818 raeburn 8350: # -------------------------- Update MySQL table for portfolio file
8351:
8352: sub update_portfolio_table {
1.821 raeburn 8353: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8354: if ($group ne '') {
8355: $file_name =~s /^\Q$group\E//;
8356: }
1.818 raeburn 8357: my $homeserver = &homeserver($uname,$udom);
8358: my $queryid=
1.821 raeburn 8359: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8360: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8361: my $reply = &get_query_reply($queryid);
8362: return $reply;
8363: }
8364:
1.899 raeburn 8365: # -------------------------- Update MySQL allusers table
8366:
8367: sub update_allusers_table {
8368: my ($uname,$udom,$names) = @_;
8369: my $homeserver = &homeserver($uname,$udom);
8370: my $queryid=
8371: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8372: 'lastname='.&escape($names->{'lastname'}).'%%'.
8373: 'firstname='.&escape($names->{'firstname'}).'%%'.
8374: 'middlename='.&escape($names->{'middlename'}).'%%'.
8375: 'generation='.&escape($names->{'generation'}).'%%'.
8376: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8377: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8378: return;
1.899 raeburn 8379: }
8380:
1.508 raeburn 8381: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8382:
8383: sub fetch_enrollment_query {
1.511 raeburn 8384: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 raeburn 8385: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8386: my $maxtries = 1;
1.508 raeburn 8387: if ($context eq 'automated') {
8388: $homeserver = $perlvar{'lonHostID'};
1.1317 raeburn 8389: $sleep = 2;
8390: $loopmax = 100;
1.547 raeburn 8391: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8392: } else {
8393: $homeserver = &homeserver($cnum,$dom);
8394: }
1.838 albertel 8395: my $host=&hostname($homeserver);
1.506 raeburn 8396: my $cmd = '';
1.1000 raeburn 8397: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8398: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8399: }
8400: $cmd =~ s/%%$//;
8401: $cmd = &escape($cmd);
8402: my $query = 'fetchenrollment';
1.620 albertel 8403: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8404: unless ($queryid=~/^\Q$host\E\_/) {
8405: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8406: return 'error: '.$queryid;
8407: }
1.1317 raeburn 8408: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8409: my $tries = 1;
8410: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 raeburn 8411: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8412: $tries ++;
8413: }
1.526 raeburn 8414: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 8415: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 8416: } else {
1.901 albertel 8417: my @responses = split(/:/,$reply);
1.1322 raeburn 8418: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 8419: foreach my $line (@responses) {
8420: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 8421: $$replyref{$key} = $value;
8422: }
8423: } else {
1.1117 foxr 8424: my $pathname = LONCAPA::tempdir();
1.800 albertel 8425: foreach my $line (@responses) {
8426: my ($key,$value) = split(/=/,$line);
1.506 raeburn 8427: $$replyref{$key} = $value;
8428: if ($value > 0) {
1.800 albertel 8429: foreach my $item (@{$$affiliatesref{$key}}) {
8430: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 8431: my $destname = $pathname.'/'.$filename;
8432: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 8433: if ($xml_classlist =~ /^error/) {
8434: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8435: } else {
1.506 raeburn 8436: if ( open(FILE,">$destname") ) {
8437: print FILE &unescape($xml_classlist);
8438: close(FILE);
1.526 raeburn 8439: } else {
8440: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 8441: }
8442: }
8443: }
8444: }
8445: }
8446: }
8447: return 'ok';
8448: }
8449: return 'error';
8450: }
8451:
1.242 www 8452: sub get_query_reply {
1.1317 raeburn 8453: my ($queryid,$sleep,$loopmax) = @_;;
8454: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8455: $sleep = 0.2;
8456: }
8457: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8458: $loopmax = 100;
8459: }
1.1117 foxr 8460: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 8461: my $reply='';
1.1317 raeburn 8462: for (1..$loopmax) {
8463: sleep($sleep);
1.240 www 8464: if (-e $replyfile.'.end') {
1.448 albertel 8465: if (open(my $fh,$replyfile)) {
1.904 albertel 8466: $reply = join('',<$fh>);
8467: close($fh);
1.240 www 8468: } else { return 'error: reply_file_error'; }
1.242 www 8469: return &unescape($reply);
8470: }
1.240 www 8471: }
1.242 www 8472: return 'timeout:'.$queryid;
1.240 www 8473: }
8474:
8475: sub courselog_query {
1.241 www 8476: #
8477: # possible filters:
8478: # url: url or symb
8479: # username
8480: # domain
8481: # action: view, submit, grade
8482: # start: timestamp
8483: # end: timestamp
8484: #
1.240 www 8485: my (%filters)=@_;
1.620 albertel 8486: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 8487: if ($filters{'url'}) {
8488: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8489: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8490: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8491: }
1.620 albertel 8492: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8493: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 8494: return &log_query($cname,$cdom,'courselog',%filters);
8495: }
8496:
8497: sub userlog_query {
1.858 raeburn 8498: #
8499: # possible filters:
8500: # action: log check role
8501: # start: timestamp
8502: # end: timestamp
8503: #
1.240 www 8504: my ($uname,$udom,%filters)=@_;
8505: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 8506: }
8507:
1.506 raeburn 8508: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8509:
8510: sub auto_run {
1.508 raeburn 8511: my ($cnum,$cdom) = @_;
1.876 raeburn 8512: my $response = 0;
8513: my $settings;
8514: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8515: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8516: $settings = $domconfig{'autoenroll'};
8517: if ($settings->{'run'} eq '1') {
8518: $response = 1;
8519: }
8520: } else {
1.934 raeburn 8521: my $homeserver;
8522: if (&is_course($cdom,$cnum)) {
8523: $homeserver = &homeserver($cnum,$cdom);
8524: } else {
8525: $homeserver = &domain($cdom,'primary');
8526: }
8527: if ($homeserver ne 'no_host') {
8528: $response = &reply('autorun:'.$cdom,$homeserver);
8529: }
1.876 raeburn 8530: }
1.506 raeburn 8531: return $response;
8532: }
1.776 albertel 8533:
1.506 raeburn 8534: sub auto_get_sections {
1.508 raeburn 8535: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 8536: my $homeserver;
8537: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8538: $homeserver = &homeserver($cnum,$cdom);
8539: }
8540: if (!defined($homeserver)) {
8541: if ($cdom =~ /^$match_domain$/) {
8542: $homeserver = &domain($cdom,'primary');
8543: }
8544: }
8545: my @secs;
8546: if (defined($homeserver)) {
8547: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8548: unless ($response eq 'refused') {
8549: @secs = split(/:/,$response);
8550: }
1.506 raeburn 8551: }
8552: return @secs;
8553: }
1.776 albertel 8554:
1.506 raeburn 8555: sub auto_new_course {
1.1099 raeburn 8556: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 8557: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 8558: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 8559: return $response;
8560: }
1.776 albertel 8561:
1.506 raeburn 8562: sub auto_validate_courseID {
1.508 raeburn 8563: my ($cnum,$cdom,$inst_course_id) = @_;
8564: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 8565: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 8566: return $response;
8567: }
1.776 albertel 8568:
1.1007 raeburn 8569: sub auto_validate_instcode {
1.1020 raeburn 8570: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 8571: my ($homeserver,$response);
8572: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8573: $homeserver = &homeserver($cnum,$cdom);
8574: }
8575: if (!defined($homeserver)) {
8576: if ($cdom =~ /^$match_domain$/) {
8577: $homeserver = &domain($cdom,'primary');
8578: }
8579: }
1.1065 raeburn 8580: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8581: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 8582: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
8583: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 8584: }
8585:
1.506 raeburn 8586: sub auto_create_password {
1.873 raeburn 8587: my ($cnum,$cdom,$authparam,$udom) = @_;
8588: my ($homeserver,$response);
1.506 raeburn 8589: my $create_passwd = 0;
8590: my $authchk = '';
1.873 raeburn 8591: if ($udom =~ /^$match_domain$/) {
8592: $homeserver = &domain($udom,'primary');
8593: }
8594: if ($homeserver eq '') {
8595: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8596: $homeserver = &homeserver($cnum,$cdom);
8597: }
8598: }
8599: if ($homeserver eq '') {
8600: $authchk = 'nodomain';
1.506 raeburn 8601: } else {
1.873 raeburn 8602: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8603: if ($response eq 'refused') {
8604: $authchk = 'refused';
8605: } else {
1.901 albertel 8606: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8607: }
1.506 raeburn 8608: }
8609: return ($authparam,$create_passwd,$authchk);
8610: }
8611:
1.706 raeburn 8612: sub auto_photo_permission {
8613: my ($cnum,$cdom,$students) = @_;
8614: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8615: my ($outcome,$perm_reqd,$conditions) =
8616: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8617: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8618: return (undef,undef);
8619: }
1.706 raeburn 8620: return ($outcome,$perm_reqd,$conditions);
8621: }
8622:
8623: sub auto_checkphotos {
8624: my ($uname,$udom,$pid) = @_;
8625: my $homeserver = &homeserver($uname,$udom);
8626: my ($result,$resulttype);
8627: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8628: &escape($uname).':'.&escape($pid),
8629: $homeserver));
1.709 albertel 8630: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8631: return (undef,undef);
8632: }
1.706 raeburn 8633: if ($outcome) {
8634: ($result,$resulttype) = split(/:/,$outcome);
8635: }
8636: return ($result,$resulttype);
8637: }
8638:
8639: sub auto_photochoice {
8640: my ($cnum,$cdom) = @_;
8641: my $homeserver = &homeserver($cnum,$cdom);
8642: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8643: &escape($cdom),
8644: $homeserver)));
1.709 albertel 8645: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8646: return (undef,undef);
8647: }
1.706 raeburn 8648: return ($update,$comment);
8649: }
8650:
8651: sub auto_photoupdate {
8652: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8653: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8654: my $host=&hostname($homeserver);
1.706 raeburn 8655: my $cmd = '';
8656: my $maxtries = 1;
1.800 albertel 8657: foreach my $affiliate (keys(%{$affiliatesref})) {
8658: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8659: }
8660: $cmd =~ s/%%$//;
8661: $cmd = &escape($cmd);
8662: my $query = 'institutionalphotos';
8663: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8664: unless ($queryid=~/^\Q$host\E\_/) {
8665: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8666: return 'error: '.$queryid;
8667: }
8668: my $reply = &get_query_reply($queryid);
8669: my $tries = 1;
8670: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8671: $reply = &get_query_reply($queryid);
8672: $tries ++;
8673: }
8674: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8675: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8676: } else {
8677: my @responses = split(/:/,$reply);
8678: my $outcome = shift(@responses);
8679: foreach my $item (@responses) {
8680: my ($key,$value) = split(/=/,$item);
8681: $$photo{$key} = $value;
8682: }
8683: return $outcome;
8684: }
8685: return 'error';
8686: }
8687:
1.521 raeburn 8688: sub auto_instcode_format {
1.793 albertel 8689: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8690: $cat_order) = @_;
1.521 raeburn 8691: my $courses = '';
1.772 raeburn 8692: my @homeservers;
1.521 raeburn 8693: if ($caller eq 'global') {
1.841 albertel 8694: my %servers = &get_servers($codedom,'library');
8695: foreach my $tryserver (keys(%servers)) {
8696: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8697: push(@homeservers,$tryserver);
8698: }
1.584 raeburn 8699: }
1.1022 raeburn 8700: } elsif ($caller eq 'requests') {
8701: if ($codedom =~ /^$match_domain$/) {
8702: my $chome = &domain($codedom,'primary');
8703: unless ($chome eq 'no_host') {
8704: push(@homeservers,$chome);
8705: }
8706: }
1.521 raeburn 8707: } else {
1.772 raeburn 8708: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8709: }
1.793 albertel 8710: foreach my $code (keys(%{$instcodes})) {
8711: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8712: }
8713: chop($courses);
1.772 raeburn 8714: my $ok_response = 0;
8715: my $response;
8716: while (@homeservers > 0 && $ok_response == 0) {
8717: my $server = shift(@homeservers);
8718: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8719: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8720: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8721: split(/:/,$response);
1.772 raeburn 8722: %{$codes} = (%{$codes},&str2hash($codes_str));
8723: push(@{$codetitles},&str2array($codetitles_str));
8724: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8725: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8726: $ok_response = 1;
8727: }
8728: }
8729: if ($ok_response) {
1.521 raeburn 8730: return 'ok';
1.772 raeburn 8731: } else {
8732: return $response;
1.521 raeburn 8733: }
8734: }
8735:
1.792 raeburn 8736: sub auto_instcode_defaults {
8737: my ($domain,$returnhash,$code_order) = @_;
8738: my @homeservers;
1.841 albertel 8739:
8740: my %servers = &get_servers($domain,'library');
8741: foreach my $tryserver (keys(%servers)) {
8742: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8743: push(@homeservers,$tryserver);
8744: }
1.792 raeburn 8745: }
1.841 albertel 8746:
1.792 raeburn 8747: my $response;
1.841 albertel 8748: foreach my $server (@homeservers) {
1.792 raeburn 8749: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8750: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8751:
8752: foreach my $pair (split(/\&/,$response)) {
8753: my ($name,$value)=split(/\=/,$pair);
8754: if ($name eq 'code_order') {
8755: @{$code_order} = split(/\&/,&unescape($value));
8756: } else {
8757: $returnhash->{&unescape($name)}=&unescape($value);
8758: }
8759: }
8760: return 'ok';
1.792 raeburn 8761: }
1.841 albertel 8762:
8763: return $response;
1.1003 raeburn 8764: }
8765:
8766: sub auto_possible_instcodes {
1.1007 raeburn 8767: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8768: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8769: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8770: return;
8771: }
1.1003 raeburn 8772: my (@homeservers,$uhome);
8773: if (defined(&domain($domain,'primary'))) {
8774: $uhome=&domain($domain,'primary');
8775: push(@homeservers,&domain($domain,'primary'));
8776: } else {
8777: my %servers = &get_servers($domain,'library');
8778: foreach my $tryserver (keys(%servers)) {
8779: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8780: push(@homeservers,$tryserver);
8781: }
8782: }
8783: }
8784: my $response;
8785: foreach my $server (@homeservers) {
8786: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8787: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8788: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8789: split(':',$response);
8790: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8791: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8792: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8793: my ($name,$value)=split('=',$item);
8794: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8795: }
8796: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8797: my ($name,$value)=split('=',$item);
8798: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8799: }
8800: return 'ok';
8801: }
8802: return $response;
8803: }
1.792 raeburn 8804:
1.1010 raeburn 8805: sub auto_courserequest_checks {
8806: my ($dom) = @_;
1.1020 raeburn 8807: my ($homeserver,%validations);
8808: if ($dom =~ /^$match_domain$/) {
8809: $homeserver = &domain($dom,'primary');
8810: }
8811: unless ($homeserver eq 'no_host') {
8812: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8813: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8814: my @items = split(/&/,$response);
8815: foreach my $item (@items) {
8816: my ($key,$value) = split('=',$item);
8817: $validations{&unescape($key)} = &thaw_unescape($value);
8818: }
8819: }
8820: }
1.1010 raeburn 8821: return %validations;
8822: }
8823:
1.1020 raeburn 8824: sub auto_courserequest_validation {
1.1255 raeburn 8825: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8826: my ($homeserver,$response);
8827: if ($dom =~ /^$match_domain$/) {
8828: $homeserver = &domain($dom,'primary');
8829: }
1.1255 raeburn 8830: unless ($homeserver eq 'no_host') {
8831: my $customdata;
8832: if (ref($custominfo) eq 'HASH') {
8833: $customdata = &freeze_escape($custominfo);
8834: }
1.1020 raeburn 8835: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8836: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 8837: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8838: $customdata,$homeserver));
1.1020 raeburn 8839: }
8840: return $response;
8841: }
8842:
1.777 albertel 8843: sub auto_validate_class_sec {
1.918 raeburn 8844: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8845: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8846: my $ownerlist;
8847: if (ref($owners) eq 'ARRAY') {
8848: $ownerlist = join(',',@{$owners});
8849: } else {
8850: $ownerlist = $owners;
8851: }
1.773 raeburn 8852: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8853: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8854: return $response;
8855: }
8856:
1.1248 raeburn 8857: sub auto_crsreq_update {
8858: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 8859: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 8860: my ($homeserver,%crsreqresponse);
8861: if ($cdom =~ /^$match_domain$/) {
8862: $homeserver = &domain($cdom,'primary');
8863: }
8864: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8865: my $info;
8866: if (ref($inbound) eq 'HASH') {
8867: $info = &freeze_escape($inbound);
8868: }
8869: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8870: ':'.&escape($action).':'.&escape($ownername).':'.
8871: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 8872: &escape($title).':'.&escape($code).':'.
8873: &escape($accessstart).':'.&escape($accessend).':'.$info,
8874: $homeserver);
1.1248 raeburn 8875: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8876: my @items = split(/&/,$response);
8877: foreach my $item (@items) {
8878: my ($key,$value) = split('=',$item);
8879: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8880: }
8881: }
8882: }
8883: return \%crsreqresponse;
8884: }
8885:
1.1305 raeburn 8886: sub auto_export_grades {
1.1309 raeburn 8887: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8888: my ($homeserver,%exportresponse);
8889: if ($cdom =~ /^$match_domain$/) {
8890: $homeserver = &domain($cdom,'primary');
8891: }
8892: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8893: my $info;
8894: if (ref($inforef) eq 'HASH') {
8895: $info = &freeze_escape($inforef);
8896: }
8897: if (ref($gradesref) eq 'HASH') {
8898: my $grades = &freeze_escape($gradesref);
8899: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8900: $info.':'.$grades,$homeserver);
8901: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8902: my @items = split(/&/,$response);
8903: foreach my $item (@items) {
8904: my ($key,$value) = split('=',$item);
8905: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8906: }
8907: }
8908: }
8909: }
8910: return \%exportresponse;
1.1305 raeburn 8911: }
8912:
1.1287 raeburn 8913: sub check_instcode_cloning {
8914: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8915: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8916: return;
8917: }
8918: my $canclone;
8919: if (@{$code_order} > 0) {
8920: my $instcoderegexp ='^';
8921: my @clonecodes = split(/\&/,$cloner);
8922: foreach my $item (@{$code_order}) {
8923: if (grep(/^\Q$item\E=/,@clonecodes)) {
8924: foreach my $pair (@clonecodes) {
8925: my ($key,$val) = split(/\=/,$pair,2);
8926: $val = &unescape($val);
8927: if ($key eq $item) {
8928: $instcoderegexp .= '('.$val.')';
8929: last;
8930: }
8931: }
8932: } else {
8933: $instcoderegexp .= $codedefaults->{$item};
8934: }
8935: }
8936: $instcoderegexp .= '$';
8937: my (@from,@to);
8938: eval {
8939: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8940: (@to) = ($clonetocode =~ /$instcoderegexp/);
8941: };
8942: if ((@from > 0) && (@to > 0)) {
8943: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8944: if (!@diffs) {
8945: $canclone = 1;
8946: }
8947: }
8948: }
8949: return $canclone;
8950: }
8951:
8952: sub default_instcode_cloning {
8953: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8954: my (%codedefaults,@code_order,$canclone);
8955: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8956: %codedefaults = %{$codedefaultsref};
8957: @code_order = @{$codeorderref};
8958: } elsif ($clonedom) {
8959: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8960: }
8961: if (($domdefclone) && (@code_order)) {
8962: my @clonecodes = split(/\+/,$domdefclone);
8963: my $instcoderegexp ='^';
8964: foreach my $item (@code_order) {
8965: if (grep(/^\Q$item\E$/,@clonecodes)) {
8966: $instcoderegexp .= '('.$codedefaults{$item}.')';
8967: } else {
8968: $instcoderegexp .= $codedefaults{$item};
8969: }
8970: }
8971: $instcoderegexp .= '$';
8972: my (@from,@to);
8973: eval {
8974: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8975: (@to) = ($clonetocode =~ /$instcoderegexp/);
8976: };
8977: if ((@from > 0) && (@to > 0)) {
8978: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8979: if (!@diffs) {
8980: $canclone = 1;
8981: }
8982: }
8983: }
8984: return $canclone;
8985: }
8986:
1.679 raeburn 8987: # ------------------------------------------------------- Course Group routines
8988:
8989: sub get_coursegroups {
1.809 raeburn 8990: my ($cdom,$cnum,$group,$namespace) = @_;
8991: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8992: }
8993:
1.679 raeburn 8994: sub modify_coursegroup {
8995: my ($cdom,$cnum,$groupsettings) = @_;
8996: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8997: }
8998:
1.809 raeburn 8999: sub toggle_coursegroup_status {
9000: my ($cdom,$cnum,$group,$action) = @_;
9001: my ($from_namespace,$to_namespace);
9002: if ($action eq 'delete') {
9003: $from_namespace = 'coursegroups';
9004: $to_namespace = 'deleted_groups';
9005: } else {
9006: $from_namespace = 'deleted_groups';
9007: $to_namespace = 'coursegroups';
9008: }
9009: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 9010: if (my $tmp = &error(%curr_group)) {
9011: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9012: return ('read error',$tmp);
9013: } else {
9014: my %savedsettings = %curr_group;
1.809 raeburn 9015: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 9016: my $deloutcome;
9017: if ($result eq 'ok') {
1.809 raeburn 9018: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 9019: } else {
9020: return ('write error',$result);
9021: }
9022: if ($deloutcome eq 'ok') {
9023: return 'ok';
9024: } else {
9025: return ('delete error',$deloutcome);
9026: }
9027: }
9028: }
9029:
1.679 raeburn 9030: sub modify_group_roles {
1.957 raeburn 9031: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 9032: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9033: my $role = 'gr/'.&escape($userprivs);
9034: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 9035: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 9036: if ($result eq 'ok') {
9037: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9038: }
1.679 raeburn 9039: return $result;
9040: }
9041:
9042: sub modify_coursegroup_membership {
9043: my ($cdom,$cnum,$membership) = @_;
9044: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9045: return $result;
9046: }
9047:
1.682 raeburn 9048: sub get_active_groups {
9049: my ($udom,$uname,$cdom,$cnum) = @_;
9050: my $now = time;
9051: my %groups = ();
9052: foreach my $key (keys(%env)) {
1.811 albertel 9053: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 9054: my ($start,$end) = split(/\./,$env{$key});
9055: if (($end!=0) && ($end<$now)) { next; }
9056: if (($start!=0) && ($start>$now)) { next; }
9057: if ($1 eq $cdom && $2 eq $cnum) {
9058: $groups{$3} = $env{$key} ;
9059: }
9060: }
9061: }
9062: return %groups;
9063: }
9064:
1.683 raeburn 9065: sub get_group_membership {
9066: my ($cdom,$cnum,$group) = @_;
9067: return(&dump('groupmembership',$cdom,$cnum,$group));
9068: }
9069:
9070: sub get_users_groups {
9071: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 9072: my @usersgroups;
1.683 raeburn 9073: my $cachetime=1800;
9074:
9075: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 9076: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9077: if (defined($cached)) {
1.734 albertel 9078: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 9079: } else {
9080: $grouplist = '';
1.816 raeburn 9081: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 9082: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 9083: my $access_end = $env{'course.'.$courseid.
9084: '.default_enrollment_end_date'};
9085: my $now = time;
9086: foreach my $key (keys(%roleshash)) {
9087: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9088: my $group = $1;
9089: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9090: my $start = $2;
9091: my $end = $1;
9092: if ($start == -1) { next; } # deleted from group
9093: if (($start!=0) && ($start>$now)) { next; }
9094: if (($end!=0) && ($end<$now)) {
9095: if ($access_end && $access_end < $now) {
9096: if ($access_end - $end < 86400) {
9097: push(@usersgroups,$group);
1.733 raeburn 9098: }
9099: }
1.817 raeburn 9100: next;
1.733 raeburn 9101: }
1.817 raeburn 9102: push(@usersgroups,$group);
1.683 raeburn 9103: }
9104: }
9105: }
1.817 raeburn 9106: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9107: $grouplist = join(':',@usersgroups);
9108: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 9109: }
1.733 raeburn 9110: return @usersgroups;
1.683 raeburn 9111: }
9112:
9113: sub devalidate_getgroups_cache {
9114: my ($udom,$uname,$cdom,$cnum)=@_;
9115: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 9116:
1.683 raeburn 9117: my $hashid="$udom:$uname:$courseid";
9118: &devalidate_cache_new('getgroups',$hashid);
9119: }
9120:
1.12 www 9121: # ------------------------------------------------------------------ Plain Text
9122:
9123: sub plaintext {
1.988 raeburn 9124: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 9125: if ($short =~ m{^cr/}) {
1.758 albertel 9126: return (split('/',$short))[-1];
9127: }
1.742 raeburn 9128: if (!defined($cid)) {
9129: $cid = $env{'request.course.id'};
9130: }
9131: my %rolenames = (
1.1008 raeburn 9132: Course => 'std',
9133: Community => 'alt1',
1.1305 raeburn 9134: Placement => 'std',
1.742 raeburn 9135: );
1.1037 raeburn 9136: if ($cid ne '') {
9137: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9138: unless ($forcedefault) {
9139: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9140: &Apache::lonlocal::mt_escape(\$roletext);
9141: return &Apache::lonlocal::mt($roletext);
9142: }
9143: }
9144: }
9145: if ((defined($type)) && (defined($rolenames{$type})) &&
9146: (defined($rolenames{$type})) &&
9147: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 9148: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 9149: } elsif ($cid ne '') {
9150: my $crstype = $env{'course.'.$cid.'.type'};
9151: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9152: (defined($prp{$short}{$rolenames{$crstype}}))) {
9153: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9154: }
1.742 raeburn 9155: }
1.1037 raeburn 9156: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 9157: }
9158:
9159: # ----------------------------------------------------------------- Assign Role
9160:
9161: sub assignrole {
1.957 raeburn 9162: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9163: $context)=@_;
1.21 www 9164: my $mrole;
9165: if ($role =~ /^cr\//) {
1.393 www 9166: my $cwosec=$url;
1.811 albertel 9167: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 9168: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 9169: my $refused = 1;
9170: if ($context eq 'requestcourses') {
9171: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9172: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9173: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9174: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9175: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9176: if ($crsenv{'internal.courseowner'} eq
9177: $env{'user.name'}.':'.$env{'user.domain'}) {
9178: $refused = '';
9179: }
9180: }
9181: }
9182: }
9183: }
9184: if ($refused) {
9185: &logthis('Refused custom assignrole: '.
9186: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9187: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9188: return 'refused';
9189: }
1.104 www 9190: }
1.21 www 9191: $mrole='cr';
1.678 raeburn 9192: } elsif ($role =~ /^gr\//) {
9193: my $cwogrp=$url;
1.811 albertel 9194: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 9195: unless (&allowed('mdg',$cwogrp)) {
9196: &logthis('Refused group assignrole: '.
9197: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9198: $env{'user.name'}.' at '.$env{'user.domain'});
9199: return 'refused';
9200: }
9201: $mrole='gr';
1.21 www 9202: } else {
1.82 www 9203: my $cwosec=$url;
1.811 albertel 9204: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9205: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9206: my $refused;
9207: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9208: if (!(&allowed('c'.$role,$url))) {
9209: $refused = 1;
9210: }
9211: } else {
9212: $refused = 1;
9213: }
1.947 raeburn 9214: if ($refused) {
1.1045 raeburn 9215: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9216: if (!$selfenroll && $context eq 'course') {
9217: my %crsenv;
9218: if ($role eq 'cc' || $role eq 'co') {
9219: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9220: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9221: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9222: if ($crsenv{'internal.courseowner'} eq
9223: $env{'user.name'}.':'.$env{'user.domain'}) {
9224: $refused = '';
9225: }
9226: }
9227: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9228: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9229: if ($crsenv{'internal.courseowner'} eq
9230: $env{'user.name'}.':'.$env{'user.domain'}) {
9231: $refused = '';
9232: }
9233: }
9234: }
9235: }
9236: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 9237: $refused = '';
1.1017 raeburn 9238: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9239: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9240: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9241: my $wrongcc;
9242: if ($cnum =~ /^$match_community$/) {
9243: $wrongcc = 1 if ($role eq 'cc');
9244: } else {
9245: $wrongcc = 1 if ($role eq 'co');
9246: }
9247: unless ($wrongcc) {
9248: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9249: if ($crsenv{'internal.courseowner'} eq
9250: $env{'user.name'}.':'.$env{'user.domain'}) {
9251: $refused = '';
9252: }
1.1017 raeburn 9253: }
9254: }
1.1183 raeburn 9255: } elsif ($context eq 'requestauthor') {
9256: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9257: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9258: if ($env{'environment.requestauthor'} eq 'automatic') {
9259: $refused = '';
9260: } else {
9261: my %domdefaults = &get_domain_defaults($udom);
9262: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9263: my $checkbystatus;
9264: if ($env{'user.adv'}) {
9265: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9266: if ($disposition eq 'automatic') {
9267: $refused = '';
9268: } elsif ($disposition eq '') {
9269: $checkbystatus = 1;
9270: }
9271: } else {
9272: $checkbystatus = 1;
9273: }
9274: if ($checkbystatus) {
9275: if ($env{'environment.inststatus'}) {
9276: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9277: foreach my $type (@inststatuses) {
9278: if (($type ne '') &&
9279: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9280: $refused = '';
9281: }
9282: }
9283: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9284: $refused = '';
9285: }
9286: }
9287: }
9288: }
9289: }
1.1017 raeburn 9290: }
9291: if ($refused) {
1.947 raeburn 9292: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9293: ' '.$role.' '.$end.' '.$start.' by '.
9294: $env{'user.name'}.' at '.$env{'user.domain'});
9295: return 'refused';
9296: }
1.932 raeburn 9297: }
1.1131 raeburn 9298: } elsif ($role eq 'au') {
9299: if ($url ne '/'.$udom.'/') {
9300: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9301: ' to assign author role for '.$uname.':'.$udom.
9302: ' in domain: '.$url.' refused (wrong domain).');
9303: return 'refused';
9304: }
1.104 www 9305: }
1.21 www 9306: $mrole=$role;
9307: }
1.620 albertel 9308: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9309: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9310: if ($end) { $command.='_'.$end; }
1.21 www 9311: if ($start) {
9312: if ($end) {
1.81 www 9313: $command.='_'.$start;
1.21 www 9314: } else {
1.81 www 9315: $command.='_0_'.$start;
1.21 www 9316: }
9317: }
1.739 raeburn 9318: my $origstart = $start;
9319: my $origend = $end;
1.957 raeburn 9320: my $delflag;
1.357 www 9321: # actually delete
9322: if ($deleteflag) {
1.373 www 9323: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9324: # modify command to delete the role
1.620 albertel 9325: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9326: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9327: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9328: # set start and finish to negative values for userrolelog
9329: $start=-1;
9330: $end=-1;
1.957 raeburn 9331: $delflag = 1;
1.357 www 9332: }
9333: }
9334: # send command
1.349 www 9335: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9336: # log new user role if status is ok
1.349 www 9337: if ($answer eq 'ok') {
1.663 raeburn 9338: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 9339: if (($role eq 'cc') || ($role eq 'in') ||
9340: ($role eq 'ep') || ($role eq 'ad') ||
9341: ($role eq 'ta') || ($role eq 'st') ||
9342: ($role=~/^cr/) || ($role eq 'gr') ||
9343: ($role eq 'co')) {
1.1200 raeburn 9344: # for course roles, perform group memberships changes triggered by role change.
9345: unless ($role =~ /^gr/) {
9346: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9347: $origstart,$selfenroll,$context);
9348: }
1.1184 raeburn 9349: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9350: $selfenroll,$context);
9351: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334 raeburn 9352: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9353: ($role eq 'da')) {
1.1184 raeburn 9354: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9355: $context);
9356: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9357: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9358: $context);
9359: }
1.1053 raeburn 9360: if ($role eq 'cc') {
9361: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9362: }
1.349 www 9363: }
9364: return $answer;
1.169 harris41 9365: }
9366:
1.1053 raeburn 9367: sub autoupdate_coowners {
9368: my ($url,$end,$start,$uname,$udom) = @_;
9369: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9370: if (($cdom ne '') && ($cnum ne '')) {
9371: my $now = time;
9372: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9373: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9374: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9375: my $instcode = $coursehash{'internal.coursecode'};
9376: if ($instcode ne '') {
1.1056 raeburn 9377: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9378: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 9379: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 9380: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9381: if ($result eq 'valid') {
9382: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 9383: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9384: push(@newcoowners,$coowner);
9385: }
9386: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9387: push(@newcoowners,$uname.':'.$udom);
9388: }
9389: @newcoowners = sort(@newcoowners);
9390: } else {
9391: push(@newcoowners,$uname.':'.$udom);
9392: }
9393: } else {
9394: if ($coursehash{'internal.co-owners'}) {
9395: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9396: unless ($coowner eq $uname.':'.$udom) {
9397: push(@newcoowners,$coowner);
9398: }
9399: }
9400: unless (@newcoowners > 0) {
9401: $delcoowners = 1;
9402: $coowners = '';
9403: }
9404: }
9405: }
9406: if (@newcoowners || $delcoowners) {
9407: &store_coowners($cdom,$cnum,$coursehash{'home'},
9408: $delcoowners,@newcoowners);
9409: }
9410: }
9411: }
9412: }
9413: }
9414: }
9415: }
9416:
9417: sub store_coowners {
9418: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9419: my $cid = $cdom.'_'.$cnum;
9420: my ($coowners,$delresult,$putresult);
9421: if (@newcoowners) {
9422: $coowners = join(',',@newcoowners);
9423: my %coownershash = (
9424: 'internal.co-owners' => $coowners,
9425: );
9426: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9427: if ($putresult eq 'ok') {
9428: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9429: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9430: }
9431: }
9432: }
9433: if ($delcoowners) {
9434: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9435: if ($delresult eq 'ok') {
9436: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9437: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9438: }
9439: }
9440: }
9441: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9442: my %crsinfo =
9443: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9444: if (ref($crsinfo{$cid}) eq 'HASH') {
9445: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9446: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9447: }
9448: }
9449: }
9450:
1.169 harris41 9451: # -------------------------------------------------- Modify user authentication
1.197 www 9452: # Overrides without validation
9453:
1.169 harris41 9454: sub modifyuserauth {
9455: my ($udom,$uname,$umode,$upass)=@_;
9456: my $uhome=&homeserver($uname,$udom);
1.197 www 9457: unless (&allowed('mau',$udom)) { return 'refused'; }
9458: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 9459: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9460: ' in domain '.$env{'request.role.domain'});
1.169 harris41 9461: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9462: &escape($upass),$uhome);
1.620 albertel 9463: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 9464: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9465: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9466: &log($udom,,$uname,$uhome,
1.620 albertel 9467: 'Authentication changed by '.$env{'user.domain'}.', '.
9468: $env{'user.name'}.', '.$umode.
1.197 www 9469: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 9470: unless ($reply eq 'ok') {
1.197 www 9471: &logthis('Authentication mode error: '.$reply);
1.169 harris41 9472: return 'error: '.$reply;
9473: }
1.170 harris41 9474: return 'ok';
1.80 www 9475: }
9476:
1.81 www 9477: # --------------------------------------------------------------- Modify a user
1.80 www 9478:
1.81 www 9479: sub modifyuser {
1.206 matthew 9480: my ($udom, $uname, $uid,
9481: $umode, $upass, $first,
9482: $middle, $last, $gene,
1.1058 raeburn 9483: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 9484: $udom= &LONCAPA::clean_domain($udom);
9485: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 9486: my $showcandelete = 'none';
9487: if (ref($candelete) eq 'ARRAY') {
9488: if (@{$candelete} > 0) {
9489: $showcandelete = join(', ',@{$candelete});
9490: }
9491: }
1.81 www 9492: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 9493: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 9494: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 9495: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9496: ' desiredhome not specified').
1.620 albertel 9497: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9498: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 9499: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 9500: my $newuser;
9501: if ($uhome eq 'no_host') {
9502: $newuser = 1;
9503: }
1.80 www 9504: # ----------------------------------------------------------------- Create User
1.406 albertel 9505: if (($uhome eq 'no_host') &&
9506: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 9507: my $unhome='';
1.844 albertel 9508: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 9509: $unhome = $desiredhome;
1.620 albertel 9510: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9511: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 9512: } else { # load balancing routine for determining $unhome
1.81 www 9513: my $loadm=10000000;
1.841 albertel 9514: my %servers = &get_servers($udom,'library');
9515: foreach my $tryserver (keys(%servers)) {
9516: my $answer=reply('load',$tryserver);
9517: if (($answer=~/\d+/) && ($answer<$loadm)) {
9518: $loadm=$answer;
9519: $unhome=$tryserver;
9520: }
1.80 www 9521: }
9522: }
9523: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 9524: return 'error: unable to find a home server for '.$uname.
9525: ' in domain '.$udom;
1.80 www 9526: }
9527: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9528: &escape($upass),$unhome);
9529: unless ($reply eq 'ok') {
9530: return 'error: '.$reply;
9531: }
1.230 stredwic 9532: $uhome=&homeserver($uname,$udom,'true');
1.80 www 9533: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 9534: return 'error: unable verify users home machine.';
1.80 www 9535: }
1.209 matthew 9536: } # End of creation of new user
1.80 www 9537: # ---------------------------------------------------------------------- Add ID
9538: if ($uid) {
9539: $uid=~tr/A-Z/a-z/;
9540: my %uidhash=&idrget($udom,$uname);
1.196 www 9541: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
9542: && (!$forceid)) {
1.80 www 9543: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 9544: return 'error: user id "'.$uid.'" does not match '.
9545: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 9546: }
9547: } else {
1.1300 raeburn 9548: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 9549: }
9550: }
9551: # -------------------------------------------------------------- Add names, etc
1.313 matthew 9552: my @tmp=&get('environment',
1.899 raeburn 9553: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 9554: 'permanentemail','inststatus'],
1.134 albertel 9555: $udom,$uname);
1.1075 raeburn 9556: my (%names,%oldnames);
1.313 matthew 9557: if ($tmp[0] =~ m/^error:.*/) {
9558: %names=();
9559: } else {
9560: %names = @tmp;
1.1075 raeburn 9561: %oldnames = %names;
1.313 matthew 9562: }
1.388 www 9563: #
1.1058 raeburn 9564: # If name, email and/or uid are blank (e.g., because an uploaded file
9565: # of users did not contain them), do not overwrite existing values
9566: # unless field is in $candelete array ref.
9567: #
9568:
9569: my @fields = ('firstname','middlename','lastname','generation',
9570: 'permanentemail','id');
9571: my %newvalues;
9572: if (ref($candelete) eq 'ARRAY') {
9573: foreach my $field (@fields) {
9574: if (grep(/^\Q$field\E$/,@{$candelete})) {
9575: if ($field eq 'firstname') {
9576: $names{$field} = $first;
9577: } elsif ($field eq 'middlename') {
9578: $names{$field} = $middle;
9579: } elsif ($field eq 'lastname') {
9580: $names{$field} = $last;
9581: } elsif ($field eq 'generation') {
9582: $names{$field} = $gene;
9583: } elsif ($field eq 'permanentemail') {
9584: $names{$field} = $email;
9585: } elsif ($field eq 'id') {
9586: $names{$field} = $uid;
9587: }
9588: }
9589: }
9590: }
1.388 www 9591: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 9592: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 9593: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 9594: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 9595: if ($email) {
9596: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 9597: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 9598: }
1.899 raeburn 9599: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 9600: if (defined($inststatus)) {
9601: $names{'inststatus'} = '';
9602: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9603: if (ref($usertypes) eq 'HASH') {
9604: my @okstatuses;
9605: foreach my $item (split(/:/,$inststatus)) {
9606: if (defined($usertypes->{$item})) {
9607: push(@okstatuses,$item);
9608: }
9609: }
9610: if (@okstatuses) {
9611: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9612: }
9613: }
9614: }
1.1075 raeburn 9615: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 9616: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 9617: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 9618: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9619: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9620: } else {
9621: $logmsg .= ' during self creation';
9622: }
1.1075 raeburn 9623: my $changed;
9624: if ($newuser) {
9625: $changed = 1;
9626: } else {
9627: foreach my $field (@fields) {
9628: if ($names{$field} ne $oldnames{$field}) {
9629: $changed = 1;
9630: last;
9631: }
9632: }
9633: }
9634: unless ($changed) {
9635: $logmsg = 'No changes in user information needed for: '.$logmsg;
9636: &logthis($logmsg);
9637: return 'ok';
9638: }
9639: my $reply = &put('environment', \%names, $udom,$uname);
9640: if ($reply ne 'ok') {
9641: return 'error: '.$reply;
9642: }
1.1087 raeburn 9643: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9644: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9645: }
1.1075 raeburn 9646: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9647: &devalidate_cache_new('namescache',$uname.':'.$udom);
9648: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9649: &logthis($logmsg);
1.134 albertel 9650: return 'ok';
1.80 www 9651: }
9652:
1.81 www 9653: # -------------------------------------------------------------- Modify student
1.80 www 9654:
1.81 www 9655: sub modifystudent {
9656: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9657: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 9658: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 9659: if (!$cid) {
1.620 albertel 9660: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9661: return 'not_in_class';
9662: }
1.80 www 9663: }
9664: # --------------------------------------------------------------- Make the user
1.81 www 9665: my $reply=&modifyuser
1.209 matthew 9666: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9667: $desiredhome,$email,$inststatus);
1.80 www 9668: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9669: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 9670: # student's environment
1.297 matthew 9671: $uid = undef if (!$forceid);
1.455 albertel 9672: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 9673: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 9674: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 9675: return $reply;
9676: }
9677:
9678: sub modify_student_enrollment {
1.1216 raeburn 9679: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314 raeburn 9680: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 9681: my ($cdom,$cnum,$chome);
9682: if (!$cid) {
1.620 albertel 9683: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9684: return 'not_in_class';
9685: }
1.620 albertel 9686: $cdom=$env{'course.'.$cid.'.domain'};
9687: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9688: } else {
9689: ($cdom,$cnum)=split(/_/,$cid);
9690: }
1.620 albertel 9691: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9692: if (!$chome) {
1.457 raeburn 9693: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9694: }
1.455 albertel 9695: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9696: # Make sure the user exists
1.81 www 9697: my $uhome=&homeserver($uname,$udom);
9698: if (($uhome eq '') || ($uhome eq 'no_host')) {
9699: return 'error: no such user';
9700: }
1.297 matthew 9701: # Get student data if we were not given enough information
9702: if (!defined($first) || $first eq '' ||
9703: !defined($last) || $last eq '' ||
9704: !defined($uid) || $uid eq '' ||
9705: !defined($middle) || $middle eq '' ||
9706: !defined($gene) || $gene eq '') {
1.294 matthew 9707: # They did not supply us with enough data to enroll the student, so
9708: # we need to pick up more information.
1.297 matthew 9709: my %tmp = &get('environment',
1.294 matthew 9710: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9711: ,$udom,$uname);
9712:
1.800 albertel 9713: #foreach my $key (keys(%tmp)) {
9714: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9715: #}
1.294 matthew 9716: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9717: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9718: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9719: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9720: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9721: }
1.556 albertel 9722: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9723: my $user = "$uname:$udom";
9724: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9725: my $reply=cput('classlist',
1.1148 raeburn 9726: {$user =>
1.1314 raeburn 9727: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 9728: $cdom,$cnum);
1.1148 raeburn 9729: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9730: &devalidate_getsection_cache($udom,$uname,$cid);
9731: } else {
1.81 www 9732: return 'error: '.$reply;
9733: }
1.297 matthew 9734: # Add student role to user
1.83 www 9735: my $uurl='/'.$cid;
1.81 www 9736: $uurl=~s/\_/\//g;
9737: if ($usec) {
9738: $uurl.='/'.$usec;
9739: }
1.1148 raeburn 9740: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9741: $selfenroll,$context);
9742: if ($result ne 'ok') {
9743: if ($old_entry{$user} ne '') {
9744: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9745: } else {
9746: $reply = &del('classlist',[$user],$cdom,$cnum);
9747: }
9748: }
9749: return $result;
1.21 www 9750: }
9751:
1.556 albertel 9752: sub format_name {
9753: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9754: my $name;
9755: if ($first ne 'lastname') {
9756: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9757: } else {
9758: if ($lastname=~/\S/) {
9759: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9760: $name=~s/\s+,/,/;
9761: } else {
9762: $name.= $firstname.' '.$middlename.' '.$generation;
9763: }
9764: }
9765: $name=~s/^\s+//;
9766: $name=~s/\s+$//;
9767: $name=~s/\s+/ /g;
9768: return $name;
9769: }
9770:
1.84 www 9771: # ------------------------------------------------- Write to course preferences
9772:
9773: sub writecoursepref {
9774: my ($courseid,%prefs)=@_;
9775: $courseid=~s/^\///;
9776: $courseid=~s/\_/\//g;
9777: my ($cdomain,$cnum)=split(/\//,$courseid);
9778: my $chome=homeserver($cnum,$cdomain);
9779: if (($chome eq '') || ($chome eq 'no_host')) {
9780: return 'error: no such course';
9781: }
9782: my $cstring='';
1.800 albertel 9783: foreach my $pref (keys(%prefs)) {
9784: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9785: }
1.84 www 9786: $cstring=~s/\&$//;
9787: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9788: }
9789:
9790: # ---------------------------------------------------------- Make/modify course
9791:
9792: sub createcourse {
1.741 raeburn 9793: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9794: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9795: $url=&declutter($url);
9796: my $cid='';
1.1028 raeburn 9797: if ($context eq 'requestcourses') {
9798: my $can_create = 0;
9799: my ($ownername,$ownerdom) = split(':',$course_owner);
9800: if ($udom eq $ownerdom) {
9801: if (&usertools_access($ownername,$ownerdom,$category,undef,
9802: $context)) {
9803: $can_create = 1;
9804: }
9805: } else {
9806: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9807: $category);
9808: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9809: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9810: if (@curr > 0) {
9811: my @options = qw(approval validate autolimit);
9812: my $optregex = join('|',@options);
9813: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9814: $can_create = 1;
9815: }
9816: }
9817: }
9818: }
9819: if ($can_create) {
9820: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9821: unless (&allowed('ccc',$udom)) {
9822: return 'refused';
9823: }
1.1017 raeburn 9824: }
9825: } else {
9826: return 'refused';
9827: }
1.1028 raeburn 9828: } elsif (!&allowed('ccc',$udom)) {
9829: return 'refused';
1.84 www 9830: }
1.1011 raeburn 9831: # --------------------------------------------------------------- Get Unique ID
9832: my $uname;
9833: if ($cnum =~ /^$match_courseid$/) {
9834: my $chome=&homeserver($cnum,$udom,'true');
9835: if (($chome eq '') || ($chome eq 'no_host')) {
9836: $uname = $cnum;
9837: } else {
1.1038 raeburn 9838: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9839: }
9840: } else {
1.1038 raeburn 9841: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9842: }
9843: return $uname if ($uname =~ /^error/);
9844: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9845: if (!defined($course_server)) {
9846: if (defined(&domain($udom,'primary'))) {
9847: $course_server = &domain($udom,'primary');
9848: } else {
9849: $course_server = $env{'user.home'};
9850: }
9851: }
9852: my %host_servers =
9853: &Apache::lonnet::get_servers($udom,'library');
9854: unless ($host_servers{$course_server}) {
9855: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9856: }
1.84 www 9857: # ------------------------------------------------------------- Make the course
9858: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9859: $course_server);
1.84 www 9860: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9861: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9862: if (($uhome eq '') || ($uhome eq 'no_host')) {
9863: return 'error: no such course';
9864: }
1.271 www 9865: # ----------------------------------------------------------------- Course made
1.516 raeburn 9866: # log existence
1.1029 raeburn 9867: my $now = time;
1.918 raeburn 9868: my $newcourse = {
9869: $udom.'_'.$uname => {
1.921 raeburn 9870: description => $description,
9871: inst_code => $inst_code,
9872: owner => $course_owner,
9873: type => $crstype,
1.1029 raeburn 9874: creator => $env{'user.name'}.':'.
9875: $env{'user.domain'},
9876: created => $now,
9877: context => $context,
1.918 raeburn 9878: },
9879: };
1.921 raeburn 9880: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9881: # set toplevel url
1.271 www 9882: my $topurl=$url;
9883: unless ($nonstandard) {
9884: # ------------------------------------------ For standard courses, make top url
9885: my $mapurl=&clutter($url);
1.278 www 9886: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9887: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9888: <map>
9889: <resource id="1" type="start"></resource>
9890: <resource id="2" src="$mapurl"></resource>
9891: <resource id="3" type="finish"></resource>
9892: <link index="1" from="1" to="2"></link>
9893: <link index="2" from="2" to="3"></link>
9894: </map>
9895: ENDINITMAP
9896: $topurl=&declutter(
1.638 albertel 9897: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9898: );
9899: }
9900: # ----------------------------------------------------------- Write preferences
1.84 www 9901: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9902: ('description' => $description,
9903: 'url' => $topurl,
9904: 'internal.creator' => $env{'user.name'}.':'.
9905: $env{'user.domain'},
9906: 'internal.created' => $now,
9907: 'internal.creationcontext' => $context)
9908: );
1.84 www 9909: return '/'.$udom.'/'.$uname;
9910: }
9911:
1.1011 raeburn 9912: # ------------------------------------------------------------------- Create ID
9913: sub generate_coursenum {
1.1038 raeburn 9914: my ($udom,$crstype) = @_;
1.1011 raeburn 9915: my $domdesc = &domain($udom);
9916: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9917: my $first;
9918: if ($crstype eq 'Community') {
9919: $first = '0';
9920: } else {
9921: $first = int(1+rand(9));
9922: }
9923: my $uname=$first.
1.1011 raeburn 9924: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9925: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9926: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9927: # ----------------------------------------------- Make sure that does not exist
9928: my $uhome=&homeserver($uname,$udom,'true');
9929: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9930: if ($crstype eq 'Community') {
9931: $first = '0';
9932: } else {
9933: $first = int(1+rand(9));
9934: }
9935: $uname=$first.
1.1011 raeburn 9936: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9937: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9938: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9939: $uhome=&homeserver($uname,$udom,'true');
9940: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9941: return 'error: unable to generate unique course-ID';
9942: }
9943: }
9944: return $uname;
9945: }
9946:
1.813 albertel 9947: sub is_course {
1.1167 droeschl 9948: my ($cdom, $cnum) = scalar(@_) == 1 ?
9949: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9950:
9951: return unless $cdom and $cnum;
9952:
9953: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9954: '.');
9955:
1.1219 raeburn 9956: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9957: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9958: }
9959:
1.1015 raeburn 9960: sub store_userdata {
9961: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9962: my $result;
1.1016 raeburn 9963: if ($datakey ne '') {
1.1013 raeburn 9964: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9965: if ($udom eq '' || $uname eq '') {
9966: $udom = $env{'user.domain'};
9967: $uname = $env{'user.name'};
9968: }
9969: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9970: if (($uhome eq '') || ($uhome eq 'no_host')) {
9971: $result = 'error: no_host';
9972: } else {
9973: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9974: $storehash->{'host'} = $perlvar{'lonHostID'};
9975:
9976: my $namevalue='';
9977: foreach my $key (keys(%{$storehash})) {
9978: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9979: }
9980: $namevalue=~s/\&$//;
1.1224 raeburn 9981: unless ($namespace eq 'courserequests') {
9982: $datakey = &escape($datakey);
9983: }
1.1105 raeburn 9984: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9985: $namevalue,$uhome);
1.1013 raeburn 9986: }
9987: } else {
9988: $result = 'error: data to store was not a hash reference';
9989: }
9990: } else {
9991: $result= 'error: invalid requestkey';
9992: }
9993: return $result;
9994: }
9995:
1.21 www 9996: # ---------------------------------------------------------- Assign Custom Role
9997:
9998: sub assigncustomrole {
1.957 raeburn 9999: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10000: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 10001: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 10002: }
10003:
10004: # ----------------------------------------------------------------- Revoke Role
10005:
10006: sub revokerole {
1.957 raeburn 10007: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10008: my $now=time;
1.965 raeburn 10009: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 10010: }
10011:
10012: # ---------------------------------------------------------- Revoke Custom Role
10013:
10014: sub revokecustomrole {
1.957 raeburn 10015: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 10016: my $now=time;
1.357 www 10017: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 10018: $deleteflag,$selfenroll,$context);
1.17 www 10019: }
10020:
1.533 banghart 10021: # ------------------------------------------------------------ Disk usage
1.535 albertel 10022: sub diskusage {
1.955 raeburn 10023: my ($udom,$uname,$directorypath,$getpropath)=@_;
10024: $directorypath =~ s/\/$//;
10025: my $listing=&reply('du2:'.&escape($directorypath).':'
10026: .&escape($getpropath).':'.&escape($uname).':'
10027: .&escape($udom),homeserver($uname,$udom));
10028: if ($listing eq 'unknown_cmd') {
10029: if ($getpropath) {
10030: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10031: }
10032: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10033: }
1.514 albertel 10034: return $listing;
1.512 banghart 10035: }
10036:
1.566 banghart 10037: sub is_locked {
1.1096 raeburn 10038: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 10039: my @check;
10040: my $is_locked;
1.1093 raeburn 10041: push (@check,$file_name);
1.613 albertel 10042: my %locked = &get('file_permissions',\@check,
1.620 albertel 10043: $env{'user.domain'},$env{'user.name'});
1.615 albertel 10044: my ($tmp)=keys(%locked);
10045: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 10046:
1.566 banghart 10047: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 10048: $is_locked = 'false';
10049: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 10050: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 10051: $is_locked = 'true';
1.1096 raeburn 10052: if (ref($which) eq 'ARRAY') {
10053: push(@{$which},$entry);
10054: } else {
10055: last;
10056: }
1.745 raeburn 10057: }
10058: }
1.566 banghart 10059: } else {
10060: $is_locked = 'false';
10061: }
1.1093 raeburn 10062: return $is_locked;
1.566 banghart 10063: }
10064:
1.759 albertel 10065: sub declutter_portfile {
10066: my ($file) = @_;
1.833 albertel 10067: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 10068: return $file;
10069: }
10070:
1.559 banghart 10071: # ------------------------------------------------------------- Mark as Read Only
10072:
10073: sub mark_as_readonly {
10074: my ($domain,$user,$files,$what) = @_;
1.613 albertel 10075: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10076: my ($tmp)=keys(%current_permissions);
10077: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 10078: foreach my $file (@{$files}) {
1.759 albertel 10079: $file = &declutter_portfile($file);
1.561 banghart 10080: push(@{$current_permissions{$file}},$what);
1.559 banghart 10081: }
1.613 albertel 10082: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10083: return;
10084: }
10085:
1.572 banghart 10086: # ------------------------------------------------------------Save Selected Files
10087:
10088: sub save_selected_files {
10089: my ($user, $path, @files) = @_;
10090: my $filename = $user."savedfiles";
1.573 banghart 10091: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 10092: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 10093: foreach my $file (@files) {
1.620 albertel 10094: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 10095: }
10096: foreach my $file (@other_files) {
1.574 banghart 10097: print (OUT $file."\n");
1.572 banghart 10098: }
1.574 banghart 10099: close (OUT);
1.572 banghart 10100: return 'ok';
10101: }
10102:
1.574 banghart 10103: sub clear_selected_files {
10104: my ($user) = @_;
10105: my $filename = $user."savedfiles";
1.1117 foxr 10106: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 10107: print (OUT undef);
10108: close (OUT);
10109: return ("ok");
10110: }
10111:
1.572 banghart 10112: sub files_in_path {
10113: my ($user, $path) = @_;
10114: my $filename = $user."savedfiles";
10115: my %return_files;
1.1117 foxr 10116: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 10117: while (my $line_in = <IN>) {
1.574 banghart 10118: chomp ($line_in);
10119: my @paths_and_file = split (m!/!, $line_in);
10120: my $file_part = pop (@paths_and_file);
10121: my $path_part = join ('/', @paths_and_file);
1.573 banghart 10122: $path_part.='/';
10123: my $path_and_file = $path_part.$file_part;
10124: if ($path_part eq $path) {
10125: $return_files{$file_part}= 'selected';
10126: }
10127: }
1.574 banghart 10128: close (IN);
10129: return (\%return_files);
1.572 banghart 10130: }
10131:
10132: # called in portfolio select mode, to show files selected NOT in current directory
10133: sub files_not_in_path {
10134: my ($user, $path) = @_;
10135: my $filename = $user."savedfiles";
10136: my @return_files;
10137: my $path_part;
1.1117 foxr 10138: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 10139: while (my $line = <IN>) {
1.572 banghart 10140: #ok, I know it's clunky, but I want it to work
1.800 albertel 10141: my @paths_and_file = split(m|/|, $line);
10142: my $file_part = pop(@paths_and_file);
10143: chomp($file_part);
10144: my $path_part = join('/', @paths_and_file);
1.572 banghart 10145: $path_part .= '/';
10146: my $path_and_file = $path_part.$file_part;
10147: if ($path_part ne $path) {
1.800 albertel 10148: push(@return_files, ($path_and_file));
1.572 banghart 10149: }
10150: }
1.800 albertel 10151: close(OUT);
1.574 banghart 10152: return (@return_files);
1.572 banghart 10153: }
10154:
1.1273 raeburn 10155: #------------------------------Submitted/Handedback Portfolio Files Versioning
10156:
10157: sub portfiles_versioning {
10158: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10159: my $portfolio_root = '/userfiles/portfolio';
10160: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10161: foreach my $file (@{$portfiles}) {
10162: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10163: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10164: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10165: my $getpropath = 1;
10166: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10167: $stu_name,$getpropath);
10168: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10169: my $new_answer =
10170: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10171: if ($new_answer ne 'problem getting file') {
10172: push(@{$versioned_portfiles}, $directory.$new_answer);
10173: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10174: [$symb,$env{'request.course.id'},'graded']);
10175: }
10176: }
10177: }
10178:
10179: sub get_next_version {
10180: my ($answer_name, $answer_ext, $dir_list) = @_;
10181: my $version;
10182: if (ref($dir_list) eq 'ARRAY') {
10183: foreach my $row (@{$dir_list}) {
10184: my ($file) = split(/\&/,$row,2);
10185: my ($file_name,$file_version,$file_ext) =
10186: &file_name_version_ext($file);
10187: if (($file_name eq $answer_name) &&
10188: ($file_ext eq $answer_ext)) {
10189: # gets here if filename and extension match,
10190: # regardless of version
10191: if ($file_version ne '') {
10192: # a versioned file is found so save it for later
10193: if ($file_version > $version) {
10194: $version = $file_version;
10195: }
10196: }
10197: }
10198: }
10199: }
10200: $version ++;
10201: return($version);
10202: }
10203:
10204: sub version_selected_portfile {
10205: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10206: my ($answer_name,$answer_ver,$answer_ext) =
10207: &file_name_version_ext($file_name);
10208: my $new_answer;
10209: $env{'form.copy'} =
10210: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10211: if($env{'form.copy'} eq '-1') {
10212: $new_answer = 'problem getting file';
10213: } else {
10214: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10215: my $copy_result =
10216: &finishuserfileupload($stu_name,$domain,'copy',
10217: '/portfolio'.$directory.$new_answer);
10218: }
10219: undef($env{'form.copy'});
10220: return ($new_answer);
10221: }
10222:
10223: sub file_name_version_ext {
10224: my ($file)=@_;
10225: my @file_parts = split(/\./, $file);
10226: my ($name,$version,$ext);
10227: if (@file_parts > 1) {
10228: $ext=pop(@file_parts);
10229: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10230: $version=pop(@file_parts);
10231: }
10232: $name=join('.',@file_parts);
10233: } else {
10234: $name=join('.',@file_parts);
10235: }
10236: return($name,$version,$ext);
10237: }
10238:
1.745 raeburn 10239: #----------------------------------------------Get portfolio file permissions
1.629 banghart 10240:
1.745 raeburn 10241: sub get_portfile_permissions {
10242: my ($domain,$user) = @_;
1.613 albertel 10243: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10244: my ($tmp)=keys(%current_permissions);
10245: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10246: return \%current_permissions;
10247: }
10248:
10249: #---------------------------------------------Get portfolio file access controls
10250:
1.749 raeburn 10251: sub get_access_controls {
1.745 raeburn 10252: my ($current_permissions,$group,$file) = @_;
1.769 albertel 10253: my %access;
10254: my $real_file = $file;
10255: $file =~ s/\.meta$//;
1.745 raeburn 10256: if (defined($file)) {
1.749 raeburn 10257: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10258: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 10259: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 10260: }
10261: }
1.745 raeburn 10262: } else {
1.749 raeburn 10263: foreach my $key (keys(%{$current_permissions})) {
10264: if ($key =~ /\0accesscontrol$/) {
10265: if (defined($group)) {
10266: if ($key !~ m-^\Q$group\E/-) {
10267: next;
10268: }
10269: }
10270: my ($fullpath) = split(/\0/,$key);
10271: if (ref($$current_permissions{$key}) eq 'HASH') {
10272: foreach my $control (keys(%{$$current_permissions{$key}})) {
10273: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10274: }
10275: }
10276: }
10277: }
10278: }
10279: return %access;
10280: }
10281:
10282: sub modify_access_controls {
10283: my ($file_name,$changes,$domain,$user)=@_;
10284: my ($outcome,$deloutcome);
10285: my %store_permissions;
10286: my %new_values;
10287: my %new_control;
10288: my %translation;
10289: my @deletions = ();
10290: my $now = time;
10291: if (exists($$changes{'activate'})) {
10292: if (ref($$changes{'activate'}) eq 'HASH') {
10293: my @newitems = sort(keys(%{$$changes{'activate'}}));
10294: my $numnew = scalar(@newitems);
10295: for (my $i=0; $i<$numnew; $i++) {
10296: my $newkey = $newitems[$i];
10297: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10298: if ($newkey =~ /^\d+:/) {
10299: $newkey =~ s/^(\d+)/$newid/;
10300: $translation{$1} = $newid;
10301: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10302: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10303: $translation{$1} = $newid;
10304: }
1.749 raeburn 10305: $new_values{$file_name."\0".$newkey} =
10306: $$changes{'activate'}{$newitems[$i]};
10307: $new_control{$newkey} = $now;
10308: }
10309: }
10310: }
10311: my %todelete;
10312: my %changed_items;
10313: foreach my $action ('delete','update') {
10314: if (exists($$changes{$action})) {
10315: if (ref($$changes{$action}) eq 'HASH') {
10316: foreach my $key (keys(%{$$changes{$action}})) {
10317: my ($itemnum) = ($key =~ /^([^:]+):/);
10318: if ($action eq 'delete') {
10319: $todelete{$itemnum} = 1;
10320: } else {
10321: $changed_items{$itemnum} = $key;
10322: }
10323: }
1.745 raeburn 10324: }
10325: }
1.749 raeburn 10326: }
10327: # get lock on access controls for file.
10328: my $lockhash = {
10329: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10330: ':'.$env{'user.domain'},
10331: };
10332: my $tries = 0;
10333: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10334:
1.1288 damieng 10335: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10336: $tries ++;
1.1289 damieng 10337: sleep(0.1);
1.749 raeburn 10338: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10339: }
10340: if ($gotlock eq 'ok') {
10341: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10342: my ($tmp)=keys(%curr_permissions);
10343: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10344: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10345: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10346: if (ref($curr_controls) eq 'HASH') {
10347: foreach my $control_item (keys(%{$curr_controls})) {
10348: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10349: if (defined($todelete{$itemnum})) {
10350: push(@deletions,$file_name."\0".$control_item);
10351: } else {
10352: if (defined($changed_items{$itemnum})) {
10353: $new_control{$changed_items{$itemnum}} = $now;
10354: push(@deletions,$file_name."\0".$control_item);
10355: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10356: } else {
10357: $new_control{$control_item} = $$curr_controls{$control_item};
10358: }
10359: }
1.745 raeburn 10360: }
10361: }
10362: }
1.970 raeburn 10363: my ($group);
10364: if (&is_course($domain,$user)) {
10365: ($group,my $file) = split(/\//,$file_name,2);
10366: }
1.749 raeburn 10367: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10368: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10369: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10370: # remove lock
10371: my @del_lock = ($file_name."\0".'locked_access_records');
10372: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 10373: my $sqlresult =
1.970 raeburn 10374: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 10375: $group);
1.749 raeburn 10376: } else {
10377: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 10378: }
1.749 raeburn 10379: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 10380: }
10381:
1.827 raeburn 10382: sub make_public_indefinitely {
1.1271 raeburn 10383: my (@requrl) = @_;
10384: return &automated_portfile_access('public',\@requrl);
10385: }
10386:
10387: sub automated_portfile_access {
10388: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 10389: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10390: return 'invalid';
10391: }
1.1271 raeburn 10392: my %urls;
10393: if (ref($addsref) eq 'ARRAY') {
10394: foreach my $requrl (@{$addsref}) {
10395: if (&is_portfolio_url($requrl)) {
10396: unless (exists($urls{$requrl})) {
10397: $urls{$requrl} = 'add';
10398: }
10399: }
10400: }
10401: }
10402: if (ref($delsref) eq 'ARRAY') {
10403: foreach my $requrl (@{$delsref}) {
10404: if (&is_portfolio_url($requrl)) {
10405: unless (exists($urls{$requrl})) {
10406: $urls{$requrl} = 'delete';
10407: }
10408: }
10409: }
10410: }
10411: unless (keys(%urls)) {
10412: return 'invalid';
10413: }
10414: my $ip;
10415: if ($accesstype eq 'ip') {
10416: if (ref($info) eq 'HASH') {
10417: if ($info->{'ip'} ne '') {
10418: $ip = $info->{'ip'};
10419: }
10420: }
10421: if ($ip eq '') {
10422: return 'invalid';
10423: }
10424: }
10425: my $errors;
1.827 raeburn 10426: my $now = time;
1.1271 raeburn 10427: my %current_perms;
10428: foreach my $requrl (sort(keys(%urls))) {
10429: my $action;
10430: if ($urls{$requrl} eq 'add') {
10431: $action = 'activate';
10432: } else {
10433: $action = 'none';
10434: }
10435: my $aclnum = 0;
1.827 raeburn 10436: my (undef,$udom,$unum,$file_name,$group) =
10437: &parse_portfolio_url($requrl);
1.1271 raeburn 10438: unless (exists($current_perms{$unum.':'.$udom})) {
10439: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10440: }
10441: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 10442: $group,$file_name);
10443: foreach my $key (keys(%{$access_controls{$file_name}})) {
10444: my ($num,$scope,$end,$start) =
10445: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 10446: if ($scope eq $accesstype) {
10447: if (($start <= $now) && ($end == 0)) {
10448: if ($accesstype eq 'ip') {
10449: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10450: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10451: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10452: if ($urls{$requrl} eq 'add') {
10453: $action = 'none';
10454: last;
10455: } else {
10456: $action = 'delete';
10457: $aclnum = $num;
10458: last;
10459: }
10460: }
10461: }
10462: }
10463: } elsif ($accesstype eq 'public') {
10464: if ($urls{$requrl} eq 'add') {
10465: $action = 'none';
10466: last;
10467: } else {
10468: $action = 'delete';
10469: $aclnum = $num;
10470: last;
10471: }
10472: }
10473: } elsif ($accesstype eq 'public') {
1.827 raeburn 10474: $action = 'update';
10475: $aclnum = $num;
1.1271 raeburn 10476: last;
1.827 raeburn 10477: }
10478: }
10479: }
10480: if ($action eq 'none') {
1.1271 raeburn 10481: next;
1.827 raeburn 10482: } else {
10483: my %changes;
10484: my $newend = 0;
10485: my $newstart = $now;
1.1271 raeburn 10486: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 10487: $changes{$action}{$newkey} = {
1.1271 raeburn 10488: type => $accesstype,
1.827 raeburn 10489: time => {
10490: start => $newstart,
10491: end => $newend,
10492: },
10493: };
1.1271 raeburn 10494: if ($accesstype eq 'ip') {
10495: $changes{$action}{$newkey}{'ip'} = [$ip];
10496: }
1.827 raeburn 10497: my ($outcome,$deloutcome,$new_values,$translation) =
10498: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 10499: unless ($outcome eq 'ok') {
10500: $errors .= $outcome.' ';
10501: }
1.827 raeburn 10502: }
1.1271 raeburn 10503: }
10504: if ($errors) {
10505: $errors =~ s/\s$//;
10506: return $errors;
1.827 raeburn 10507: } else {
1.1271 raeburn 10508: return 'ok';
1.827 raeburn 10509: }
10510: }
10511:
1.745 raeburn 10512: #------------------------------------------------------Get Marked as Read Only
10513:
10514: sub get_marked_as_readonly {
10515: my ($domain,$user,$what,$group) = @_;
10516: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 10517: my @readonly_files;
1.629 banghart 10518: my $cmp1=$what;
10519: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10520: while (my ($file_name,$value) = each(%{$current_permissions})) {
10521: if (defined($group)) {
10522: if ($file_name !~ m-^\Q$group\E/-) {
10523: next;
10524: }
10525: }
1.561 banghart 10526: if (ref($value) eq "ARRAY"){
10527: foreach my $stored_what (@{$value}) {
1.629 banghart 10528: my $cmp2=$stored_what;
1.759 albertel 10529: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 10530: $cmp2=join('',@{$stored_what});
1.745 raeburn 10531: }
1.629 banghart 10532: if ($cmp1 eq $cmp2) {
1.561 banghart 10533: push(@readonly_files, $file_name);
1.745 raeburn 10534: last;
1.563 banghart 10535: } elsif (!defined($what)) {
10536: push(@readonly_files, $file_name);
1.745 raeburn 10537: last;
1.561 banghart 10538: }
10539: }
1.745 raeburn 10540: }
1.561 banghart 10541: }
10542: return @readonly_files;
10543: }
1.577 banghart 10544: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 10545:
1.577 banghart 10546: sub get_marked_as_readonly_hash {
1.745 raeburn 10547: my ($current_permissions,$group,$what) = @_;
1.577 banghart 10548: my %readonly_files;
1.745 raeburn 10549: while (my ($file_name,$value) = each(%{$current_permissions})) {
10550: if (defined($group)) {
10551: if ($file_name !~ m-^\Q$group\E/-) {
10552: next;
10553: }
10554: }
1.577 banghart 10555: if (ref($value) eq "ARRAY"){
10556: foreach my $stored_what (@{$value}) {
1.745 raeburn 10557: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 10558: foreach my $lock_descriptor(@{$stored_what}) {
10559: if ($lock_descriptor eq 'graded') {
10560: $readonly_files{$file_name} = 'graded';
10561: } elsif ($lock_descriptor eq 'handback') {
10562: $readonly_files{$file_name} = 'handback';
10563: } else {
10564: if (!exists($readonly_files{$file_name})) {
10565: $readonly_files{$file_name} = 'locked';
10566: }
10567: }
1.745 raeburn 10568: }
1.750 banghart 10569: }
1.577 banghart 10570: }
10571: }
10572: }
10573: return %readonly_files;
10574: }
1.559 banghart 10575: # ------------------------------------------------------------ Unmark as Read Only
10576:
10577: sub unmark_as_readonly {
1.629 banghart 10578: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10579: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 10580: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 10581: $file_name = &declutter_portfile($file_name);
1.634 albertel 10582: my $symb_crs = $what;
10583: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 10584: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 10585: my ($tmp)=keys(%current_permissions);
10586: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10587: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 10588: foreach my $file (@readonly_files) {
1.759 albertel 10589: my $clean_file = &declutter_portfile($file);
10590: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 10591: my $current_locks = $current_permissions{$file};
1.563 banghart 10592: my @new_locks;
10593: my @del_keys;
10594: if (ref($current_locks) eq "ARRAY"){
10595: foreach my $locker (@{$current_locks}) {
1.632 albertel 10596: my $compare=$locker;
1.749 raeburn 10597: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 10598: $compare=join('',@{$locker});
1.746 raeburn 10599: if ($compare ne $symb_crs) {
10600: push(@new_locks, $locker);
10601: }
1.563 banghart 10602: }
10603: }
1.650 albertel 10604: if (scalar(@new_locks) > 0) {
1.563 banghart 10605: $current_permissions{$file} = \@new_locks;
10606: } else {
10607: push(@del_keys, $file);
1.613 albertel 10608: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 10609: delete($current_permissions{$file});
1.563 banghart 10610: }
10611: }
1.561 banghart 10612: }
1.613 albertel 10613: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10614: return;
10615: }
1.512 banghart 10616:
1.17 www 10617: # ------------------------------------------------------------ Directory lister
10618:
10619: sub dirlist {
1.955 raeburn 10620: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10621: $uri=~s/^\///;
10622: $uri=~s/\/$//;
1.253 stredwic 10623: my ($udom, $uname);
1.955 raeburn 10624: if ($getuserdir) {
1.253 stredwic 10625: $udom = $userdomain;
10626: $uname = $username;
1.955 raeburn 10627: } else {
10628: (undef,$udom,$uname)=split(/\//,$uri);
10629: if(defined($userdomain)) {
10630: $udom = $userdomain;
10631: }
10632: if(defined($username)) {
10633: $uname = $username;
10634: }
1.253 stredwic 10635: }
1.955 raeburn 10636: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10637:
1.955 raeburn 10638: $dirRoot = $perlvar{'lonDocRoot'};
10639: if (defined($getpropath)) {
10640: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10641: $dirRoot =~ s/\/$//;
1.955 raeburn 10642: } elsif (defined($getuserdir)) {
10643: my $subdir=$uname.'__';
10644: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10645: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10646: ."/$udom/$subdir/$uname";
10647: } elsif (defined($alternateRoot)) {
10648: $dirRoot = $alternateRoot;
1.751 banghart 10649: }
1.253 stredwic 10650:
10651: if($udom) {
10652: if($uname) {
1.1135 raeburn 10653: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10654: if ($uhome eq 'no_host') {
10655: return ([],'no_host');
10656: }
1.955 raeburn 10657: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10658: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10659: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10660: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10661: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10662: } else {
10663: @listing_results = map { &unescape($_); } split(/:/,$listing);
10664: }
1.605 matthew 10665: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10666: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10667: @listing_results = split(/:/,$listing);
10668: } else {
10669: @listing_results = map { &unescape($_); } split(/:/,$listing);
10670: }
1.1135 raeburn 10671: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10672: ($listing eq 'rejected') || ($listing eq 'refused') ||
10673: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10674: return ([],$listing);
10675: } else {
10676: return (\@listing_results);
1.1135 raeburn 10677: }
1.955 raeburn 10678: } elsif(!$alternateRoot) {
1.1136 raeburn 10679: my (%allusers,%listerror);
1.841 albertel 10680: my %servers = &get_servers($udom,'library');
1.955 raeburn 10681: foreach my $tryserver (keys(%servers)) {
10682: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10683: &escape($udom),$tryserver);
10684: if ($listing eq 'unknown_cmd') {
10685: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10686: $udom, $tryserver);
10687: } else {
10688: @listing_results = map { &unescape($_); } split(/:/,$listing);
10689: }
1.841 albertel 10690: if ($listing eq 'unknown_cmd') {
10691: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10692: $udom, $tryserver);
10693: @listing_results = split(/:/,$listing);
10694: } else {
10695: @listing_results =
10696: map { &unescape($_); } split(/:/,$listing);
10697: }
1.1136 raeburn 10698: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10699: ($listing eq 'rejected') || ($listing eq 'refused') ||
10700: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10701: $listerror{$tryserver} = $listing;
10702: } else {
1.841 albertel 10703: foreach my $line (@listing_results) {
10704: my ($entry) = split(/&/,$line,2);
10705: $allusers{$entry} = 1;
10706: }
10707: }
1.253 stredwic 10708: }
1.1136 raeburn 10709: my @alluserslist=();
1.800 albertel 10710: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 10711: push(@alluserslist,$user.'&user');
1.253 stredwic 10712: }
1.1318 droeschl 10713:
10714: if (!%listerror) {
10715: # no errors
10716: return (\@alluserslist);
10717: } elsif (scalar(keys(%servers)) == 1) {
10718: # one library server, one error
10719: my ($key) = keys(%listerror);
10720: return (\@alluserslist, $listerror{$key});
10721: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10722: # con_lost indicates that we might miss data from at least one
10723: # library server
10724: return (\@alluserslist, 'con_lost');
10725: } else {
10726: # multiple library servers and no con_lost -> data should be
10727: # complete.
10728: return (\@alluserslist);
10729: }
10730:
1.253 stredwic 10731: } else {
1.1136 raeburn 10732: return ([],'missing username');
1.253 stredwic 10733: }
1.955 raeburn 10734: } elsif(!defined($getpropath)) {
1.1136 raeburn 10735: my $path = $perlvar{'lonDocRoot'}.'/res/';
10736: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10737: return (\@all_domains);
1.955 raeburn 10738: } else {
1.1136 raeburn 10739: return ([],'missing domain');
1.275 stredwic 10740: }
10741: }
10742:
10743: # --------------------------------------------- GetFileTimestamp
10744: # This function utilizes dirlist and returns the date stamp for
10745: # when it was last modified. It will also return an error of -1
10746: # if an error occurs
10747:
10748: sub GetFileTimestamp {
1.955 raeburn 10749: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 10750: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10751: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 10752: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10753: undef,$getuserdir);
10754: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10755: return -1;
10756: }
10757: if (ref($fileref) eq 'ARRAY') {
10758: my @stats = split('&',$fileref->[0]);
1.375 matthew 10759: # @stats contains first the filename, then the stat output
10760: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 10761: } else {
10762: return -1;
1.253 stredwic 10763: }
1.26 www 10764: }
10765:
1.712 albertel 10766: sub stat_file {
10767: my ($uri) = @_;
1.787 albertel 10768: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 10769:
1.955 raeburn 10770: my ($udom,$uname,$file);
1.712 albertel 10771: if ($uri =~ m-^/(uploaded|editupload)/-) {
10772: ($udom,$uname,$file) =
1.811 albertel 10773: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 10774: $file = 'userfiles/'.$file;
10775: }
10776: if ($uri =~ m-^/res/-) {
10777: ($udom,$uname) =
1.807 albertel 10778: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 10779: $file = $uri;
10780: }
10781:
10782: if (!$udom || !$uname || !$file) {
10783: # unable to handle the uri
10784: return ();
10785: }
1.956 raeburn 10786: my $getpropath;
10787: if ($file =~ /^userfiles\//) {
10788: $getpropath = 1;
10789: }
1.1136 raeburn 10790: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10791: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10792: return ();
10793: } else {
10794: if (ref($listref) eq 'ARRAY') {
10795: my @stats = split('&',$listref->[0]);
10796: shift(@stats); #filename is first
10797: return @stats;
10798: }
1.712 albertel 10799: }
10800: return ();
10801: }
10802:
1.1313 raeburn 10803: # --------------------------------------------------------- recursedirs
10804: # Recursive function to traverse either a specific user's Authoring Space
10805: # or corresponding Published Resource Space, and populate the hash ref:
10806: # $dirhashref with URLs of all directories, and if $filehashref hash
10807: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
10808: # or .rights files in resource space, and .meta, .save, .log, and .bak
10809: # files in Authoring Space.
10810: #
10811: # Inputs:
10812: #
10813: # $is_home - true if current server is home server for user's space
10814: # $context - either: priv, or res respectively for Authoring or Resource Space.
10815: # $docroot - Document root (i.e., /home/httpd/html
10816: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
10817: # $relpath - Current path (relative to top level).
10818: # $dirhashref - reference to hash to populate with URLs of directories (Required)
10819: # $filehashref - reference to hash to populate with URLs of files (Optional)
10820: #
10821: # Returns: nothing
10822: #
10823: # Side Effects: populates $dirhashref, and $filehashref (if provided).
10824: #
10825: # Currently used by interface/londocs.pm to create linked select boxes for
10826: # directory and filename to import a Course "Author" resource into a course, and
10827: # also to create linked select boxes for Authoring Space and Directory to choose
10828: # save location for creation of a new "standard" problem from the Course Editor.
10829: #
10830:
10831: sub recursedirs {
10832: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
10833: return unless (ref($dirhashref) eq 'HASH');
10834: my $currpath = $docroot.$toppath;
10835: if ($relpath) {
10836: $currpath .= "/$relpath";
10837: }
10838: my $savefile;
10839: if (ref($filehashref)) {
10840: $savefile = 1;
10841: }
10842: if ($is_home) {
10843: if (opendir(my $dirh,$currpath)) {
10844: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
10845: next if ($item eq '');
10846: if (-d "$currpath/$item") {
10847: my $newpath;
10848: if ($relpath) {
10849: $newpath = "$relpath/$item";
10850: } else {
10851: $newpath = $item;
10852: }
10853: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10854: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10855: } elsif ($savefile) {
10856: if ($context eq 'priv') {
10857: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10858: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10859: }
10860: } else {
10861: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
10862: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10863: }
10864: }
10865: }
10866: }
10867: closedir($dirh);
10868: }
10869: } else {
10870: my ($dirlistref,$listerror) =
10871: &dirlist($toppath.$relpath);
10872: my @dir_lines;
10873: my $dirptr=16384;
10874: if (ref($dirlistref) eq 'ARRAY') {
10875: foreach my $dir_line (sort
10876: {
10877: my ($afile)=split('&',$a,2);
10878: my ($bfile)=split('&',$b,2);
10879: return (lc($afile) cmp lc($bfile));
10880: } (@{$dirlistref})) {
10881: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
10882: split(/\&/,$dir_line,16);
10883: $item =~ s/\s+$//;
10884: next if (($item =~ /^\.\.?$/) || ($obs));
10885: if ($dirptr&$testdir) {
10886: my $newpath;
10887: if ($relpath) {
10888: $newpath = "$relpath/$item";
10889: } else {
10890: $relpath = '/';
10891: $newpath = $item;
10892: }
10893: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10894: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10895: } elsif ($savefile) {
10896: if ($context eq 'priv') {
10897: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10898: $filehashref->{$relpath}{$item} = 1;
10899: }
10900: } else {
10901: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
10902: $filehashref->{$relpath}{$item} = 1;
10903: }
10904: }
10905: }
10906: }
10907: }
10908: }
10909: return;
10910: }
10911:
1.26 www 10912: # -------------------------------------------------------- Value of a Condition
10913:
1.713 albertel 10914: # gets the value of a specific preevaluated condition
10915: # stored in the string $env{user.state.<cid>}
10916: # or looks up a condition reference in the bighash and if if hasn't
10917: # already been evaluated recurses into docondval to get the value of
10918: # the condition, then memoizing it to
10919: # $env{user.state.<cid>.<condition>}
1.40 www 10920: sub directcondval {
10921: my $number=shift;
1.620 albertel 10922: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10923: &Apache::lonuserstate::evalstate();
10924: }
1.713 albertel 10925: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10926: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10927: } elsif ($number =~ /^_/) {
10928: my $sub_condition;
10929: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10930: &GDBM_READER(),0640)) {
10931: $sub_condition=$bighash{'conditions'.$number};
10932: untie(%bighash);
10933: }
10934: my $value = &docondval($sub_condition);
1.949 raeburn 10935: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10936: return $value;
10937: }
1.620 albertel 10938: if ($env{'user.state.'.$env{'request.course.id'}}) {
10939: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10940: } else {
10941: return 2;
10942: }
10943: }
10944:
1.713 albertel 10945: # get the collection of conditions for this resource
1.26 www 10946: sub condval {
10947: my $condidx=shift;
1.54 www 10948: my $allpathcond='';
1.713 albertel 10949: foreach my $cond (split(/\|/,$condidx)) {
10950: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10951: $allpathcond.=
10952: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10953: }
1.191 harris41 10954: }
1.54 www 10955: $allpathcond=~s/\|$//;
1.713 albertel 10956: return &docondval($allpathcond);
10957: }
10958:
10959: #evaluates an expression of conditions
10960: sub docondval {
10961: my ($allpathcond) = @_;
10962: my $result=0;
10963: if ($env{'request.course.id'}
10964: && defined($allpathcond)) {
10965: my $operand='|';
10966: my @stack;
10967: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10968: if ($chunk eq '(') {
10969: push @stack,($operand,$result);
10970: } elsif ($chunk eq ')') {
10971: my $before=pop @stack;
10972: if (pop @stack eq '&') {
10973: $result=$result>$before?$before:$result;
10974: } else {
10975: $result=$result>$before?$result:$before;
10976: }
10977: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10978: $operand=$chunk;
10979: } else {
10980: my $new=directcondval($chunk);
10981: if ($operand eq '&') {
10982: $result=$result>$new?$new:$result;
10983: } else {
10984: $result=$result>$new?$result:$new;
10985: }
10986: }
10987: }
1.26 www 10988: }
10989: return $result;
1.421 albertel 10990: }
10991:
10992: # ---------------------------------------------------- Devalidate courseresdata
10993:
10994: sub devalidatecourseresdata {
10995: my ($coursenum,$coursedomain)=@_;
10996: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10997: &devalidate_cache_new('courseres',$hashid);
1.28 www 10998: }
10999:
1.763 www 11000:
1.200 www 11001: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 11002: #
11003: # Parameters:
11004: # $coursenum - Number of the course.
11005: # $coursedomain - Domain at which the course was created.
11006: # Returns:
11007: # A hash of the course parameters along (I think) with timestamps
11008: # and version info.
1.877 foxr 11009:
1.624 albertel 11010: sub get_courseresdata {
11011: my ($coursenum,$coursedomain)=@_;
1.200 www 11012: my $coursehom=&homeserver($coursenum,$coursedomain);
11013: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 11014: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 11015: my %dumpreply;
1.417 albertel 11016: unless (defined($cached)) {
1.624 albertel 11017: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 11018: $result=\%dumpreply;
1.251 albertel 11019: my ($tmp) = keys(%dumpreply);
11020: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 11021: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 11022: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11023: return $tmp;
1.416 albertel 11024: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 11025: $result=undef;
1.599 albertel 11026: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 11027: }
11028: }
1.624 albertel 11029: return $result;
11030: }
11031:
1.633 albertel 11032: sub devalidateuserresdata {
11033: my ($uname,$udom)=@_;
11034: my $hashid="$udom:$uname";
11035: &devalidate_cache_new('userres',$hashid);
11036: }
11037:
1.624 albertel 11038: sub get_userresdata {
11039: my ($uname,$udom)=@_;
11040: #most student don\'t have any data set, check if there is some data
11041: if (&EXT_cache_status($udom,$uname)) { return undef; }
11042:
11043: my $hashid="$udom:$uname";
11044: my ($result,$cached)=&is_cached_new('userres',$hashid);
11045: if (!defined($cached)) {
11046: my %resourcedata=&dump('resourcedata',$udom,$uname);
11047: $result=\%resourcedata;
11048: &do_cache_new('userres',$hashid,$result,600);
11049: }
11050: my ($tmp)=keys(%$result);
11051: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11052: return $result;
11053: }
11054: #error 2 occurs when the .db doesn't exist
11055: if ($tmp!~/error: 2 /) {
1.1294 raeburn 11056: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11057: &logthis("<font color=\"blue\">WARNING:".
11058: " Trying to get resource data for ".
11059: $uname." at ".$udom.": ".
11060: $tmp."</font>");
11061: }
1.624 albertel 11062: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 11063: #&EXT_cache_set($udom,$uname);
11064: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 11065: undef($tmp); # not really an error so don't send it back
1.624 albertel 11066: }
11067: return $tmp;
11068: }
1.879 foxr 11069: #----------------------------------------------- resdata - return resource data
11070: # Purpose:
11071: # Return resource data for either users or for a course.
11072: # Parameters:
11073: # $name - Course/user name.
11074: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 11075: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 11076: # $mapp - decluttered URL of enclosing map
11077: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
11078: # $recurseup - Ref to array of map URLs, starting with map containing
11079: # $mapp up through hierarchy of nested maps to top level map.
11080: # $courseid - CourseID (first part of param identifier).
11081: # $modifier - Middle part of param identifier.
11082: # $what - Last part of param identifier.
1.879 foxr 11083: # @which - Array of names of resources desired.
11084: # Returns:
11085: # The value of the first reasource in @which that is found in the
11086: # resource hash.
11087: # Exceptional Conditions:
11088: # If the $type passed in is not valid (not the string 'course' or
11089: # 'user', an undefined reference is returned.
11090: # If none of the resources are found, an undef is returned
1.624 albertel 11091: sub resdata {
1.1301 raeburn 11092: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11093: $modifier,$what,@which)=@_;
1.624 albertel 11094: my $result;
11095: if ($type eq 'course') {
11096: $result=&get_courseresdata($name,$domain);
11097: } elsif ($type eq 'user') {
11098: $result=&get_userresdata($name,$domain);
11099: }
11100: if (!ref($result)) { return $result; }
1.251 albertel 11101: foreach my $item (@which) {
1.1301 raeburn 11102: if ($item->[1] eq 'course') {
11103: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11104: unless ($$recursed) {
1.1302 raeburn 11105: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 11106: $$recursed = 1;
11107: }
11108: foreach my $item (@${recurseup}) {
11109: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11110: last if (defined($result->{$norecursechk}));
11111: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11112: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11113: }
11114: }
11115: }
11116: if (defined($result->{$item->[0]})) {
1.927 albertel 11117: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 11118: }
1.250 albertel 11119: }
1.291 albertel 11120: return undef;
1.200 www 11121: }
11122:
1.1298 raeburn 11123: sub get_domain_ltitools {
11124: my ($cdom) = @_;
11125: my %ltitools;
11126: my ($result,$cached)=&is_cached_new('ltitools',$cdom);
11127: if (defined($cached)) {
11128: if (ref($result) eq 'HASH') {
11129: %ltitools = %{$result};
11130: }
11131: } else {
11132: my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
11133: if (ref($domconfig{'ltitools'}) eq 'HASH') {
11134: %ltitools = %{$domconfig{'ltitools'}};
1.1344 raeburn 11135: my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
11136: if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
11137: foreach my $id (keys(%ltitools)) {
11138: if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
11139: foreach my $item ('key','secret') {
11140: $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
11141: }
11142: }
11143: }
11144: }
1.1298 raeburn 11145: }
11146: my $cachetime = 24*60*60;
11147: &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
11148: }
11149: return %ltitools;
11150: }
11151:
1.1236 raeburn 11152: sub get_numsuppfiles {
11153: my ($cnum,$cdom,$ignorecache)=@_;
11154: my $hashid=$cnum.':'.$cdom;
11155: my ($suppcount,$cached);
11156: unless ($ignorecache) {
11157: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11158: }
11159: unless (defined($cached)) {
11160: my $chome=&homeserver($cnum,$cdom);
11161: unless ($chome eq 'no_host') {
11162: ($suppcount,my $errors) = (0,0);
11163: my $suppmap = 'supplemental.sequence';
11164: ($suppcount,$errors) =
11165: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11166: }
11167: &do_cache_new('suppcount',$hashid,$suppcount,600);
11168: }
11169: return $suppcount;
11170: }
11171:
1.379 matthew 11172: #
11173: # EXT resource caching routines
11174: #
11175:
1.1302 raeburn 11176: {
11177: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11178: #
11179: # The course for which we cache
11180: my $cachedmapkey='';
11181: # The cached recursive maps for this course
11182: my %cachedmaps=();
11183: # When this was last done
11184: my $cachedmaptime='';
11185:
1.379 matthew 11186: sub clear_EXT_cache_status {
1.383 albertel 11187: &delenv('cache.EXT.');
1.379 matthew 11188: }
11189:
11190: sub EXT_cache_status {
11191: my ($target_domain,$target_user) = @_;
1.383 albertel 11192: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 11193: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 11194: # We know already the user has no data
11195: return 1;
11196: } else {
11197: return 0;
11198: }
11199: }
11200:
11201: sub EXT_cache_set {
11202: my ($target_domain,$target_user) = @_;
1.383 albertel 11203: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 11204: #&appenv({$cachename => time});
1.379 matthew 11205: }
11206:
1.28 www 11207: # --------------------------------------------------------- Value of a Variable
1.58 www 11208: sub EXT {
1.715 albertel 11209:
1.1228 raeburn 11210: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 11211: unless ($varname) { return ''; }
1.218 albertel 11212: #get real user name/domain, courseid and symb
11213: my $courseid;
1.359 albertel 11214: my $publicuser;
1.427 www 11215: if ($symbparm) {
11216: $symbparm=&get_symb_from_alias($symbparm);
11217: }
1.218 albertel 11218: if (!($uname && $udom)) {
1.790 albertel 11219: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 11220: if (!$symbparm) { $symbparm=$cursymb; }
11221: } else {
1.620 albertel 11222: $courseid=$env{'request.course.id'};
1.218 albertel 11223: }
1.48 www 11224: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11225: my $rest;
1.320 albertel 11226: if (defined($therest[0])) {
1.48 www 11227: $rest=join('.',@therest);
11228: } else {
11229: $rest='';
11230: }
1.320 albertel 11231:
1.57 www 11232: my $qualifierrest=$qualifier;
11233: if ($rest) { $qualifierrest.='.'.$rest; }
11234: my $spacequalifierrest=$space;
11235: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 11236: if ($realm eq 'user') {
1.48 www 11237: # --------------------------------------------------------------- user.resource
11238: if ($space eq 'resource') {
1.651 albertel 11239: if ( (defined($Apache::lonhomework::parsing_a_problem)
11240: || defined($Apache::lonhomework::parsing_a_task))
11241: &&
1.744 albertel 11242: ($symbparm eq &symbread()) ) {
11243: # if we are in the middle of processing the resource the
11244: # get the value we are planning on committing
11245: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11246: return $Apache::lonhomework::results{$qualifierrest};
11247: } else {
11248: return $Apache::lonhomework::history{$qualifierrest};
11249: }
1.335 albertel 11250: } else {
1.359 albertel 11251: my %restored;
1.620 albertel 11252: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 11253: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11254: } else {
11255: %restored=&restore($symbparm,$courseid,$udom,$uname);
11256: }
1.335 albertel 11257: return $restored{$qualifierrest};
11258: }
1.48 www 11259: # ----------------------------------------------------------------- user.access
11260: } elsif ($space eq 'access') {
1.218 albertel 11261: # FIXME - not supporting calls for a specific user
1.48 www 11262: return &allowed($qualifier,$rest);
11263: # ------------------------------------------ user.preferences, user.environment
11264: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 11265: if (($uname eq $env{'user.name'}) &&
11266: ($udom eq $env{'user.domain'})) {
11267: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 11268: } else {
1.359 albertel 11269: my %returnhash;
11270: if (!$publicuser) {
11271: %returnhash=&userenvironment($udom,$uname,
11272: $qualifierrest);
11273: }
1.218 albertel 11274: return $returnhash{$qualifierrest};
11275: }
1.48 www 11276: # ----------------------------------------------------------------- user.course
11277: } elsif ($space eq 'course') {
1.218 albertel 11278: # FIXME - not supporting calls for a specific user
1.620 albertel 11279: return $env{join('.',('request.course',$qualifier))};
1.48 www 11280: # ------------------------------------------------------------------- user.role
11281: } elsif ($space eq 'role') {
1.218 albertel 11282: # FIXME - not supporting calls for a specific user
1.620 albertel 11283: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 11284: if ($qualifier eq 'value') {
11285: return $role;
11286: } elsif ($qualifier eq 'extent') {
11287: return $where;
11288: }
11289: # ----------------------------------------------------------------- user.domain
11290: } elsif ($space eq 'domain') {
1.218 albertel 11291: return $udom;
1.48 www 11292: # ------------------------------------------------------------------- user.name
11293: } elsif ($space eq 'name') {
1.218 albertel 11294: return $uname;
1.48 www 11295: # ---------------------------------------------------- Any other user namespace
1.29 www 11296: } else {
1.359 albertel 11297: my %reply;
11298: if (!$publicuser) {
11299: %reply=&get($space,[$qualifierrest],$udom,$uname);
11300: }
11301: return $reply{$qualifierrest};
1.48 www 11302: }
1.236 www 11303: } elsif ($realm eq 'query') {
11304: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 11305: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11306: [$spacequalifierrest]);
1.620 albertel 11307: return $env{'form.'.$spacequalifierrest};
1.236 www 11308: } elsif ($realm eq 'request') {
1.48 www 11309: # ------------------------------------------------------------- request.browser
11310: if ($space eq 'browser') {
1.1145 bisitz 11311: return $env{'browser.'.$qualifier};
1.57 www 11312: # ------------------------------------------------------------ request.filename
11313: } else {
1.620 albertel 11314: return $env{'request.'.$spacequalifierrest};
1.29 www 11315: }
1.28 www 11316: } elsif ($realm eq 'course') {
1.48 www 11317: # ---------------------------------------------------------- course.description
1.620 albertel 11318: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 11319: } elsif ($realm eq 'resource') {
1.165 www 11320:
1.620 albertel 11321: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 11322: if (!$symbparm) { $symbparm=&symbread(); }
11323: }
1.693 albertel 11324:
1.1232 raeburn 11325: if ($qualifier eq '') {
11326: if ($space eq 'title') {
11327: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11328: return &gettitle($symbparm);
11329: }
1.693 albertel 11330:
1.1232 raeburn 11331: if ($space eq 'map') {
11332: my ($map) = &decode_symb($symbparm);
11333: return &symbread($map);
11334: }
11335: if ($space eq 'maptitle') {
11336: my ($map) = &decode_symb($symbparm);
11337: return &gettitle($map);
11338: }
11339: if ($space eq 'filename') {
11340: if ($symbparm) {
11341: return &clutter((&decode_symb($symbparm))[2]);
11342: }
11343: return &hreflocation('',$env{'request.filename'});
1.905 albertel 11344: }
1.1232 raeburn 11345:
1.1233 raeburn 11346: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11347: if ($space eq 'visibleparts') {
11348: my $navmap = Apache::lonnavmaps::navmap->new();
11349: my $item;
11350: if (ref($navmap)) {
11351: my $res = $navmap->getBySymb($symbparm);
11352: my $parts = $res->parts();
11353: if (ref($parts) eq 'ARRAY') {
11354: $item = join(',',@{$parts});
11355: }
11356: undef($navmap);
1.1232 raeburn 11357: }
1.1233 raeburn 11358: return $item;
1.1232 raeburn 11359: }
11360: }
11361: }
1.693 albertel 11362:
1.1301 raeburn 11363: my ($section, $group, @groups, @recurseup, $recursed);
11364: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 11365: if (($courseid eq '') && ($cid)) {
11366: $courseid = $cid;
11367: }
11368: if (($symbparm && $courseid) &&
11369: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 11370:
1.218 albertel 11371: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 11372:
1.60 www 11373: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 11374: my $symbp=$symbparm;
1.1301 raeburn 11375: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 11376: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 11377: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 11378: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 11379: if (($env{'user.name'} eq $uname) &&
11380: ($env{'user.domain'} eq $udom)) {
11381: $section=$env{'request.course.sec'};
1.733 raeburn 11382: @groups = split(/:/,$env{'request.course.groups'});
11383: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 11384: } else {
1.539 albertel 11385: if (! defined($usection)) {
1.551 albertel 11386: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 11387: } else {
11388: $section = $usection;
11389: }
1.733 raeburn 11390: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 11391: }
11392:
11393: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11394: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 11395: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 11396: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11397:
1.593 albertel 11398: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 11399: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 11400: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 11401: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 11402:
1.60 www 11403: # ----------------------------------------------------------- first, check user
1.624 albertel 11404:
1.1301 raeburn 11405: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11406: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 11407: ([$courselevelr,'resource'],
11408: [$courselevelm,'map' ],
1.1301 raeburn 11409: [$courseleveli,'map' ],
1.927 albertel 11410: [$courselevel, 'course' ]));
1.931 albertel 11411: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 11412:
1.594 albertel 11413: # ------------------------------------------------ second, check some of course
1.684 raeburn 11414: my $coursereply;
1.691 raeburn 11415: if (@groups > 0) {
11416: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 11417: $recurseparm,$mapparm,$spacequalifierrest,
11418: $mapp,\$recursed,\@recurseup);
11419: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 11420: }
1.96 www 11421:
1.684 raeburn 11422: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 11423: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 11424: 'course',$mapp,\$recursed,\@recurseup,
11425: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 11426: ([$seclevelr, 'resource'],
11427: [$seclevelm, 'map' ],
1.1301 raeburn 11428: [$secleveli, 'map' ],
1.927 albertel 11429: [$seclevel, 'course' ],
11430: [$courselevelr,'resource']));
11431: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 11432:
1.60 www 11433: # ------------------------------------------------------ third, check map parms
1.218 albertel 11434: my %parmhash=();
11435: my $thisparm='';
11436: if (tie(%parmhash,'GDBM_File',
1.620 albertel 11437: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 11438: &GDBM_READER(),0640)) {
1.218 albertel 11439: $thisparm=$parmhash{$symbparm};
11440: untie(%parmhash);
11441: }
1.927 albertel 11442: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 11443: }
1.594 albertel 11444: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 11445:
11446: my $what = $spacequalifierrest;
11447: $what=~s/\./\_/;
1.282 albertel 11448: my $filename;
11449: if (!$symbparm) { $symbparm=&symbread(); }
11450: if ($symbparm) {
1.409 www 11451: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 11452: } else {
1.620 albertel 11453: $filename=$env{'request.filename'};
1.282 albertel 11454: }
1.1301 raeburn 11455: my $metadata=&metadata($filename,$what);
1.927 albertel 11456: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301 raeburn 11457: $metadata=&metadata($filename,'parameter_'.$what);
1.927 albertel 11458: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 11459:
1.1301 raeburn 11460: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 11461: if ($symbparm && defined($courseid) &&
1.620 albertel 11462: $courseid eq $env{'request.course.id'}) {
1.624 albertel 11463: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11464: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 11465: 'course',$mapp,\$recursed,\@recurseup,
11466: $courseid,'.',$spacequalifierrest,
1.927 albertel 11467: ([$courselevelm,'map' ],
1.1301 raeburn 11468: [$courseleveli,'map' ],
1.927 albertel 11469: [$courselevel, 'course']));
11470: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 11471: }
1.145 www 11472: # ------------------------------------------------------------------ Cascade up
1.218 albertel 11473: unless ($space eq '0') {
1.336 albertel 11474: my @parts=split(/_/,$space);
11475: my $id=pop(@parts);
11476: my $part=join('_',@parts);
11477: if ($part eq '') { $part='0'; }
1.927 albertel 11478: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 11479: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 11480: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 11481: }
1.395 albertel 11482: if ($recurse) { return undef; }
11483: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 11484: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 11485: # ---------------------------------------------------- Any other user namespace
11486: } elsif ($realm eq 'environment') {
11487: # ----------------------------------------------------------------- environment
1.620 albertel 11488: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11489: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 11490: } else {
1.770 albertel 11491: if ($uname eq 'anonymous' && $udom eq '') {
11492: return '';
11493: }
1.219 albertel 11494: my %returnhash=&userenvironment($udom,$uname,
11495: $spacequalifierrest);
11496: return $returnhash{$spacequalifierrest};
11497: }
1.28 www 11498: } elsif ($realm eq 'system') {
1.48 www 11499: # ----------------------------------------------------------------- system.time
11500: if ($space eq 'time') {
11501: return time;
11502: }
1.696 albertel 11503: } elsif ($realm eq 'server') {
11504: # ----------------------------------------------------------------- system.time
11505: if ($space eq 'name') {
11506: return $ENV{'SERVER_NAME'};
11507: }
1.28 www 11508: }
1.48 www 11509: return '';
1.61 www 11510: }
11511:
1.927 albertel 11512: sub get_reply {
11513: my ($reply_value) = @_;
1.940 raeburn 11514: if (ref($reply_value) eq 'ARRAY') {
11515: if (wantarray) {
11516: return @$reply_value;
11517: }
11518: return $reply_value->[0];
11519: } else {
11520: return $reply_value;
1.927 albertel 11521: }
11522: }
11523:
1.691 raeburn 11524: sub check_group_parms {
1.1301 raeburn 11525: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11526: $recursed,$recurseupref) = @_;
11527: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11528: [$what,'course']);
11529: my $coursereply;
1.691 raeburn 11530: foreach my $group (@{$groups}) {
1.1301 raeburn 11531: my @groupitems = ();
1.691 raeburn 11532: foreach my $level (@levels) {
1.927 albertel 11533: my $item = $courseid.'.['.$group.'].'.$level->[0];
11534: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11535: }
1.1301 raeburn 11536: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11537: $env{'course.'.$courseid.'.domain'},
11538: 'course',$mapp,$recursed,$recurseupref,
11539: $courseid,'.['.$group.'].',$what,
11540: @groupitems);
11541: last if (defined($coursereply));
1.691 raeburn 11542: }
11543: return $coursereply;
11544: }
11545:
1.1301 raeburn 11546: sub get_map_hierarchy {
1.1302 raeburn 11547: my ($mapname,$courseid) = @_;
11548: my @recurseup = ();
1.1301 raeburn 11549: if ($mapname) {
1.1302 raeburn 11550: if (($cachedmapkey eq $courseid) &&
11551: (abs($cachedmaptime-time)<5)) {
11552: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11553: return @{$cachedmaps{$mapname}};
11554: }
11555: }
1.1301 raeburn 11556: my $navmap = Apache::lonnavmaps::navmap->new();
11557: if (ref($navmap)) {
11558: @recurseup = $navmap->recurseup_maps($mapname);
11559: undef($navmap);
1.1302 raeburn 11560: $cachedmaps{$mapname} = \@recurseup;
11561: $cachedmaptime=time;
11562: $cachedmapkey=$courseid;
1.1301 raeburn 11563: }
11564: }
11565: return @recurseup;
11566: }
11567:
1.1302 raeburn 11568: }
11569:
1.691 raeburn 11570: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11571: my ($courseid,@groups) = @_;
11572: @groups = sort(@groups);
1.691 raeburn 11573: return @groups;
11574: }
11575:
1.395 albertel 11576: sub packages_tab_default {
11577: my ($uri,$varname)=@_;
11578: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11579:
11580: my (@extension,@specifics,$do_default);
11581: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11582: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11583: if ($pack_type eq 'default') {
11584: $do_default=1;
11585: } elsif ($pack_type eq 'extension') {
11586: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11587: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11588: # only look at packages defaults for packages that this id is
1.738 albertel 11589: push(@specifics,[$package,$pack_type,$pack_part]);
11590: }
11591: }
11592: # first look for a package that matches the requested part id
11593: foreach my $package (@specifics) {
11594: my (undef,$pack_type,$pack_part)=@{$package};
11595: next if ($pack_part ne $part);
11596: if (defined($packagetab{"$pack_type&$name&default"})) {
11597: return $packagetab{"$pack_type&$name&default"};
11598: }
11599: }
11600: # look for any possible matching non extension_ package
11601: foreach my $package (@specifics) {
11602: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11603: if (defined($packagetab{"$pack_type&$name&default"})) {
11604: return $packagetab{"$pack_type&$name&default"};
11605: }
1.585 albertel 11606: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11607: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11608: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11609: }
11610: }
1.738 albertel 11611: # look for any posible extension_ match
11612: foreach my $package (@extension) {
11613: my ($package,$pack_type)=@{$package};
11614: if (defined($packagetab{"$pack_type&$name&default"})) {
11615: return $packagetab{"$pack_type&$name&default"};
11616: }
11617: if (defined($packagetab{$package."&$name&default"})) {
11618: return $packagetab{$package."&$name&default"};
11619: }
11620: }
11621: # look for a global default setting
11622: if ($do_default && defined($packagetab{"default&$name&default"})) {
11623: return $packagetab{"default&$name&default"};
11624: }
1.395 albertel 11625: return undef;
11626: }
11627:
1.334 albertel 11628: sub add_prefix_and_part {
11629: my ($prefix,$part)=@_;
11630: my $keyroot;
11631: if (defined($prefix) && $prefix !~ /^__/) {
11632: # prefix that has a part already
11633: $keyroot=$prefix;
11634: } elsif (defined($prefix)) {
11635: # prefix that is missing a part
11636: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11637: } else {
11638: # no prefix at all
11639: if (defined($part)) { $keyroot='_'.$part; }
11640: }
11641: return $keyroot;
11642: }
11643:
1.71 www 11644: # ---------------------------------------------------------------- Get metadata
11645:
1.599 albertel 11646: my %metaentry;
1.1070 www 11647: my %importedpartids;
1.71 www 11648: sub metadata {
1.176 www 11649: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11650: $uri=&declutter($uri);
1.288 albertel 11651: # if it is a non metadata possible uri return quickly
1.529 albertel 11652: if (($uri eq '') ||
11653: (($uri =~ m|^/*adm/|) &&
1.1343 raeburn 11654: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 11655: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11656: return undef;
11657: }
1.1261 raeburn 11658: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11659: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11660: return undef;
1.288 albertel 11661: }
1.73 www 11662: my $filename=$uri;
11663: $uri=~s/\.meta$//;
1.172 www 11664: #
11665: # Is the metadata already cached?
1.177 www 11666: # Look at timestamp of caching
1.172 www 11667: # Everything is cached by the main uri, libraries are never directly cached
11668: #
1.428 albertel 11669: if (!defined($liburi)) {
1.599 albertel 11670: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11671: if (defined($cached)) { return $result->{':'.$what}; }
11672: }
11673: {
1.1069 www 11674: # Imported parts would go here
1.1070 www 11675: my %importedids=();
11676: my @origfileimportpartids=();
1.1069 www 11677: my $importedparts=0;
1.172 www 11678: #
11679: # Is this a recursive call for a library?
11680: #
1.599 albertel 11681: # if (! exists($metacache{$uri})) {
11682: # $metacache{$uri}={};
11683: # }
1.924 albertel 11684: my $cachetime = 60*60;
1.171 www 11685: if ($liburi) {
11686: $liburi=&declutter($liburi);
11687: $filename=$liburi;
1.401 bowersj2 11688: } else {
1.599 albertel 11689: &devalidate_cache_new('meta',$uri);
11690: undef(%metaentry);
1.401 bowersj2 11691: }
1.140 www 11692: my %metathesekeys=();
1.73 www 11693: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 11694: my $metastring;
1.1140 www 11695: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 11696: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 11697: $metastring =
1.929 albertel 11698: &Apache::lonnet::ssi_body($which,
1.924 albertel 11699: ('grade_target' => 'meta'));
11700: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 11701: } elsif (($uri !~ m -^(editupload)/-) &&
11702: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 11703: my $file=&filelocation('',&clutter($filename));
1.599 albertel 11704: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 11705: $metastring=&getfile($file);
1.489 albertel 11706: }
1.208 albertel 11707: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 11708: my $token;
1.140 www 11709: undef %metathesekeys;
1.71 www 11710: while ($token=$parser->get_token) {
1.339 albertel 11711: if ($token->[0] eq 'S') {
11712: if (defined($token->[2]->{'package'})) {
1.172 www 11713: #
11714: # This is a package - get package info
11715: #
1.339 albertel 11716: my $package=$token->[2]->{'package'};
11717: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11718: if (defined($token->[2]->{'id'})) {
11719: $keyroot.='_'.$token->[2]->{'id'};
11720: }
1.599 albertel 11721: if ($metaentry{':packages'}) {
11722: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 11723: } else {
1.599 albertel 11724: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 11725: }
1.736 albertel 11726: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 11727: my $part=$keyroot;
11728: $part=~s/^\_//;
1.736 albertel 11729: if ($pack_entry=~/^\Q$package\E\&/ ||
11730: $pack_entry=~/^\Q$package\E_0\&/) {
11731: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11732: # ignore package.tab specified default values
11733: # here &package_tab_default() will fetch those
11734: if ($subp eq 'default') { next; }
1.736 albertel 11735: my $value=$packagetab{$pack_entry};
1.432 albertel 11736: my $unikey;
11737: if ($pack =~ /_0$/) {
11738: $unikey='parameter_0_'.$name;
11739: $part=0;
11740: } else {
11741: $unikey='parameter'.$keyroot.'_'.$name;
11742: }
1.339 albertel 11743: if ($subp eq 'display') {
11744: $value.=' [Part: '.$part.']';
11745: }
1.599 albertel 11746: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11747: $metathesekeys{$unikey}=1;
1.599 albertel 11748: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11749: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11750: }
1.599 albertel 11751: if (defined($metaentry{':'.$unikey.'.default'})) {
11752: $metaentry{':'.$unikey}=
11753: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11754: }
1.339 albertel 11755: }
11756: }
11757: } else {
1.172 www 11758: #
11759: # This is not a package - some other kind of start tag
1.339 albertel 11760: #
11761: my $entry=$token->[1];
1.1068 www 11762: my $unikey='';
1.175 www 11763:
1.339 albertel 11764: if ($entry eq 'import') {
1.175 www 11765: #
11766: # Importing a library here
1.339 albertel 11767: #
1.1067 www 11768: my $location=$parser->get_text('/import');
11769: my $dir=$filename;
11770: $dir=~s|[^/]*$||;
11771: $location=&filelocation($dir,$location);
1.1069 www 11772:
1.1068 www 11773: my $importmode=$token->[2]->{'importmode'};
11774: if ($importmode eq 'problem') {
1.1069 www 11775: # Import as problem/response
1.1068 www 11776: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11777: } elsif ($importmode eq 'part') {
11778: # Import as part(s)
1.1069 www 11779: $importedparts=1;
11780: # We need to get the original file and the imported file to get the part order correct
11781: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11782: # Load and inspect original file
1.1070 www 11783: if ($#origfileimportpartids<0) {
11784: undef(%importedpartids);
11785: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11786: my $origfile=&getfile($origfilelocation);
11787: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11788: }
11789:
1.1069 www 11790: # Load and inspect imported file
11791: my $impfile=&getfile($location);
11792: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11793: if ($#impfilepartids>=0) {
11794: # This problem had parts
1.1070 www 11795: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11796: } else {
11797: # Importing by turning a single problem into a problem part
11798: # It gets the import-tags ID as part-ID
11799: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11800: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11801: }
1.1068 www 11802: } else {
11803: # Normal import
11804: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11805: if (defined($token->[2]->{'id'})) {
11806: $unikey.='_'.$token->[2]->{'id'};
11807: }
1.1067 www 11808: }
11809:
1.339 albertel 11810: if ($depthcount<20) {
1.736 albertel 11811: my $metadata =
11812: &metadata($uri,'keys', $location,$unikey,
11813: $depthcount+1);
11814: foreach my $meta (split(',',$metadata)) {
11815: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11816: $metathesekeys{$meta}=1;
1.339 albertel 11817: }
1.1068 www 11818:
11819: }
1.1067 www 11820: } else {
11821: #
11822: # Not importing, some other kind of non-package, non-library start tag
11823: #
11824: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11825: if (defined($token->[2]->{'id'})) {
11826: $unikey.='_'.$token->[2]->{'id'};
11827: }
1.339 albertel 11828: if (defined($token->[2]->{'name'})) {
11829: $unikey.='_'.$token->[2]->{'name'};
11830: }
11831: $metathesekeys{$unikey}=1;
1.736 albertel 11832: foreach my $param (@{$token->[3]}) {
11833: $metaentry{':'.$unikey.'.'.$param} =
11834: $token->[2]->{$param};
1.339 albertel 11835: }
11836: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11837: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11838: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11839: # only ws inside the tag, and not in default, so use default
11840: # as value
1.599 albertel 11841: $metaentry{':'.$unikey}=$default;
1.908 albertel 11842: } elsif ( $internaltext =~ /\S/ ) {
11843: # something interesting inside the tag
11844: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11845: } else {
1.908 albertel 11846: # no interesting values, don't set a default
1.339 albertel 11847: }
1.172 www 11848: # end of not-a-package not-a-library import
1.339 albertel 11849: }
1.172 www 11850: # end of not-a-package start tag
1.339 albertel 11851: }
1.172 www 11852: # the next is the end of "start tag"
1.339 albertel 11853: }
11854: }
1.483 albertel 11855: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11856: $extension = lc($extension);
11857: if ($extension eq 'htm') { $extension='html'; }
11858:
1.737 albertel 11859: foreach my $key (keys(%packagetab)) {
1.483 albertel 11860: #no specific packages #how's our extension
11861: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11862: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11863: \%metathesekeys);
11864: }
1.883 albertel 11865:
11866: if (!exists($metaentry{':packages'})
11867: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11868: foreach my $key (keys(%packagetab)) {
1.483 albertel 11869: #no specific packages well let's get default then
11870: if ($key!~/^default&/) { next; }
1.488 albertel 11871: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 11872: \%metathesekeys);
11873: }
11874: }
1.338 www 11875: # are there custom rights to evaluate
1.599 albertel 11876: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 11877:
1.338 www 11878: #
11879: # Importing a rights file here
1.339 albertel 11880: #
11881: unless ($depthcount) {
1.599 albertel 11882: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 11883: my $dir=$filename;
11884: $dir=~s|[^/]*$||;
11885: $location=&filelocation($dir,$location);
1.736 albertel 11886: my $rights_metadata =
11887: &metadata($uri,'keys',$location,'_rights',
11888: $depthcount+1);
11889: foreach my $rights (split(',',$rights_metadata)) {
11890: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11891: $metathesekeys{$rights}=1;
1.339 albertel 11892: }
11893: }
11894: }
1.737 albertel 11895: # uniqifiy package listing
11896: my %seen;
11897: my @uniq_packages =
11898: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11899: $metaentry{':packages'} = join(',',@uniq_packages);
11900:
1.1070 www 11901: if ($importedparts) {
11902: # We had imported parts and need to rebuild partorder
11903: $metaentry{':partorder'}='';
11904: $metathesekeys{'partorder'}=1;
11905: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11906: if ($origfileimportpartids[$index] eq 'part') {
11907: # original part, part of the problem
11908: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11909: } else {
11910: # we have imported parts at this position
11911: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11912: }
11913: }
11914: $metaentry{':partorder'}=~s/^\,//;
11915: }
11916:
1.737 albertel 11917: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 11918: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 11919: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 11920: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 11921: # this is the end of "was not already recently cached
1.71 www 11922: }
1.599 albertel 11923: return $metaentry{':'.$what};
1.261 albertel 11924: }
11925:
1.488 albertel 11926: sub metadata_create_package_def {
1.483 albertel 11927: my ($uri,$key,$package,$metathesekeys)=@_;
11928: my ($pack,$name,$subp)=split(/\&/,$key);
11929: if ($subp eq 'default') { next; }
11930:
1.599 albertel 11931: if (defined($metaentry{':packages'})) {
11932: $metaentry{':packages'}.=','.$package;
1.483 albertel 11933: } else {
1.599 albertel 11934: $metaentry{':packages'}=$package;
1.483 albertel 11935: }
11936: my $value=$packagetab{$key};
11937: my $unikey;
11938: $unikey='parameter_0_'.$name;
1.599 albertel 11939: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 11940: $$metathesekeys{$unikey}=1;
1.599 albertel 11941: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11942: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 11943: }
1.599 albertel 11944: if (defined($metaentry{':'.$unikey.'.default'})) {
11945: $metaentry{':'.$unikey}=
11946: $metaentry{':'.$unikey.'.default'};
1.483 albertel 11947: }
11948: }
11949:
1.261 albertel 11950: sub metadata_generate_part0 {
11951: my ($metadata,$metacache,$uri) = @_;
11952: my %allnames;
1.737 albertel 11953: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 11954: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 11955: my $part=$$metacache{':'.$metakey.'.part'};
11956: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 11957: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 11958: $allnames{$name}=$part;
11959: }
11960: }
11961: }
11962: foreach my $name (keys(%allnames)) {
11963: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 11964: my $key=":parameter_0_$name";
1.261 albertel 11965: $$metacache{"$key.part"}='0';
11966: $$metacache{"$key.name"}=$name;
1.428 albertel 11967: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 11968: $allnames{$name}.'_'.$name.
11969: '.type'};
1.428 albertel 11970: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 11971: '.display'};
1.644 www 11972: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 11973: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 11974: $$metacache{"$key.display"}=$olddis;
11975: }
1.71 www 11976: }
11977:
1.764 albertel 11978: # ------------------------------------------------------ Devalidate title cache
11979:
11980: sub devalidate_title_cache {
11981: my ($url)=@_;
11982: if (!$env{'request.course.id'}) { return; }
11983: my $symb=&symbread($url);
11984: if (!$symb) { return; }
11985: my $key=$env{'request.course.id'}."\0".$symb;
11986: &devalidate_cache_new('title',$key);
11987: }
11988:
1.1014 droeschl 11989: # ------------------------------------------------- Get the title of a course
11990:
11991: sub current_course_title {
11992: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11993: }
1.301 www 11994: # ------------------------------------------------- Get the title of a resource
11995:
11996: sub gettitle {
11997: my $urlsymb=shift;
11998: my $symb=&symbread($urlsymb);
1.534 albertel 11999: if ($symb) {
1.620 albertel 12000: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 12001: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 12002: if (defined($cached)) {
12003: return $result;
12004: }
1.534 albertel 12005: my ($map,$resid,$url)=&decode_symb($symb);
12006: my $title='';
1.907 albertel 12007: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12008: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12009: } else {
12010: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12011: &GDBM_READER(),0640)) {
12012: my $mapid=$bighash{'map_pc_'.&clutter($map)};
12013: $title=$bighash{'title_'.$mapid.'.'.$resid};
12014: untie(%bighash);
12015: }
1.534 albertel 12016: }
12017: $title=~s/\&colon\;/\:/gs;
12018: if ($title) {
1.1159 www 12019: # Remember both $symb and $title for dynamic metadata
12020: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 12021: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 12022: # Cache this title and then return it
1.599 albertel 12023: return &do_cache_new('title',$key,$title,600);
1.534 albertel 12024: }
12025: $urlsymb=$url;
12026: }
12027: my $title=&metadata($urlsymb,'title');
12028: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
12029: return $title;
1.301 www 12030: }
1.613 albertel 12031:
1.614 albertel 12032: sub get_slot {
12033: my ($which,$cnum,$cdom)=@_;
12034: if (!$cnum || !$cdom) {
1.790 albertel 12035: (undef,my $courseid)=&whichuser();
1.620 albertel 12036: $cdom=$env{'course.'.$courseid.'.domain'};
12037: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 12038: }
1.703 albertel 12039: my $key=join("\0",'slots',$cdom,$cnum,$which);
12040: my %slotinfo;
12041: if (exists($remembered{$key})) {
12042: $slotinfo{$which} = $remembered{$key};
12043: } else {
12044: %slotinfo=&get('slots',[$which],$cdom,$cnum);
12045: &Apache::lonhomework::showhash(%slotinfo);
12046: my ($tmp)=keys(%slotinfo);
12047: if ($tmp=~/^error:/) { return (); }
12048: $remembered{$key} = $slotinfo{$which};
12049: }
1.616 albertel 12050: if (ref($slotinfo{$which}) eq 'HASH') {
12051: return %{$slotinfo{$which}};
12052: }
12053: return $slotinfo{$which};
1.614 albertel 12054: }
1.1150 raeburn 12055:
12056: sub get_reservable_slots {
12057: my ($cnum,$cdom,$uname,$udom) = @_;
12058: my $now = time;
12059: my $reservable_info;
12060: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12061: if (exists($remembered{$key})) {
12062: $reservable_info = $remembered{$key};
12063: } else {
12064: my %resv;
12065: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12066: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12067: $reservable_info = \%resv;
12068: $remembered{$key} = $reservable_info;
12069: }
12070: return $reservable_info;
12071: }
12072:
12073: sub get_course_slots {
12074: my ($cnum,$cdom) = @_;
12075: my $hashid=$cnum.':'.$cdom;
12076: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12077: if (defined($cached)) {
12078: if (ref($result) eq 'HASH') {
12079: return %{$result};
12080: }
12081: } else {
12082: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12083: my ($tmp) = keys(%slots);
12084: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 12085: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 12086: return %slots;
12087: }
12088: }
12089: return;
12090: }
12091:
12092: sub devalidate_slots_cache {
12093: my ($cnum,$cdom)=@_;
12094: my $hashid=$cnum.':'.$cdom;
12095: &devalidate_cache_new('allslots',$hashid);
12096: }
12097:
1.1181 raeburn 12098: sub get_coursechange {
12099: my ($cdom,$cnum) = @_;
12100: if ($cdom eq '' || $cnum eq '') {
12101: return unless ($env{'request.course.id'});
12102: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12103: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12104: }
12105: my $hashid=$cdom.'_'.$cnum;
12106: my ($change,$cached)=&is_cached_new('crschange',$hashid);
12107: if ((defined($cached)) && ($change ne '')) {
12108: return $change;
12109: } else {
12110: my %crshash;
12111: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12112: if ($crshash{'internal.contentchange'} eq '') {
12113: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12114: if ($change eq '') {
12115: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12116: $change = $crshash{'internal.created'};
12117: }
12118: } else {
12119: $change = $crshash{'internal.contentchange'};
12120: }
12121: my $cachetime = 600;
12122: &do_cache_new('crschange',$hashid,$change,$cachetime);
12123: }
12124: return $change;
12125: }
12126:
12127: sub devalidate_coursechange_cache {
12128: my ($cnum,$cdom)=@_;
12129: my $hashid=$cnum.':'.$cdom;
12130: &devalidate_cache_new('crschange',$hashid);
12131: }
12132:
1.31 www 12133: # ------------------------------------------------- Update symbolic store links
12134:
12135: sub symblist {
12136: my ($mapname,%newhash)=@_;
1.438 www 12137: $mapname=&deversion(&declutter($mapname));
1.31 www 12138: my %hash;
1.620 albertel 12139: if (($env{'request.course.fn'}) && (%newhash)) {
12140: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12141: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 12142: foreach my $url (keys(%newhash)) {
1.711 albertel 12143: next if ($url eq 'last_known'
12144: && $env{'form.no_update_last_known'});
12145: $hash{declutter($url)}=&encode_symb($mapname,
12146: $newhash{$url}->[1],
12147: $newhash{$url}->[0]);
1.191 harris41 12148: }
1.31 www 12149: if (untie(%hash)) {
12150: return 'ok';
12151: }
12152: }
12153: }
12154: return 'error';
1.212 www 12155: }
12156:
12157: # --------------------------------------------------------------- Verify a symb
12158:
12159: sub symbverify {
1.1190 raeburn 12160: my ($symb,$thisurl,$encstate)=@_;
1.510 www 12161: my $thisfn=$thisurl;
1.439 www 12162: $thisfn=&declutter($thisfn);
1.215 www 12163: # direct jump to resource in page or to a sequence - will construct own symbs
12164: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12165: # check URL part
1.409 www 12166: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 12167:
1.431 www 12168: unless ($url eq $thisfn) { return 0; }
1.213 www 12169:
1.216 www 12170: $symb=&symbclean($symb);
1.510 www 12171: $thisurl=&deversion($thisurl);
1.439 www 12172: $thisfn=&deversion($thisfn);
1.213 www 12173:
12174: my %bighash;
12175: my $okay=0;
1.431 www 12176:
1.620 albertel 12177: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12178: &GDBM_READER(),0640)) {
1.1204 raeburn 12179: my $noclutter;
1.1032 raeburn 12180: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12181: $thisurl =~ s/\?.+$//;
1.1204 raeburn 12182: if ($map =~ m{^uploaded/.+\.page$}) {
12183: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12184: $thisurl =~ s{^\Qhttp://https://\E}{https://};
12185: $noclutter = 1;
12186: }
12187: }
12188: my $ids;
12189: if ($noclutter) {
12190: $ids=$bighash{'ids_'.$thisurl};
12191: } else {
12192: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 12193: }
1.1102 raeburn 12194: unless ($ids) {
12195: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
12196: $ids=$bighash{$idkey};
1.216 www 12197: }
12198: if ($ids) {
12199: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 12200: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 12201: $symb =~ s/\?.+$//;
1.1202 raeburn 12202: }
1.800 albertel 12203: foreach my $id (split(/\,/,$ids)) {
12204: my ($mapid,$resid)=split(/\./,$id);
1.216 www 12205: if (
12206: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 12207: eq $symb) {
12208: if (ref($encstate)) {
12209: $$encstate = $bighash{'encrypted_'.$id};
12210: }
1.620 albertel 12211: if (($env{'request.role.adv'}) ||
1.1101 raeburn 12212: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12213: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 12214: $okay=1;
1.1202 raeburn 12215: last;
1.582 albertel 12216: }
12217: }
1.216 www 12218: }
12219: }
1.213 www 12220: untie(%bighash);
12221: }
12222: return $okay;
1.31 www 12223: }
12224:
1.210 www 12225: # --------------------------------------------------------------- Clean-up symb
12226:
12227: sub symbclean {
12228: my $symb=shift;
1.568 albertel 12229: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 12230: # remove version from map
12231: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 12232:
1.210 www 12233: # remove version from URL
12234: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 12235:
1.507 www 12236: # remove wrapper
12237:
1.510 www 12238: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 12239: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 12240: return $symb;
1.409 www 12241: }
12242:
12243: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 12244:
12245: sub encode_symb {
12246: my ($map,$resid,$url)=@_;
12247: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12248: }
1.409 www 12249:
12250: sub decode_symb {
1.568 albertel 12251: my $symb=shift;
12252: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12253: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 12254: return (&fixversion($map),$resid,&fixversion($url));
12255: }
12256:
12257: sub fixversion {
12258: my $fn=shift;
1.609 banghart 12259: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 12260: my %bighash;
12261: my $uri=&clutter($fn);
1.620 albertel 12262: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 12263: # is this cached?
1.599 albertel 12264: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 12265: if (defined($cached)) { return $result; }
12266: # unfortunately not cached, or expired
1.620 albertel 12267: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 12268: &GDBM_READER(),0640)) {
12269: if ($bighash{'version_'.$uri}) {
12270: my $version=$bighash{'version_'.$uri};
1.444 www 12271: unless (($version eq 'mostrecent') ||
12272: ($version==&getversion($uri))) {
1.440 www 12273: $uri=~s/\.(\w+)$/\.$version\.$1/;
12274: }
12275: }
12276: untie %bighash;
1.413 www 12277: }
1.599 albertel 12278: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 12279: }
12280:
12281: sub deversion {
12282: my $url=shift;
12283: $url=~s/\.\d+\.(\w+)$/\.$1/;
12284: return $url;
1.210 www 12285: }
12286:
1.31 www 12287: # ------------------------------------------------------ Return symb list entry
12288:
12289: sub symbread {
1.1282 raeburn 12290: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265 raeburn 12291: my $cache_str='request.symbread.cached.'.$thisfn;
1.1282 raeburn 12292: if (defined($env{$cache_str})) {
12293: if ($ignorecachednull) {
12294: return $env{$cache_str} unless ($env{$cache_str} eq '');
12295: } else {
12296: return $env{$cache_str};
12297: }
12298: }
1.242 www 12299: # no filename provided? try from environment
1.1265 raeburn 12300: unless ($thisfn) {
1.620 albertel 12301: if ($env{'request.symb'}) {
12302: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 12303: }
1.620 albertel 12304: $thisfn=$env{'request.filename'};
1.44 www 12305: }
1.569 albertel 12306: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 12307: # is that filename actually a symb? Verify, clean, and return
12308: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 12309: if (&symbverify($thisfn,$1)) {
1.620 albertel 12310: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 12311: }
1.242 www 12312: }
1.44 www 12313: $thisfn=declutter($thisfn);
1.31 www 12314: my %hash;
1.37 www 12315: my %bighash;
12316: my $syval='';
1.620 albertel 12317: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 12318: my $targetfn = $thisfn;
1.609 banghart 12319: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 12320: $targetfn = 'adm/wrapper/'.$thisfn;
12321: }
1.687 albertel 12322: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12323: $targetfn=$1;
12324: }
1.620 albertel 12325: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12326: &GDBM_READER(),0640)) {
1.481 raeburn 12327: $syval=$hash{$targetfn};
1.37 www 12328: untie(%hash);
12329: }
12330: # ---------------------------------------------------------- There was an entry
12331: if ($syval) {
1.601 albertel 12332: #unless ($syval=~/\_\d+$/) {
1.620 albertel 12333: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 12334: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12335: #return $env{$cache_str}='';
1.601 albertel 12336: #}
12337: #$syval.=$1;
12338: #}
1.37 www 12339: } else {
12340: # ------------------------------------------------------- Was not in symb table
1.620 albertel 12341: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12342: &GDBM_READER(),0640)) {
1.37 www 12343: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 12344: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 12345: unless ($ids) {
12346: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 12347: }
12348: unless ($ids) {
12349: # alias?
12350: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 12351: }
1.37 www 12352: if ($ids) {
12353: # ------------------------------------------------------------------- Has ID(s)
12354: my @possibilities=split(/\,/,$ids);
1.39 www 12355: if ($#possibilities==0) {
12356: # ----------------------------------------------- There is only one possibility
1.37 www 12357: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 12358: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12359: $resid,$thisfn);
1.1282 raeburn 12360: if (ref($possibles) eq 'HASH') {
12361: $possibles->{$syval} = 1;
12362: }
12363: if ($checkforblock) {
12364: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12365: if (@blockers) {
12366: $syval = '';
12367: return;
12368: }
12369: }
12370: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 12371: # ------------------------------------------ There is more than one possibility
12372: my $realpossible=0;
1.800 albertel 12373: foreach my $id (@possibilities) {
12374: my $file=$bighash{'src_'.$id};
1.1282 raeburn 12375: my $canaccess;
12376: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12377: $canaccess = 1;
12378: } else {
12379: $canaccess = &allowed('bre',$file);
12380: }
12381: if ($canaccess) {
12382: my ($mapid,$resid)=split(/\./,$id);
12383: if ($bighash{'map_type_'.$mapid} ne 'page') {
12384: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12385: $resid,$thisfn);
12386: if (ref($possibles) eq 'HASH') {
12387: $possibles->{$syval} = 1;
12388: }
12389: if ($checkforblock) {
12390: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12391: unless (@blockers > 0) {
12392: $syval = $poss_syval;
12393: $realpossible++;
12394: }
12395: } else {
12396: $syval = $poss_syval;
12397: $realpossible++;
12398: }
12399: }
1.39 www 12400: }
1.191 harris41 12401: }
1.39 www 12402: if ($realpossible!=1) { $syval=''; }
1.249 www 12403: } else {
12404: $syval='';
1.37 www 12405: }
12406: }
1.1282 raeburn 12407: untie(%bighash);
1.481 raeburn 12408: }
1.31 www 12409: }
1.62 www 12410: if ($syval) {
1.620 albertel 12411: return $env{$cache_str}=$syval;
1.62 www 12412: }
1.31 www 12413: }
1.949 raeburn 12414: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12415: return $env{$cache_str}='';
1.31 www 12416: }
12417:
12418: # ---------------------------------------------------------- Return random seed
12419:
1.32 www 12420: sub numval {
12421: my $txt=shift;
12422: $txt=~tr/A-J/0-9/;
12423: $txt=~tr/a-j/0-9/;
12424: $txt=~tr/K-T/0-9/;
12425: $txt=~tr/k-t/0-9/;
12426: $txt=~tr/U-Z/0-5/;
12427: $txt=~tr/u-z/0-5/;
12428: $txt=~s/\D//g;
1.564 albertel 12429: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 12430: return int($txt);
1.368 albertel 12431: }
12432:
1.484 albertel 12433: sub numval2 {
12434: my $txt=shift;
12435: $txt=~tr/A-J/0-9/;
12436: $txt=~tr/a-j/0-9/;
12437: $txt=~tr/K-T/0-9/;
12438: $txt=~tr/k-t/0-9/;
12439: $txt=~tr/U-Z/0-5/;
12440: $txt=~tr/u-z/0-5/;
12441: $txt=~s/\D//g;
12442: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12443: my $total;
12444: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 12445: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 12446: return int($total);
12447: }
12448:
1.575 albertel 12449: sub numval3 {
12450: use integer;
12451: my $txt=shift;
12452: $txt=~tr/A-J/0-9/;
12453: $txt=~tr/a-j/0-9/;
12454: $txt=~tr/K-T/0-9/;
12455: $txt=~tr/k-t/0-9/;
12456: $txt=~tr/U-Z/0-5/;
12457: $txt=~tr/u-z/0-5/;
12458: $txt=~s/\D//g;
12459: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12460: my $total;
12461: foreach my $val (@txts) { $total+=$val; }
12462: if ($_64bit) { $total=(($total<<32)>>32); }
12463: return $total;
12464: }
12465:
1.675 albertel 12466: sub digest {
12467: my ($data)=@_;
12468: my $digest=&Digest::MD5::md5($data);
12469: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12470: my ($e,$f);
12471: {
12472: use integer;
12473: $e=($a+$b);
12474: $f=($c+$d);
12475: if ($_64bit) {
12476: $e=(($e<<32)>>32);
12477: $f=(($f<<32)>>32);
12478: }
12479: }
12480: if (wantarray) {
12481: return ($e,$f);
12482: } else {
12483: my $g;
12484: {
12485: use integer;
12486: $g=($e+$f);
12487: if ($_64bit) {
12488: $g=(($g<<32)>>32);
12489: }
12490: }
12491: return $g;
12492: }
12493: }
12494:
1.368 albertel 12495: sub latest_rnd_algorithm_id {
1.675 albertel 12496: return '64bit5';
1.366 albertel 12497: }
1.32 www 12498:
1.503 albertel 12499: sub get_rand_alg {
12500: my ($courseid)=@_;
1.790 albertel 12501: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12502: if ($courseid) {
1.620 albertel 12503: return $env{"course.$courseid.rndseed"};
1.503 albertel 12504: }
12505: return &latest_rnd_algorithm_id();
12506: }
12507:
1.562 albertel 12508: sub validCODE {
12509: my ($CODE)=@_;
12510: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12511: return 0;
12512: }
12513:
1.491 albertel 12514: sub getCODE {
1.620 albertel 12515: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12516: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12517: defined($Apache::lonhomework::parsing_a_task) ) &&
12518: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12519: return $Apache::lonhomework::history{'resource.CODE'};
12520: }
12521: return undef;
12522: }
1.1133 foxr 12523: #
12524: # Determines the random seed for a specific context:
12525: #
12526: # parameters:
12527: # symb - in course context the symb for the seed.
12528: # course_id - The course id of the form domain_coursenum.
12529: # domain - Domain for the user.
12530: # course - Course for the user.
12531: # cenv - environment of the course.
12532: #
12533: # NOTE:
12534: # All parameters are picked out of the environment if missing
12535: # or not defined.
12536: # If a symb cannot be determined the current time is used instead.
12537: #
12538: # For a given well defined symb, courside, domain, username,
12539: # and course environment, the seed is reproducible.
12540: #
1.31 www 12541: sub rndseed {
1.1133 foxr 12542: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12543: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12544: if (!defined($symb)) {
1.366 albertel 12545: unless ($symb=$wsymb) { return time; }
12546: }
1.1146 foxr 12547: if (!defined $courseid) {
12548: $courseid=$wcourseid;
12549: }
12550: if (!defined $domain) { $domain=$wdomain; }
12551: if (!defined $username) { $username=$wusername }
1.1133 foxr 12552:
12553: my $which;
12554: if (defined($cenv->{'rndseed'})) {
12555: $which = $cenv->{'rndseed'};
12556: } else {
12557: $which =&get_rand_alg($courseid);
12558: }
1.491 albertel 12559: if (defined(&getCODE())) {
1.1133 foxr 12560:
1.675 albertel 12561: if ($which eq '64bit5') {
12562: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12563: } elsif ($which eq '64bit4') {
1.575 albertel 12564: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12565: } else {
12566: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12567: }
1.675 albertel 12568: } elsif ($which eq '64bit5') {
12569: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12570: } elsif ($which eq '64bit4') {
12571: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12572: } elsif ($which eq '64bit3') {
12573: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12574: } elsif ($which eq '64bit2') {
12575: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12576: } elsif ($which eq '64bit') {
12577: return &rndseed_64bit($symb,$courseid,$domain,$username);
12578: }
12579: return &rndseed_32bit($symb,$courseid,$domain,$username);
12580: }
12581:
12582: sub rndseed_32bit {
12583: my ($symb,$courseid,$domain,$username)=@_;
12584: {
12585: use integer;
12586: my $symbchck=unpack("%32C*",$symb) << 27;
12587: my $symbseed=numval($symb) << 22;
12588: my $namechck=unpack("%32C*",$username) << 17;
12589: my $nameseed=numval($username) << 12;
12590: my $domainseed=unpack("%32C*",$domain) << 7;
12591: my $courseseed=unpack("%32C*",$courseid);
12592: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12593: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12594: #&logthis("rndseed :$num:$symb");
1.564 albertel 12595: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 12596: return $num;
12597: }
12598: }
12599:
12600: sub rndseed_64bit {
12601: my ($symb,$courseid,$domain,$username)=@_;
12602: {
12603: use integer;
12604: my $symbchck=unpack("%32S*",$symb) << 21;
12605: my $symbseed=numval($symb) << 10;
12606: my $namechck=unpack("%32S*",$username);
12607:
12608: my $nameseed=numval($username) << 21;
12609: my $domainseed=unpack("%32S*",$domain) << 10;
12610: my $courseseed=unpack("%32S*",$courseid);
12611:
12612: my $num1=$symbchck+$symbseed+$namechck;
12613: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12614: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12615: #&logthis("rndseed :$num:$symb");
1.564 albertel 12616: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 12617: return "$num1,$num2";
1.155 albertel 12618: }
1.366 albertel 12619: }
12620:
1.443 albertel 12621: sub rndseed_64bit2 {
12622: my ($symb,$courseid,$domain,$username)=@_;
12623: {
12624: use integer;
12625: # strings need to be an even # of cahracters long, it it is odd the
12626: # last characters gets thrown away
12627: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12628: my $symbseed=numval($symb) << 10;
12629: my $namechck=unpack("%32S*",$username.' ');
12630:
12631: my $nameseed=numval($username) << 21;
1.501 albertel 12632: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12633: my $courseseed=unpack("%32S*",$courseid.' ');
12634:
12635: my $num1=$symbchck+$symbseed+$namechck;
12636: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12637: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12638: #&logthis("rndseed :$num:$symb");
1.803 albertel 12639: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 12640: return "$num1,$num2";
12641: }
12642: }
12643:
12644: sub rndseed_64bit3 {
12645: my ($symb,$courseid,$domain,$username)=@_;
12646: {
12647: use integer;
12648: # strings need to be an even # of cahracters long, it it is odd the
12649: # last characters gets thrown away
12650: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12651: my $symbseed=numval2($symb) << 10;
12652: my $namechck=unpack("%32S*",$username.' ');
12653:
12654: my $nameseed=numval2($username) << 21;
1.443 albertel 12655: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12656: my $courseseed=unpack("%32S*",$courseid.' ');
12657:
12658: my $num1=$symbchck+$symbseed+$namechck;
12659: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12660: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12661: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 12662: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12663:
1.503 albertel 12664: return "$num1:$num2";
1.443 albertel 12665: }
12666: }
12667:
1.575 albertel 12668: sub rndseed_64bit4 {
12669: my ($symb,$courseid,$domain,$username)=@_;
12670: {
12671: use integer;
12672: # strings need to be an even # of cahracters long, it it is odd the
12673: # last characters gets thrown away
12674: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12675: my $symbseed=numval3($symb) << 10;
12676: my $namechck=unpack("%32S*",$username.' ');
12677:
12678: my $nameseed=numval3($username) << 21;
12679: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12680: my $courseseed=unpack("%32S*",$courseid.' ');
12681:
12682: my $num1=$symbchck+$symbseed+$namechck;
12683: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12684: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12685: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 12686: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12687:
1.575 albertel 12688: return "$num1:$num2";
12689: }
12690: }
12691:
1.675 albertel 12692: sub rndseed_64bit5 {
12693: my ($symb,$courseid,$domain,$username)=@_;
12694: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12695: return "$num1:$num2";
12696: }
12697:
1.366 albertel 12698: sub rndseed_CODE_64bit {
12699: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 12700: {
1.366 albertel 12701: use integer;
1.443 albertel 12702: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 12703: my $symbseed=numval2($symb);
1.491 albertel 12704: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12705: my $CODEseed=numval(&getCODE());
1.443 albertel 12706: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 12707: my $num1=$symbseed+$CODEchck;
12708: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12709: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12710: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 12711: if ($_64bit) { $num1=(($num1<<32)>>32); }
12712: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 12713: return "$num1:$num2";
1.366 albertel 12714: }
12715: }
12716:
1.575 albertel 12717: sub rndseed_CODE_64bit4 {
12718: my ($symb,$courseid,$domain,$username)=@_;
12719: {
12720: use integer;
12721: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12722: my $symbseed=numval3($symb);
12723: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12724: my $CODEseed=numval3(&getCODE());
12725: my $courseseed=unpack("%32S*",$courseid.' ');
12726: my $num1=$symbseed+$CODEchck;
12727: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12728: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12729: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 12730: if ($_64bit) { $num1=(($num1<<32)>>32); }
12731: if ($_64bit) { $num2=(($num2<<32)>>32); }
12732: return "$num1:$num2";
12733: }
12734: }
12735:
1.675 albertel 12736: sub rndseed_CODE_64bit5 {
12737: my ($symb,$courseid,$domain,$username)=@_;
12738: my $code = &getCODE();
12739: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12740: return "$num1:$num2";
12741: }
12742:
1.366 albertel 12743: sub setup_random_from_rndseed {
12744: my ($rndseed)=@_;
1.503 albertel 12745: if ($rndseed =~/([,:])/) {
1.1262 raeburn 12746: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12747: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12748: &Math::Random::random_set_seed_from_phrase($rndseed);
12749: } else {
12750: &Math::Random::random_set_seed($num1,$num2);
12751: }
1.366 albertel 12752: } else {
12753: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12754: }
1.36 albertel 12755: }
12756:
1.474 albertel 12757: sub latest_receipt_algorithm_id {
1.835 albertel 12758: return 'receipt3';
1.474 albertel 12759: }
12760:
1.480 www 12761: sub recunique {
12762: my $fucourseid=shift;
12763: my $unique;
1.835 albertel 12764: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12765: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12766: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12767: } else {
12768: $unique=$perlvar{'lonReceipt'};
12769: }
12770: return unpack("%32C*",$unique);
12771: }
12772:
12773: sub recprefix {
12774: my $fucourseid=shift;
12775: my $prefix;
1.835 albertel 12776: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12777: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12778: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12779: } else {
12780: $prefix=$perlvar{'lonHostID'};
12781: }
12782: return unpack("%32C*",$prefix);
12783: }
12784:
1.76 www 12785: sub ireceipt {
1.474 albertel 12786: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12787:
12788: my $return =&recprefix($fucourseid).'-';
12789:
12790: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12791: $env{'request.state'} eq 'construct') {
12792: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12793: return $return;
12794: }
12795:
1.76 www 12796: my $cuname=unpack("%32C*",$funame);
12797: my $cudom=unpack("%32C*",$fudom);
12798: my $cucourseid=unpack("%32C*",$fucourseid);
12799: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12800: my $cunique=&recunique($fucourseid);
1.474 albertel 12801: my $cpart=unpack("%32S*",$part);
1.835 albertel 12802: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12803:
1.790 albertel 12804: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12805:
12806: $return.= ($cunique%$cuname+
12807: $cunique%$cudom+
12808: $cusymb%$cuname+
12809: $cusymb%$cudom+
12810: $cucourseid%$cuname+
12811: $cucourseid%$cudom+
12812: $cpart%$cuname+
12813: $cpart%$cudom);
12814: } else {
12815: $return.= ($cunique%$cuname+
12816: $cunique%$cudom+
12817: $cusymb%$cuname+
12818: $cusymb%$cudom+
12819: $cucourseid%$cuname+
12820: $cucourseid%$cudom);
12821: }
12822: return $return;
1.76 www 12823: }
12824:
12825: sub receipt {
1.474 albertel 12826: my ($part)=@_;
1.790 albertel 12827: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 12828: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 12829: }
1.260 ng 12830:
1.790 albertel 12831: sub whichuser {
12832: my ($passedsymb)=@_;
12833: my ($symb,$courseid,$domain,$name,$publicuser);
12834: if (defined($env{'form.grade_symb'})) {
12835: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12836: my $allowed=&allowed('vgr',$tmp_courseid);
12837: if (!$allowed &&
12838: exists($env{'request.course.sec'}) &&
12839: $env{'request.course.sec'} !~ /^\s*$/) {
12840: $allowed=&allowed('vgr',$tmp_courseid.
12841: '/'.$env{'request.course.sec'});
12842: }
12843: if ($allowed) {
12844: ($symb)=&get_env_multiple('form.grade_symb');
12845: $courseid=$tmp_courseid;
12846: ($domain)=&get_env_multiple('form.grade_domain');
12847: ($name)=&get_env_multiple('form.grade_username');
12848: return ($symb,$courseid,$domain,$name,$publicuser);
12849: }
12850: }
12851: if (!$passedsymb) {
12852: $symb=&symbread();
12853: } else {
12854: $symb=$passedsymb;
12855: }
12856: $courseid=$env{'request.course.id'};
12857: $domain=$env{'user.domain'};
12858: $name=$env{'user.name'};
12859: if ($name eq 'public' && $domain eq 'public') {
12860: if (!defined($env{'form.username'})) {
12861: $env{'form.username'}.=time.rand(10000000);
12862: }
12863: $name.=$env{'form.username'};
12864: }
12865: return ($symb,$courseid,$domain,$name,$publicuser);
12866:
12867: }
12868:
1.36 albertel 12869: # ------------------------------------------------------------ Serves up a file
1.472 albertel 12870: # returns either the contents of the file or
12871: # -1 if the file doesn't exist
1.481 raeburn 12872: #
12873: # if the target is a file that was uploaded via DOCS,
12874: # a check will be made to see if a current copy exists on the local server,
12875: # if it does this will be served, otherwise a copy will be retrieved from
12876: # the home server for the course and stored in /home/httpd/html/userfiles on
12877: # the local server.
1.472 albertel 12878:
1.36 albertel 12879: sub getfile {
1.538 albertel 12880: my ($file) = @_;
1.609 banghart 12881: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 12882: &repcopy($file);
12883: return &readfile($file);
12884: }
12885:
12886: sub repcopy_userfile {
12887: my ($file)=@_;
1.1142 raeburn 12888: my $londocroot = $perlvar{'lonDocRoot'};
12889: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 12890: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 12891: my ($cdom,$cnum,$filename) =
1.811 albertel 12892: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 12893: my $uri="/uploaded/$cdom/$cnum/$filename";
12894: if (-e "$file") {
1.828 www 12895: # we already have a local copy, check it out
1.538 albertel 12896: my @fileinfo = stat($file);
1.828 www 12897: my $rtncode;
12898: my $info;
1.538 albertel 12899: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 12900: if ($lwpresp ne 'ok') {
1.828 www 12901: # there is no such file anymore, even though we had a local copy
1.482 albertel 12902: if ($rtncode eq '404') {
1.538 albertel 12903: unlink($file);
1.482 albertel 12904: }
12905: return -1;
12906: }
12907: if ($info < $fileinfo[9]) {
1.828 www 12908: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 12909: return 'ok';
1.828 www 12910: } else {
12911: # the file is outdated, get rid of it
12912: unlink($file);
1.482 albertel 12913: }
1.828 www 12914: }
12915: # one way or the other, at this point, we don't have the file
12916: # construct the correct path for the file
12917: my @parts = ($cdom,$cnum);
12918: if ($filename =~ m|^(.+)/[^/]+$|) {
12919: push @parts, split(/\//,$1);
12920: }
12921: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12922: foreach my $part (@parts) {
12923: $path .= '/'.$part;
12924: if (!-e $path) {
12925: mkdir($path,0770);
1.482 albertel 12926: }
12927: }
1.828 www 12928: # now the path exists for sure
12929: # get a user agent
12930: my $transferfile=$file.'.in.transfer';
12931: # FIXME: this should flock
12932: if (-e $transferfile) { return 'ok'; }
12933: my $request;
12934: $uri=~s/^\///;
1.980 raeburn 12935: my $homeserver = &homeserver($cnum,$cdom);
12936: my $protocol = $protocol{$homeserver};
12937: $protocol = 'http' if ($protocol ne 'https');
12938: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.1345 raeburn 12939: my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828 www 12940: # did it work?
12941: if ($response->is_error()) {
12942: unlink($transferfile);
12943: &logthis("Userfile repcopy failed for $uri");
12944: return -1;
12945: }
12946: # worked, rename the transfer file
12947: rename($transferfile,$file);
1.607 raeburn 12948: return 'ok';
1.481 raeburn 12949: }
12950:
1.517 albertel 12951: sub tokenwrapper {
12952: my $uri=shift;
1.980 raeburn 12953: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 12954: $uri=~s|^/||;
1.620 albertel 12955: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 12956: my $token=$1;
1.552 albertel 12957: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12958: if ($udom && $uname && $file) {
12959: $file=~s|(\?\.*)*$||;
1.949 raeburn 12960: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 12961: my $homeserver = &homeserver($uname,$udom);
12962: my $protocol = $protocol{$homeserver};
12963: $protocol = 'http' if ($protocol ne 'https');
12964: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 12965: (($uri=~/\?/)?'&':'?').'token='.$token.
12966: '&tokenissued='.$perlvar{'lonHostID'};
12967: } else {
12968: return '/adm/notfound.html';
12969: }
12970: }
12971:
1.828 www 12972: # call with reqtype HEAD: get last modification time
12973: # call with reqtype GET: get the file contents
12974: # Do not call this with reqtype GET for large files! It loads everything into memory
12975: #
1.481 raeburn 12976: sub getuploaded {
12977: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12978: $uri=~s/^\///;
1.980 raeburn 12979: my $homeserver = &homeserver($cnum,$cdom);
12980: my $protocol = $protocol{$homeserver};
12981: $protocol = 'http' if ($protocol ne 'https');
12982: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 12983: my $request=new HTTP::Request($reqtype,$uri);
1.1345 raeburn 12984: my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481 raeburn 12985: $$rtncode = $response->code;
1.482 albertel 12986: if (! $response->is_success()) {
12987: return 'failed';
12988: }
12989: if ($reqtype eq 'HEAD') {
1.486 www 12990: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 12991: } elsif ($reqtype eq 'GET') {
12992: $$info = $response->content;
1.472 albertel 12993: }
1.482 albertel 12994: return 'ok';
1.36 albertel 12995: }
12996:
1.481 raeburn 12997: sub readfile {
12998: my $file = shift;
12999: if ( (! -e $file ) || ($file eq '') ) { return -1; };
13000: my $fh;
13001: open($fh,"<$file");
13002: my $a='';
1.800 albertel 13003: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 13004: return $a;
13005: }
13006:
1.36 albertel 13007: sub filelocation {
1.590 banghart 13008: my ($dir,$file) = @_;
13009: my $location;
13010: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 13011:
13012: if ($file =~ m-^/adm/-) {
13013: $file=~s-^/adm/wrapper/-/-;
13014: $file=~s-^/adm/coursedocs/showdoc/-/-;
13015: }
1.882 albertel 13016:
1.1139 www 13017: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 13018: $location = $file;
1.609 banghart 13019: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 13020: my ($udom,$uname,$filename)=
1.811 albertel 13021: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 13022: my $home=&homeserver($uname,$udom);
13023: my $is_me=0;
13024: my @ids=¤t_machine_ids();
13025: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13026: if ($is_me) {
1.1117 foxr 13027: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 13028: } else {
13029: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13030: $udom.'/'.$uname.'/'.$filename;
13031: }
1.882 albertel 13032: } elsif ($file =~ m-^/adm/-) {
13033: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 13034: } else {
13035: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 13036: $file=~s:^/(res|priv)/:/:;
13037: my $space=$1;
1.590 banghart 13038: if ( !( $file =~ m:^/:) ) {
13039: $location = $dir. '/'.$file;
13040: } else {
1.1142 raeburn 13041: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 13042: }
1.59 albertel 13043: }
1.590 banghart 13044: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 13045: while ($location=~m{/\.\./}) {
13046: if ($location =~ m{/[^/]+/\.\./}) {
13047: $location=~ s{/[^/]+/\.\./}{/}g;
13048: } else {
13049: $location=~ s{/\.\./}{/}g;
13050: }
13051: } #remove dir/..
1.590 banghart 13052: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13053: return $location;
1.46 www 13054: }
1.36 albertel 13055:
1.46 www 13056: sub hreflocation {
13057: my ($dir,$file)=@_;
1.980 raeburn 13058: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 13059: $file=filelocation($dir,$file);
1.700 albertel 13060: } elsif ($file=~m-^/adm/-) {
13061: $file=~s-^/adm/wrapper/-/-;
13062: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 13063: }
13064: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13065: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13066: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 13067: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13068: {/uploaded/$1/$2/}x;
1.46 www 13069: }
1.913 albertel 13070: if ($file=~ m{^/userfiles/}) {
13071: $file =~ s{^/userfiles/}{/uploaded/};
13072: }
1.462 albertel 13073: return $file;
1.465 albertel 13074: }
13075:
1.1139 www 13076:
13077:
13078:
13079:
1.465 albertel 13080: sub current_machine_domains {
1.853 albertel 13081: return &machine_domains(&hostname($perlvar{'lonHostID'}));
13082: }
13083:
13084: sub machine_domains {
13085: my ($hostname) = @_;
1.465 albertel 13086: my @domains;
1.838 albertel 13087: my %hostname = &all_hostnames();
1.465 albertel 13088: while( my($id, $name) = each(%hostname)) {
1.467 matthew 13089: # &logthis("-$id-$name-$hostname-");
1.465 albertel 13090: if ($hostname eq $name) {
1.844 albertel 13091: push(@domains,&host_domain($id));
1.465 albertel 13092: }
13093: }
13094: return @domains;
13095: }
13096:
13097: sub current_machine_ids {
1.853 albertel 13098: return &machine_ids(&hostname($perlvar{'lonHostID'}));
13099: }
13100:
13101: sub machine_ids {
13102: my ($hostname) = @_;
13103: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 13104: my @ids;
1.888 albertel 13105: my %name_to_host = &all_names();
1.889 albertel 13106: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13107: return @{ $name_to_host{$hostname} };
13108: }
13109: return;
1.31 www 13110: }
13111:
1.824 raeburn 13112: sub additional_machine_domains {
13113: my @domains;
13114: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
13115: while( my $line = <$fh>) {
13116: $line =~ s/\s//g;
13117: push(@domains,$line);
13118: }
13119: return @domains;
13120: }
13121:
13122: sub default_login_domain {
13123: my $domain = $perlvar{'lonDefDomain'};
13124: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13125: foreach my $posdom (¤t_machine_domains(),
13126: &additional_machine_domains()) {
13127: if (lc($posdom) eq lc($testdomain)) {
13128: $domain=$posdom;
13129: last;
13130: }
13131: }
13132: return $domain;
13133: }
13134:
1.31 www 13135: # ------------------------------------------------------------- Declutters URLs
13136:
13137: sub declutter {
13138: my $thisfn=shift;
1.569 albertel 13139: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 13140: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13141: $thisfn=~s{^/home/httpd/html}{};
13142: }
1.31 www 13143: $thisfn=~s/^\///;
1.697 albertel 13144: $thisfn=~s|^adm/wrapper/||;
13145: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 13146: $thisfn=~s/^res\///;
1.1172 bisitz 13147: $thisfn=~s/^priv\///;
1.1032 raeburn 13148: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13149: $thisfn=~s/\?.+$//;
13150: }
1.268 www 13151: return $thisfn;
13152: }
13153:
13154: # ------------------------------------------------------------- Clutter up URLs
13155:
13156: sub clutter {
13157: my $thisfn='/'.&declutter(shift);
1.887 albertel 13158: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 13159: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 13160: $thisfn='/res'.$thisfn;
13161: }
1.1031 raeburn 13162: if ($thisfn !~m|^/adm|) {
13163: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 13164: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 13165: } else {
13166: my ($ext) = ($thisfn =~ /\.(\w+)$/);
13167: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 13168: if ($embstyle eq 'ssi'
13169: || ($embstyle eq 'hdn')
13170: || ($embstyle eq 'rat')
13171: || ($embstyle eq 'prv')
13172: || ($embstyle eq 'ign')) {
13173: #do nothing with these
13174: } elsif (($embstyle eq 'img')
1.695 albertel 13175: || ($embstyle eq 'emb')
13176: || ($embstyle eq 'wrp')) {
13177: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 13178: } elsif ($embstyle eq 'unk'
13179: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 13180: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 13181: } else {
1.718 www 13182: # &logthis("Got a blank emb style");
1.695 albertel 13183: }
1.694 albertel 13184: }
1.1343 raeburn 13185: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298 raeburn 13186: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 13187: }
1.31 www 13188: return $thisfn;
1.12 www 13189: }
13190:
1.787 albertel 13191: sub clutter_with_no_wrapper {
13192: my $uri = &clutter(shift);
13193: if ($uri =~ m-^/adm/-) {
13194: $uri =~ s-^/adm/wrapper/-/-;
13195: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
13196: }
13197: return $uri;
13198: }
13199:
1.557 albertel 13200: sub freeze_escape {
13201: my ($value)=@_;
13202: if (ref($value)) {
13203: $value=&nfreeze($value);
13204: return '__FROZEN__'.&escape($value);
13205: }
13206: return &escape($value);
13207: }
13208:
1.11 www 13209:
1.557 albertel 13210: sub thaw_unescape {
13211: my ($value)=@_;
13212: if ($value =~ /^__FROZEN__/) {
13213: substr($value,0,10,undef);
13214: $value=&unescape($value);
13215: return &thaw($value);
13216: }
13217: return &unescape($value);
13218: }
13219:
1.436 albertel 13220: sub correct_line_ends {
13221: my ($result)=@_;
13222: $$result =~s/\r\n/\n/mg;
13223: $$result =~s/\r/\n/mg;
1.415 albertel 13224: }
1.1 albertel 13225: # ================================================================ Main Program
13226:
1.184 www 13227: sub goodbye {
1.204 albertel 13228: &logthis("Starting Shut down");
1.443 albertel 13229: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 13230: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 13231: #converted
1.599 albertel 13232: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 13233: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13234: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13235: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 13236: #1.1 only
1.870 albertel 13237: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13238: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13239: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13240: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13241: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 13242: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13243: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 13244: &flushcourselogs();
13245: &logthis("Shutting down");
13246: }
13247:
1.852 albertel 13248: sub get_dns {
1.1210 raeburn 13249: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 13250: if (!$ignore_cache) {
13251: my ($content,$cached)=
13252: &Apache::lonnet::is_cached_new('dns',$url);
13253: if ($cached) {
1.1210 raeburn 13254: &$func($content,$hashref);
1.869 albertel 13255: return;
13256: }
13257: }
13258:
13259: my %alldns;
1.852 albertel 13260: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13261: foreach my $dns (<$config>) {
13262: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 13263: my $line = $1;
13264: my ($host,$protocol) = split(/:/,$line);
13265: if ($protocol ne 'https') {
13266: $protocol = 'http';
13267: }
13268: $alldns{$host} = $protocol;
1.869 albertel 13269: }
13270: while (%alldns) {
1.1263 raeburn 13271: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979 raeburn 13272: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345 raeburn 13273: my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979 raeburn 13274: delete($alldns{$dns});
1.852 albertel 13275: next if ($response->is_error());
13276: my @content = split("\n",$response->content);
1.1210 raeburn 13277: unless ($nocache) {
1.1219 raeburn 13278: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 13279: }
13280: &$func(\@content,$hashref);
1.869 albertel 13281: return;
1.852 albertel 13282: }
13283: close($config);
1.871 albertel 13284: my $which = (split('/',$url))[3];
13285: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13286: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 13287: my @content = <$config>;
1.1210 raeburn 13288: &$func(\@content,$hashref);
13289: return;
13290: }
13291:
13292: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 13293: sub parse_dns_checksums_tab {
1.1210 raeburn 13294: my ($lines,$hashref) = @_;
1.1264 raeburn 13295: my $lonhost = $perlvar{'lonHostID'};
13296: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 13297: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 13298: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13299: my $webconfdir = '/etc/httpd/conf';
13300: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13301: $webconfdir = '/etc/apache2';
13302: } elsif ($distro =~ /^sles(\d+)$/) {
13303: if ($1 >= 10) {
13304: $webconfdir = '/etc/apache2';
13305: }
13306: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13307: if ($1 >= 10.0) {
13308: $webconfdir = '/etc/apache2';
13309: }
13310: }
1.1210 raeburn 13311: my ($release,$timestamp) = split(/\-/,$loncaparev);
13312: my (%chksum,%revnum);
13313: if (ref($lines) eq 'ARRAY') {
13314: chomp(@{$lines});
1.1238 raeburn 13315: my $version = shift(@{$lines});
13316: if ($version eq $release) {
1.1210 raeburn 13317: foreach my $line (@{$lines}) {
1.1238 raeburn 13318: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 13319: if ($file =~ m{^/etc/httpd/conf}) {
13320: if ($webconfdir eq '/etc/apache2') {
13321: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13322: }
13323: }
1.1238 raeburn 13324: $chksum{$file} = $shasum;
13325: $revnum{$file} = $version;
1.1210 raeburn 13326: }
13327: if (ref($hashref) eq 'HASH') {
13328: %{$hashref} = (
13329: sums => \%chksum,
13330: versions => \%revnum,
13331: );
13332: }
13333: }
13334: }
1.869 albertel 13335: return;
1.852 albertel 13336: }
1.1210 raeburn 13337:
13338: sub fetch_dns_checksums {
1.1238 raeburn 13339: my %checksums;
13340: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 13341: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 13342: my ($release,$timestamp) = split(/\-/,$loncaparev);
13343: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 13344: \%checksums);
1.1210 raeburn 13345: return \%checksums;
13346: }
13347:
1.327 albertel 13348: # ------------------------------------------------------------ Read domain file
13349: {
1.852 albertel 13350: my $loaded;
1.846 albertel 13351: my %domain;
13352:
1.852 albertel 13353: sub parse_domain_tab {
13354: my ($lines) = @_;
13355: foreach my $line (@$lines) {
13356: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 13357:
1.846 albertel 13358: chomp($line);
1.852 albertel 13359: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 13360: my %this_domain;
13361: foreach my $field ('description', 'auth_def', 'auth_arg_def',
13362: 'lang_def', 'city', 'longi', 'lati',
13363: 'primary') {
13364: $this_domain{$field} = shift(@elements);
13365: }
13366: $domain{$name} = \%this_domain;
1.852 albertel 13367: }
13368: }
1.864 albertel 13369:
13370: sub reset_domain_info {
13371: undef($loaded);
13372: undef(%domain);
13373: }
13374:
1.852 albertel 13375: sub load_domain_tab {
1.1293 raeburn 13376: my ($ignore_cache,$nocache) = @_;
13377: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 13378: my $fh;
13379: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
13380: my @lines = <$fh>;
13381: &parse_domain_tab(\@lines);
1.448 albertel 13382: }
1.852 albertel 13383: close($fh);
13384: $loaded = 1;
1.327 albertel 13385: }
1.846 albertel 13386:
13387: sub domain {
1.852 albertel 13388: &load_domain_tab() if (!$loaded);
13389:
1.846 albertel 13390: my ($name,$what) = @_;
13391: return if ( !exists($domain{$name}) );
13392:
13393: if (!$what) {
13394: return $domain{$name}{'description'};
13395: }
13396: return $domain{$name}{$what};
13397: }
1.974 raeburn 13398:
13399: sub domain_info {
13400: &load_domain_tab() if (!$loaded);
13401: return %domain;
13402: }
13403:
1.327 albertel 13404: }
13405:
13406:
1.1 albertel 13407: # ------------------------------------------------------------- Read hosts file
13408: {
1.838 albertel 13409: my %hostname;
1.844 albertel 13410: my %hostdom;
1.845 albertel 13411: my %libserv;
1.852 albertel 13412: my $loaded;
1.888 albertel 13413: my %name_to_host;
1.1074 raeburn 13414: my %internetdom;
1.1107 raeburn 13415: my %LC_dns_serv;
1.852 albertel 13416:
13417: sub parse_hosts_tab {
13418: my ($file) = @_;
13419: foreach my $configline (@$file) {
13420: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 13421: chomp($configline);
13422: if ($configline =~ /^\^/) {
13423: if ($configline =~ /^\^([\w.\-]+)/) {
13424: $LC_dns_serv{$1} = 1;
13425: }
13426: next;
13427: }
1.1074 raeburn 13428: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 13429: $name=~s/\s//g;
13430: if ($id && $domain && $role && $name) {
1.1351 raeburn 13431: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13432: my $curr = $hostname{$id};
13433: my $skip;
13434: if (ref($name_to_host{$curr}) eq 'ARRAY') {
13435: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13436: $skip = 1;
13437: } else {
13438: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13439: }
13440: }
13441: unless ($skip) {
13442: push(@{$name_to_host{$name}},$id);
13443: }
13444: } else {
13445: push(@{$name_to_host{$name}},$id);
13446: }
1.852 albertel 13447: $hostname{$id}=$name;
13448: $hostdom{$id}=$domain;
13449: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 13450: if (defined($protocol)) {
13451: if ($protocol eq 'https') {
13452: $protocol{$id} = $protocol;
13453: } else {
13454: $protocol{$id} = 'http';
13455: }
1.968 raeburn 13456: } else {
1.969 raeburn 13457: $protocol{$id} = 'http';
1.968 raeburn 13458: }
1.1074 raeburn 13459: if (defined($intdom)) {
13460: $internetdom{$id} = $intdom;
13461: }
1.852 albertel 13462: }
13463: }
13464: }
1.864 albertel 13465:
13466: sub reset_hosts_info {
1.897 albertel 13467: &purge_remembered();
1.864 albertel 13468: &reset_domain_info();
13469: &reset_hosts_ip_info();
1.1339 raeburn 13470: undef(%internetdom);
1.892 albertel 13471: undef(%name_to_host);
1.864 albertel 13472: undef(%hostname);
13473: undef(%hostdom);
13474: undef(%libserv);
13475: undef($loaded);
13476: }
1.1 albertel 13477:
1.852 albertel 13478: sub load_hosts_tab {
1.1293 raeburn 13479: my ($ignore_cache,$nocache) = @_;
13480: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852 albertel 13481: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13482: my @config = <$config>;
13483: &parse_hosts_tab(\@config);
13484: close($config);
13485: $loaded=1;
1.1 albertel 13486: }
1.852 albertel 13487:
1.838 albertel 13488: sub hostname {
1.852 albertel 13489: &load_hosts_tab() if (!$loaded);
13490:
1.838 albertel 13491: my ($lonid) = @_;
13492: return $hostname{$lonid};
13493: }
1.845 albertel 13494:
1.838 albertel 13495: sub all_hostnames {
1.852 albertel 13496: &load_hosts_tab() if (!$loaded);
13497:
1.838 albertel 13498: return %hostname;
13499: }
1.845 albertel 13500:
1.888 albertel 13501: sub all_names {
1.1293 raeburn 13502: my ($ignore_cache,$nocache) = @_;
13503: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 13504:
13505: return %name_to_host;
13506: }
13507:
1.974 raeburn 13508: sub all_host_domain {
13509: &load_hosts_tab() if (!$loaded);
13510: return %hostdom;
13511: }
13512:
1.1339 raeburn 13513: sub all_host_intdom {
13514: &load_hosts_tab() if (!$loaded);
13515: return %internetdom;
13516: }
13517:
1.845 albertel 13518: sub is_library {
1.852 albertel 13519: &load_hosts_tab() if (!$loaded);
13520:
1.845 albertel 13521: return exists($libserv{$_[0]});
13522: }
13523:
13524: sub all_library {
1.852 albertel 13525: &load_hosts_tab() if (!$loaded);
13526:
1.845 albertel 13527: return %libserv;
13528: }
13529:
1.1062 droeschl 13530: sub unique_library {
13531: #2x reverse removes all hostnames that appear more than once
13532: my %unique = reverse &all_library();
13533: return reverse %unique;
13534: }
13535:
1.841 albertel 13536: sub get_servers {
1.852 albertel 13537: &load_hosts_tab() if (!$loaded);
13538:
1.841 albertel 13539: my ($domain,$type) = @_;
13540: my %possible_hosts = ($type eq 'library') ? %libserv
13541: : %hostname;
13542: my %result;
1.842 albertel 13543: if (ref($domain) eq 'ARRAY') {
13544: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 13545: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 13546: $result{$host} = $hostname;
13547: }
13548: }
13549: } else {
13550: while ( my ($host,$hostname) = each(%possible_hosts)) {
13551: if ($hostdom{$host} eq $domain) {
13552: $result{$host} = $hostname;
13553: }
1.841 albertel 13554: }
13555: }
13556: return %result;
13557: }
1.845 albertel 13558:
1.1062 droeschl 13559: sub get_unique_servers {
13560: my %unique = reverse &get_servers(@_);
13561: return reverse %unique;
13562: }
13563:
1.844 albertel 13564: sub host_domain {
1.852 albertel 13565: &load_hosts_tab() if (!$loaded);
13566:
1.844 albertel 13567: my ($lonid) = @_;
13568: return $hostdom{$lonid};
13569: }
13570:
1.841 albertel 13571: sub all_domains {
1.852 albertel 13572: &load_hosts_tab() if (!$loaded);
13573:
1.841 albertel 13574: my %seen;
13575: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13576: return @uniq;
13577: }
1.1074 raeburn 13578:
13579: sub internet_dom {
13580: &load_hosts_tab() if (!$loaded);
13581:
13582: my ($lonid) = @_;
13583: return $internetdom{$lonid};
13584: }
1.1107 raeburn 13585:
13586: sub is_LC_dns {
13587: &load_hosts_tab() if (!$loaded);
13588:
13589: my ($hostname) = @_;
13590: return exists($LC_dns_serv{$hostname});
13591: }
13592:
1.1 albertel 13593: }
13594:
1.847 albertel 13595: {
13596: my %iphost;
1.856 albertel 13597: my %name_to_ip;
13598: my %lonid_to_ip;
1.869 albertel 13599:
1.847 albertel 13600: sub get_hosts_from_ip {
13601: my ($ip) = @_;
13602: my %iphosts = &get_iphost();
13603: if (ref($iphosts{$ip})) {
13604: return @{$iphosts{$ip}};
13605: }
13606: return;
1.839 albertel 13607: }
1.864 albertel 13608:
13609: sub reset_hosts_ip_info {
13610: undef(%iphost);
13611: undef(%name_to_ip);
13612: undef(%lonid_to_ip);
13613: }
1.856 albertel 13614:
13615: sub get_host_ip {
13616: my ($lonid) = @_;
13617: if (exists($lonid_to_ip{$lonid})) {
13618: return $lonid_to_ip{$lonid};
13619: }
13620: my $name=&hostname($lonid);
13621: my $ip = gethostbyname($name);
13622: return if (!$ip || length($ip) ne 4);
13623: $ip=inet_ntoa($ip);
13624: $name_to_ip{$name} = $ip;
13625: $lonid_to_ip{$lonid} = $ip;
13626: return $ip;
13627: }
1.847 albertel 13628:
13629: sub get_iphost {
1.1293 raeburn 13630: my ($ignore_cache,$nocache) = @_;
1.894 albertel 13631:
1.869 albertel 13632: if (!$ignore_cache) {
13633: if (%iphost) {
13634: return %iphost;
13635: }
13636: my ($ip_info,$cached)=
13637: &Apache::lonnet::is_cached_new('iphost','iphost');
13638: if ($cached) {
13639: %iphost = %{$ip_info->[0]};
13640: %name_to_ip = %{$ip_info->[1]};
13641: %lonid_to_ip = %{$ip_info->[2]};
13642: return %iphost;
13643: }
13644: }
1.894 albertel 13645:
13646: # get yesterday's info for fallback
13647: my %old_name_to_ip;
13648: my ($ip_info,$cached)=
13649: &Apache::lonnet::is_cached_new('iphost','iphost');
13650: if ($cached) {
13651: %old_name_to_ip = %{$ip_info->[1]};
13652: }
13653:
1.1293 raeburn 13654: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 13655: foreach my $name (keys(%name_to_host)) {
1.847 albertel 13656: my $ip;
13657: if (!exists($name_to_ip{$name})) {
13658: $ip = gethostbyname($name);
13659: if (!$ip || length($ip) ne 4) {
1.894 albertel 13660: if (defined($old_name_to_ip{$name})) {
13661: $ip = $old_name_to_ip{$name};
13662: &logthis("Can't find $name defaulting to old $ip");
13663: } else {
13664: &logthis("Name $name no IP found");
13665: next;
13666: }
13667: } else {
13668: $ip=inet_ntoa($ip);
1.847 albertel 13669: }
13670: $name_to_ip{$name} = $ip;
13671: } else {
13672: $ip = $name_to_ip{$name};
1.653 albertel 13673: }
1.888 albertel 13674: foreach my $id (@{ $name_to_host{$name} }) {
13675: $lonid_to_ip{$id} = $ip;
13676: }
13677: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 13678: }
1.1293 raeburn 13679: unless ($nocache) {
13680: &do_cache_new('iphost','iphost',
13681: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13682: 48*60*60);
13683: }
1.869 albertel 13684:
1.847 albertel 13685: return %iphost;
1.598 albertel 13686: }
13687:
1.992 raeburn 13688: #
13689: # Given a DNS returns the loncapa host name for that DNS
13690: #
13691: sub host_from_dns {
13692: my ($dns) = @_;
13693: my @hosts;
13694: my $ip;
13695:
1.993 raeburn 13696: if (exists($name_to_ip{$dns})) {
1.992 raeburn 13697: $ip = $name_to_ip{$dns};
13698: }
13699: if (!$ip) {
13700: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13701: if (length($ip) == 4) {
13702: $ip = &IO::Socket::inet_ntoa($ip);
13703: }
13704: }
13705: if ($ip) {
13706: @hosts = get_hosts_from_ip($ip);
13707: return $hosts[0];
13708: }
13709: return undef;
1.986 foxr 13710: }
1.992 raeburn 13711:
1.1074 raeburn 13712: sub get_internet_names {
13713: my ($lonid) = @_;
13714: return if ($lonid eq '');
13715: my ($idnref,$cached)=
13716: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13717: if ($cached) {
13718: return $idnref;
13719: }
13720: my $ip = &get_host_ip($lonid);
13721: my @hosts = &get_hosts_from_ip($ip);
13722: my %iphost = &get_iphost();
13723: my (@idns,%seen);
13724: foreach my $id (@hosts) {
13725: my $dom = &host_domain($id);
13726: my $prim_id = &domain($dom,'primary');
13727: my $prim_ip = &get_host_ip($prim_id);
13728: next if ($seen{$prim_ip});
13729: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13730: foreach my $id (@{$iphost{$prim_ip}}) {
13731: my $intdom = &internet_dom($id);
13732: unless (grep(/^\Q$intdom\E$/,@idns)) {
13733: push(@idns,$intdom);
13734: }
13735: }
13736: }
13737: $seen{$prim_ip} = 1;
13738: }
1.1219 raeburn 13739: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 13740: }
13741:
1.986 foxr 13742: }
13743:
1.1079 raeburn 13744: sub all_loncaparevs {
1.1249 raeburn 13745: 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 13746: }
13747:
1.1227 raeburn 13748: # ---------------------------------------------------------- Read loncaparev table
13749: {
13750: sub load_loncaparevs {
13751: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13752: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13753: while (my $configline=<$config>) {
13754: chomp($configline);
13755: my ($hostid,$loncaparev)=split(/:/,$configline);
13756: $loncaparevs{$hostid}=$loncaparev;
13757: }
13758: close($config);
13759: }
13760: }
13761: }
13762: }
13763:
13764: # ---------------------------------------------------------- Read serverhostID table
13765: {
13766: sub load_serverhomeIDs {
13767: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13768: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13769: while (my $configline=<$config>) {
13770: chomp($configline);
13771: my ($name,$id)=split(/:/,$configline);
13772: $serverhomeIDs{$name}=$id;
13773: }
13774: close($config);
13775: }
13776: }
13777: }
13778: }
13779:
13780:
1.862 albertel 13781: BEGIN {
13782:
13783: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13784: unless ($readit) {
13785: {
13786: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13787: %perlvar = (%perlvar,%{$configvars});
13788: }
13789:
13790:
1.1 albertel 13791: # ------------------------------------------------------ Read spare server file
13792: {
1.448 albertel 13793: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 13794:
13795: while (my $configline=<$config>) {
13796: chomp($configline);
1.284 matthew 13797: if ($configline) {
1.784 albertel 13798: my ($host,$type) = split(':',$configline,2);
1.785 albertel 13799: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 13800: push(@{ $spareid{$type} }, $host);
1.1 albertel 13801: }
13802: }
1.448 albertel 13803: close($config);
1.1 albertel 13804: }
1.11 www 13805: # ------------------------------------------------------------ Read permissions
13806: {
1.448 albertel 13807: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 13808:
13809: while (my $configline=<$config>) {
1.448 albertel 13810: chomp($configline);
13811: if ($configline) {
13812: my ($role,$perm)=split(/ /,$configline);
13813: if ($perm ne '') { $pr{$role}=$perm; }
13814: }
1.11 www 13815: }
1.448 albertel 13816: close($config);
1.11 www 13817: }
13818:
13819: # -------------------------------------------- Read plain texts for permissions
13820: {
1.448 albertel 13821: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 13822:
13823: while (my $configline=<$config>) {
1.448 albertel 13824: chomp($configline);
13825: if ($configline) {
1.742 raeburn 13826: my ($short,@plain)=split(/:/,$configline);
13827: %{$prp{$short}} = ();
13828: if (@plain > 0) {
13829: $prp{$short}{'std'} = $plain[0];
13830: for (my $i=1; $i<@plain; $i++) {
13831: $prp{$short}{'alt'.$i} = $plain[$i];
13832: }
13833: }
1.448 albertel 13834: }
1.135 www 13835: }
1.448 albertel 13836: close($config);
1.135 www 13837: }
13838:
13839: # ---------------------------------------------------------- Read package table
13840: {
1.448 albertel 13841: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 13842:
13843: while (my $configline=<$config>) {
1.483 albertel 13844: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 13845: chomp($configline);
13846: my ($short,$plain)=split(/:/,$configline);
13847: my ($pack,$name)=split(/\&/,$short);
13848: if ($plain ne '') {
13849: $packagetab{$pack.'&'.$name.'&name'}=$name;
13850: $packagetab{$short}=$plain;
13851: }
1.11 www 13852: }
1.448 albertel 13853: close($config);
1.329 matthew 13854: }
13855:
1.1073 raeburn 13856: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 13857:
13858: &load_loncaparevs();
1.1073 raeburn 13859:
1.1074 raeburn 13860: # ---------------------------------------------------------- Read serverhostID table
13861:
1.1227 raeburn 13862: &load_serverhomeIDs();
13863:
13864: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 13865: {
13866: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13867: if (-e $file) {
13868: my $parser = HTML::LCParser->new($file);
13869: while (my $token = $parser->get_token()) {
13870: if ($token->[0] eq 'S') {
13871: my $item = $token->[1];
13872: my $name = $token->[2]{'name'};
13873: my $value = $token->[2]{'value'};
1.1285 raeburn 13874: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 13875: my $namematch = $token->[2]{'namematch'};
13876: if ($item eq 'parameter') {
13877: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
13878: my $release = $parser->get_text();
13879: $release =~ s/(^\s*|\s*$ )//gx;
13880: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
13881: }
13882: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 13883: my $release = $parser->get_text();
13884: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 13885: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 13886: }
13887: }
13888: }
13889: }
1.1073 raeburn 13890: }
13891:
1.1138 raeburn 13892: # ---------------------------------------------------------- Read managers table
13893: {
13894: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13895: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
13896: while (my $configline=<$config>) {
13897: chomp($configline);
13898: next if ($configline =~ /^\#/);
13899: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13900: $managerstab{$configline} = 1;
13901: }
13902: }
13903: close($config);
13904: }
13905: }
13906: }
13907:
1.329 matthew 13908: # ------------- set up temporary directory
13909: {
1.1117 foxr 13910: $tmpdir = LONCAPA::tempdir();
1.329 matthew 13911:
1.11 www 13912: }
13913:
1.794 albertel 13914: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13915: 'compress_threshold'=> 20_000,
13916: });
1.185 www 13917:
1.281 www 13918: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 13919: $dumpcount=0;
1.958 www 13920: $locknum=0;
1.22 www 13921:
1.163 harris41 13922: &logtouch();
1.672 albertel 13923: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 13924: $readit=1;
1.564 albertel 13925: {
13926: use integer;
13927: my $test=(2**32)+1;
1.568 albertel 13928: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 13929: &logthis(" Detected 64bit platform ($_64bit)");
13930: }
1.195 www 13931: }
1.1 albertel 13932: }
1.179 www 13933:
1.1 albertel 13934: 1;
1.191 harris41 13935: __END__
13936:
1.243 albertel 13937: =pod
13938:
1.191 harris41 13939: =head1 NAME
13940:
1.243 albertel 13941: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 13942:
13943: =head1 SYNOPSIS
13944:
1.243 albertel 13945: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 13946:
13947: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13948:
1.243 albertel 13949: Common parameters:
13950:
13951: =over 4
13952:
13953: =item *
13954:
13955: $uname : an internal username (if $cname expecting a course Id specifically)
13956:
13957: =item *
13958:
13959: $udom : a domain (if $cdom expecting a course's domain specifically)
13960:
13961: =item *
13962:
13963: $symb : a resource instance identifier
13964:
13965: =item *
13966:
13967: $namespace : the name of a .db file that contains the data needed or
13968: being set.
13969:
13970: =back
13971:
1.394 bowersj2 13972: =head1 OVERVIEW
1.191 harris41 13973:
1.394 bowersj2 13974: lonnet provides subroutines which interact with the
13975: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13976: about classes, users, and resources.
1.243 albertel 13977:
13978: For many of these objects you can also use this to store data about
13979: them or modify them in various ways.
1.191 harris41 13980:
1.394 bowersj2 13981: =head2 Symbs
1.191 harris41 13982:
1.394 bowersj2 13983: To identify a specific instance of a resource, LON-CAPA uses symbols
13984: or "symbs"X<symb>. These identifiers are built from the URL of the
13985: map, the resource number of the resource in the map, and the URL of
13986: the resource itself. The latter is somewhat redundant, but might help
13987: if maps change.
13988:
13989: An example is
13990:
13991: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13992:
13993: The respective map entry is
13994:
13995: <resource id="19" src="/res/msu/korte/tests/part12.problem"
13996: title="Problem 2">
13997: </resource>
13998:
13999: Symbs are used by the random number generator, as well as to store and
14000: restore data specific to a certain instance of for example a problem.
14001:
14002: =head2 Storing And Retrieving Data
14003:
14004: X<store()>X<cstore()>X<restore()>Three of the most important functions
14005: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14006: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14007: is is the non-critical message twin of cstore. These functions are for
14008: handlers to store a perl hash to a user's permanent data space in an
14009: easy manner, and to retrieve it again on another call. It is expected
14010: that a handler would use this once at the beginning to retrieve data,
14011: and then again once at the end to send only the new data back.
14012:
14013: The data is stored in the user's data directory on the user's
14014: homeserver under the ID of the course.
14015:
14016: The hash that is returned by restore will have all of the previous
14017: value for all of the elements of the hash.
14018:
14019: Example:
14020:
14021: #creating a hash
14022: my %hash;
14023: $hash{'foo'}='bar';
14024:
14025: #storing it
14026: &Apache::lonnet::cstore(\%hash);
14027:
14028: #changing a value
14029: $hash{'foo'}='notbar';
14030:
14031: #adding a new value
14032: $hash{'bar'}='foo';
14033: &Apache::lonnet::cstore(\%hash);
14034:
14035: #retrieving the hash
14036: my %history=&Apache::lonnet::restore();
14037:
14038: #print the hash
14039: foreach my $key (sort(keys(%history))) {
14040: print("\%history{$key} = $history{$key}");
14041: }
14042:
14043: Will print out:
1.191 harris41 14044:
1.394 bowersj2 14045: %history{1:foo} = bar
14046: %history{1:keys} = foo:timestamp
14047: %history{1:timestamp} = 990455579
14048: %history{2:bar} = foo
14049: %history{2:foo} = notbar
14050: %history{2:keys} = foo:bar:timestamp
14051: %history{2:timestamp} = 990455580
14052: %history{bar} = foo
14053: %history{foo} = notbar
14054: %history{timestamp} = 990455580
14055: %history{version} = 2
14056:
14057: Note that the special hash entries C<keys>, C<version> and
14058: C<timestamp> were added to the hash. C<version> will be equal to the
14059: total number of versions of the data that have been stored. The
14060: C<timestamp> attribute will be the UNIX time the hash was
14061: stored. C<keys> is available in every historical section to list which
14062: keys were added or changed at a specific historical revision of a
14063: hash.
14064:
14065: B<Warning>: do not store the hash that restore returns directly. This
14066: will cause a mess since it will restore the historical keys as if the
14067: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 14068:
1.394 bowersj2 14069: Calling convention:
1.191 harris41 14070:
1.1225 raeburn 14071: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 14072: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 14073:
1.394 bowersj2 14074: For more detailed information, see lonnet specific documentation.
1.191 harris41 14075:
1.394 bowersj2 14076: =head1 RETURN MESSAGES
1.191 harris41 14077:
1.394 bowersj2 14078: =over 4
1.191 harris41 14079:
1.394 bowersj2 14080: =item * B<con_lost>: unable to contact remote host
1.191 harris41 14081:
1.394 bowersj2 14082: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14083: when the connection is brought back up
1.191 harris41 14084:
1.394 bowersj2 14085: =item * B<con_failed>: unable to contact remote host and unable to save message
14086: for later delivery
1.191 harris41 14087:
1.967 bisitz 14088: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 14089:
1.394 bowersj2 14090: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 14091: that was requested
1.191 harris41 14092:
1.243 albertel 14093: =back
1.191 harris41 14094:
1.243 albertel 14095: =head1 PUBLIC SUBROUTINES
1.191 harris41 14096:
1.243 albertel 14097: =head2 Session Environment Functions
1.191 harris41 14098:
1.243 albertel 14099: =over 4
1.191 harris41 14100:
1.394 bowersj2 14101: =item *
14102: X<appenv()>
1.949 raeburn 14103: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 14104: the user envirnoment file, and will be restored for each access this
1.620 albertel 14105: user makes during this session, also modifies the %env for the current
1.949 raeburn 14106: process. Optional rolesarrayref - if defined contains a reference to an array
14107: of roles which are exempt from the restriction on modifying user.role entries
14108: in the user's environment.db and in %env.
1.191 harris41 14109:
14110: =item *
1.394 bowersj2 14111: X<delenv()>
1.987 raeburn 14112: B<delenv($delthis,$regexp)>: removes all items from the session
14113: environment file that begin with $delthis. If the
14114: optional second arg - $regexp - is true, $delthis is treated as a
14115: regular expression, otherwise \Q$delthis\E is used.
14116: The values are also deleted from the current processes %env.
1.191 harris41 14117:
1.795 albertel 14118: =item * get_env_multiple($name)
14119:
14120: gets $name from the %env hash, it seemlessly handles the cases where multiple
14121: values may be defined and end up as an array ref.
14122:
14123: returns an array of values
14124:
1.243 albertel 14125: =back
14126:
14127: =head2 User Information
1.191 harris41 14128:
1.243 albertel 14129: =over 4
1.191 harris41 14130:
14131: =item *
1.394 bowersj2 14132: X<queryauthenticate()>
14133: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 14134: authentication scheme
14135:
14136: =item *
1.394 bowersj2 14137: X<authenticate()>
1.1073 raeburn 14138: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 14139: authenticate user from domain's lib servers (first use the current
14140: one). C<$upass> should be the users password.
1.1073 raeburn 14141: $checkdefauth is optional (value is 1 if a check should be made to
14142: authenticate user using default authentication method, and allow
14143: account creation if username does not have account in the domain).
14144: $clientcancheckhost is optional (value is 1 if checking whether the
14145: server can host will occur on the client side in lonauth.pm).
1.191 harris41 14146:
14147: =item *
1.394 bowersj2 14148: X<homeserver()>
14149: B<homeserver($uname,$udom)>: find the server which has
14150: the user's directory and files (there must be only one), this caches
14151: the answer, and also caches if there is a borken connection.
1.191 harris41 14152:
14153: =item *
1.394 bowersj2 14154: X<idget()>
1.1300 raeburn 14155: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
14156: a list of student/employee IDs or clicker IDs
14157: (student/employee IDs are a unique resource in a domain, there must be
14158: only 1 ID per username, and only 1 username per ID in a specific domain).
14159: clickerIDs are not necessarily unique, as students might share clickers.
14160: (returns hash: id=>name,id=>name)
1.191 harris41 14161:
14162: =item *
1.394 bowersj2 14163: X<idrget()>
14164: B<idrget($udom,@unames)>: find the IDs behind a list of
14165: usernames (returns hash: name=>id,name=>id)
1.191 harris41 14166:
14167: =item *
1.394 bowersj2 14168: X<idput()>
1.1300 raeburn 14169: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
14170: names and associated student/employee IDs or clicker IDs.
14171:
14172: =item *
14173: X<iddel()>
14174: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
14175: student/employee ID or clicker ID username look-ups from domain.
14176: The homeserver ($uhome) and namespace ($namespace) are optional.
14177: If no $uhome is provided, it will be determined usig &homeserver()
14178: for each user. If no $namespace is provided, the default is ids.
14179:
14180: =item *
14181: X<updateclickers()>
14182: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
14183: clicker ID-to-username look-ups in clickers.db on library server.
14184: Permitted actions are add or del (i.e., add or delete). The
14185: clickers.db contains clickerID as keys (escaped), and each corresponding
14186: value is an escaped comma-separated list of usernames (for whom the
14187: library server is the homeserver), who registered that particular ID.
14188: If $critical is true, the update will be sent via &critical, otherwise
14189: &reply() will be used.
1.191 harris41 14190:
14191: =item *
1.394 bowersj2 14192: X<rolesinit()>
1.1169 droeschl 14193: B<rolesinit($udom,$username)>: get user privileges.
14194: returns user role, first access and timer interval hashes
1.243 albertel 14195:
14196: =item *
1.1171 droeschl 14197: X<privileged()>
14198: B<privileged($username,$domain)>: returns a true if user has a
14199: privileged and active role (i.e. su or dc), false otherwise.
14200:
14201: =item *
1.551 albertel 14202: X<getsection()>
14203: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 14204: course $cname, return section name/number or '' for "not in course"
14205: and '-1' for "no section"
14206:
14207: =item *
1.394 bowersj2 14208: X<userenvironment()>
14209: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 14210: passed in @what from the requested user's environment, returns a hash
14211:
1.858 raeburn 14212: =item *
14213: X<userlog_query()>
1.859 albertel 14214: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14215: activity.log file. %filters defines filters applied when parsing the
14216: log file. These can be start or end timestamps, or the type of action
14217: - log to look for Login or Logout events, check for Checkin or
14218: Checkout, role for role selection. The response is in the form
14219: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
14220: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 14221:
1.243 albertel 14222: =back
14223:
14224: =head2 User Roles
14225:
14226: =over 4
14227:
14228: =item *
14229:
1.1284 raeburn 14230: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14231: returns codes for allowed actions.
14232:
14233: The first argument is required, all others are optional.
14234:
14235: $priv is the privilege being checked.
14236: $uri contains additional information about what is being checked for access (e.g.,
14237: URL, course ID etc.).
14238: $symb is the unique resource instance identifier in a course; if needed,
14239: but not provided, it will be retrieved via a call to &symbread().
14240: $role is the role for which a priv is being checked (only used if priv is evb).
14241: $clientip is the user's IP address (only used when checking for access to portfolio
14242: files).
14243: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14244: prevents recursive calls to &allowed.
14245:
1.243 albertel 14246: F: full access
14247: U,I,K: authentication modes (cxx only)
14248: '': forbidden
14249: 1: user needs to choose course
14250: 2: browse allowed
1.766 albertel 14251: A: passphrase authentication needed
1.1284 raeburn 14252: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 14253:
14254: =item *
14255:
1.1192 raeburn 14256: constructaccess($url,$setpriv) : check for access to construction space URL
14257:
14258: See if the owner domain and name in the URL match those in the
14259: expected environment. If so, return three element list
14260: ($ownername,$ownerdomain,$ownerhome).
14261:
14262: Otherwise return the null string.
14263:
14264: If second argument 'setpriv' is true, it assigns the privileges,
14265: and returns the same three element list, unless the owner has
14266: blocked "ad hoc" Domain Coordinator access to the Author Space,
14267: in which case the null string is returned.
14268:
14269: =item *
14270:
1.1326 raeburn 14271: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14272: define a custom role rolename set privileges in format of lonTabs/roles.tab
14273: for system, domain, and course level. $uname and $udom are optional (current
14274: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 14275:
14276: =item *
14277:
1.988 raeburn 14278: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
14279: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 14280: $type is Course (default) or Community.
1.988 raeburn 14281: If $forcedefault evaluates to true, text returned will be default
14282: text for $type. Otherwise, if this is a course, the text returned
14283: will be a custom name for the role (if defined in the course's
14284: environment). If no custom name is defined the default is returned.
14285:
1.832 raeburn 14286: =item *
14287:
1.1219 raeburn 14288: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 14289: All arguments are optional. Returns a hash of a roles, either for
14290: co-author/assistant author roles for a user's Construction Space
1.906 albertel 14291: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 14292: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14293: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14294: For each key, value is set to colon-separated start and end times for
14295: the role. If no username and domain are specified, will default to
1.934 raeburn 14296: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 14297: of role statuses (active, future or previous), roles
14298: (e.g., cc,in, st etc.) and domains of the roles which can be used
14299: to restrict the list of roles reported. If no array ref is
14300: provided for types, will default to return only active roles.
1.834 albertel 14301:
1.1195 raeburn 14302: =item *
14303:
14304: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 14305: user: $uname:$udom has a role in the course: $cdom_$cnum.
14306:
14307: Additional optional arguments are: $type (if role checking is to be restricted
14308: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 14309: available roles) or future (roles available in the future), and
14310: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 14311: have active Domain Coordinator role in course's domain or in additional
14312: domains (specified in 'Domains to check for privileged users' in course
14313: environment -- set via: Course Settings -> Classlists and staff listing).
14314:
14315: =item *
14316:
14317: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14318: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14319: $possdomains and $possroles are optional array refs -- to domains to check and
14320: roles to check. If $possdomains is not specified, a dump will be done of the
14321: users' roles.db to check for a dc or su role in any domain. This can be
14322: time consuming if &privileged is called repeatedly (e.g., when displaying a
14323: classlist), so in such cases, supplying a $possdomains array is preferred, as
14324: this then allows &privileged_by_domain() to be used, which caches the identity
14325: of privileged users, eliminating the need for repeated calls to &dump().
14326:
14327: =item *
14328:
14329: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14330: where the outer hash keys are domains specified in the $possdomains array ref,
14331: next inner hash keys are privileged roles specified in the $roles array ref,
14332: and the innermost hash contains key = value pairs for username:domain = end:start
14333: for active or future "privileged" users with that role in that domain. To avoid
14334: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14335: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 14336:
1.243 albertel 14337: =back
14338:
14339: =head2 User Modification
14340:
14341: =over 4
14342:
14343: =item *
14344:
1.957 raeburn 14345: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 14346: user for the level given by URL. Optional start and end dates (leave empty
14347: string or zero for "no date")
1.191 harris41 14348:
14349: =item *
14350:
1.243 albertel 14351: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14352: change a users, password, possible return values are: ok,
14353: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14354: refused
1.191 harris41 14355:
14356: =item *
14357:
1.243 albertel 14358: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 14359:
14360: =item *
14361:
1.1058 raeburn 14362: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14363: $forceid,$desiredhome,$email,$inststatus,$candelete) :
14364:
14365: will update user information (firstname,middlename,lastname,generation,
14366: permanentemail), and if forceid is true, student/employee ID also.
14367: A user's institutional affiliation(s) can also be updated.
14368: User information fields will not be overwritten with empty entries
14369: unless the field is included in the $candelete array reference.
14370: This array is included when a single user is modified via "Manage Users",
14371: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 14372:
14373: =item *
14374:
1.286 matthew 14375: modifystudent
14376:
1.957 raeburn 14377: modify a student's enrollment and identification information.
1.1235 raeburn 14378: The course id is resolved based on the current user's environment.
14379: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 14380: associated with a course.
14381:
1.297 matthew 14382: This call is essentially a wrapper for lonnet::modifyuser and
14383: lonnet::modify_student_enrollment
1.286 matthew 14384:
14385: Inputs:
14386:
14387: =over 4
14388:
1.957 raeburn 14389: =item B<$udom> Student's loncapa domain
1.286 matthew 14390:
1.957 raeburn 14391: =item B<$uname> Student's loncapa login name
1.286 matthew 14392:
1.964 bisitz 14393: =item B<$uid> Student/Employee ID
1.286 matthew 14394:
1.957 raeburn 14395: =item B<$umode> Student's authentication mode
1.286 matthew 14396:
1.957 raeburn 14397: =item B<$upass> Student's password
1.286 matthew 14398:
1.957 raeburn 14399: =item B<$first> Student's first name
1.286 matthew 14400:
1.957 raeburn 14401: =item B<$middle> Student's middle name
1.286 matthew 14402:
1.957 raeburn 14403: =item B<$last> Student's last name
1.286 matthew 14404:
1.957 raeburn 14405: =item B<$gene> Student's generation
1.286 matthew 14406:
1.957 raeburn 14407: =item B<$usec> Student's section in course
1.286 matthew 14408:
14409: =item B<$end> Unix time of the roles expiration
14410:
14411: =item B<$start> Unix time of the roles start date
14412:
14413: =item B<$forceid> If defined, allow $uid to be changed
14414:
14415: =item B<$desiredhome> server to use as home server for student
14416:
1.957 raeburn 14417: =item B<$email> Student's permanent e-mail address
14418:
14419: =item B<$type> Type of enrollment (auto or manual)
14420:
1.963 raeburn 14421: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
14422:
14423: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 14424:
1.963 raeburn 14425: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 14426:
1.963 raeburn 14427: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 14428:
1.1216 raeburn 14429: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14430:
14431: =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 14432:
1.286 matthew 14433: =back
1.297 matthew 14434:
14435: =item *
14436:
14437: modify_student_enrollment
14438:
1.1235 raeburn 14439: Change a student's enrollment status in a class. The environment variable
1.297 matthew 14440: 'role.request.course' must be defined for this function to proceed.
14441:
14442: Inputs:
14443:
14444: =over 4
14445:
1.1235 raeburn 14446: =item $udom, student's domain
1.297 matthew 14447:
1.1235 raeburn 14448: =item $uname, student's name
1.297 matthew 14449:
1.1235 raeburn 14450: =item $uid, student's user id
1.297 matthew 14451:
1.1235 raeburn 14452: =item $first, student's first name
1.297 matthew 14453:
14454: =item $middle
14455:
14456: =item $last
14457:
14458: =item $gene
14459:
14460: =item $usec
14461:
14462: =item $end
14463:
14464: =item $start
14465:
1.957 raeburn 14466: =item $type
14467:
14468: =item $locktype
14469:
14470: =item $cid
14471:
14472: =item $selfenroll
14473:
14474: =item $context
14475:
1.1216 raeburn 14476: =item $credits, number of credits student will earn from this class
14477:
1.1314 raeburn 14478: =item $instsec, institutional course section code for student
14479:
1.297 matthew 14480: =back
14481:
1.191 harris41 14482:
14483: =item *
14484:
1.243 albertel 14485: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14486: custom role; give a custom role to a user for the level given by URL. Specify
14487: name and domain of role author, and role name
1.191 harris41 14488:
14489: =item *
14490:
1.243 albertel 14491: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 14492:
14493: =item *
14494:
1.243 albertel 14495: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14496:
14497: =back
14498:
14499: =head2 Course Infomation
14500:
14501: =over 4
1.191 harris41 14502:
14503: =item *
14504:
1.1118 foxr 14505: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 14506: specified course id, including all environment settings for the
14507: course, the description of the course will be in the hash under the
14508: key 'description'
1.191 harris41 14509:
1.1118 foxr 14510: $options is an optional parameter that if supplied is a hash reference that controls
14511: what how this function works. It has the following key/values:
14512:
14513: =over 4
14514:
14515: =item freshen_cache
14516:
14517: If defined, and the environment cache for the course is valid, it is
14518: returned in the returned hash.
14519:
14520: =item one_time
14521:
14522: If defined, the last cache time is set to _now_
14523:
14524: =item user
14525:
14526: If defined, the supplied username is used instead of the current user.
14527:
14528:
14529: =back
14530:
1.191 harris41 14531: =item *
14532:
1.624 albertel 14533: resdata($name,$domain,$type,@which) : request for current parameter
14534: setting for a specific $type, where $type is either 'course' or 'user',
14535: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 14536: answers for 10 minutes.
1.243 albertel 14537:
1.877 foxr 14538: =item *
14539:
14540: get_courseresdata($courseid, $domain) : dump the entire course resource
14541: data base, returning a hash that is keyed by the resource name and has
14542: values that are the resource value. I believe that the timestamps and
14543: versions are also returned.
14544:
1.1236 raeburn 14545: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14546: supplemental content area. This routine caches the number of files for
14547: 10 minutes.
14548:
1.243 albertel 14549: =back
14550:
14551: =head2 Course Modification
14552:
14553: =over 4
1.191 harris41 14554:
14555: =item *
14556:
1.243 albertel 14557: writecoursepref($courseid,%prefs) : write preferences (environment
14558: database) for a course
1.191 harris41 14559:
14560: =item *
14561:
1.1011 raeburn 14562: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14563:
14564: =item *
14565:
1.1038 raeburn 14566: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 14567:
1.1167 droeschl 14568: =item *
14569:
14570: is_course($courseid), is_course($cdom, $cnum)
14571:
14572: Accepts either a combined $courseid (in the form of domain_courseid) or the
14573: two component version $cdom, $cnum. It checks if the specified course exists.
14574:
14575: Returns:
14576: undef if the course doesn't exist, otherwise
14577: in scalar context the combined courseid.
14578: in list context the two components of the course identifier, domain and
14579: courseid.
14580:
1.243 albertel 14581: =back
14582:
14583: =head2 Resource Subroutines
14584:
14585: =over 4
1.191 harris41 14586:
14587: =item *
14588:
1.243 albertel 14589: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 14590:
14591: =item *
14592:
1.243 albertel 14593: repcopy($filename) : subscribes to the requested file, and attempts to
14594: replicate from the owning library server, Might return
1.607 raeburn 14595: 'unavailable', 'not_found', 'forbidden', 'ok', or
14596: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 14597: resource. Expects the local filesystem pathname
14598: (/home/httpd/html/res/....)
14599:
14600: =back
14601:
14602: =head2 Resource Information
14603:
14604: =over 4
1.191 harris41 14605:
14606: =item *
14607:
1.1228 raeburn 14608: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
14609: and returns the value of a variety of different possible values,
14610: $varname should be a request string, and the other parameters can be
14611: used to specify who and what one is asking about. Ordinarily, $cid
14612: does not need to be specified, as it is retrived from
14613: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14614: within lonuserstate::loadmap() when initializing a course, before
14615: $env{'request.course.id'} has been set, so it needs to be provided
14616: in that one case.
1.243 albertel 14617:
14618: Possible values for $varname are environment.lastname (or other item
14619: from the envirnment hash), user.name (or someother aspect about the
14620: user), resource.0.maxtries (or some other part and parameter of a
14621: resource)
1.204 albertel 14622:
14623: =item *
14624:
1.243 albertel 14625: directcondval($number) : get current value of a condition; reads from a state
14626: string
1.204 albertel 14627:
14628: =item *
14629:
1.243 albertel 14630: condval($condidx) : value of condition index based on state
1.204 albertel 14631:
14632: =item *
14633:
1.243 albertel 14634: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14635: resource's metadata, $what should be either a specific key, or either
14636: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14637: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14638:
14639: this function automatically caches all requests
1.191 harris41 14640:
14641: =item *
14642:
1.243 albertel 14643: metadata_query($query,$custom,$customshow) : make a metadata query against the
14644: network of library servers; returns file handle of where SQL and regex results
14645: will be stored for query
1.191 harris41 14646:
14647: =item *
14648:
1.1282 raeburn 14649: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14650: return symbolic list entry (all arguments optional).
14651:
14652: Args: filename is the filename (including path) for the file for which a symb
14653: is required; donotrecurse, if true will prevent calls to allowed() being made
14654: to check access status if more than one resource was found in the bighash
14655: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14656: a randompick); ignorecachednull, if true will prevent a symb of '' being
14657: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14658: cause possible symbs to be checked to determine if they are subject to content
14659: blocking, if so they will not be included as possible symbs; possibles is a
14660: ref to a hash, which, as a side effect, will be populated with all possible
14661: symbs (content blocking not tested).
14662:
1.243 albertel 14663: returns the data handle
1.191 harris41 14664:
14665: =item *
14666:
1.1190 raeburn 14667: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
14668: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 14669: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 14670: on failure, user must be in a course, as it assumes the existence of
14671: the course initial hash, and uses $env('request.course.id'}. The third
14672: arg is an optional reference to a scalar. If this arg is passed in the
14673: call to symbverify, it will be set to 1 if the symb has been set to be
14674: encrypted; otherwise it will be null.
1.191 harris41 14675:
14676: =item *
14677:
1.243 albertel 14678: symbclean($symb) : removes versions numbers from a symb, returns the
14679: cleaned symb
1.191 harris41 14680:
14681: =item *
14682:
1.243 albertel 14683: is_on_map($uri) : checks if the $uri is somewhere on the current
14684: course map, user must be in a course for it to work.
1.191 harris41 14685:
14686: =item *
14687:
1.243 albertel 14688: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 14689:
14690: =item *
14691:
1.243 albertel 14692: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14693: a random seed, all arguments are optional, if they aren't sent it uses the
14694: environment to derive them. Note: if symb isn't sent and it can't get one
14695: from &symbread it will use the current time as its return value
1.191 harris41 14696:
14697: =item *
14698:
1.243 albertel 14699: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14700: unfakeable, receipt
1.191 harris41 14701:
14702: =item *
14703:
1.620 albertel 14704: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 14705:
14706: =item *
14707:
1.243 albertel 14708: countacc($url) : count the number of accesses to a given URL
1.191 harris41 14709:
14710: =item *
14711:
1.243 albertel 14712: 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 14713:
14714: =item *
14715:
1.243 albertel 14716: 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 14717:
14718: =item *
14719:
1.243 albertel 14720: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 14721:
14722: =item *
14723:
1.243 albertel 14724: devalidate($symb) : devalidate temporary spreadsheet calculations,
14725: forcing spreadsheet to reevaluate the resource scores next time.
14726:
1.1195 raeburn 14727: =item *
14728:
1.1196 raeburn 14729: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14730: when viewing in course context.
1.1195 raeburn 14731:
1.1196 raeburn 14732: input: six args -- filename (decluttered), course number, course domain,
14733: url, symb (if registered) and group (if this is a
14734: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 14735:
1.1196 raeburn 14736: output: array of five scalars --
1.1195 raeburn 14737: $cfile -- url for file editing if editable on current server
14738: $home -- homeserver of resource (i.e., for author if published,
14739: or course if uploaded.).
14740: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 14741: $forceedit -- 1 if icon/link should be to go to edit mode
14742: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 14743:
14744: =item *
14745:
14746: is_course_upload($file,$cnum,$cdom)
14747:
14748: Used in course context to determine if current file was uploaded to
14749: the course (i.e., would be found in /userfiles/docs on the course's
14750: homeserver.
14751:
14752: input: 3 args -- filename (decluttered), course number and course domain.
14753: output: boolean -- 1 if file was uploaded.
14754:
1.243 albertel 14755: =back
14756:
14757: =head2 Storing/Retreiving Data
14758:
14759: =over 4
1.191 harris41 14760:
14761: =item *
14762:
1.1269 raeburn 14763: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14764: permanently for this url; hashref needs to be given and should be a \%hashname;
14765: the remaining args aren't required and if they aren't passed or are '' they will
14766: be derived from the env (with the exception of $laststore, which is an
14767: optional arg used when a user's submission is stored in grading).
14768: $laststore is $version=$timestamp, where $version is the most recent version
14769: number retrieved for the corresponding $symb in the $namespace db file, and
14770: $timestamp is the timestamp for that transaction (UNIX time).
14771: $laststore is currently only passed when cstore() is called by
14772: structuretags::finalize_storage().
1.191 harris41 14773:
14774: =item *
14775:
1.1269 raeburn 14776: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14777: but uses critical subroutine
1.191 harris41 14778:
14779: =item *
14780:
1.243 albertel 14781: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14782: all args are optional
1.191 harris41 14783:
14784: =item *
14785:
1.717 albertel 14786: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14787: dumps the complete (or key matching regexp) namespace into a hash
14788: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14789: normally &store()ed into
14790:
14791: $range should be either an integer '100' (give me the first 100
14792: matching records)
14793: or be two integers sperated by a - with no spaces
14794: '30-50' (give me the 30th through the 50th matching
14795: records)
14796:
14797:
14798: =item *
14799:
1.1269 raeburn 14800: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 14801: replaces a &store() version of data with a replacement set of data
14802: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 14803: reference. If $tolog is true, the transaction is logged in the courselog
14804: with an action=PUTSTORE.
1.717 albertel 14805:
14806: =item *
14807:
1.243 albertel 14808: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14809: works very similar to store/cstore, but all data is stored in a
14810: temporary location and can be reset using tmpreset, $storehash should
14811: be a hash reference, returns nothing on success
1.191 harris41 14812:
14813: =item *
14814:
1.243 albertel 14815: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14816: similar to restore, but all data is stored in a temporary location and
14817: can be reset using tmpreset. Returns a hash of values on success,
14818: error string otherwise.
1.191 harris41 14819:
14820: =item *
14821:
1.243 albertel 14822: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14823: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 14824:
14825: =item *
14826:
1.243 albertel 14827: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14828: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 14829:
14830: =item *
14831:
1.243 albertel 14832: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14833: namesp ($udom and $uname are optional)
1.191 harris41 14834:
14835: =item *
14836:
1.702 albertel 14837: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 14838: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 14839: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 14840:
1.702 albertel 14841: $range should be either an integer '100' (give me the first 100
14842: matching records)
14843: or be two integers sperated by a - with no spaces
14844: '30-50' (give me the 30th through the 50th matching
14845: records)
1.449 matthew 14846: =item *
14847:
14848: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14849: $store can be a scalar, an array reference, or if the amount to be
14850: incremented is > 1, a hash reference.
14851:
14852: ($udom and $uname are optional)
1.191 harris41 14853:
14854: =item *
14855:
1.243 albertel 14856: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14857: ($udom and $uname are optional)
1.191 harris41 14858:
14859: =item *
14860:
1.243 albertel 14861: cput($namespace,$storehash,$udom,$uname) : critical put
14862: ($udom and $uname are optional)
1.191 harris41 14863:
14864: =item *
14865:
1.748 albertel 14866: newput($namespace,$storehash,$udom,$uname) :
14867:
14868: Attempts to store the items in the $storehash, but only if they don't
14869: currently exist, if this succeeds you can be certain that you have
14870: successfully created a new key value pair in the $namespace db.
14871:
14872:
14873: Args:
14874: $namespace: name of database to store values to
14875: $storehash: hashref to store to the db
14876: $udom: (optional) domain of user containing the db
14877: $uname: (optional) name of user caontaining the db
14878:
14879: Returns:
14880: 'ok' -> succeeded in storing all keys of $storehash
14881: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14882: least <key> already existed in the db (other
14883: requested keys may also already exist)
1.967 bisitz 14884: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 14885: 'con_lost' -> unable to contact request server
14886: 'refused' -> action was not allowed by remote machine
14887:
14888:
14889: =item *
14890:
1.243 albertel 14891: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14892: reference filled in from namesp (encrypts the return communication)
14893: ($udom and $uname are optional)
1.191 harris41 14894:
14895: =item *
14896:
1.243 albertel 14897: log($udom,$name,$home,$message) : write to permanent log for user; use
14898: critical subroutine
14899:
1.806 raeburn 14900: =item *
14901:
1.860 raeburn 14902: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14903: array reference filled in from namespace found in domain level on either
14904: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 14905:
14906: =item *
14907:
1.860 raeburn 14908: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14909: domain level either on specified domain server ($uhome) or primary domain
14910: server ($udom and $uhome are optional)
1.806 raeburn 14911:
1.943 raeburn 14912: =item *
14913:
1.1240 raeburn 14914: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14915: for: authentication, language, quotas, timezone, date locale, and portal URL in
14916: the target domain.
14917:
14918: May also include additional key => value pairs for the following groups:
14919:
14920: =over
14921:
14922: =item
14923: disk quotas (MB allocated by default to portfolios and authoring spaces).
14924:
14925: =over
14926:
14927: =item defaultquota, authorquota
14928:
14929: =back
14930:
14931: =item
14932: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14933: portfolio for users).
14934:
14935: =over
14936:
14937: =item
14938: aboutme, blog, webdav, portfolio
14939:
14940: =back
14941:
14942: =item
14943: requestcourses: ability to request courses, and how requests are processed.
14944:
14945: =over
14946:
14947: =item
1.1305 raeburn 14948: official, unofficial, community, textbook, placement
1.1240 raeburn 14949:
14950: =back
14951:
14952: =item
14953: inststatus: types of institutional affiliation, and order in which they are displayed.
14954:
14955: =over
14956:
14957: =item
1.1256 raeburn 14958: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 14959:
14960: =back
14961:
14962: =item
14963: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14964: for course's uploaded content.
14965:
14966: =over
14967:
14968: =item
1.1246 raeburn 14969: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 14970: communityquota, textbookquota, placementquota
1.1240 raeburn 14971:
14972: =back
14973:
14974: =item
14975: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14976: on your servers.
14977:
14978: =over
14979:
14980: =item
14981: remotesessions, hostedsessions
14982:
14983: =back
14984:
14985: =back
14986:
14987: In cases where a domain coordinator has never used the "Set Domain Configuration"
14988: utility to create a configuration.db file on a domain's primary library server
14989: only the following domain defaults: auth_def, auth_arg_def, lang_def
14990: -- corresponding values are authentication type (internal, krb4, krb5,
14991: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
14992: will be available. Values are retrieved from cache (if current), unless the
14993: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14994: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14995:
14996: Typical usage:
1.943 raeburn 14997:
1.1240 raeburn 14998: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 14999:
1.243 albertel 15000: =back
15001:
15002: =head2 Network Status Functions
15003:
15004: =over 4
1.191 harris41 15005:
15006: =item *
15007:
1.1137 raeburn 15008: dirlist() : return directory list based on URI (first arg).
15009:
15010: Inputs: 1 required, 5 optional.
15011:
15012: =over
15013:
15014: =item
15015: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15016:
15017: =item
15018: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
15019:
15020: =item
15021: $username - username of user/course to be listed. Extracted from $uri if absent.
15022:
15023: =item
15024: $getpropath - boolean: 1 if prepend path using &propath().
15025:
15026: =item
15027: $getuserdir - boolean: 1 if prepend path for "userfiles".
15028:
15029: =item
15030: $alternateRoot - path to prepend in place of path from $uri.
15031:
15032: =back
15033:
15034: Returns: Array of up to two items.
15035:
15036: =over
15037:
15038: a reference to an array of files/subdirectories
15039:
15040: =over
15041:
15042: Each element in the array of files/subdirectories is a & separated list of
15043: item name and the result of running stat on the item. If dirlist was requested
15044: for a file instead of a directory, the item name will be ''. For a directory
15045: listing, if the item is a metadata file, the element will end &N&M
15046: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15047: default copyright set (1).
15048:
15049: =back
15050:
15051: a scalar containing error condition (if encountered).
15052:
15053: =over
15054:
15055: =item
15056: no_host (no homeserver identified for $username:$domain).
15057:
15058: =item
15059: no_such_host (server contacted for listing not identified as valid host).
15060:
15061: =item
15062: con_lost (connection to remote server failed).
15063:
15064: =item
15065: refused (invalid $username:$domain received on lond side).
15066:
15067: =item
15068: no_such_dir (directory at specified path on lond side does not exist).
15069:
15070: =item
15071: empty (directory at specified path on lond side is empty).
15072:
15073: =over
15074:
15075: This is currently not encountered because the &ls3, &ls2,
15076: &ls (_handler) routines on the lond side do not filter out
15077: . and .. from a directory listing.
15078:
15079: =back
15080:
15081: =back
15082:
15083: =back
1.191 harris41 15084:
15085: =item *
15086:
1.243 albertel 15087: spareserver() : find server with least workload from spare.tab
15088:
1.986 foxr 15089:
15090: =item *
15091:
15092: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15093: if there is no corresponding loncapa host.
15094:
1.243 albertel 15095: =back
15096:
1.986 foxr 15097:
1.243 albertel 15098: =head2 Apache Request
15099:
15100: =over 4
1.191 harris41 15101:
15102: =item *
15103:
1.243 albertel 15104: ssi($url,%hash) : server side include, does a complete request cycle on url to
15105: localhost, posts hash
15106:
15107: =back
15108:
15109: =head2 Data to String to Data
15110:
15111: =over 4
1.191 harris41 15112:
15113: =item *
15114:
1.243 albertel 15115: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15116: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 15117:
15118: =item *
15119:
1.243 albertel 15120: hashref2str($hashref) : convert a hashref into a string complete with
15121: escaping and '=' and '&' separators, supports elements that are
15122: arrayrefs and hashrefs
1.191 harris41 15123:
15124: =item *
15125:
1.243 albertel 15126: arrayref2str($arrayref) : convert an arrayref into a string complete
15127: with escaping and '&' separators, supports elements that are arrayrefs
15128: and hashrefs
1.191 harris41 15129:
15130: =item *
15131:
1.243 albertel 15132: str2hash($string) : convert string to hash using unescaping and
15133: splitting on '=' and '&', supports elements that are arrayrefs and
15134: hashrefs
1.191 harris41 15135:
15136: =item *
15137:
1.243 albertel 15138: str2array($string) : convert string to hash using unescaping and
15139: splitting on '&', supports elements that are arrayrefs and hashrefs
15140:
15141: =back
15142:
15143: =head2 Logging Routines
15144:
15145:
15146: These routines allow one to make log messages in the lonnet.log and
15147: lonnet.perm logfiles.
1.191 harris41 15148:
1.1119 foxr 15149: =over 4
15150:
1.191 harris41 15151: =item *
15152:
1.243 albertel 15153: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 15154:
15155: =item *
15156:
1.243 albertel 15157: logthis() : append message to the normal lonnet.log file, it gets
15158: preiodically rolled over and deleted.
1.191 harris41 15159:
15160: =item *
15161:
1.243 albertel 15162: logperm() : append a permanent message to lonnet.perm.log, this log
15163: file never gets deleted by any automated portion of the system, only
15164: messages of critical importance should go in here.
15165:
1.1119 foxr 15166:
1.243 albertel 15167: =back
15168:
15169: =head2 General File Helper Routines
15170:
15171: =over 4
1.191 harris41 15172:
15173: =item *
15174:
1.481 raeburn 15175: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15176: (a) files in /uploaded
15177: (i) If a local copy of the file exists -
15178: compares modification date of local copy with last-modified date for
15179: definitive version stored on home server for course. If local copy is
15180: stale, requests a new version from the home server and stores it.
15181: If the original has been removed from the home server, then local copy
15182: is unlinked.
15183: (ii) If local copy does not exist -
15184: requests the file from the home server and stores it.
15185:
15186: If $caller is 'uploadrep':
15187: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15188: for request for files originally uploaded via DOCS.
15189: - returns 'ok' if fresh local copy now available, -1 otherwise.
15190:
15191: Otherwise:
15192: This indicates a call from the content generation phase of the request.
15193: - returns the entire contents of the file or -1.
15194:
15195: (b) files in /res
15196: - returns the entire contents of a file or -1;
15197: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 15198:
1.712 albertel 15199:
15200: =item *
15201:
15202: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15203: reference
15204:
15205: returns either a stat() list of data about the file or an empty list
15206: if the file doesn't exist or couldn't find out about it (connection
15207: problems or user unknown)
15208:
1.191 harris41 15209: =item *
15210:
1.243 albertel 15211: filelocation($dir,$file) : returns file system location of a file
15212: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15213: directory that relative $file lookups are to looked in ($dir of /a/dir
15214: and a file of ../bob will become /a/bob)
1.191 harris41 15215:
15216: =item *
15217:
15218: hreflocation($dir,$file) : returns file system location or a URL; same as
15219: filelocation except for hrefs
15220:
15221: =item *
15222:
1.1261 raeburn 15223: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15224: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 15225:
1.243 albertel 15226: =back
15227:
1.608 albertel 15228: =head2 Usererfile file routines (/uploaded*)
15229:
15230: =over 4
15231:
15232: =item *
15233:
15234: userfileupload(): main rotine for putting a file in a user or course's
15235: filespace, arguments are,
15236:
1.620 albertel 15237: formname - required - this is the name of the element in $env where the
1.608 albertel 15238: filename, and the contents of the file to create/modifed exist
1.620 albertel 15239: the filename is in $env{'form.'.$formname.'.filename'} and the
15240: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 15241: context - if coursedoc, store the file in the course of the active role
15242: of the current user;
15243: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15244: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 15245: subdir - required - subdirectory to put the file in under ../userfiles/
15246: if undefined, it will be placed in "unknown"
15247:
15248: (This routine calls clean_filename() to remove any dangerous
15249: characters from the filename, and then calls finuserfileupload() to
15250: complete the transaction)
15251:
15252: returns either the url of the uploaded file (/uploaded/....) if successful
15253: and /adm/notfound.html if unsuccessful
15254:
15255: =item *
15256:
15257: clean_filename(): routine for cleaing a filename up for storage in
15258: userfile space, argument is:
15259:
15260: filename - proposed filename
15261:
15262: returns: the new clean filename
15263:
15264: =item *
15265:
1.1090 raeburn 15266: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 15267: userspace, probably shouldn't be called directly
15268:
15269: docuname: username or courseid of destination for the file
15270: docudom: domain of user/course of destination for the file
15271: formname: same as for userfileupload()
1.1090 raeburn 15272: fname: filename (including subdirectories) for the file
15273: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15274: allfiles: reference to hash used to store objects found by parser
15275: codebase: reference to hash used for codebases of java objects found by parser
15276: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15277: thumbheight: height (pixels) of thumbnail to be created for uploaded image
15278: resizewidth: width to be used to resize image using resizeImage from ImageMagick
15279: resizeheight: height to be used to resize image using resizeImage from ImageMagick
15280: context: if 'overwrite', will move the uploaded file from its temporary location to
15281: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 15282: mimetype: reference to scalar to accommodate mime type determined
15283: from File::MMagic if $parser = parse.
1.608 albertel 15284:
15285: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 15286: and /adm/notfound.html if unsuccessful (or an error message if context
15287: was 'overwrite').
15288:
1.608 albertel 15289:
15290: =item *
15291:
15292: renameuserfile(): renames an existing userfile to a new name
15293:
15294: Args:
15295: docuname: username or courseid of destination for the file
15296: docudom: domain of user/course of destination for the file
15297: old: current file name (including any subdirs under userfiles)
15298: new: desired file name (including any subdirs under userfiles)
15299:
15300: =item *
15301:
15302: mkdiruserfile(): creates a directory is a userfiles dir
15303:
15304: Args:
15305: docuname: username or courseid of destination for the file
15306: docudom: domain of user/course of destination for the file
15307: dir: dir to create (including any subdirs under userfiles)
15308:
15309: =item *
15310:
15311: removeuserfile(): removes a file that exists in userfiles
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: fname: filname to delete (including any subdirs under userfiles)
15317:
15318: =item *
15319:
15320: removeuploadedurl(): convience function for removeuserfile()
15321:
15322: Args:
15323: url: a full /uploaded/... url to delete
15324:
1.747 albertel 15325: =item *
15326:
15327: get_portfile_permissions():
15328: Args:
15329: domain: domain of user or course contain the portfolio files
15330: user: name of user or num of course contain the portfolio files
15331: Returns:
15332: hashref of a dump of the proper file_permissions.db
15333:
15334:
15335: =item *
15336:
15337: get_access_controls():
15338:
15339: Args:
15340: current_permissions: the hash ref returned from get_portfile_permissions()
15341: group: (optional) the group you want the files associated with
15342: file: (optional) the file you want access info on
15343:
15344: Returns:
1.749 raeburn 15345: a hash (keys are file names) of hashes containing
15346: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15347: values are XML containing access control settings (see below)
1.747 albertel 15348:
15349: Internal notes:
15350:
1.749 raeburn 15351: access controls are stored in file_permissions.db as key=value pairs.
15352: key -> path to file/file_name\0uniqueID:scope_end_start
15353: where scope -> public,guest,course,group,domains or users.
15354: end -> UNIX time for end of access (0 -> no end date)
15355: start -> UNIX time for start of access
15356:
15357: value -> XML description of access control
15358: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15359: <start></start>
15360: <end></end>
15361:
15362: <password></password> for scope type = guest
15363:
15364: <domain></domain> for scope type = course or group
15365: <number></number>
15366: <roles id="">
15367: <role></role>
15368: <access></access>
15369: <section></section>
15370: <group></group>
15371: </roles>
15372:
15373: <dom></dom> for scope type = domains
15374:
15375: <users> for scope type = users
15376: <user>
15377: <uname></uname>
15378: <udom></udom>
15379: </user>
15380: </users>
15381: </scope>
15382:
15383: Access data is also aggregated for each file in an additional key=value pair:
15384: key -> path to file/file_name\0accesscontrol
15385: value -> reference to hash
15386: hash contains key = value pairs
15387: where key = uniqueID:scope_end_start
15388: value = UNIX time record was last updated
15389:
15390: Used to improve speed of look-ups of access controls for each file.
15391:
15392: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15393:
1.1198 raeburn 15394: =item *
15395:
1.749 raeburn 15396: modify_access_controls():
15397:
15398: Modifies access controls for a portfolio file
15399: Args
15400: 1. file name
15401: 2. reference to hash of required changes,
15402: 3. domain
15403: 4. username
15404: where domain,username are the domain of the portfolio owner
15405: (either a user or a course)
15406:
15407: Returns:
15408: 1. result of additions or updates ('ok' or 'error', with error message).
15409: 2. result of deletions ('ok' or 'error', with error message).
15410: 3. reference to hash of any new or updated access controls.
15411: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15412: key = integer (inbound ID)
1.1198 raeburn 15413: value = uniqueID
15414:
15415: =item *
15416:
15417: get_timebased_id():
15418:
15419: Attempts to get a unique timestamp-based suffix for use with items added to a
15420: course via the Course Editor (e.g., folders, composite pages,
15421: group bulletin boards).
15422:
15423: Args: (first three required; six others optional)
15424:
15425: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15426: docssequence, or name of group
15427:
15428: 2. keyid (alphanumeric): name of temporary locking key in hash,
15429: e.g., num, boardids
15430:
15431: 3. namespace: name of gdbm file used to store suffixes already assigned;
15432: file will be named nohist_namespace.db
15433:
15434: 4. cdom: domain of course; default is current course domain from %env
15435:
15436: 5. cnum: course number; default is current course number from %env
15437:
15438: 6. idtype: set to concat if an additional digit is to be appended to the
15439: unix timestamp to form the suffix, if the plain timestamp is already
15440: in use. Default is to not do this, but simply increment the unix
15441: timestamp by 1 until a unique key is obtained.
15442:
15443: 7. who: holder of locking key; defaults to user:domain for user.
15444:
15445: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15446: retrying); default is 3.
15447:
15448: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15449:
15450: Returns:
15451:
15452: 1. suffix obtained (numeric)
15453:
15454: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15455:
15456: 3. error: contains (localized) error message if an error occurred.
15457:
1.747 albertel 15458:
1.608 albertel 15459: =back
15460:
1.243 albertel 15461: =head2 HTTP Helper Routines
15462:
15463: =over 4
15464:
1.191 harris41 15465: =item *
15466:
15467: escape() : unpack non-word characters into CGI-compatible hex codes
15468:
15469: =item *
15470:
15471: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15472:
1.243 albertel 15473: =back
15474:
15475: =head1 PRIVATE SUBROUTINES
15476:
15477: =head2 Underlying communication routines (Shouldn't call)
15478:
15479: =over 4
15480:
15481: =item *
15482:
15483: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15484:
15485: =item *
15486:
15487: reply() : uses subreply to send a message to remote machine, logs all failures
15488:
15489: =item *
15490:
15491: critical() : passes a critical message to another server; if cannot
15492: get through then place message in connection buffer directory and
15493: returns con_delayed, if incapable of saving message, returns
15494: con_failed
15495:
15496: =item *
15497:
15498: reconlonc() : tries to reconnect lonc client processes.
15499:
15500: =back
15501:
15502: =head2 Resource Access Logging
15503:
15504: =over 4
15505:
15506: =item *
15507:
15508: flushcourselogs() : flush (save) buffer logs and access logs
15509:
15510: =item *
15511:
15512: courselog($what) : save message for course in hash
15513:
15514: =item *
15515:
15516: courseacclog($what) : save message for course using &courselog(). Perform
15517: special processing for specific resource types (problems, exams, quizzes, etc).
15518:
1.191 harris41 15519: =item *
15520:
15521: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15522: as a PerlChildExitHandler
1.243 albertel 15523:
15524: =back
15525:
15526: =head2 Other
15527:
15528: =over 4
15529:
15530: =item *
15531:
15532: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 15533:
15534: =back
15535:
15536: =cut
1.877 foxr 15537:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>