Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1327
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1327 ! raeburn 4: # $Id: lonnet.pm,v 1.1326 2016/10/05 16:28:41 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.1182 foxr 78:
1.1173 foxr 79: use Encode;
80:
1.1245 raeburn 81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 82: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
83: %managerstab);
1.871 albertel 84:
85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
86: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
87: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 88: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 89:
1.1 albertel 90: use IO::Socket;
1.31 www 91: use GDBM_File;
1.208 albertel 92: use HTML::LCParser;
1.88 www 93: use Fcntl qw(:flock);
1.870 albertel 94: use Storable qw(thaw nfreeze);
1.1289 damieng 95: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599 albertel 96: use Cache::Memcached;
1.676 albertel 97: use Digest::MD5;
1.790 albertel 98: use Math::Random;
1.1024 raeburn 99: use File::MMagic;
1.807 albertel 100: use LONCAPA qw(:DEFAULT :match);
1.740 www 101: use LONCAPA::Configuration;
1.1160 www 102: use LONCAPA::lonmetadata;
1.1167 droeschl 103: use LONCAPA::Lond;
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: }
246: }
247: }
248: if ($uselocal) {
249: $rep = LONCAPA::Lond::server_certs(\%perlvar);
250: } else {
251: $rep=&reply('servercerts',$lonhost);
252: }
253: my ($result,%returnhash);
254: if (defined($lonhost)) {
255: if (!defined(&hostname($lonhost))) {
256: return;
257: }
258: }
259: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
260: ($rep eq 'unknown_cmd')) {
261: $result = $rep;
262: } else {
263: $result = 'ok';
264: my @pairs=split(/\&/,$rep);
265: foreach my $item (@pairs) {
266: my ($key,$value)=split(/=/,$item,2);
267: my $what = &unescape($key);
268: $returnhash{$what}=&thaw_unescape($value);
269: }
270: }
271: return ($result,\%returnhash);
272: }
273:
1.993 raeburn 274: sub get_server_loncaparev {
1.1073 raeburn 275: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 276: if (defined($lonhost)) {
277: if (!defined(&hostname($lonhost))) {
278: undef($lonhost);
279: }
280: }
281: if (!defined($lonhost)) {
282: if (defined(&domain($dom,'primary'))) {
283: $lonhost=&domain($dom,'primary');
284: if ($lonhost eq 'no_host') {
285: undef($lonhost);
286: }
287: }
288: }
289: if (defined($lonhost)) {
1.1073 raeburn 290: my $cachetime = 12*3600;
291: if (!$ignore_cache) {
292: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
293: if (defined($cached)) {
294: return $loncaparev;
295: }
296: }
297: my ($answer,$loncaparev);
298: my @ids=¤t_machine_ids();
299: if (grep(/^\Q$lonhost\E$/,@ids)) {
300: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 301: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 302: $loncaparev = $1;
303: }
304: } else {
305: $answer = &reply('serverloncaparev',$lonhost);
306: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
307: if ($caller eq 'loncron') {
308: my $ua=new LWP::UserAgent;
1.1082 raeburn 309: $ua->timeout(4);
1.1073 raeburn 310: my $protocol = $protocol{$lonhost};
311: $protocol = 'http' if ($protocol ne 'https');
312: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
313: my $request=new HTTP::Request('GET',$url);
314: my $response=$ua->request($request);
315: unless ($response->is_error()) {
316: my $content = $response->content;
1.1081 raeburn 317: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 318: $loncaparev = $1;
319: }
320: }
321: } else {
322: $loncaparev = $loncaparevs{$lonhost};
323: }
1.1081 raeburn 324: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 325: $loncaparev = $1;
326: }
1.993 raeburn 327: }
1.1073 raeburn 328: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 329: }
330: }
331:
1.1074 raeburn 332: sub get_server_homeID {
333: my ($hostname,$ignore_cache,$caller) = @_;
334: unless ($ignore_cache) {
335: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
336: if (defined($cached)) {
337: return $serverhomeID;
338: }
339: }
340: my $cachetime = 12*3600;
341: my $serverhomeID;
342: if ($caller eq 'loncron') {
343: my @machine_ids = &machine_ids($hostname);
344: foreach my $id (@machine_ids) {
345: my $response = &reply('serverhomeID',$id);
346: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
347: $serverhomeID = $response;
348: last;
349: }
350: }
351: if ($serverhomeID eq '') {
352: $serverhomeID = $machine_ids[-1];
353: }
354: } else {
355: $serverhomeID = $serverhomeIDs{$hostname};
356: }
357: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
358: }
359:
1.1121 raeburn 360: sub get_remote_globals {
361: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 362: my ($result,%returnhash,%whatneeded);
363: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 364: foreach my $what (sort(keys(%{$whathash}))) {
365: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 366: my ($response,$cached);
1.1121 raeburn 367: unless ($ignore_cache) {
1.1125 raeburn 368: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 369: }
370: if (defined($cached)) {
1.1125 raeburn 371: $returnhash{$what} = $response;
1.1121 raeburn 372: } else {
1.1125 raeburn 373: $whatneeded{$what} = 1;
1.1121 raeburn 374: }
375: }
1.1125 raeburn 376: if (keys(%whatneeded) == 0) {
377: $result = 'ok';
378: } else {
1.1121 raeburn 379: my $requested = &freeze_escape(\%whatneeded);
380: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 381: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
382: ($rep eq 'unknown_cmd')) {
383: $result = $rep;
384: } else {
385: $result = 'ok';
1.1121 raeburn 386: my @pairs=split(/\&/,$rep);
1.1125 raeburn 387: foreach my $item (@pairs) {
388: my ($key,$value)=split(/=/,$item,2);
389: my $what = &unescape($key);
390: my $hashid = $lonhost.'-'.$what;
391: $returnhash{$what}=&thaw_unescape($value);
392: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 393: }
394: }
395: }
396: }
1.1125 raeburn 397: return ($result,\%returnhash);
1.1121 raeburn 398: }
399:
1.1124 raeburn 400: sub remote_devalidate_cache {
1.1241 raeburn 401: my ($lonhost,$cachekeys) = @_;
402: my $items;
403: return unless (ref($cachekeys) eq 'ARRAY');
404: my $cachestr = join('&',@{$cachekeys});
405: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 406: return $response;
407: }
408:
1.1 albertel 409: # -------------------------------------------------- Non-critical communication
410: sub subreply {
411: my ($cmd,$server)=@_;
1.838 albertel 412: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 413: #
414: # With loncnew process trimming, there's a timing hole between lonc server
415: # process exit and the master server picking up the listen on the AF_UNIX
416: # socket. In that time interval, a lock file will exist:
417:
418: my $lockfile=$peerfile.".lock";
419: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
1.1289 damieng 420: sleep(0.1);
1.549 foxr 421: }
422: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 423: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 424: #
1.550 foxr 425: # We'll give the connection a few tries before abandoning it. If
426: # connection is not possible, we'll con_lost back to the client.
427: #
428: my $client;
429: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
430: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
431: Type => SOCK_STREAM,
432: Timeout => 10);
1.869 albertel 433: if ($client) {
1.550 foxr 434: last; # Connected!
1.850 albertel 435: } else {
1.853 albertel 436: &create_connection(&hostname($server),$server);
1.550 foxr 437: }
1.1289 damieng 438: sleep(0.1); # Try again later if failed connection.
1.550 foxr 439: }
440: my $answer;
441: if ($client) {
1.704 albertel 442: print $client "sethost:$server:$cmd\n";
1.550 foxr 443: $answer=<$client>;
444: if (!$answer) { $answer="con_lost"; }
445: chomp($answer);
446: } else {
447: $answer = 'con_lost'; # Failed connection.
448: }
1.1 albertel 449: return $answer;
450: }
451:
452: sub reply {
453: my ($cmd,$server)=@_;
1.838 albertel 454: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 455: my $answer=subreply($cmd,$server);
1.65 www 456: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 457: &logthis("<font color=\"blue\">WARNING:".
1.12 www 458: " $cmd to $server returned $answer</font>");
459: }
1.1 albertel 460: return $answer;
461: }
462:
463: # ----------------------------------------------------------- Send USR1 to lonc
464:
465: sub reconlonc {
1.891 albertel 466: my ($lonid) = @_;
467: if ($lonid) {
1.1295 raeburn 468: my $hostname = &hostname($lonid);
1.891 albertel 469: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
470: if ($hostname && -e $peerfile) {
471: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
472: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
473: Type => SOCK_STREAM,
474: Timeout => 10);
475: if ($client) {
476: print $client ("reset_retries\n");
477: my $answer=<$client>;
478: #reset just this one.
479: }
480: }
481: return;
482: }
483:
1.836 www 484: &logthis("Trying to reconnect lonc");
1.1 albertel 485: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 486: if (open(my $fh,"<$loncfile")) {
1.1 albertel 487: my $loncpid=<$fh>;
488: chomp($loncpid);
489: if (kill 0 => $loncpid) {
490: &logthis("lonc at pid $loncpid responding, sending USR1");
491: kill USR1 => $loncpid;
492: sleep 1;
1.1295 raeburn 493: } else {
1.12 www 494: &logthis(
1.672 albertel 495: "<font color=\"blue\">WARNING:".
1.12 www 496: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 497: }
498: } else {
1.836 www 499: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 500: }
501: }
502:
503: # ------------------------------------------------------ Critical communication
1.12 www 504:
1.1 albertel 505: sub critical {
506: my ($cmd,$server)=@_;
1.838 albertel 507: unless (&hostname($server)) {
1.672 albertel 508: &logthis("<font color=\"blue\">WARNING:".
1.89 www 509: " Critical message to unknown server ($server)</font>");
510: return 'no_such_host';
511: }
1.1 albertel 512: my $answer=reply($cmd,$server);
513: if ($answer eq 'con_lost') {
1.1295 raeburn 514: &reconlonc($server);
1.589 albertel 515: my $answer=reply($cmd,$server);
1.1 albertel 516: if ($answer eq 'con_lost') {
517: my $now=time;
518: my $middlename=$cmd;
1.5 www 519: $middlename=substr($middlename,0,16);
1.1 albertel 520: $middlename=~s/\W//g;
521: my $dfilename=
1.305 www 522: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
523: $dumpcount++;
1.1 albertel 524: {
1.448 albertel 525: my $dfh;
526: if (open($dfh,">$dfilename")) {
527: print $dfh "$cmd\n";
528: close($dfh);
529: }
1.1 albertel 530: }
1.1288 damieng 531: sleep 1;
1.1 albertel 532: my $wcmd='';
533: {
1.448 albertel 534: my $dfh;
535: if (open($dfh,"<$dfilename")) {
536: $wcmd=<$dfh>;
537: close($dfh);
538: }
1.1 albertel 539: }
540: chomp($wcmd);
1.7 www 541: if ($wcmd eq $cmd) {
1.672 albertel 542: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 543: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 544: &logperm("D:$server:$cmd");
545: return 'con_delayed';
546: } else {
1.672 albertel 547: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 548: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 549: &logperm("F:$server:$cmd");
550: return 'con_failed';
551: }
552: }
553: }
554: return $answer;
1.405 albertel 555: }
556:
1.755 albertel 557: # ------------------------------------------- check if return value is an error
558:
559: sub error {
560: my ($result) = @_;
1.756 albertel 561: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 562: if ($2 == 2) { return undef; }
563: return $1;
564: }
565: return undef;
566: }
567:
1.783 albertel 568: sub convert_and_load_session_env {
569: my ($lonidsdir,$handle)=@_;
570: my @profile;
571: {
1.917 albertel 572: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
573: if (!$opened) {
1.915 albertel 574: return 0;
575: }
1.783 albertel 576: flock($idf,LOCK_SH);
577: @profile=<$idf>;
578: close($idf);
579: }
580: my %temp_env;
581: foreach my $line (@profile) {
1.786 albertel 582: if ($line !~ m/=/) {
583: return 0;
584: }
1.783 albertel 585: chomp($line);
586: my ($envname,$envvalue)=split(/=/,$line,2);
587: $temp_env{&unescape($envname)} = &unescape($envvalue);
588: }
589: unlink("$lonidsdir/$handle.id");
590: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
591: 0640)) {
592: %disk_env = %temp_env;
593: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
594: untie(%disk_env);
595: }
1.786 albertel 596: return 1;
1.783 albertel 597: }
598:
1.374 www 599: # ------------------------------------------- Transfer profile into environment
1.780 albertel 600: my $env_loaded;
601: sub transfer_profile_to_env {
1.788 albertel 602: my ($lonidsdir,$handle,$force_transfer) = @_;
603: if (!$force_transfer && $env_loaded) { return; }
1.374 www 604:
1.720 albertel 605: if (!defined($lonidsdir)) {
606: $lonidsdir = $perlvar{'lonIDsDir'};
607: }
608: if (!defined($handle)) {
609: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
610: }
611:
1.786 albertel 612: my $convert;
613: {
1.917 albertel 614: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
615: if (!$opened) {
1.915 albertel 616: return;
617: }
1.786 albertel 618: flock($idf,LOCK_SH);
619: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
620: &GDBM_READER(),0640)) {
621: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
622: untie(%disk_env);
623: } else {
624: $convert = 1;
625: }
626: }
627: if ($convert) {
628: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
629: &logthis("Failed to load session, or convert session.");
630: }
1.374 www 631: }
1.783 albertel 632:
1.786 albertel 633: my %remove;
1.783 albertel 634: while ( my $envname = each(%env) ) {
1.433 matthew 635: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
636: if ($time < time-300) {
1.783 albertel 637: $remove{$key}++;
1.433 matthew 638: }
639: }
640: }
1.783 albertel 641:
1.619 albertel 642: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 643: $env_loaded=1;
1.783 albertel 644: foreach my $expired_key (keys(%remove)) {
1.433 matthew 645: &delenv($expired_key);
1.374 www 646: }
1.1 albertel 647: }
648:
1.916 albertel 649: # ---------------------------------------------------- Check for valid session
650: sub check_for_valid_session {
1.1245 raeburn 651: my ($r,$name,$userhashref) = @_;
1.916 albertel 652: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 653: if ($name eq '') {
654: $name = 'lonID';
655: }
656: my $lonid=$cookies{$name};
1.916 albertel 657: return undef if (!$lonid);
658:
659: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 660: my $lonidsdir;
661: if ($name eq 'lonDAV') {
662: $lonidsdir=$r->dir_config('lonDAVsessDir');
663: } else {
664: $lonidsdir=$r->dir_config('lonIDsDir');
665: }
1.916 albertel 666: return undef if (!-e "$lonidsdir/$handle.id");
667:
1.917 albertel 668: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
669: return undef if (!$opened);
1.916 albertel 670:
671: flock($idf,LOCK_SH);
672: my %disk_env;
673: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
674: &GDBM_READER(),0640)) {
675: return undef;
676: }
677:
678: if (!defined($disk_env{'user.name'})
679: || !defined($disk_env{'user.domain'})) {
680: return undef;
681: }
1.1245 raeburn 682:
683: if (ref($userhashref) eq 'HASH') {
684: $userhashref->{'name'} = $disk_env{'user.name'};
685: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212 raeburn 686: }
1.1245 raeburn 687:
1.916 albertel 688: return $handle;
689: }
690:
1.830 albertel 691: sub timed_flock {
692: my ($file,$lock_type) = @_;
693: my $failed=0;
694: eval {
695: local $SIG{__DIE__}='DEFAULT';
696: local $SIG{ALRM}=sub {
697: $failed=1;
698: die("failed lock");
699: };
700: alarm(13);
701: flock($file,$lock_type);
702: alarm(0);
703: };
704: if ($failed) {
705: return undef;
706: } else {
707: return 1;
708: }
709: }
710:
1.5 www 711: # ---------------------------------------------------------- Append Environment
712:
713: sub appenv {
1.949 raeburn 714: my ($newenv,$roles) = @_;
715: if (ref($newenv) eq 'HASH') {
716: foreach my $key (keys(%{$newenv})) {
717: my $refused = 0;
718: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
719: $refused = 1;
720: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 721: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 722: if (grep(/^\Q$role\E$/,@{$roles})) {
723: $refused = 0;
724: }
725: }
726: }
727: if ($refused) {
728: &logthis("<font color=\"blue\">WARNING: ".
729: "Attempt to modify environment ".$key." to ".$newenv->{$key}
730: .'</font>');
731: delete($newenv->{$key});
732: } else {
733: $env{$key}=$newenv->{$key};
734: }
735: }
736: my $opened = open(my $env_file,'+<',$env{'user.environment'});
737: if ($opened
738: && &timed_flock($env_file,LOCK_EX)
739: &&
740: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
741: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
742: while (my ($key,$value) = each(%{$newenv})) {
743: $disk_env{$key} = $value;
744: }
745: untie(%disk_env);
1.35 www 746: }
1.191 harris41 747: }
1.56 www 748: return 'ok';
749: }
750: # ----------------------------------------------------- Delete from Environment
751:
752: sub delenv {
1.1104 raeburn 753: my ($delthis,$regexp,$roles) = @_;
754: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
755: my $refused = 1;
756: if (ref($roles) eq 'ARRAY') {
757: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
758: if (grep(/^\Q$role\E$/,@{$roles})) {
759: $refused = 0;
760: }
761: }
762: if ($refused) {
763: &logthis("<font color=\"blue\">WARNING: ".
764: "Attempt to delete from environment ".$delthis);
765: return 'error';
766: }
1.56 www 767: }
1.917 albertel 768: my $opened = open(my $env_file,'+<',$env{'user.environment'});
769: if ($opened
1.915 albertel 770: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 771: &&
772: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
773: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 774: foreach my $key (keys(%disk_env)) {
1.987 raeburn 775: if ($regexp) {
776: if ($key=~/^$delthis/) {
777: delete($env{$key});
778: delete($disk_env{$key});
779: }
780: } else {
781: if ($key=~/^\Q$delthis\E/) {
782: delete($env{$key});
783: delete($disk_env{$key});
784: }
785: }
1.448 albertel 786: }
1.783 albertel 787: untie(%disk_env);
1.5 www 788: }
789: return 'ok';
1.369 albertel 790: }
791:
1.790 albertel 792: sub get_env_multiple {
793: my ($name) = @_;
794: my @values;
795: if (defined($env{$name})) {
796: # exists is it an array
797: if (ref($env{$name})) {
798: @values=@{ $env{$name} };
799: } else {
800: $values[0]=$env{$name};
801: }
802: }
803: return(@values);
804: }
805:
1.958 www 806: # ------------------------------------------------------------------- Locking
807:
808: sub set_lock {
809: my ($text)=@_;
810: $locknum++;
811: my $id=$$.'-'.$locknum;
812: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
813: 'session.lock.'.$id => $text});
814: return $id;
815: }
816:
817: sub get_locks {
818: my $num=0;
819: my %texts=();
820: foreach my $lock (split(/\,/,$env{'session.locks'})) {
821: if ($lock=~/\w/) {
822: $num++;
823: $texts{$lock}=$env{'session.lock.'.$lock};
824: }
825: }
826: return ($num,%texts);
827: }
828:
829: sub remove_lock {
830: my ($id)=@_;
831: my $newlocks='';
832: foreach my $lock (split(/\,/,$env{'session.locks'})) {
833: if (($lock=~/\w/) && ($lock ne $id)) {
834: $newlocks.=','.$lock;
835: }
836: }
837: &appenv({'session.locks' => $newlocks});
838: &delenv('session.lock.'.$id);
839: }
840:
841: sub remove_all_locks {
842: my $activelocks=$env{'session.locks'};
843: foreach my $lock (split(/\,/,$env{'session.locks'})) {
844: if ($lock=~/\w/) {
845: &remove_lock($lock);
846: }
847: }
848: }
849:
850:
1.369 albertel 851: # ------------------------------------------ Find out current server userload
852: sub userload {
853: my $numusers=0;
854: {
855: opendir(LONIDS,$perlvar{'lonIDsDir'});
856: my $filename;
857: my $curtime=time;
858: while ($filename=readdir(LONIDS)) {
1.925 albertel 859: next if ($filename eq '.' || $filename eq '..');
860: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 861: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 862: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 863: }
864: closedir(LONIDS);
865: }
866: my $userloadpercent=0;
867: my $maxuserload=$perlvar{'lonUserLoadLim'};
868: if ($maxuserload) {
1.371 albertel 869: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 870: }
1.372 albertel 871: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 872: return $userloadpercent;
1.283 www 873: }
874:
1.1 albertel 875: # ------------------------------ Find server with least workload from spare.tab
1.11 www 876:
1.1 albertel 877: sub spareserver {
1.1083 raeburn 878: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 879: my $spare_server;
1.370 albertel 880: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 881: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
882: : $userloadpercent;
1.1083 raeburn 883: my ($uint_dom,$remotesessions);
884: if (($udom ne '') && (&domain($udom) ne '')) {
885: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
886: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
887: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
888: $remotesessions = $udomdefaults{'remotesessions'};
889: }
1.1123 raeburn 890: my $spareshash = &this_host_spares($udom);
891: if (ref($spareshash) eq 'HASH') {
892: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
893: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279 raeburn 894: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
895: $try_server));
1.1123 raeburn 896: ($spare_server, $lowest_load) =
897: &compare_server_load($try_server, $spare_server, $lowest_load);
898: }
1.1083 raeburn 899: }
1.784 albertel 900:
1.1123 raeburn 901: my $found_server = ($spare_server ne '' && $lowest_load < 100);
902:
903: if (!$found_server) {
904: if (ref($spareshash->{'default'}) eq 'ARRAY') {
905: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279 raeburn 906: next unless (&spare_can_host($udom,$uint_dom,
907: $remotesessions,$try_server));
1.1123 raeburn 908: ($spare_server, $lowest_load) =
909: &compare_server_load($try_server, $spare_server, $lowest_load);
910: }
911: }
912: }
1.784 albertel 913: }
914:
915: if (!$want_server_name) {
1.968 raeburn 916: my $protocol = 'http';
917: if ($protocol{$spare_server} eq 'https') {
918: $protocol = $protocol{$spare_server};
919: }
1.1001 raeburn 920: if (defined($spare_server)) {
921: my $hostname = &hostname($spare_server);
1.1083 raeburn 922: if (defined($hostname)) {
1.1001 raeburn 923: $spare_server = $protocol.'://'.$hostname;
924: }
925: }
1.784 albertel 926: }
927: return $spare_server;
928: }
929:
930: sub compare_server_load {
1.1253 raeburn 931: my ($try_server, $spare_server, $lowest_load, $required) = @_;
932:
933: if ($required) {
934: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
935: my $remoterev = &get_server_loncaparev(undef,$try_server);
936: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
937: if (($major eq '' && $minor eq '') ||
938: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
939: return ($spare_server,$lowest_load);
940: }
941: }
1.784 albertel 942:
943: my $loadans = &reply('load', $try_server);
944: my $userloadans = &reply('userload',$try_server);
945:
946: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 947: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 948: }
949:
950: my $load;
951: if ($loadans =~ /\d/) {
952: if ($userloadans =~ /\d/) {
953: #both are numbers, pick the bigger one
954: $load = ($loadans > $userloadans) ? $loadans
955: : $userloadans;
1.411 albertel 956: } else {
1.784 albertel 957: $load = $loadans;
1.411 albertel 958: }
1.784 albertel 959: } else {
960: $load = $userloadans;
961: }
962:
963: if (($load =~ /\d/) && ($load < $lowest_load)) {
964: $spare_server = $try_server;
965: $lowest_load = $load;
1.370 albertel 966: }
1.784 albertel 967: return ($spare_server,$lowest_load);
1.202 matthew 968: }
1.914 albertel 969:
970: # --------------------------- ask offload servers if user already has a session
971: sub find_existing_session {
972: my ($udom,$uname) = @_;
1.1123 raeburn 973: my $spareshash = &this_host_spares($udom);
974: if (ref($spareshash) eq 'HASH') {
975: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
976: foreach my $try_server (@{ $spareshash->{'primary'} }) {
977: return $try_server if (&has_user_session($try_server, $udom, $uname));
978: }
979: }
980: if (ref($spareshash->{'default'}) eq 'ARRAY') {
981: foreach my $try_server (@{ $spareshash->{'default'} }) {
982: return $try_server if (&has_user_session($try_server, $udom, $uname));
983: }
984: }
1.914 albertel 985: }
986: return;
987: }
988:
989: # -------------------------------- ask if server already has a session for user
990: sub has_user_session {
991: my ($lonid,$udom,$uname) = @_;
992: my $result = &reply(join(':','userhassession',
993: map {&escape($_)} ($udom,$uname)),$lonid);
994: return 1 if ($result eq 'ok');
995:
996: return 0;
997: }
998:
1.1076 raeburn 999: # --------- determine least loaded server in a user's domain which allows login
1000:
1001: sub choose_server {
1.1259 raeburn 1002: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1003: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1004: my %servers = &get_servers($udom);
1.1076 raeburn 1005: my $lowest_load = 30000;
1.1259 raeburn 1006: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1007: if ($skiploadbal) {
1008: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1009: unless (defined($cached)) {
1010: my $cachetime = 60*60*24;
1011: my %domconfig =
1012: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1013: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1014: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1015: $cachetime);
1016: }
1017: }
1018: }
1.1076 raeburn 1019: foreach my $lonhost (keys(%servers)) {
1.1259 raeburn 1020: if ($skiploadbal) {
1021: if (ref($balancers) eq 'HASH') {
1022: next if (exists($balancers->{$lonhost}));
1023: }
1024: }
1.1115 raeburn 1025: my $loginvia;
1026: if ($checkloginvia) {
1027: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1028: if ($loginvia) {
1029: my ($server,$path) = split(/:/,$loginvia);
1030: ($login_host, $lowest_load) =
1.1253 raeburn 1031: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1032: if ($login_host eq $server) {
1033: $portal_path = $path;
1.1151 raeburn 1034: $isredirect = 1;
1.1116 raeburn 1035: }
1036: } else {
1037: ($login_host, $lowest_load) =
1.1253 raeburn 1038: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1039: if ($login_host eq $lonhost) {
1040: $portal_path = '';
1.1151 raeburn 1041: $isredirect = '';
1.1116 raeburn 1042: }
1043: }
1044: } else {
1.1076 raeburn 1045: ($login_host, $lowest_load) =
1.1253 raeburn 1046: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1047: }
1048: }
1049: if ($login_host ne '') {
1.1116 raeburn 1050: $hostname = &hostname($login_host);
1.1076 raeburn 1051: }
1.1151 raeburn 1052: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 1053: }
1054:
1.202 matthew 1055: # --------------------------------------------- Try to change a user's password
1056:
1057: sub changepass {
1.799 raeburn 1058: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1059: $currentpass = &escape($currentpass);
1060: $newpass = &escape($newpass);
1.1030 raeburn 1061: my $lonhost = $perlvar{'lonHostID'};
1062: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1063: $server);
1064: if (! $answer) {
1065: &logthis("No reply on password change request to $server ".
1066: "by $uname in domain $udom.");
1067: } elsif ($answer =~ "^ok") {
1068: &logthis("$uname in $udom successfully changed their password ".
1069: "on $server.");
1070: } elsif ($answer =~ "^pwchange_failure") {
1071: &logthis("$uname in $udom was unable to change their password ".
1072: "on $server. The action was blocked by either lcpasswd ".
1073: "or pwchange");
1074: } elsif ($answer =~ "^non_authorized") {
1075: &logthis("$uname in $udom did not get their password correct when ".
1076: "attempting to change it on $server.");
1077: } elsif ($answer =~ "^auth_mode_error") {
1078: &logthis("$uname in $udom attempted to change their password despite ".
1079: "not being locally or internally authenticated on $server.");
1080: } elsif ($answer =~ "^unknown_user") {
1081: &logthis("$uname in $udom attempted to change their password ".
1082: "on $server but were unable to because $server is not ".
1083: "their home server.");
1084: } elsif ($answer =~ "^refused") {
1085: &logthis("$server refused to change $uname in $udom password because ".
1086: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1087: } elsif ($answer =~ "invalid_client") {
1088: &logthis("$server refused to change $uname in $udom password because ".
1089: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1090: }
1091: return $answer;
1.1 albertel 1092: }
1093:
1.169 harris41 1094: # ----------------------- Try to determine user's current authentication scheme
1095:
1096: sub queryauthenticate {
1097: my ($uname,$udom)=@_;
1.456 albertel 1098: my $uhome=&homeserver($uname,$udom);
1099: if (!$uhome) {
1100: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1101: return 'no_host';
1102: }
1103: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1104: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1105: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1106: }
1.456 albertel 1107: return $answer;
1.169 harris41 1108: }
1109:
1.1 albertel 1110: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1111:
1.1 albertel 1112: sub authenticate {
1.1073 raeburn 1113: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1114: $upass=&escape($upass);
1115: $uname= &LONCAPA::clean_username($uname);
1.836 www 1116: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1117: my $newhome;
1.836 www 1118: if ((!$uhome) || ($uhome eq 'no_host')) {
1119: # Maybe the machine was offline and only re-appeared again recently?
1120: &reconlonc();
1121: # One more
1.952 raeburn 1122: $uhome=&homeserver($uname,$udom,1);
1123: if (($uhome eq 'no_host') && $checkdefauth) {
1124: if (defined(&domain($udom,'primary'))) {
1125: $newhome=&domain($udom,'primary');
1126: }
1127: if ($newhome ne '') {
1128: $uhome = $newhome;
1129: }
1130: }
1.836 www 1131: if ((!$uhome) || ($uhome eq 'no_host')) {
1132: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1133: return 'no_host';
1134: }
1.1 albertel 1135: }
1.1073 raeburn 1136: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1137: if ($answer eq 'authorized') {
1.952 raeburn 1138: if ($newhome) {
1139: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1140: return 'no_account_on_host';
1141: } else {
1142: &logthis("User $uname at $udom authorized by $uhome");
1143: return $uhome;
1144: }
1.471 albertel 1145: }
1146: if ($answer eq 'non_authorized') {
1147: &logthis("User $uname at $udom rejected by $uhome");
1148: return 'no_host';
1.9 www 1149: }
1.471 albertel 1150: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1151: return 'no_host';
1152: }
1153:
1.1073 raeburn 1154: sub can_host_session {
1.1074 raeburn 1155: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1156: my $canhost = 1;
1.1074 raeburn 1157: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1158: if (ref($remotesessions) eq 'HASH') {
1159: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1160: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1161: $canhost = 0;
1162: } else {
1163: $canhost = 1;
1164: }
1165: }
1166: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1167: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1168: $canhost = 1;
1169: } else {
1170: $canhost = 0;
1171: }
1172: }
1173: if ($canhost) {
1174: if ($remotesessions->{'version'} ne '') {
1175: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1176: if ($reqmajor ne '' && $reqminor ne '') {
1177: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1178: my $major = $1;
1179: my $minor = $2;
1180: if (($major < $reqmajor ) ||
1181: (($major == $reqmajor) && ($minor < $reqminor))) {
1182: $canhost = 0;
1183: }
1184: } else {
1185: $canhost = 0;
1186: }
1187: }
1188: }
1189: }
1190: }
1191: if ($canhost) {
1192: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1193: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1194: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1195: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1196: if (($uint_dom ne '') &&
1197: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1198: $canhost = 0;
1199: } else {
1200: $canhost = 1;
1201: }
1202: }
1203: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1204: if (($uint_dom ne '') &&
1205: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1206: $canhost = 1;
1207: } else {
1208: $canhost = 0;
1209: }
1210: }
1211: }
1212: }
1213: return $canhost;
1214: }
1215:
1.1083 raeburn 1216: sub spare_can_host {
1217: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1218: my $canhost=1;
1.1279 raeburn 1219: my $try_server_hostname = &hostname($try_server);
1220: my $serverhomeID = &get_server_homeID($try_server_hostname);
1221: my $serverhomedom = &host_domain($serverhomeID);
1222: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1223: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1224: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1225: $canhost = 0;
1226: }
1227: }
1228: if (($canhost) && ($uint_dom)) {
1229: my @intdoms;
1230: my $internet_names = &get_internet_names($try_server);
1231: if (ref($internet_names) eq 'ARRAY') {
1232: @intdoms = @{$internet_names};
1233: }
1234: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1235: my $remoterev = &get_server_loncaparev(undef,$try_server);
1236: $canhost = &can_host_session($udom,$try_server,$remoterev,
1237: $remotesessions,
1238: $defdomdefaults{'hostedsessions'});
1239: }
1.1083 raeburn 1240: }
1241: return $canhost;
1242: }
1243:
1.1123 raeburn 1244: sub this_host_spares {
1245: my ($dom) = @_;
1.1126 raeburn 1246: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1247: my @hosts = ¤t_machine_ids();
1248: foreach my $lonhost (@hosts) {
1249: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1250: $dom_in_use = $dom;
1251: $lonhost_in_use = $lonhost;
1.1123 raeburn 1252: last;
1253: }
1254: }
1.1126 raeburn 1255: if ($dom_in_use ne '') {
1256: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1257: }
1258: if (ref($result) ne 'HASH') {
1259: $lonhost_in_use = $perlvar{'lonHostID'};
1260: $dom_in_use = &host_domain($lonhost_in_use);
1261: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1262: if (ref($result) ne 'HASH') {
1263: $result = \%spareid;
1264: }
1265: }
1266: return $result;
1267: }
1268:
1269: sub spares_for_offload {
1270: my ($dom_in_use,$lonhost_in_use) = @_;
1271: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1272: if (defined($cached)) {
1273: return $result;
1274: } else {
1.1126 raeburn 1275: my $cachetime = 60*60*24;
1276: my %domconfig =
1277: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1278: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1279: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1280: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1281: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1282: }
1283: }
1284: }
1285: }
1.1126 raeburn 1286: return;
1.1123 raeburn 1287: }
1288:
1.1129 raeburn 1289: sub get_lonbalancer_config {
1290: my ($servers) = @_;
1291: my ($currbalancer,$currtargets);
1292: if (ref($servers) eq 'HASH') {
1293: foreach my $server (keys(%{$servers})) {
1294: my %what = (
1295: spareid => 1,
1296: perlvar => 1,
1297: );
1298: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1299: if ($result eq 'ok') {
1300: if (ref($returnhash) eq 'HASH') {
1301: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1302: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1303: $currbalancer = $server;
1304: $currtargets = {};
1305: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1306: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1307: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1308: }
1309: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1310: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1311: }
1312: }
1313: last;
1314: }
1315: }
1316: }
1317: }
1318: }
1319: }
1320: return ($currbalancer,$currtargets);
1321: }
1322:
1323: sub check_loadbalancing {
1324: my ($uname,$udom) = @_;
1.1191 raeburn 1325: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1326: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1327: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1328: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1329: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1330: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1331: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1332: my $serverhomedom = &host_domain($lonhost);
1.1307 raeburn 1333: my $domneedscache;
1.1129 raeburn 1334: my $cachetime = 60*60*24;
1335:
1336: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1337: $dom_in_use = $udom;
1338: $homeintdom = 1;
1339: } else {
1340: $dom_in_use = $serverhomedom;
1341: }
1342: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1343: unless (defined($cached)) {
1344: my %domconfig =
1345: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1346: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1347: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307 raeburn 1348: } else {
1349: $domneedscache = $dom_in_use;
1.1129 raeburn 1350: }
1351: }
1352: if (ref($result) eq 'HASH') {
1.1191 raeburn 1353: ($is_balancer,$currtargets,$currrules) =
1354: &check_balancer_result($result,@hosts);
1.1129 raeburn 1355: if ($is_balancer) {
1356: if (ref($currrules) eq 'HASH') {
1357: if ($homeintdom) {
1358: if ($uname ne '') {
1359: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1360: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1361: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1362: $rule_in_effect = $currrules->{'_LC_author'};
1363: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1364: $rule_in_effect = $currrules->{'_LC_adv'}
1365: }
1366: }
1367: if ($rule_in_effect eq '') {
1368: my %userenv = &userenvironment($udom,$uname,'inststatus');
1369: if ($userenv{'inststatus'} ne '') {
1370: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1371: my ($othertitle,$usertypes,$types) =
1372: &Apache::loncommon::sorted_inst_types($udom);
1373: if (ref($types) eq 'ARRAY') {
1374: foreach my $type (@{$types}) {
1375: if (grep(/^\Q$type\E$/,@statuses)) {
1376: if (exists($currrules->{$type})) {
1377: $rule_in_effect = $currrules->{$type};
1378: }
1379: }
1380: }
1381: }
1382: } else {
1383: if (exists($currrules->{'default'})) {
1384: $rule_in_effect = $currrules->{'default'};
1385: }
1386: }
1387: }
1388: } else {
1389: if (exists($currrules->{'default'})) {
1390: $rule_in_effect = $currrules->{'default'};
1391: }
1392: }
1393: } else {
1394: if ($currrules->{'_LC_external'} ne '') {
1395: $rule_in_effect = $currrules->{'_LC_external'};
1396: }
1397: }
1398: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1399: $uname,$udom);
1400: }
1401: }
1402: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1403: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1404: unless (defined($cached)) {
1405: my %domconfig =
1406: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1407: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307 raeburn 1408: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1409: } else {
1410: $domneedscache = $serverhomedom;
1.1129 raeburn 1411: }
1412: }
1413: if (ref($result) eq 'HASH') {
1.1191 raeburn 1414: ($is_balancer,$currtargets,$currrules) =
1415: &check_balancer_result($result,@hosts);
1416: if ($is_balancer) {
1.1129 raeburn 1417: if (ref($currrules) eq 'HASH') {
1418: if ($currrules->{'_LC_internetdom'} ne '') {
1419: $rule_in_effect = $currrules->{'_LC_internetdom'};
1420: }
1421: }
1422: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1423: $uname,$udom);
1424: }
1425: } else {
1426: if ($perlvar{'lonBalancer'} eq 'yes') {
1427: $is_balancer = 1;
1428: $offloadto = &this_host_spares($dom_in_use);
1429: }
1.1307 raeburn 1430: unless (defined($cached)) {
1431: $domneedscache = $serverhomedom;
1432: }
1.1129 raeburn 1433: }
1434: } else {
1435: if ($perlvar{'lonBalancer'} eq 'yes') {
1436: $is_balancer = 1;
1437: $offloadto = &this_host_spares($dom_in_use);
1438: }
1.1307 raeburn 1439: unless (defined($cached)) {
1440: $domneedscache = $serverhomedom;
1441: }
1442: }
1443: if ($domneedscache) {
1444: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1445: }
1.1176 raeburn 1446: if ($is_balancer) {
1447: my $lowest_load = 30000;
1448: if (ref($offloadto) eq 'HASH') {
1449: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1450: foreach my $try_server (@{$offloadto->{'primary'}}) {
1451: ($otherserver,$lowest_load) =
1452: &compare_server_load($try_server,$otherserver,$lowest_load);
1453: }
1.1129 raeburn 1454: }
1.1176 raeburn 1455: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1456:
1.1176 raeburn 1457: if (!$found_server) {
1458: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1459: foreach my $try_server (@{$offloadto->{'default'}}) {
1460: ($otherserver,$lowest_load) =
1461: &compare_server_load($try_server,$otherserver,$lowest_load);
1462: }
1463: }
1464: }
1465: } elsif (ref($offloadto) eq 'ARRAY') {
1466: if (@{$offloadto} == 1) {
1467: $otherserver = $offloadto->[0];
1468: } elsif (@{$offloadto} > 1) {
1469: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1470: ($otherserver,$lowest_load) =
1471: &compare_server_load($try_server,$otherserver,$lowest_load);
1472: }
1473: }
1474: }
1.1176 raeburn 1475: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1476: $is_balancer = 0;
1477: if ($uname ne '' && $udom ne '') {
1478: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1479:
1480: &appenv({'user.loadbalexempt' => $lonhost,
1481: 'user.loadbalcheck.time' => time});
1482: }
1.1129 raeburn 1483: }
1484: }
1485: }
1486: return ($is_balancer,$otherserver);
1487: }
1488:
1.1191 raeburn 1489: sub check_balancer_result {
1490: my ($result,@hosts) = @_;
1491: my ($is_balancer,$currtargets,$currrules);
1492: if (ref($result) eq 'HASH') {
1493: if ($result->{'lonhost'} ne '') {
1494: my $currbalancer = $result->{'lonhost'};
1495: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1496: $is_balancer = 1;
1497: $currtargets = $result->{'targets'};
1498: $currrules = $result->{'rules'};
1499: }
1500: } else {
1501: foreach my $key (keys(%{$result})) {
1502: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1503: (ref($result->{$key}) eq 'HASH')) {
1504: $is_balancer = 1;
1505: $currrules = $result->{$key}{'rules'};
1506: $currtargets = $result->{$key}{'targets'};
1507: last;
1508: }
1509: }
1510: }
1511: }
1512: return ($is_balancer,$currtargets,$currrules);
1513: }
1514:
1.1129 raeburn 1515: sub get_loadbalancer_targets {
1516: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1517: my $offloadto;
1.1175 raeburn 1518: if ($rule_in_effect eq 'none') {
1519: return [$perlvar{'lonHostID'}];
1520: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1521: $offloadto = $currtargets;
1522: } else {
1523: if ($rule_in_effect eq 'homeserver') {
1524: my $homeserver = &homeserver($uname,$udom);
1525: if ($homeserver ne 'no_host') {
1526: $offloadto = [$homeserver];
1527: }
1528: } elsif ($rule_in_effect eq 'externalbalancer') {
1529: my %domconfig =
1530: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1531: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1532: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1533: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1534: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1535: }
1536: }
1537: } else {
1.1178 raeburn 1538: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1539: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1540: if (&hostname($remotebalancer) ne '') {
1541: $offloadto = [$remotebalancer];
1542: }
1543: }
1544: } elsif (&hostname($rule_in_effect) ne '') {
1545: $offloadto = [$rule_in_effect];
1546: }
1547: }
1548: return $offloadto;
1549: }
1550:
1.1127 raeburn 1551: sub internet_dom_servers {
1552: my ($dom) = @_;
1553: my (%uniqservers,%servers);
1554: my $primaryserver = &hostname(&domain($dom,'primary'));
1555: my @machinedoms = &machine_domains($primaryserver);
1556: foreach my $mdom (@machinedoms) {
1557: my %currservers = %servers;
1558: my %server = &get_servers($mdom);
1559: %servers = (%currservers,%server);
1560: }
1561: my %by_hostname;
1562: foreach my $id (keys(%servers)) {
1563: push(@{$by_hostname{$servers{$id}}},$id);
1564: }
1565: foreach my $hostname (sort(keys(%by_hostname))) {
1566: if (@{$by_hostname{$hostname}} > 1) {
1567: my $match = 0;
1568: foreach my $id (@{$by_hostname{$hostname}}) {
1569: if (&host_domain($id) eq $dom) {
1570: $uniqservers{$id} = $hostname;
1571: $match = 1;
1572: }
1573: }
1574: unless ($match) {
1575: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1576: }
1577: } else {
1578: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1579: }
1580: }
1581: return %uniqservers;
1582: }
1583:
1.1 albertel 1584: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1585:
1.599 albertel 1586: my %homecache;
1.1 albertel 1587: sub homeserver {
1.230 stredwic 1588: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1589: my $index="$uname:$udom";
1.426 albertel 1590:
1.599 albertel 1591: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1592:
1593: my %servers = &get_servers($udom,'library');
1594: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1595: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1596: exists($badServerCache{$tryserver}));
1.841 albertel 1597:
1598: my $answer=reply("home:$udom:$uname",$tryserver);
1599: if ($answer eq 'found') {
1600: delete($badServerCache{$tryserver});
1601: return $homecache{$index}=$tryserver;
1602: } elsif ($answer eq 'no_host') {
1603: $badServerCache{$tryserver}=1;
1604: }
1.1 albertel 1605: }
1606: return 'no_host';
1.70 www 1607: }
1608:
1.1300 raeburn 1609: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70 www 1610:
1611: sub idget {
1.1300 raeburn 1612: my ($udom,$idsref,$namespace)=@_;
1.70 www 1613: my %returnhash=();
1.1300 raeburn 1614: my @ids=();
1615: if (ref($idsref) eq 'ARRAY') {
1616: @ids = @{$idsref};
1617: } else {
1618: return %returnhash;
1619: }
1620: if ($namespace eq '') {
1621: $namespace = 'ids';
1622: }
1.70 www 1623:
1.841 albertel 1624: my %servers = &get_servers($udom,'library');
1625: foreach my $tryserver (keys(%servers)) {
1.1299 raeburn 1626: my $idlist=join('&', map { &escape($_); } @ids);
1.1300 raeburn 1627: if ($namespace eq 'ids') {
1628: $idlist=~tr/A-Z/a-z/;
1629: }
1630: my $reply;
1631: if ($namespace eq 'ids') {
1632: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1633: } else {
1634: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1635: }
1.841 albertel 1636: my @answer=();
1637: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1638: @answer=split(/\&/,$reply);
1639: } ;
1640: my $i;
1641: for ($i=0;$i<=$#ids;$i++) {
1642: if ($answer[$i]) {
1.1299 raeburn 1643: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300 raeburn 1644: }
1.841 albertel 1645: }
1.1300 raeburn 1646: }
1.70 www 1647: return %returnhash;
1648: }
1649:
1650: # ------------------------------------- Find the IDs behind a list of usernames
1651:
1652: sub idrget {
1653: my ($udom,@unames)=@_;
1654: my %returnhash=();
1.800 albertel 1655: foreach my $uname (@unames) {
1656: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1657: }
1.70 www 1658: return %returnhash;
1659: }
1660:
1.1300 raeburn 1661: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70 www 1662:
1663: sub idput {
1.1300 raeburn 1664: my ($udom,$idsref,$uhom,$namespace)=@_;
1.70 www 1665: my %servers=();
1.1300 raeburn 1666: my %ids=();
1667: my %byid = ();
1668: if (ref($idsref) eq 'HASH') {
1669: %ids=%{$idsref};
1670: }
1671: if ($namespace eq '') {
1672: $namespace = 'ids';
1673: }
1.800 albertel 1674: foreach my $uname (keys(%ids)) {
1675: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300 raeburn 1676: if ($uhom eq '') {
1677: $uhom=&homeserver($uname,$udom);
1678: }
1.70 www 1679: if ($uhom ne 'no_host') {
1.800 albertel 1680: my $esc_unam=&escape($uname);
1.1300 raeburn 1681: if ($namespace eq 'ids') {
1682: my $id=&escape($ids{$uname});
1683: $id=~tr/A-Z/a-z/;
1684: my $esc_unam=&escape($uname);
1685: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70 www 1686: } else {
1.1300 raeburn 1687: my @currids = split(/,/,$ids{$uname});
1688: foreach my $id (@currids) {
1689: $byid{$uhom}{$id} .= $uname.',';
1690: }
1691: }
1692: }
1693: }
1694: if ($namespace eq 'clickers') {
1695: foreach my $server (keys(%byid)) {
1696: if (ref($byid{$server}) eq 'HASH') {
1697: foreach my $id (keys(%{$byid{$server}})) {
1698: $byid{$server} =~ s/,$//;
1699: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
1700: }
1.70 www 1701: }
1702: }
1.191 harris41 1703: }
1.800 albertel 1704: foreach my $server (keys(%servers)) {
1.1300 raeburn 1705: $servers{$server} =~ s/\&$//;
1706: if ($namespace eq 'ids') {
1707: &critical('idput:'.$udom.':'.$servers{$server},$server);
1708: } else {
1709: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
1710: }
1.191 harris41 1711: }
1.344 www 1712: }
1713:
1.1300 raeburn 1714: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231 raeburn 1715:
1716: sub iddel {
1.1300 raeburn 1717: my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231 raeburn 1718: my %result=();
1.1300 raeburn 1719: my %ids=();
1720: my %byid = ();
1721: if (ref($idshashref) eq 'HASH') {
1722: %ids=%{$idshashref};
1723: } else {
1.1231 raeburn 1724: return %result;
1725: }
1.1300 raeburn 1726: if ($namespace eq '') {
1727: $namespace = 'ids';
1728: }
1.1231 raeburn 1729: my %servers=();
1.1300 raeburn 1730: while (my ($id,$unamestr) = each(%ids)) {
1731: if ($namespace eq 'ids') {
1732: my $uhom = $uhome;
1733: if ($uhom eq '') {
1734: $uhom=&homeserver($unamestr,$udom);
1735: }
1736: if ($uhom ne 'no_host') {
1737: $servers{$uhom}.='&'.&escape($id);
1738: }
1739: } else {
1740: my @curritems = split(/,/,$ids{$id});
1741: foreach my $uname (@curritems) {
1742: my $uhom = $uhome;
1743: if ($uhom eq '') {
1744: $uhom=&homeserver($uname,$udom);
1745: }
1746: if ($uhom ne 'no_host') {
1747: $byid{$uhom}{$id} .= $uname.',';
1748: }
1749: }
1.1231 raeburn 1750: }
1.1300 raeburn 1751: }
1752: if ($namespace eq 'clickers') {
1753: foreach my $server (keys(%byid)) {
1754: if (ref($byid{$server}) eq 'HASH') {
1755: foreach my $id (keys(%{$byid{$server}})) {
1756: $byid{$server}{$id} =~ s/,$//;
1757: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
1758: }
1.1231 raeburn 1759: }
1760: }
1761: }
1762: foreach my $server (keys(%servers)) {
1.1300 raeburn 1763: $servers{$server} =~ s/\&$//;
1764: if ($namespace eq 'ids') {
1765: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1766: } elsif ($namespace eq 'clickers') {
1767: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
1768: }
1.1231 raeburn 1769: }
1770: return %result;
1771: }
1772:
1.1300 raeburn 1773: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
1774:
1775: sub updateclickers {
1776: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
1777: my %clickers;
1778: if (ref($idshashref) eq 'HASH') {
1779: %clickers=%{$idshashref};
1780: } else {
1781: return;
1782: }
1783: my $items='';
1784: foreach my $item (keys(%clickers)) {
1785: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
1786: }
1787: $items=~s/\&$//;
1788: my $request = "updateclickers:$udom:$action:$items";
1789: if ($critical) {
1790: return &critical($request,$uhome);
1791: } else {
1792: return &reply($request,$uhome);
1793: }
1794: }
1795:
1.1023 raeburn 1796: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1797: sub dump_dom {
1.1165 droeschl 1798: my ($namespace, $udom, $regexp) = @_;
1799:
1800: $udom ||= $env{'user.domain'};
1801:
1802: return () unless $udom;
1803:
1804: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1805: }
1806:
1.1023 raeburn 1807: # ------------------------------------------ get items from domain db files
1.806 raeburn 1808:
1809: sub get_dom {
1.860 raeburn 1810: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267 raeburn 1811: return if ($udom eq 'public');
1.806 raeburn 1812: my $items='';
1813: foreach my $item (@$storearr) {
1814: $items.=&escape($item).'&';
1815: }
1816: $items=~s/\&$//;
1.860 raeburn 1817: if (!$udom) {
1818: $udom=$env{'user.domain'};
1.1267 raeburn 1819: return if ($udom eq 'public');
1.860 raeburn 1820: if (defined(&domain($udom,'primary'))) {
1821: $uhome=&domain($udom,'primary');
1822: } else {
1.874 albertel 1823: undef($uhome);
1.860 raeburn 1824: }
1825: } else {
1826: if (!$uhome) {
1827: if (defined(&domain($udom,'primary'))) {
1828: $uhome=&domain($udom,'primary');
1829: }
1830: }
1831: }
1832: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1833: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1834: my %returnhash;
1.875 albertel 1835: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1836: return %returnhash;
1837: }
1.806 raeburn 1838: my @pairs=split(/\&/,$rep);
1839: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1840: return @pairs;
1841: }
1842: my $i=0;
1843: foreach my $item (@$storearr) {
1844: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1845: $i++;
1846: }
1847: return %returnhash;
1848: } else {
1.880 banghart 1849: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1850: }
1851: }
1852:
1853: # -------------------------------------------- put items in domain db files
1854:
1855: sub put_dom {
1.860 raeburn 1856: my ($namespace,$storehash,$udom,$uhome)=@_;
1857: if (!$udom) {
1858: $udom=$env{'user.domain'};
1859: if (defined(&domain($udom,'primary'))) {
1860: $uhome=&domain($udom,'primary');
1861: } else {
1.874 albertel 1862: undef($uhome);
1.860 raeburn 1863: }
1864: } else {
1865: if (!$uhome) {
1866: if (defined(&domain($udom,'primary'))) {
1867: $uhome=&domain($udom,'primary');
1868: }
1869: }
1870: }
1871: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1872: my $items='';
1873: foreach my $item (keys(%$storehash)) {
1874: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1875: }
1876: $items=~s/\&$//;
1877: return &reply("putdom:$udom:$namespace:$items",$uhome);
1878: } else {
1.860 raeburn 1879: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1880: }
1881: }
1882:
1.1023 raeburn 1883: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1884: sub newput_dom {
1.1023 raeburn 1885: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1886: my $result;
1887: if (!$udom) {
1888: $udom=$env{'user.domain'};
1889: }
1.1023 raeburn 1890: if ($udom) {
1891: my $uname = &get_domainconfiguser($udom);
1892: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1893: }
1894: return $result;
1895: }
1896:
1.1023 raeburn 1897: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1898: sub del_dom {
1.1023 raeburn 1899: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1900: if (ref($storearr) eq 'ARRAY') {
1901: if (!$udom) {
1902: $udom=$env{'user.domain'};
1903: }
1.1023 raeburn 1904: if ($udom) {
1905: my $uname = &get_domainconfiguser($udom);
1906: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1907: }
1908: }
1909: }
1910:
1.1023 raeburn 1911: # ----------------------------------construct domainconfig user for a domain
1912: sub get_domainconfiguser {
1913: my ($udom) = @_;
1914: return $udom.'-domainconfig';
1915: }
1916:
1.837 raeburn 1917: sub retrieve_inst_usertypes {
1918: my ($udom) = @_;
1919: my (%returnhash,@order);
1.989 raeburn 1920: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1921: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1922: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 1923: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1924: } else {
1925: if (defined(&domain($udom,'primary'))) {
1926: my $uhome=&domain($udom,'primary');
1927: my $rep=&reply("inst_usertypes:$udom",$uhome);
1928: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 1929: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1930: return (\%returnhash,\@order);
1931: }
1932: my ($hashitems,$orderitems) = split(/:/,$rep);
1933: my @pairs=split(/\&/,$hashitems);
1934: foreach my $item (@pairs) {
1935: my ($key,$value)=split(/=/,$item,2);
1936: $key = &unescape($key);
1937: next if ($key =~ /^error: 2 /);
1938: $returnhash{$key}=&thaw_unescape($value);
1939: }
1940: my @esc_order = split(/\&/,$orderitems);
1941: foreach my $item (@esc_order) {
1942: push(@order,&unescape($item));
1943: }
1944: } else {
1.1256 raeburn 1945: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1946: }
1.1256 raeburn 1947: return (\%returnhash,\@order);
1.837 raeburn 1948: }
1949: }
1950:
1.868 raeburn 1951: sub is_domainimage {
1952: my ($url) = @_;
1.1306 raeburn 1953: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 1954: if (&domain($1) ne '') {
1955: return '1';
1956: }
1957: }
1958: return;
1959: }
1960:
1.899 raeburn 1961: sub inst_directory_query {
1962: my ($srch) = @_;
1963: my $udom = $srch->{'srchdomain'};
1964: my %results;
1965: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1966: my $outcome;
1.899 raeburn 1967: if ($homeserver ne '') {
1.904 albertel 1968: my $queryid=&reply("querysend:instdirsearch:".
1969: &escape($srch->{'srchby'}).':'.
1970: &escape($srch->{'srchterm'}).':'.
1971: &escape($srch->{'srchtype'}),$homeserver);
1972: my $host=&hostname($homeserver);
1973: if ($queryid !~/^\Q$host\E\_/) {
1974: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1975: return;
1976: }
1977: my $response = &get_query_reply($queryid);
1978: my $maxtries = 5;
1979: my $tries = 1;
1980: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1981: $response = &get_query_reply($queryid);
1982: $tries ++;
1983: }
1984:
1985: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1986: if ($response eq 'unavailable') {
1987: $outcome = $response;
1988: } else {
1989: $outcome = 'ok';
1990: my @matches = split(/\n/,$response);
1991: foreach my $match (@matches) {
1992: my ($key,$value) = split(/=/,$match);
1993: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1994: }
1.899 raeburn 1995: }
1996: }
1997: }
1.909 raeburn 1998: return ($outcome,%results);
1.899 raeburn 1999: }
2000:
2001: sub usersearch {
2002: my ($srch) = @_;
2003: my $dom = $srch->{'srchdomain'};
2004: my %results;
2005: my %libserv = &all_library();
2006: my $query = 'usersearch';
2007: foreach my $tryserver (keys(%libserv)) {
2008: if (&host_domain($tryserver) eq $dom) {
2009: my $host=&hostname($tryserver);
2010: my $queryid=
1.911 raeburn 2011: &reply("querysend:".&escape($query).':'.
2012: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2013: &escape($srch->{'srchtype'}).':'.
2014: &escape($srch->{'srchterm'}),$tryserver);
2015: if ($queryid !~/^\Q$host\E\_/) {
2016: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2017: next;
1.899 raeburn 2018: }
2019: my $reply = &get_query_reply($queryid);
2020: my $maxtries = 1;
2021: my $tries = 1;
2022: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2023: $reply = &get_query_reply($queryid);
2024: $tries ++;
2025: }
2026: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2027: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2028: } else {
1.911 raeburn 2029: my @matches;
2030: if ($reply =~ /\n/) {
2031: @matches = split(/\n/,$reply);
2032: } else {
2033: @matches = split(/\&/,$reply);
2034: }
1.899 raeburn 2035: foreach my $match (@matches) {
2036: my ($uname,$udom,%userhash);
1.911 raeburn 2037: foreach my $entry (split(/:/,$match)) {
2038: my ($key,$value) =
2039: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2040: $userhash{$key} = $value;
2041: if ($key eq 'username') {
2042: $uname = $value;
2043: } elsif ($key eq 'domain') {
2044: $udom = $value;
1.911 raeburn 2045: }
1.899 raeburn 2046: }
2047: $results{$uname.':'.$udom} = \%userhash;
2048: }
2049: }
2050: }
2051: }
2052: return %results;
2053: }
2054:
1.912 raeburn 2055: sub get_instuser {
2056: my ($udom,$uname,$id) = @_;
2057: my $homeserver = &domain($udom,'primary');
2058: my ($outcome,%results);
2059: if ($homeserver ne '') {
2060: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2061: &escape($id).':'.&escape($udom),$homeserver);
2062: my $host=&hostname($homeserver);
2063: if ($queryid !~/^\Q$host\E\_/) {
2064: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2065: return;
2066: }
2067: my $response = &get_query_reply($queryid);
2068: my $maxtries = 5;
2069: my $tries = 1;
2070: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2071: $response = &get_query_reply($queryid);
2072: $tries ++;
2073: }
2074: if (!&error($response) && $response ne 'refused') {
2075: if ($response eq 'unavailable') {
2076: $outcome = $response;
2077: } else {
2078: $outcome = 'ok';
2079: my @matches = split(/\n/,$response);
2080: foreach my $match (@matches) {
2081: my ($key,$value) = split(/=/,$match);
2082: $results{&unescape($key)} = &thaw_unescape($value);
2083: }
2084: }
2085: }
2086: }
2087: my %userinfo;
2088: if (ref($results{$uname}) eq 'HASH') {
2089: %userinfo = %{$results{$uname}};
2090: }
2091: return ($outcome,%userinfo);
2092: }
2093:
1.1290 raeburn 2094: sub get_multiple_instusers {
2095: my ($udom,$users,$caller) = @_;
2096: my ($outcome,$results);
2097: if (ref($users) eq 'HASH') {
2098: my $count = keys(%{$users});
2099: my $requested = &freeze_escape($users);
2100: my $homeserver = &domain($udom,'primary');
2101: if ($homeserver ne '') {
2102: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2103: my $host=&hostname($homeserver);
2104: if ($queryid !~/^\Q$host\E\_/) {
2105: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2106: ' for host: '.$homeserver.'in domain '.$udom);
2107: return ($outcome,$results);
2108: }
2109: my $response = &get_query_reply($queryid);
2110: my $maxtries = 5;
2111: if ($count > 100) {
2112: $maxtries = 1+int($count/20);
2113: }
2114: my $tries = 1;
2115: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2116: $response = &get_query_reply($queryid);
2117: $tries ++;
2118: }
2119: if ($response eq '') {
2120: $results = {};
2121: foreach my $key (keys(%{$users})) {
2122: my ($uname,$id);
2123: if ($caller eq 'id') {
2124: $id = $key;
2125: } else {
2126: $uname = $key;
2127: }
2128: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291 raeburn 2129: $outcome = $resp;
1.1290 raeburn 2130: if ($resp eq 'ok') {
2131: %{$results} = (%{$results}, %info);
2132: } else {
2133: last;
2134: }
2135: }
2136: } elsif(!&error($response) && ($response ne 'refused')) {
2137: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2138: $outcome = $response;
2139: } else {
1.1291 raeburn 2140: ($outcome,my $userdata) = split(/=/,$response,2);
1.1290 raeburn 2141: if ($outcome eq 'ok') {
2142: $results = &thaw_unescape($userdata);
2143: }
2144: }
2145: }
2146: }
2147: }
2148: return ($outcome,$results);
2149: }
2150:
1.912 raeburn 2151: sub inst_rulecheck {
1.923 raeburn 2152: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2153: my %returnhash;
2154: if ($udom ne '') {
2155: if (ref($rules) eq 'ARRAY') {
2156: @{$rules} = map {&escape($_);} (@{$rules});
2157: my $rulestr = join(':',@{$rules});
2158: my $homeserver=&domain($udom,'primary');
2159: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2160: my $response;
2161: if ($item eq 'username') {
2162: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2163: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2164: $homeserver));
1.923 raeburn 2165: } elsif ($item eq 'id') {
2166: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2167: ':'.&escape($id).':'.$rulestr,
2168: $homeserver));
1.945 raeburn 2169: } elsif ($item eq 'selfcreate') {
2170: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2171: &escape($udom).':'.&escape($uname).
2172: ':'.$rulestr,$homeserver));
1.923 raeburn 2173: }
1.912 raeburn 2174: if ($response ne 'refused') {
2175: my @pairs=split(/\&/,$response);
2176: foreach my $item (@pairs) {
2177: my ($key,$value)=split(/=/,$item,2);
2178: $key = &unescape($key);
2179: next if ($key =~ /^error: 2 /);
2180: $returnhash{$key}=&thaw_unescape($value);
2181: }
2182: }
2183: }
2184: }
2185: }
2186: return %returnhash;
2187: }
2188:
2189: sub inst_userrules {
1.923 raeburn 2190: my ($udom,$check) = @_;
1.912 raeburn 2191: my (%ruleshash,@ruleorder);
2192: if ($udom ne '') {
2193: my $homeserver=&domain($udom,'primary');
2194: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2195: my $response;
2196: if ($check eq 'id') {
2197: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2198: $homeserver);
1.943 raeburn 2199: } elsif ($check eq 'email') {
2200: $response=&reply('instemailrules:'.&escape($udom),
2201: $homeserver);
1.923 raeburn 2202: } else {
2203: $response=&reply('instuserrules:'.&escape($udom),
2204: $homeserver);
2205: }
1.912 raeburn 2206: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2207: ($response ne 'unknown_cmd') &&
1.912 raeburn 2208: ($response ne 'no_such_host')) {
2209: my ($hashitems,$orderitems) = split(/:/,$response);
2210: my @pairs=split(/\&/,$hashitems);
2211: foreach my $item (@pairs) {
2212: my ($key,$value)=split(/=/,$item,2);
2213: $key = &unescape($key);
2214: next if ($key =~ /^error: 2 /);
2215: $ruleshash{$key}=&thaw_unescape($value);
2216: }
2217: my @esc_order = split(/\&/,$orderitems);
2218: foreach my $item (@esc_order) {
2219: push(@ruleorder,&unescape($item));
2220: }
2221: }
2222: }
2223: }
2224: return (\%ruleshash,\@ruleorder);
2225: }
2226:
1.976 raeburn 2227: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2228:
2229: sub get_domain_defaults {
1.1240 raeburn 2230: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2231: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2232: my $cachetime = 60*60*24;
1.1240 raeburn 2233: unless ($ignore_cache) {
2234: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2235: if (defined($cached)) {
2236: if (ref($result) eq 'HASH') {
2237: return %{$result};
2238: }
1.943 raeburn 2239: }
2240: }
2241: my %domdefaults;
2242: my %domconfig =
1.989 raeburn 2243: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2244: 'requestcourses','inststatus',
1.1183 raeburn 2245: 'coursedefaults','usersessions',
1.1258 raeburn 2246: 'requestauthor','selfenrollment',
1.1320 raeburn 2247: 'coursecategories','ssl','autoenroll',
2248: 'trust'],$domain);
1.1305 raeburn 2249: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2250: if (ref($domconfig{'defaults'}) eq 'HASH') {
2251: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2252: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2253: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2254: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2255: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2256: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2257: } else {
2258: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2259: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2260: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2261: }
1.976 raeburn 2262: if (ref($domconfig{'quotas'}) eq 'HASH') {
2263: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2264: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2265: } else {
2266: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2267: }
1.1177 raeburn 2268: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2269: foreach my $item (@usertools) {
2270: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2271: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2272: }
2273: }
1.1229 raeburn 2274: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2275: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2276: }
1.976 raeburn 2277: }
1.985 raeburn 2278: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 raeburn 2279: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2280: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2281: }
2282: }
1.1183 raeburn 2283: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2284: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2285: }
1.989 raeburn 2286: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2287: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2288: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2289: }
2290: }
1.1047 raeburn 2291: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2292: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2293: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2294: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2295: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2296: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2297: }
1.1254 raeburn 2298: foreach my $type (@coursetypes) {
2299: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2300: unless ($type eq 'community') {
2301: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2302: }
2303: }
2304: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2305: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2306: }
1.1277 raeburn 2307: if ($domdefaults{'postsubmit'} eq 'on') {
2308: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2309: $domdefaults{$type.'postsubtimeout'} =
2310: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2311: }
2312: }
1.1230 raeburn 2313: }
1.1286 raeburn 2314: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2315: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2316: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2317: if (@clonecodes) {
2318: $domdefaults{'canclone'} = join('+',@clonecodes);
2319: }
2320: }
2321: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2322: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2323: }
1.1047 raeburn 2324: }
1.1073 raeburn 2325: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2326: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2327: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2328: }
2329: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2330: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2331: }
1.1279 raeburn 2332: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2333: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2334: }
1.1073 raeburn 2335: }
1.1254 raeburn 2336: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2337: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2338: my @settings = ('types','registered','enroll_dates','access_dates','section',
2339: 'approval','limit');
2340: foreach my $type (@coursetypes) {
2341: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2342: my @mgrdc = ();
2343: foreach my $item (@settings) {
2344: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2345: push(@mgrdc,$item);
2346: }
2347: }
2348: if (@mgrdc) {
2349: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2350: }
2351: }
2352: }
2353: }
2354: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2355: foreach my $type (@coursetypes) {
2356: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2357: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2358: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2359: }
2360: }
2361: }
2362: }
2363: }
1.1258 raeburn 2364: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2365: $domdefaults{'catauth'} = 'std';
2366: $domdefaults{'catunauth'} = 'std';
2367: if ($domconfig{'coursecategories'}{'auth'}) {
2368: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2369: }
2370: if ($domconfig{'coursecategories'}{'unauth'}) {
2371: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2372: }
2373: }
1.1315 raeburn 2374: if (ref($domconfig{'ssl'}) eq 'HASH') {
2375: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2376: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2377: }
2378: if (ref($domconfig{'ssl'}{'connect'}) eq 'HASH') {
2379: $domdefaults{'connect'} = $domconfig{'ssl'}{'connect'};
2380: }
2381: }
1.1320 raeburn 2382: if (ref($domconfig{'trust'}) eq 'HASH') {
2383: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2384: foreach my $prefix (@prefixes) {
2385: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2386: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2387: }
2388: }
2389: }
1.1314 raeburn 2390: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2391: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2392: }
1.1219 raeburn 2393: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2394: return %domdefaults;
2395: }
2396:
1.1311 raeburn 2397: sub course_portal_url {
2398: my ($cnum,$cdom) = @_;
2399: my $chome = &homeserver($cnum,$cdom);
2400: my $hostname = &hostname($chome);
2401: my $protocol = $protocol{$chome};
2402: $protocol = 'http' if ($protocol ne 'https');
2403: my %domdefaults = &get_domain_defaults($cdom);
2404: my $firsturl;
2405: if ($domdefaults{'portal_def'}) {
2406: $firsturl = $domdefaults{'portal_def'};
2407: } else {
2408: $firsturl = $protocol.'://'.$hostname;
2409: }
2410: return $firsturl;
2411: }
2412:
1.344 www 2413: # --------------------------------------------------- Assign a key to a student
2414:
2415: sub assign_access_key {
1.364 www 2416: #
2417: # a valid key looks like uname:udom#comments
2418: # comments are being appended
2419: #
1.498 www 2420: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2421: $kdom=
1.620 albertel 2422: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2423: $knum=
1.620 albertel 2424: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2425: $cdom=
1.620 albertel 2426: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2427: $cnum=
1.620 albertel 2428: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2429: $udom=$env{'user.name'} unless (defined($udom));
2430: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2431: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2432: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2433: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2434: # assigned to this person
2435: # - this should not happen,
1.345 www 2436: # unless something went wrong
2437: # the first time around
2438: # ready to assign
1.364 www 2439: $logentry=$1.'; '.$logentry;
1.496 www 2440: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2441: $kdom,$knum) eq 'ok') {
1.345 www 2442: # key now belongs to user
1.346 www 2443: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2444: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2445: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2446: return 'ok';
2447: } else {
2448: return
2449: 'error: Count not permanently assign key, will need to be re-entered later.';
2450: }
2451: } else {
2452: return 'error: Could not assign key, try again later.';
2453: }
1.364 www 2454: } elsif (!$existing{$ckey}) {
1.345 www 2455: # the key does not exist
2456: return 'error: The key does not exist';
2457: } else {
2458: # the key is somebody else's
2459: return 'error: The key is already in use';
2460: }
1.344 www 2461: }
2462:
1.364 www 2463: # ------------------------------------------ put an additional comment on a key
2464:
2465: sub comment_access_key {
2466: #
2467: # a valid key looks like uname:udom#comments
2468: # comments are being appended
2469: #
2470: my ($ckey,$cdom,$cnum,$logentry)=@_;
2471: $cdom=
1.620 albertel 2472: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2473: $cnum=
1.620 albertel 2474: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2475: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2476: if ($existing{$ckey}) {
2477: $existing{$ckey}.='; '.$logentry;
2478: # ready to assign
1.367 www 2479: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2480: $cdom,$cnum) eq 'ok') {
2481: return 'ok';
2482: } else {
2483: return 'error: Count not store comment.';
2484: }
2485: } else {
2486: # the key does not exist
2487: return 'error: The key does not exist';
2488: }
2489: }
2490:
1.344 www 2491: # ------------------------------------------------------ Generate a set of keys
2492:
2493: sub generate_access_keys {
1.364 www 2494: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2495: $cdom=
1.620 albertel 2496: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2497: $cnum=
1.620 albertel 2498: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2499: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2500: unless (($cdom) && ($cnum)) { return 0; }
2501: if ($number>10000) { return 0; }
2502: sleep(2); # make sure don't get same seed twice
2503: srand(time()^($$+($$<<15))); # from "Programming Perl"
2504: my $total=0;
2505: for (my $i=1;$i<=$number;$i++) {
2506: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2507: sprintf("%lx",int(100000*rand)).'-'.
2508: sprintf("%lx",int(100000*rand));
2509: $newkey=~s/1/g/g; # folks mix up 1 and l
2510: $newkey=~s/0/h/g; # and also 0 and O
2511: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2512: if ($existing{$newkey}) {
2513: $i--;
2514: } else {
1.364 www 2515: if (&put('accesskeys',
2516: { $newkey => '# generated '.localtime().
1.620 albertel 2517: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2518: '; '.$logentry },
2519: $cdom,$cnum) eq 'ok') {
1.344 www 2520: $total++;
2521: }
2522: }
2523: }
1.620 albertel 2524: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2525: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2526: return $total;
2527: }
2528:
2529: # ------------------------------------------------------- Validate an accesskey
2530:
2531: sub validate_access_key {
2532: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2533: $cdom=
1.620 albertel 2534: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2535: $cnum=
1.620 albertel 2536: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2537: $udom=$env{'user.domain'} unless (defined($udom));
2538: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2539: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2540: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2541: }
2542:
2543: # ------------------------------------- Find the section of student in a course
1.652 albertel 2544: sub devalidate_getsection_cache {
2545: my ($udom,$unam,$courseid)=@_;
2546: my $hashid="$udom:$unam:$courseid";
2547: &devalidate_cache_new('getsection',$hashid);
2548: }
1.298 matthew 2549:
1.815 albertel 2550: sub courseid_to_courseurl {
2551: my ($courseid) = @_;
2552: #already url style courseid
2553: return $courseid if ($courseid =~ m{^/});
2554:
2555: if (exists($env{'course.'.$courseid.'.num'})) {
2556: my $cnum = $env{'course.'.$courseid.'.num'};
2557: my $cdom = $env{'course.'.$courseid.'.domain'};
2558: return "/$cdom/$cnum";
2559: }
2560:
2561: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2562: if (exists($courseinfo{'num'})) {
2563: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2564: }
2565:
2566: return undef;
2567: }
2568:
1.298 matthew 2569: sub getsection {
2570: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2571: my $cachetime=1800;
1.551 albertel 2572:
2573: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2574: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2575: if (defined($cached)) { return $result; }
2576:
1.298 matthew 2577: my %Pending;
2578: my %Expired;
2579: #
2580: # Each role can either have not started yet (pending), be active,
2581: # or have expired.
2582: #
2583: # If there is an active role, we are done.
2584: #
2585: # If there is more than one role which has not started yet,
2586: # choose the one which will start sooner
2587: # If there is one role which has not started yet, return it.
2588: #
2589: # If there is more than one expired role, choose the one which ended last.
2590: # If there is a role which has expired, return it.
2591: #
1.815 albertel 2592: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2593: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2594: foreach my $key (keys(%roleshash)) {
1.479 albertel 2595: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2596: my $section=$1;
2597: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2598: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2599: my $now=time;
1.548 albertel 2600: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2601: $Expired{$end}=$section;
2602: next;
2603: }
1.548 albertel 2604: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2605: $Pending{$start}=$section;
2606: next;
2607: }
1.599 albertel 2608: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2609: }
2610: #
2611: # Presumedly there will be few matching roles from the above
2612: # loop and the sorting time will be negligible.
2613: if (scalar(keys(%Pending))) {
2614: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2615: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2616: }
2617: if (scalar(keys(%Expired))) {
2618: my @sorted = sort {$a <=> $b} keys(%Expired);
2619: my $time = pop(@sorted);
1.599 albertel 2620: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2621: }
1.599 albertel 2622: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2623: }
1.70 www 2624:
1.599 albertel 2625: sub save_cache {
2626: &purge_remembered();
1.722 albertel 2627: #&Apache::loncommon::validate_page();
1.620 albertel 2628: undef(%env);
1.780 albertel 2629: undef($env_loaded);
1.599 albertel 2630: }
1.452 albertel 2631:
1.599 albertel 2632: my $to_remember=-1;
2633: my %remembered;
2634: my %accessed;
2635: my $kicks=0;
2636: my $hits=0;
1.849 albertel 2637: sub make_key {
2638: my ($name,$id) = @_;
1.872 albertel 2639: if (length($id) > 65
2640: && length(&escape($id)) > 200) {
2641: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2642: }
1.849 albertel 2643: return &escape($name.':'.$id);
2644: }
2645:
1.599 albertel 2646: sub devalidate_cache_new {
2647: my ($name,$id,$debug) = @_;
2648: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319 damieng 2649: my $remembered_id=$name.':'.$id;
1.849 albertel 2650: $id=&make_key($name,$id);
1.599 albertel 2651: $memcache->delete($id);
1.1319 damieng 2652: delete($remembered{$remembered_id});
2653: delete($accessed{$remembered_id});
1.599 albertel 2654: }
2655:
2656: sub is_cached_new {
2657: my ($name,$id,$debug) = @_;
1.1319 damieng 2658: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
2659: if (exists($remembered{$remembered_id})) {
2660: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2661: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2662: $hits++;
1.1319 damieng 2663: return ($remembered{$remembered_id},1);
1.599 albertel 2664: }
1.1319 damieng 2665: $id=&make_key($name,$id);
1.599 albertel 2666: my $value = $memcache->get($id);
2667: if (!(defined($value))) {
2668: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2669: return (undef,undef);
1.416 albertel 2670: }
1.599 albertel 2671: if ($value eq '__undef__') {
2672: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2673: $value=undef;
2674: }
1.1319 damieng 2675: &make_room($remembered_id,$value,$debug);
1.599 albertel 2676: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2677: return ($value,1);
2678: }
2679:
2680: sub do_cache_new {
2681: my ($name,$id,$value,$time,$debug) = @_;
1.1319 damieng 2682: my $remembered_id=$name.':'.$id;
1.849 albertel 2683: $id=&make_key($name,$id);
1.599 albertel 2684: my $setvalue=$value;
2685: if (!defined($setvalue)) {
2686: $setvalue='__undef__';
2687: }
1.623 albertel 2688: if (!defined($time) ) {
2689: $time=600;
2690: }
1.599 albertel 2691: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2692: my $result = $memcache->set($id,$setvalue,$time);
2693: if (! $result) {
1.872 albertel 2694: &logthis("caching of id -> $id failed");
1.910 albertel 2695: $memcache->disconnect_all();
1.872 albertel 2696: }
1.600 albertel 2697: # need to make a copy of $value
1.1319 damieng 2698: &make_room($remembered_id,$value,$debug);
1.599 albertel 2699: return $value;
2700: }
2701:
2702: sub make_room {
1.1319 damieng 2703: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2704:
1.1319 damieng 2705: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2706: : $value;
1.599 albertel 2707: if ($to_remember<0) { return; }
1.1319 damieng 2708: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2709: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2710: my $to_kick;
2711: my $max_time=0;
2712: foreach my $other (keys(%accessed)) {
2713: if (&tv_interval($accessed{$other}) > $max_time) {
2714: $to_kick=$other;
2715: $max_time=&tv_interval($accessed{$other});
2716: }
2717: }
2718: delete($remembered{$to_kick});
2719: delete($accessed{$to_kick});
2720: $kicks++;
2721: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2722: return;
2723: }
2724:
1.599 albertel 2725: sub purge_remembered {
1.604 albertel 2726: #&logthis("Tossing ".scalar(keys(%remembered)));
2727: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2728: undef(%remembered);
2729: undef(%accessed);
1.428 albertel 2730: }
1.70 www 2731: # ------------------------------------- Read an entry from a user's environment
2732:
2733: sub userenvironment {
2734: my ($udom,$unam,@what)=@_;
1.976 raeburn 2735: my $items;
2736: foreach my $item (@what) {
2737: $items.=&escape($item).'&';
2738: }
2739: $items=~s/\&$//;
1.70 www 2740: my %returnhash=();
1.1009 raeburn 2741: my $uhome = &homeserver($unam,$udom);
2742: unless ($uhome eq 'no_host') {
2743: my @answer=split(/\&/,
2744: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2745: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2746: return %returnhash;
2747: }
1.1009 raeburn 2748: my $i;
2749: for ($i=0;$i<=$#what;$i++) {
2750: $returnhash{$what[$i]}=&unescape($answer[$i]);
2751: }
1.70 www 2752: }
2753: return %returnhash;
1.1 albertel 2754: }
2755:
1.617 albertel 2756: # ---------------------------------------------------------- Get a studentphoto
2757: sub studentphoto {
2758: my ($udom,$unam,$ext) = @_;
2759: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2760: if (defined($env{'request.course.id'})) {
1.708 raeburn 2761: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2762: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2763: return(&retrievestudentphoto($udom,$unam,$ext));
2764: } else {
2765: my ($result,$perm_reqd)=
1.707 albertel 2766: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2767: if ($result eq 'ok') {
2768: if (!($perm_reqd eq 'yes')) {
2769: return(&retrievestudentphoto($udom,$unam,$ext));
2770: }
2771: }
2772: }
2773: }
2774: } else {
2775: my ($result,$perm_reqd) =
1.707 albertel 2776: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2777: if ($result eq 'ok') {
2778: if (!($perm_reqd eq 'yes')) {
2779: return(&retrievestudentphoto($udom,$unam,$ext));
2780: }
2781: }
2782: }
2783: return '/adm/lonKaputt/lonlogo_broken.gif';
2784: }
2785:
2786: sub retrievestudentphoto {
2787: my ($udom,$unam,$ext,$type) = @_;
2788: my $home=&Apache::lonnet::homeserver($unam,$udom);
2789: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2790: if ($ret eq 'ok') {
2791: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2792: if ($type eq 'thumbnail') {
2793: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2794: }
2795: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2796: return $tokenurl;
2797: } else {
2798: if ($type eq 'thumbnail') {
2799: return '/adm/lonKaputt/genericstudent_tn.gif';
2800: } else {
2801: return '/adm/lonKaputt/lonlogo_broken.gif';
2802: }
1.617 albertel 2803: }
2804: }
2805:
1.263 www 2806: # -------------------------------------------------------------------- New chat
2807:
2808: sub chatsend {
1.724 raeburn 2809: my ($newentry,$anon,$group)=@_;
1.620 albertel 2810: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2811: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2812: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2813: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2814: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2815: &escape($newentry)).':'.$group,$chome);
1.292 www 2816: }
2817:
2818: # ------------------------------------------ Find current version of a resource
2819:
2820: sub getversion {
2821: my $fname=&clutter(shift);
1.1189 raeburn 2822: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2823: return ¤tversion(&filelocation('',$fname));
2824: }
2825:
2826: sub currentversion {
2827: my $fname=shift;
2828: my $author=$fname;
2829: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2830: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2831: my $home=&homeserver($uname,$udom);
1.292 www 2832: if ($home eq 'no_host') {
2833: return -1;
2834: }
1.1112 www 2835: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2836: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2837: return -1;
2838: }
1.1112 www 2839: return $answer;
1.263 www 2840: }
2841:
1.1111 www 2842: #
2843: # Return special version number of resource if set by override, empty otherwise
2844: #
2845: sub usedversion {
2846: my $fname=shift;
2847: unless ($fname) { $fname=$env{'request.uri'}; }
2848: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2849: if ($urlversion) { return $urlversion; }
2850: return '';
2851: }
2852:
1.1 albertel 2853: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2854:
1.1 albertel 2855: sub subscribe {
2856: my $fname=shift;
1.761 raeburn 2857: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2858: $fname=~s/[\n\r]//g;
1.1 albertel 2859: my $author=$fname;
2860: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2861: my ($udom,$uname)=split(/\//,$author);
2862: my $home=homeserver($uname,$udom);
1.335 albertel 2863: if ($home eq 'no_host') {
2864: return 'not_found';
1.1 albertel 2865: }
2866: my $answer=reply("sub:$fname",$home);
1.64 www 2867: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2868: $answer.=' by '.$home;
2869: }
1.1 albertel 2870: return $answer;
2871: }
2872:
1.8 www 2873: # -------------------------------------------------------------- Replicate file
2874:
2875: sub repcopy {
2876: my $filename=shift;
1.23 www 2877: $filename=~s/\/+/\//g;
1.1142 raeburn 2878: my $londocroot = $perlvar{'lonDocRoot'};
2879: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2880: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2881: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2882: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2883: return &repcopy_userfile($filename);
2884: }
1.532 albertel 2885: $filename=~s/[\n\r]//g;
1.8 www 2886: my $transname="$filename.in.transfer";
1.828 www 2887: # FIXME: this should flock
1.607 raeburn 2888: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2889: my $remoteurl=subscribe($filename);
1.64 www 2890: if ($remoteurl =~ /^con_lost by/) {
2891: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2892: return 'unavailable';
1.8 www 2893: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2894: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2895: return 'not_found';
1.64 www 2896: } elsif ($remoteurl =~ /^rejected by/) {
2897: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2898: return 'forbidden';
1.20 www 2899: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2900: return 'ok';
1.8 www 2901: } else {
1.290 www 2902: my $author=$filename;
2903: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2904: my ($udom,$uname)=split(/\//,$author);
2905: my $home=homeserver($uname,$udom);
2906: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2907: my @parts=split(/\//,$filename);
2908: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2909: if ($path ne "$londocroot/res") {
1.8 www 2910: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2911: return 'bad_request';
1.8 www 2912: }
2913: my $count;
2914: for ($count=5;$count<$#parts;$count++) {
2915: $path.="/$parts[$count]";
2916: if ((-e $path)!=1) {
2917: mkdir($path,0777);
2918: }
2919: }
2920: my $ua=new LWP::UserAgent;
2921: my $request=new HTTP::Request('GET',"$remoteurl");
2922: my $response=$ua->request($request,$transname);
2923: if ($response->is_error()) {
2924: unlink($transname);
2925: my $message=$response->status_line;
1.672 albertel 2926: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2927: ." LWP get: $message: $filename</font>");
1.607 raeburn 2928: return 'unavailable';
1.8 www 2929: } else {
1.16 www 2930: if ($remoteurl!~/\.meta$/) {
2931: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2932: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2933: if ($mresponse->is_error()) {
2934: unlink($filename.'.meta');
2935: &logthis(
1.672 albertel 2936: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2937: }
2938: }
1.8 www 2939: rename($transname,$filename);
1.607 raeburn 2940: return 'ok';
1.8 www 2941: }
1.290 www 2942: }
1.8 www 2943: }
1.330 www 2944: }
2945:
2946: # ------------------------------------------------ Get server side include body
2947: sub ssi_body {
1.381 albertel 2948: my ($filelink,%form)=@_;
1.606 matthew 2949: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2950: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2951: }
1.953 www 2952: my $output='';
2953: my $response;
1.980 raeburn 2954: if ($filelink=~/^https?\:/) {
1.954 raeburn 2955: ($output,$response)=&externalssi($filelink);
1.953 www 2956: } else {
1.1004 droeschl 2957: $filelink .= $filelink=~/\?/ ? '&' : '?';
2958: $filelink .= 'inhibitmenu=yes';
1.953 www 2959: ($output,$response)=&ssi($filelink,%form);
2960: }
1.778 albertel 2961: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2962: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2963: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2964: if (wantarray) {
2965: return ($output, $response);
2966: } else {
2967: return $output;
2968: }
1.8 www 2969: }
2970:
1.15 www 2971: # --------------------------------------------------------- Server Side Include
2972:
1.782 albertel 2973: sub absolute_url {
2974: my ($host_name) = @_;
2975: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2976: if ($host_name eq '') {
2977: $host_name = $ENV{'SERVER_NAME'};
2978: }
2979: return $protocol.$host_name;
2980: }
2981:
1.942 foxr 2982: #
2983: # Server side include.
2984: # Parameters:
2985: # fn Possibly encrypted resource name/id.
2986: # form Hash that describes how the rendering should be done
2987: # and other things.
1.944 foxr 2988: # Returns:
1.950 raeburn 2989: # Scalar context: The content of the response.
2990: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2991: #
1.15 www 2992: sub ssi {
2993:
1.944 foxr 2994: my ($fn,%form)=@_;
1.15 www 2995: my $ua=new LWP::UserAgent;
1.23 www 2996: my $request;
1.711 albertel 2997:
2998: $form{'no_update_last_known'}=1;
1.895 albertel 2999: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3000: if (%form) {
1.782 albertel 3001: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272 droeschl 3002: $request->content(join('&',map {
3003: my $name = escape($_);
3004: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3005: ? join("&$name=", map {escape($_) } @{$form{$_}})
3006: : &escape($form{$_}) );
3007: } keys(%form)));
1.23 www 3008: } else {
1.782 albertel 3009: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 3010: }
3011:
1.15 www 3012: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 3013: my $response= $ua->request($request);
1.1182 foxr 3014: my $content = $response->content;
3015:
3016:
1.944 foxr 3017: if (wantarray) {
1.1173 foxr 3018: return ($content, $response);
1.944 foxr 3019: } else {
1.1173 foxr 3020: return $content;
1.942 foxr 3021: }
1.324 www 3022: }
3023:
3024: sub externalssi {
3025: my ($url)=@_;
3026: my $ua=new LWP::UserAgent;
3027: my $request=new HTTP::Request('GET',$url);
3028: my $response=$ua->request($request);
1.954 raeburn 3029: if (wantarray) {
3030: return ($response->content, $response);
3031: } else {
3032: return $response->content;
3033: }
1.15 www 3034: }
1.254 www 3035:
1.492 albertel 3036: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3037:
3038: sub allowuploaded {
3039: my ($srcurl,$url)=@_;
3040: $url=&clutter(&declutter($url));
3041: my $dir=$url;
3042: $dir=~s/\/[^\/]+$//;
3043: my %httpref=();
3044: my $httpurl=&hreflocation('',$url);
3045: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3046: &Apache::lonnet::appenv(\%httpref);
1.254 www 3047: }
1.477 raeburn 3048:
1.1193 raeburn 3049: #
3050: # Determine if the current user should be able to edit a particular resource,
3051: # when viewing in course context.
3052: # (a) When viewing resource used to determine if "Edit" item is included in
3053: # Functions.
3054: # (b) When displaying folder contents in course editor, used to determine if
3055: # "Edit" link will be displayed alongside resource.
3056: #
1.1196 raeburn 3057: # input: six args -- filename (decluttered), course number, course domain,
3058: # url, symb (if registered) and group (if this is a group
3059: # item -- e.g., bulletin board, group page etc.).
3060: # output: array of five scalars --
1.1193 raeburn 3061: # $cfile -- url for file editing if editable on current server
3062: # $home -- homeserver of resource (i.e., for author if published,
3063: # or course if uploaded.).
3064: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 3065: # $forceedit -- 1 if icon/link should be to go to edit mode
3066: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 3067: #
3068:
3069: sub can_edit_resource {
1.1194 raeburn 3070: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3071: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3072: #
3073: # For aboutme pages user can only edit his/her own.
3074: #
1.1199 raeburn 3075: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 3076: my ($sdom,$sname) = ($1,$2);
3077: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3078: $home = $env{'user.home'};
3079: $cfile = $resurl;
3080: if ($env{'form.forceedit'}) {
3081: $forceview = 1;
3082: } else {
3083: $forceedit = 1;
3084: }
3085: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3086: } else {
3087: return;
3088: }
3089: }
3090:
3091: if ($env{'request.course.id'}) {
3092: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3093: if ($group ne '') {
3094: # if this is a group homepage or group bulletin board, check group privs
3095: my $allowed = 0;
1.1197 raeburn 3096: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3097: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3098: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3099: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3100: $allowed = 1;
3101: }
1.1197 raeburn 3102: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3103: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3104: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3105: $allowed = 1;
3106: }
3107: }
3108: if ($allowed) {
3109: $home=&homeserver($cnum,$cdom);
3110: if ($env{'form.forceedit'}) {
3111: $forceview = 1;
3112: } else {
3113: $forceedit = 1;
3114: }
3115: $cfile = $resurl;
3116: } else {
3117: return;
3118: }
3119: } else {
1.1208 raeburn 3120: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3121: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3122: return;
3123: }
3124: } elsif (!$crsedit) {
1.1194 raeburn 3125: #
3126: # No edit allowed where CC has switched to student role.
3127: #
3128: return;
3129: }
3130: }
3131: }
3132:
1.1193 raeburn 3133: if ($file ne '') {
3134: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3135: if (&is_course_upload($file,$cnum,$cdom)) {
3136: $uploaded = 1;
3137: $incourse = 1;
1.1193 raeburn 3138: if ($file =~/\.(htm|html|css|js|txt)$/) {
3139: $cfile = &hreflocation('',$file);
1.1201 raeburn 3140: if ($env{'form.forceedit'}) {
3141: $forceview = 1;
3142: } else {
3143: $forceedit = 1;
3144: }
1.1194 raeburn 3145: }
3146: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3147: $incourse = 1;
3148: if ($env{'form.forceedit'}) {
3149: $forceview = 1;
3150: } else {
3151: $forceedit = 1;
3152: }
3153: $cfile = $resurl;
3154: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3155: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3156: $incourse = 1;
3157: if ($env{'form.forceedit'}) {
3158: $forceview = 1;
3159: } else {
3160: $forceedit = 1;
3161: }
3162: $cfile = $resurl;
1.1199 raeburn 3163: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3164: $incourse = 1;
3165: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3166: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3167: $incourse = 1;
1.1199 raeburn 3168: if ($env{'form.forceedit'}) {
3169: $forceview = 1;
3170: } else {
3171: $forceedit = 1;
3172: }
3173: $cfile = $resurl;
1.1298 raeburn 3174: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
3175: $incourse = 1;
3176: if ($env{'form.forceedit'}) {
3177: $forceview = 1;
3178: } else {
3179: $forceedit = 1;
3180: }
3181: $cfile = $resurl;
1.1208 raeburn 3182: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3183: $incourse = 1;
3184: if ($env{'form.forceedit'}) {
3185: $forceview = 1;
3186: } else {
3187: $forceedit = 1;
3188: }
3189: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3190: }
3191: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3192: my $template = '/res/lib/templates/simpleproblem.problem';
3193: if (&is_on_map($template)) {
3194: $incourse = 1;
3195: $forceview = 1;
3196: $cfile = $template;
1.1193 raeburn 3197: }
1.1199 raeburn 3198: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3199: $incourse = 1;
3200: if ($env{'form.forceedit'}) {
3201: $forceview = 1;
3202: } else {
3203: $forceedit = 1;
3204: }
3205: $cfile = $resurl;
1.1298 raeburn 3206: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3207: $incourse = 1;
3208: if ($env{'form.forceedit'}) {
3209: $forceview = 1;
3210: } else {
3211: $forceedit = 1;
3212: }
3213: $cfile = $resurl;
1.1199 raeburn 3214: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3215: $incourse = 1;
3216: $forceview = 1;
3217: if ($symb) {
3218: my ($map,$id,$res)=&decode_symb($symb);
3219: $env{'request.symb'} = $symb;
3220: $cfile = &clutter($res);
3221: } else {
3222: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3223: my $escfile = &unescape($cfile);
3224: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
3225: $cfile = '/adm/wrapper'.$escfile;
3226: } else {
3227: $escfile =~ s{^http://}{};
3228: $cfile = &escape("/adm/wrapper/ext/$escfile");
3229: }
1.1199 raeburn 3230: }
1.1234 raeburn 3231: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3232: if ($env{'form.forceedit'}) {
3233: $forceview = 1;
3234: } else {
3235: $forceedit = 1;
3236: }
3237: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 3238: }
3239: }
1.1194 raeburn 3240: if ($uploaded || $incourse) {
3241: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 3242: } elsif ($file !~ m{/$}) {
1.1193 raeburn 3243: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3244: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3245: # Check that the user has permission to edit this resource
3246: my $setpriv = 1;
3247: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3248: if (defined($cfudom)) {
3249: $home=&homeserver($cfuname,$cfudom);
3250: $cfile=$file;
3251: }
3252: }
1.1194 raeburn 3253: if (($cfile ne '') && (!$incourse || $uploaded) &&
3254: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 3255: my @ids=¤t_machine_ids();
3256: unless (grep(/^\Q$home\E$/,@ids)) {
3257: $switchserver=1;
3258: }
3259: }
3260: }
1.1194 raeburn 3261: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 3262: }
3263:
3264: sub is_course_upload {
3265: my ($file,$cnum,$cdom) = @_;
3266: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3267: $uploadpath =~ s{^\/}{};
1.1201 raeburn 3268: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3269: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 3270: return 1;
3271: }
3272: return;
3273: }
3274:
1.1194 raeburn 3275: sub in_course {
1.1195 raeburn 3276: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3277: if ($hideprivileged) {
3278: my $skipuser;
1.1219 raeburn 3279: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3280: my @possdoms = ($cdom);
3281: if ($coursehash{'checkforpriv'}) {
3282: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3283: }
3284: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3285: $skipuser = 1;
3286: if ($coursehash{'nothideprivileged'}) {
3287: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3288: my $user;
3289: if ($item =~ /:/) {
3290: $user = $item;
3291: } else {
3292: $user = join(':',split(/[\@]/,$item));
3293: }
3294: if ($user eq $uname.':'.$udom) {
3295: undef($skipuser);
3296: last;
3297: }
3298: }
3299: }
3300: if ($skipuser) {
3301: return 0;
3302: }
3303: }
3304: }
1.1194 raeburn 3305: $type ||= 'any';
3306: if (!defined($cdom) || !defined($cnum)) {
3307: my $cid = $env{'request.course.id'};
3308: $cdom = $env{'course.'.$cid.'.domain'};
3309: $cnum = $env{'course.'.$cid.'.num'};
3310: }
3311: my $typesref;
1.1195 raeburn 3312: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3313: $typesref = ['active','previous','future'];
3314: } elsif ($type eq 'previous' || $type eq 'future') {
3315: $typesref = [$type];
3316: }
3317: my %roles = &get_my_roles($uname,$udom,'userroles',
3318: $typesref,undef,[$cdom]);
3319: my ($tmp) = keys(%roles);
3320: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3321: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3322: if (@course_roles > 0) {
3323: return 1;
3324: }
3325: return 0;
3326: }
3327:
1.478 albertel 3328: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3329: # input: action, courseID, current domain, intended
1.637 raeburn 3330: # path to file, source of file, instruction to parse file for objects,
3331: # ref to hash for embedded objects,
3332: # ref to hash for codebase of java objects.
1.1095 raeburn 3333: # reference to scalar to accommodate mime type determined
3334: # from File::MMagic if $parser = parse.
1.637 raeburn 3335: #
1.485 raeburn 3336: # output: url to file (if action was uploaddoc),
3337: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3338: #
1.478 albertel 3339: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3340: # course.
1.477 raeburn 3341: #
1.478 albertel 3342: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3343: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3344: # course's home server.
1.477 raeburn 3345: #
1.478 albertel 3346: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3347: # be copied from $source (current location) to
3348: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3349: # and will then be copied to
3350: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3351: # course's home server.
1.485 raeburn 3352: #
1.481 raeburn 3353: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3354: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3355: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3356: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3357: # in course's home server.
1.637 raeburn 3358: #
1.477 raeburn 3359:
3360: sub process_coursefile {
1.1095 raeburn 3361: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3362: $mimetype)=@_;
1.477 raeburn 3363: my $fetchresult;
1.638 albertel 3364: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3365: if ($action eq 'propagate') {
1.638 albertel 3366: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3367: $home);
1.481 raeburn 3368: } else {
1.477 raeburn 3369: my $fpath = '';
3370: my $fname = $file;
1.478 albertel 3371: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3372: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3373: my $filepath = &build_filepath($fpath);
1.481 raeburn 3374: if ($action eq 'copy') {
3375: if ($source eq '') {
3376: $fetchresult = 'no source file';
3377: return $fetchresult;
3378: } else {
3379: my $destination = $filepath.'/'.$fname;
3380: rename($source,$destination);
3381: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3382: $home);
1.481 raeburn 3383: }
3384: } elsif ($action eq 'uploaddoc') {
3385: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3386: print $fh $env{'form.'.$source};
1.481 raeburn 3387: close($fh);
1.637 raeburn 3388: if ($parser eq 'parse') {
1.1024 raeburn 3389: my $mm = new File::MMagic;
1.1095 raeburn 3390: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3391: if ($type eq 'text/html') {
1.1024 raeburn 3392: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3393: unless ($parse_result eq 'ok') {
3394: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3395: }
1.637 raeburn 3396: }
1.1095 raeburn 3397: if (ref($mimetype)) {
3398: $$mimetype = $type;
3399: }
1.637 raeburn 3400: }
1.477 raeburn 3401: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3402: $home);
1.481 raeburn 3403: if ($fetchresult eq 'ok') {
3404: return '/uploaded/'.$fpath.'/'.$fname;
3405: } else {
3406: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3407: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3408: return '/adm/notfound.html';
3409: }
1.477 raeburn 3410: }
3411: }
1.485 raeburn 3412: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3413: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3414: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3415: }
3416: return $fetchresult;
3417: }
3418:
1.637 raeburn 3419: sub build_filepath {
3420: my ($fpath) = @_;
3421: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3422: unless ($fpath eq '') {
3423: my @parts=split('/',$fpath);
3424: foreach my $part (@parts) {
3425: $filepath.= '/'.$part;
3426: if ((-e $filepath)!=1) {
3427: mkdir($filepath,0777);
3428: }
3429: }
3430: }
3431: return $filepath;
3432: }
3433:
3434: sub store_edited_file {
1.638 albertel 3435: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3436: my $file = $primary_url;
3437: $file =~ s#^/uploaded/$docudom/$docuname/##;
3438: my $fpath = '';
3439: my $fname = $file;
3440: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3441: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3442: my $filepath = &build_filepath($fpath);
3443: open(my $fh,'>'.$filepath.'/'.$fname);
3444: print $fh $content;
3445: close($fh);
1.638 albertel 3446: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3447: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3448: $home);
1.637 raeburn 3449: if ($$fetchresult eq 'ok') {
3450: return '/uploaded/'.$fpath.'/'.$fname;
3451: } else {
1.638 albertel 3452: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3453: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3454: return '/adm/notfound.html';
3455: }
3456: }
3457:
1.531 albertel 3458: sub clean_filename {
1.831 albertel 3459: my ($fname,$args)=@_;
1.315 www 3460: # Replace Windows backslashes by forward slashes
1.257 www 3461: $fname=~s/\\/\//g;
1.831 albertel 3462: if (!$args->{'keep_path'}) {
3463: # Get rid of everything but the actual filename
3464: $fname=~s/^.*\/([^\/]+)$/$1/;
3465: }
1.315 www 3466: # Replace spaces by underscores
3467: $fname=~s/\s+/\_/g;
3468: # Replace all other weird characters by nothing
1.831 albertel 3469: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3470: # Replace all .\d. sequences with _\d. so they no longer look like version
3471: # numbers
3472: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3473: return $fname;
3474: }
1.1051 raeburn 3475: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3476: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3477: # image with the same aspect ratio as the original, but with dimensions which do
3478: # not exceed $resizewidth and $resizeheight.
3479:
1.984 neumanie 3480: sub resizeImage {
1.1051 raeburn 3481: my ($img_path,$resizewidth,$resizeheight) = @_;
3482: my $ima = Image::Magick->new;
3483: my $resized;
3484: if (-e $img_path) {
3485: $ima->Read($img_path);
3486: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3487: my $width = $ima->Get('width');
3488: my $height = $ima->Get('height');
3489: if ($width > $resizewidth) {
3490: my $factor = $width/$resizewidth;
3491: my $newheight = $height/$factor;
3492: $ima->Scale(width=>$resizewidth,height=>$newheight);
3493: $resized = 1;
3494: }
3495: }
3496: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3497: my $width = $ima->Get('width');
3498: my $height = $ima->Get('height');
3499: if ($height > $resizeheight) {
3500: my $factor = $height/$resizeheight;
3501: my $newwidth = $width/$factor;
3502: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3503: $resized = 1;
3504: }
3505: }
3506: if ($resized) {
3507: $ima->Write($img_path);
3508: }
3509: }
3510: return;
1.977 amueller 3511: }
3512:
1.608 albertel 3513: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3514: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3515: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3516: # $context - possible values: coursedoc, existingfile, overwrite,
3517: # canceloverwrite, or ''.
3518: # if 'coursedoc': upload to the current course
3519: # if 'existingfile': write file to tmp/overwrites directory
3520: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3521: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3522: # $subdir - directory in userfile to store the file into
1.858 raeburn 3523: # $parser - instruction to parse file for objects ($parser = parse)
3524: # $allfiles - reference to hash for embedded objects
3525: # $codebase - reference to hash for codebase of java objects
3526: # $desuname - username for permanent storage of uploaded file
3527: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3528: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3529: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3530: # $resizewidth - width (pixels) to which to resize uploaded image
3531: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3532: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3533: # from File::MMagic.
1.858 raeburn 3534: #
1.686 albertel 3535: # output: url of file in userspace, or error: <message>
3536: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3537:
1.531 albertel 3538: sub userfileupload {
1.1090 raeburn 3539: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3540: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3541: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3542: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3543: $fname=&clean_filename($fname);
1.1090 raeburn 3544: # See if there is anything left
1.257 www 3545: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3546: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3547: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3548: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3549: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3550: my $now = time;
1.1090 raeburn 3551: my $filepath;
1.1095 raeburn 3552: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3553: $filepath = 'tmp/helprequests/'.$now;
3554: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3555: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3556: '_'.$env{'user.domain'}.'/pending';
3557: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3558: my ($docuname,$docudom);
3559: if ($destudom) {
3560: $docudom = $destudom;
3561: } else {
3562: $docudom = $env{'user.domain'};
3563: }
3564: if ($destuname) {
3565: $docuname = $destuname;
3566: } else {
3567: $docuname = $env{'user.name'};
3568: }
3569: if (exists($env{'form.group'})) {
3570: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3571: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3572: }
3573: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3574: if ($context eq 'canceloverwrite') {
3575: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3576: if (-e $tempfile) {
3577: my @info = stat($tempfile);
3578: if ($info[9] eq $env{'form.timestamp'}) {
3579: unlink($tempfile);
3580: }
3581: }
3582: return;
1.523 raeburn 3583: }
3584: }
1.1090 raeburn 3585: # Create the directory if not present
1.741 raeburn 3586: my @parts=split(/\//,$filepath);
3587: my $fullpath = $perlvar{'lonDaemons'};
3588: for (my $i=0;$i<@parts;$i++) {
3589: $fullpath .= '/'.$parts[$i];
3590: if ((-e $fullpath)!=1) {
3591: mkdir($fullpath,0777);
3592: }
3593: }
3594: open(my $fh,'>'.$fullpath.'/'.$fname);
3595: print $fh $env{'form.'.$formname};
3596: close($fh);
1.1090 raeburn 3597: if ($context eq 'existingfile') {
3598: my @info = stat($fullpath.'/'.$fname);
3599: return ($fullpath.'/'.$fname,$info[9]);
3600: } else {
3601: return $fullpath.'/'.$fname;
3602: }
1.523 raeburn 3603: }
1.995 raeburn 3604: if ($subdir eq 'scantron') {
3605: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3606: } else {
1.995 raeburn 3607: $fname="$subdir/$fname";
3608: }
1.1090 raeburn 3609: if ($context eq 'coursedoc') {
1.638 albertel 3610: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3611: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3612: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3613: return &finishuserfileupload($docuname,$docudom,
3614: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3615: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3616: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3617: } else {
1.1218 raeburn 3618: if ($env{'form.folder'}) {
3619: $fname=$env{'form.folder'}.'/'.$fname;
3620: }
1.638 albertel 3621: return &process_coursefile('uploaddoc',$docuname,$docudom,
3622: $fname,$formname,$parser,
1.1095 raeburn 3623: $allfiles,$codebase,$mimetype);
1.481 raeburn 3624: }
1.719 banghart 3625: } elsif (defined($destuname)) {
3626: my $docuname=$destuname;
3627: my $docudom=$destudom;
1.860 raeburn 3628: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3629: $parser,$allfiles,$codebase,
1.1051 raeburn 3630: $thumbwidth,$thumbheight,
1.1095 raeburn 3631: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3632: } else {
1.638 albertel 3633: my $docuname=$env{'user.name'};
3634: my $docudom=$env{'user.domain'};
1.1220 raeburn 3635: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3636: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3637: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3638: }
1.860 raeburn 3639: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3640: $parser,$allfiles,$codebase,
1.1051 raeburn 3641: $thumbwidth,$thumbheight,
1.1095 raeburn 3642: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3643: }
1.271 www 3644: }
3645:
3646: sub finishuserfileupload {
1.860 raeburn 3647: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3648: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3649: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3650: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3651:
1.860 raeburn 3652: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3653: $file=$fname;
3654: if ($fname=~m|/|) {
3655: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3656: $path.=$fnamepath.'/';
3657: }
1.259 www 3658: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3659: my $count;
3660: for ($count=4;$count<=$#parts;$count++) {
3661: $filepath.="/$parts[$count]";
3662: if ((-e $filepath)!=1) {
3663: mkdir($filepath,0777);
3664: }
3665: }
1.984 neumanie 3666:
1.258 www 3667: # Save the file
3668: {
1.701 albertel 3669: if (!open(FH,'>'.$filepath.'/'.$file)) {
3670: &logthis('Failed to create '.$filepath.'/'.$file);
3671: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3672: return '/adm/notfound.html';
3673: }
1.1090 raeburn 3674: if ($context eq 'overwrite') {
1.1117 foxr 3675: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3676: my $target = $filepath.'/'.$file;
3677: if (-e $source) {
3678: my @info = stat($source);
3679: if ($info[9] eq $env{'form.timestamp'}) {
3680: unless (&File::Copy::move($source,$target)) {
3681: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3682: return "Moving from $source failed";
3683: }
3684: } else {
3685: return "Temporary file: $source had unexpected date/time for last modification";
3686: }
3687: } else {
3688: return "Temporary file: $source missing";
3689: }
3690: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3691: &logthis('Failed to write to '.$filepath.'/'.$file);
3692: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3693: return '/adm/notfound.html';
3694: }
1.570 albertel 3695: close(FH);
1.1051 raeburn 3696: if ($resizewidth && $resizeheight) {
3697: my $mm = new File::MMagic;
3698: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3699: if ($mime_type =~ m{^image/}) {
3700: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3701: }
1.977 amueller 3702: }
1.258 www 3703: }
1.1152 raeburn 3704: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3705: if (ref($mimetype)) {
3706: if ($$mimetype eq '') {
3707: my $mm = new File::MMagic;
3708: my $type = $mm->checktype_filename($filepath.'/'.$file);
3709: $$mimetype = $type;
3710: }
3711: }
3712: }
1.637 raeburn 3713: if ($parser eq 'parse') {
1.1152 raeburn 3714: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3715: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3716: $allfiles,$codebase);
3717: unless ($parse_result eq 'ok') {
3718: &logthis('Failed to parse '.$filepath.$file.
3719: ' for embedded media: '.$parse_result);
3720: }
1.637 raeburn 3721: }
3722: }
1.860 raeburn 3723: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3724: my $input = $filepath.'/'.$file;
3725: my $output = $filepath.'/'.'tn-'.$file;
3726: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3727: system("convert -sample $thumbsize $input $output");
3728: if (-e $filepath.'/'.'tn-'.$file) {
3729: $fetchthumb = 1;
3730: }
3731: }
1.858 raeburn 3732:
1.259 www 3733: # Notify homeserver to grep it
3734: #
1.984 neumanie 3735: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3736: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3737: if ($fetchresult eq 'ok') {
1.860 raeburn 3738: if ($fetchthumb) {
3739: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3740: if ($thumbresult ne 'ok') {
3741: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3742: $docuhome.': '.$thumbresult);
3743: }
3744: }
1.259 www 3745: #
1.258 www 3746: # Return the URL to it
1.494 albertel 3747: return '/uploaded/'.$path.$file;
1.263 www 3748: } else {
1.494 albertel 3749: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3750: ': '.$fetchresult);
1.263 www 3751: return '/adm/notfound.html';
1.858 raeburn 3752: }
1.493 albertel 3753: }
3754:
1.637 raeburn 3755: sub extract_embedded_items {
1.961 raeburn 3756: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3757: my @state = ();
1.1164 raeburn 3758: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3759: my %javafiles = (
3760: codebase => '',
3761: code => '',
3762: archive => ''
3763: );
3764: my %mediafiles = (
3765: src => '',
3766: movie => '',
3767: );
1.648 raeburn 3768: my $p;
3769: if ($content) {
3770: $p = HTML::LCParser->new($content);
3771: } else {
1.961 raeburn 3772: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3773: }
1.641 albertel 3774: while (my $t=$p->get_token()) {
1.640 albertel 3775: if ($t->[0] eq 'S') {
3776: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3777: push(@state, $tagname);
1.648 raeburn 3778: if (lc($tagname) eq 'allow') {
3779: &add_filetype($allfiles,$attr->{'src'},'src');
3780: }
1.640 albertel 3781: if (lc($tagname) eq 'img') {
3782: &add_filetype($allfiles,$attr->{'src'},'src');
3783: }
1.886 albertel 3784: if (lc($tagname) eq 'a') {
1.1222 raeburn 3785: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3786: &add_filetype($allfiles,$attr->{'href'},'href');
3787: }
1.886 albertel 3788: }
1.645 raeburn 3789: if (lc($tagname) eq 'script') {
1.1164 raeburn 3790: my $src;
1.645 raeburn 3791: if ($attr->{'archive'} =~ /\.jar$/i) {
3792: &add_filetype($allfiles,$attr->{'archive'},'archive');
3793: } else {
1.1164 raeburn 3794: if ($attr->{'src'} ne '') {
3795: $src = $attr->{'src'};
3796: &add_filetype($allfiles,$src,'src');
3797: }
3798: }
3799: my $text = $p->get_trimmed_text();
3800: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3801: my @swfargs = split(/,/,$1);
3802: foreach my $item (@swfargs) {
3803: $item =~ s/["']//g;
3804: $item =~ s/^\s+//;
3805: $item =~ s/\s+$//;
3806: }
3807: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3808: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3809: push(@{$related{$swfargs[0]}},$swfargs[2]);
3810: } else {
3811: $related{$swfargs[0]} = [$swfargs[2]];
3812: }
3813: }
1.645 raeburn 3814: }
3815: }
3816: if (lc($tagname) eq 'link') {
3817: if (lc($attr->{'rel'}) eq 'stylesheet') {
3818: &add_filetype($allfiles,$attr->{'href'},'href');
3819: }
3820: }
1.640 albertel 3821: if (lc($tagname) eq 'object' ||
3822: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3823: foreach my $item (keys(%javafiles)) {
3824: $javafiles{$item} = '';
3825: }
1.1164 raeburn 3826: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3827: $lastids{lc($tagname)} = $attr->{'id'};
3828: }
1.640 albertel 3829: }
3830: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3831: my $name = lc($attr->{'name'});
3832: foreach my $item (keys(%javafiles)) {
3833: if ($name eq $item) {
3834: $javafiles{$item} = $attr->{'value'};
3835: last;
3836: }
3837: }
1.1164 raeburn 3838: my $pathfrom;
1.640 albertel 3839: foreach my $item (keys(%mediafiles)) {
3840: if ($name eq $item) {
1.1164 raeburn 3841: $pathfrom = $attr->{'value'};
3842: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3843: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3844: last;
3845: }
3846: }
1.1164 raeburn 3847: if ($name eq 'flashvars') {
3848: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3849: }
3850: if ($pathfrom ne '') {
3851: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3852: $pathfrom);
3853: }
1.640 albertel 3854: }
3855: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3856: foreach my $item (keys(%javafiles)) {
3857: if ($attr->{$item}) {
3858: $javafiles{$item} = $attr->{$item};
3859: last;
3860: }
3861: }
3862: foreach my $item (keys(%mediafiles)) {
3863: if ($attr->{$item}) {
3864: &add_filetype($allfiles,$attr->{$item},$item);
3865: last;
3866: }
3867: }
1.1164 raeburn 3868: if (lc($tagname) eq 'embed') {
3869: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3870: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3871: $attr->{'src'});
3872: }
3873: }
1.640 albertel 3874: }
1.1243 raeburn 3875: if (lc($tagname) eq 'iframe') {
3876: my $src = $attr->{'src'} ;
3877: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3878: &add_filetype($allfiles,$src,'src');
3879: } elsif ($src =~ m{^/}) {
3880: if ($env{'request.course.id'}) {
3881: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3882: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3883: my $url = &hreflocation('',$fullpath);
3884: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3885: my $relpath = $1;
3886: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3887: &add_filetype($allfiles,$1,'src');
3888: }
3889: }
3890: }
3891: }
3892: }
1.1164 raeburn 3893: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3894: pop(@state);
1.1164 raeburn 3895: }
1.640 albertel 3896: } elsif ($t->[0] eq 'E') {
3897: my ($tagname) = ($t->[1]);
3898: if ($javafiles{'codebase'} ne '') {
3899: $javafiles{'codebase'} .= '/';
3900: }
3901: if (lc($tagname) eq 'applet' ||
3902: lc($tagname) eq 'object' ||
3903: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3904: ) {
3905: foreach my $item (keys(%javafiles)) {
3906: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3907: my $file=$javafiles{'codebase'}.$javafiles{$item};
3908: &add_filetype($allfiles,$file,$item);
3909: }
3910: }
3911: }
3912: pop @state;
3913: }
3914: }
1.1164 raeburn 3915: foreach my $id (sort(keys(%flashvars))) {
3916: if ($shockwave{$id} ne '') {
3917: my @pairs = split(/\&/,$flashvars{$id});
3918: foreach my $pair (@pairs) {
3919: my ($key,$value) = split(/\=/,$pair);
3920: if ($key eq 'thumb') {
3921: &add_filetype($allfiles,$value,$key);
3922: } elsif ($key eq 'content') {
3923: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3924: my ($ext) = ($value =~ /\.([^.]+)$/);
3925: if ($ext ne '') {
3926: &add_filetype($allfiles,$path.$value,$ext);
3927: }
3928: }
3929: }
3930: }
3931: }
1.637 raeburn 3932: return 'ok';
3933: }
3934:
1.639 albertel 3935: sub add_filetype {
3936: my ($allfiles,$file,$type)=@_;
3937: if (exists($allfiles->{$file})) {
3938: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3939: push(@{$allfiles->{$file}}, &escape($type));
3940: }
3941: } else {
3942: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3943: }
3944: }
3945:
1.1164 raeburn 3946: sub embedded_dependency {
3947: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3948: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3949: if (($identifier ne '') &&
3950: (ref($related->{$identifier}) eq 'ARRAY') &&
3951: ($pathfrom ne '')) {
3952: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3953: foreach my $dep (@{$related->{$identifier}}) {
3954: &add_filetype($allfiles,$path.$dep,'object');
3955: }
3956: }
3957: }
3958: return;
3959: }
3960:
1.493 albertel 3961: sub removeuploadedurl {
1.984 neumanie 3962: my ($url)=@_;
3963: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3964: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3965: }
3966:
3967: sub removeuserfile {
3968: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3969: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3970: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3971: if ($result eq 'ok') {
1.798 raeburn 3972: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3973: my $metafile = $fname.'.meta';
3974: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3975: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3976: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3977: my $sqlresult =
1.823 albertel 3978: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3979: 'portfolio_metadata',$group,
3980: 'delete');
1.798 raeburn 3981: }
3982: }
3983: return $result;
1.257 www 3984: }
1.15 www 3985:
1.530 albertel 3986: sub mkdiruserfile {
3987: my ($docuname,$docudom,$dir)=@_;
3988: my $home=&homeserver($docuname,$docudom);
3989: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3990: }
3991:
1.531 albertel 3992: sub renameuserfile {
3993: my ($docuname,$docudom,$old,$new)=@_;
3994: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3995: my $result = &reply("renameuserfile:$docudom:$docuname:".
3996: &escape("$old").':'.&escape("$new"),$home);
3997: if ($result eq 'ok') {
3998: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3999: my $oldmeta = $old.'.meta';
4000: my $newmeta = $new.'.meta';
4001: my $metaresult =
4002: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4003: my $url = "/uploaded/$docudom/$docuname/$old";
4004: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4005: my $sqlresult =
1.823 albertel 4006: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4007: 'portfolio_metadata',$group,
4008: 'delete');
1.798 raeburn 4009: }
4010: }
4011: return $result;
1.531 albertel 4012: }
4013:
1.14 www 4014: # ------------------------------------------------------------------------- Log
4015:
4016: sub log {
4017: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4018: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4019: }
4020:
4021: # ------------------------------------------------------------------ Course Log
1.352 www 4022: #
4023: # This routine flushes several buffers of non-mission-critical nature
4024: #
1.157 www 4025:
4026: sub flushcourselogs {
1.352 www 4027: &logthis('Flushing log buffers');
4028: #
4029: # course logs
4030: # This is a log of all transactions in a course, which can be used
4031: # for data mining purposes
4032: #
4033: # It also collects the courseid database, which lists last transaction
4034: # times and course titles for all courseids
4035: #
4036: my %courseidbuffer=();
1.921 raeburn 4037: foreach my $crsid (keys(%courselogs)) {
1.352 www 4038: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4039: &escape($courselogs{$crsid}),
4040: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4041: delete $courselogs{$crsid};
4042: } else {
4043: &logthis('Failed to flush log buffer for '.$crsid);
4044: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4045: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4046: " exceeded maximum size, deleting.</font>");
4047: delete $courselogs{$crsid};
4048: }
1.352 www 4049: }
1.920 raeburn 4050: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4051: 'description' => $coursedescrbuf{$crsid},
4052: 'inst_code' => $courseinstcodebuf{$crsid},
4053: 'type' => $coursetypebuf{$crsid},
4054: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4055: };
1.191 harris41 4056: }
1.352 www 4057: #
4058: # Write course id database (reverse lookup) to homeserver of courses
4059: # Is used in pickcourse
4060: #
1.840 albertel 4061: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4062: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4063: $courseidbuffer{$crs_home},
4064: $crs_home,'timeonly');
1.352 www 4065: }
4066: #
4067: # File accesses
4068: # Writes to the dynamic metadata of resources to get hit counts, etc.
4069: #
1.449 matthew 4070: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4071: if ($entry =~ /___count$/) {
4072: my ($dom,$name);
1.807 albertel 4073: ($dom,$name,undef)=
1.811 albertel 4074: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4075: if (! defined($dom) || $dom eq '' ||
4076: ! defined($name) || $name eq '') {
1.620 albertel 4077: my $cid = $env{'request.course.id'};
4078: $dom = $env{'request.'.$cid.'.domain'};
4079: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4080: }
1.450 matthew 4081: my $value = $accesshash{$entry};
4082: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4083: my %temphash=($url => $value);
1.449 matthew 4084: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4085: if ($result eq 'ok') {
4086: delete $accesshash{$entry};
4087: }
4088: } else {
1.811 albertel 4089: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4090: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4091: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4092: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4093: delete $accesshash{$entry};
4094: }
1.185 www 4095: }
1.191 harris41 4096: }
1.352 www 4097: #
4098: # Roles
4099: # Reverse lookup of user roles for course faculty/staff and co-authorship
4100: #
1.800 albertel 4101: foreach my $entry (keys(%userrolehash)) {
1.351 www 4102: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4103: split(/\:/,$entry);
4104: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4105: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4106: $rudom,$runame) eq 'ok') {
4107: delete $userrolehash{$entry};
4108: }
4109: }
1.662 raeburn 4110: #
1.1327 ! raeburn 4111: # Reverse lookup of domain roles (dc, ad, li, sc, dh, au)
1.662 raeburn 4112: #
4113: my %domrolebuffer = ();
1.1000 raeburn 4114: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4115: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4116: if ($domrolebuffer{$rudom}) {
4117: $domrolebuffer{$rudom}.='&'.&escape($entry).
4118: '='.&escape($domainrolehash{$entry});
4119: } else {
4120: $domrolebuffer{$rudom}.=&escape($entry).
4121: '='.&escape($domainrolehash{$entry});
4122: }
4123: delete $domainrolehash{$entry};
4124: }
4125: foreach my $dom (keys(%domrolebuffer)) {
1.1324 raeburn 4126: my %servers;
4127: if (defined(&domain($dom,'primary'))) {
4128: my $primary=&domain($dom,'primary');
4129: my $hostname=&hostname($primary);
4130: $servers{$primary} = $hostname;
4131: } else {
4132: %servers = &get_servers($dom,'library');
4133: }
1.841 albertel 4134: foreach my $tryserver (keys(%servers)) {
1.1324 raeburn 4135: if (&reply('domroleput:'.$dom.':'.
4136: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4137: last;
4138: } else {
1.841 albertel 4139: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4140: }
1.662 raeburn 4141: }
4142: }
1.186 www 4143: $dumpcount++;
1.157 www 4144: }
4145:
4146: sub courselog {
4147: my $what=shift;
1.158 www 4148: $what=time.':'.$what;
1.620 albertel 4149: unless ($env{'request.course.id'}) { return ''; }
4150: $coursedombuf{$env{'request.course.id'}}=
4151: $env{'course.'.$env{'request.course.id'}.'.domain'};
4152: $coursenumbuf{$env{'request.course.id'}}=
4153: $env{'course.'.$env{'request.course.id'}.'.num'};
4154: $coursehombuf{$env{'request.course.id'}}=
4155: $env{'course.'.$env{'request.course.id'}.'.home'};
4156: $coursedescrbuf{$env{'request.course.id'}}=
4157: $env{'course.'.$env{'request.course.id'}.'.description'};
4158: $courseinstcodebuf{$env{'request.course.id'}}=
4159: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4160: $courseownerbuf{$env{'request.course.id'}}=
4161: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4162: $coursetypebuf{$env{'request.course.id'}}=
4163: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4164: if (defined $courselogs{$env{'request.course.id'}}) {
4165: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4166: } else {
1.620 albertel 4167: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4168: }
1.620 albertel 4169: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4170: &flushcourselogs();
4171: }
1.158 www 4172: }
4173:
4174: sub courseacclog {
4175: my $fnsymb=shift;
1.620 albertel 4176: unless ($env{'request.course.id'}) { return ''; }
4177: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4178: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4179: $what.=':POST';
1.583 matthew 4180: # FIXME: Probably ought to escape things....
1.800 albertel 4181: foreach my $key (keys(%env)) {
4182: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4183: my $formitem = $1;
4184: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4185: $what.=':'.$formitem.'='.$env{$key};
4186: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4187: $what.=':'.$formitem.'='.$env{$key};
4188: }
1.158 www 4189: }
1.191 harris41 4190: }
1.583 matthew 4191: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4192: # FIXME: We should not be depending on a form parameter that someone
4193: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4194: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4195: $what.= ':POST';
4196: # FIXME: Probably ought to escape things....
4197: foreach my $element ('courseexp','crsfulltext','crsrelated',
4198: 'crsdiscuss') {
1.620 albertel 4199: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4200: }
4201: }
1.158 www 4202: }
4203: &courselog($what);
1.149 www 4204: }
4205:
1.185 www 4206: sub countacc {
4207: my $url=&declutter(shift);
1.458 matthew 4208: return if (! defined($url) || $url eq '');
1.620 albertel 4209: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4210: #
4211: # Mark that this url was used in this course
4212: #
1.620 albertel 4213: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4214: #
4215: # Increase the access count for this resource in this child process
4216: #
1.281 www 4217: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4218: $accesshash{$key}++;
1.185 www 4219: }
1.349 www 4220:
1.361 www 4221: sub linklog {
4222: my ($from,$to)=@_;
4223: $from=&declutter($from);
4224: $to=&declutter($to);
4225: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4226: $accesshash{$to.'___'.$from.'___goto'}=1;
4227: }
1.1160 www 4228:
4229: sub statslog {
4230: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4231: if ($users<2) { return; }
4232: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4233: 'course' => $env{'request.course.id'},
4234: 'sections' => '"all"',
4235: 'num_students' => $users,
4236: 'part' => $part,
4237: 'symb' => $symb,
4238: 'mean_tries' => $av_attempts,
4239: 'deg_of_diff' => $degdiff});
4240: foreach my $key (keys(%dynstore)) {
4241: $accesshash{$key}=$dynstore{$key};
4242: }
4243: }
1.361 www 4244:
1.349 www 4245: sub userrolelog {
4246: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4247: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4248: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4249: $userrolehash
4250: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4251: =$tend.':'.$tstart;
1.662 raeburn 4252: }
1.1169 droeschl 4253: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4254: $userrolehash
4255: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4256: =$tend.':'.$tstart;
4257: }
1.1327 ! raeburn 4258: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh)/ ) {
1.662 raeburn 4259: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4260: $domainrolehash
4261: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4262: = $tend.':'.$tstart;
4263: }
1.351 www 4264: }
4265:
1.957 raeburn 4266: sub courserolelog {
4267: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 4268: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4269: my $cdom = $1;
4270: my $cnum = $2;
4271: my $sec = $3;
4272: my $namespace = 'rolelog';
4273: my %storehash = (
4274: role => $trole,
4275: start => $tstart,
4276: end => $tend,
4277: selfenroll => $selfenroll,
4278: context => $context,
4279: );
4280: if ($trole eq 'gr') {
4281: $namespace = 'groupslog';
4282: $storehash{'group'} = $sec;
4283: } else {
4284: $storehash{'section'} = $sec;
4285: }
1.1188 raeburn 4286: &write_log('course',$namespace,\%storehash,$delflag,$username,
4287: $domain,$cnum,$cdom);
1.1184 raeburn 4288: if (($trole ne 'st') || ($sec ne '')) {
4289: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4290: }
4291: }
4292: return;
4293: }
4294:
1.1184 raeburn 4295: sub domainrolelog {
4296: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4297: if ($area =~ m{^/($match_domain)/$}) {
4298: my $cdom = $1;
4299: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4300: my $namespace = 'rolelog';
4301: my %storehash = (
4302: role => $trole,
4303: start => $tstart,
4304: end => $tend,
4305: context => $context,
4306: );
1.1188 raeburn 4307: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4308: $domain,$domconfiguser,$cdom);
1.1184 raeburn 4309: }
4310: return;
4311:
4312: }
4313:
4314: sub coauthorrolelog {
4315: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4316: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4317: my $audom = $1;
4318: my $auname = $2;
4319: my $namespace = 'rolelog';
4320: my %storehash = (
4321: role => $trole,
4322: start => $tstart,
4323: end => $tend,
4324: context => $context,
4325: );
1.1188 raeburn 4326: &write_log('author',$namespace,\%storehash,$delflag,$username,
4327: $domain,$auname,$audom);
1.1184 raeburn 4328: }
4329: return;
4330: }
4331:
1.351 www 4332: sub get_course_adv_roles {
1.948 raeburn 4333: my ($cid,$codes) = @_;
1.620 albertel 4334: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4335: my %coursehash=&coursedescription($cid);
1.988 raeburn 4336: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4337: my %nothide=();
1.800 albertel 4338: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4339: if ($user !~ /:/) {
4340: $nothide{join(':',split(/[\@]/,$user))}=1;
4341: } else {
4342: $nothide{$user}=1;
4343: }
1.470 www 4344: }
1.1219 raeburn 4345: my @possdoms = ($coursehash{'domain'});
4346: if ($coursehash{'checkforpriv'}) {
4347: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4348: }
1.351 www 4349: my %returnhash=();
4350: my %dumphash=
4351: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4352: my $now=time;
1.997 raeburn 4353: my %privileged;
1.1000 raeburn 4354: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4355: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4356: if (($tstart) && ($tstart<0)) { next; }
4357: if (($tend) && ($tend<$now)) { next; }
4358: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4359: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4360: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 4361: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4362: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4363: if ($role eq 'cr') { next; }
1.948 raeburn 4364: if ($codes) {
4365: if ($section) { $role .= ':'.$section; }
4366: if ($returnhash{$role}) {
4367: $returnhash{$role}.=','.$username.':'.$domain;
4368: } else {
4369: $returnhash{$role}=$username.':'.$domain;
4370: }
1.351 www 4371: } else {
1.988 raeburn 4372: my $key=&plaintext($role,$crstype);
1.973 bisitz 4373: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4374: if ($returnhash{$key}) {
4375: $returnhash{$key}.=','.$username.':'.$domain;
4376: } else {
4377: $returnhash{$key}=$username.':'.$domain;
4378: }
1.351 www 4379: }
1.948 raeburn 4380: }
1.400 www 4381: return %returnhash;
4382: }
4383:
4384: sub get_my_roles {
1.937 raeburn 4385: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4386: unless (defined($uname)) { $uname=$env{'user.name'}; }
4387: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4388: my (%dumphash,%nothide);
1.1086 raeburn 4389: if ($context eq 'userroles') {
1.1166 raeburn 4390: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4391: } else {
1.1219 raeburn 4392: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4393: if ($hidepriv) {
4394: my %coursehash=&coursedescription($udom.'_'.$uname);
4395: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4396: if ($user !~ /:/) {
4397: $nothide{join(':',split(/[\@]/,$user))} = 1;
4398: } else {
4399: $nothide{$user} = 1;
4400: }
4401: }
4402: }
1.858 raeburn 4403: }
1.400 www 4404: my %returnhash=();
4405: my $now=time;
1.999 raeburn 4406: my %privileged;
1.800 albertel 4407: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4408: my ($role,$tend,$tstart);
4409: if ($context eq 'userroles') {
1.1149 raeburn 4410: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4411: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4412: } else {
4413: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4414: }
1.400 www 4415: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4416: my $status = 'active';
1.939 raeburn 4417: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4418: $status = 'previous';
4419: }
4420: if (($tstart) && ($now<$tstart)) {
4421: $status = 'future';
4422: }
4423: if (ref($types) eq 'ARRAY') {
4424: if (!grep(/^\Q$status\E$/,@{$types})) {
4425: next;
4426: }
4427: } else {
4428: if ($status ne 'active') {
4429: next;
4430: }
4431: }
1.867 raeburn 4432: my ($rolecode,$username,$domain,$section,$area);
4433: if ($context eq 'userroles') {
1.1186 raeburn 4434: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4435: (undef,$domain,$username,$section) = split(/\//,$area);
4436: } else {
4437: ($role,$username,$domain,$section) = split(/\:/,$entry);
4438: }
1.832 raeburn 4439: if (ref($roledoms) eq 'ARRAY') {
4440: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4441: next;
4442: }
4443: }
4444: if (ref($roles) eq 'ARRAY') {
4445: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4446: if ($role =~ /^cr\//) {
4447: if (!grep(/^cr$/,@{$roles})) {
4448: next;
4449: }
1.1104 raeburn 4450: } elsif ($role =~ /^gr\//) {
4451: if (!grep(/^gr$/,@{$roles})) {
4452: next;
4453: }
1.922 raeburn 4454: } else {
4455: next;
4456: }
1.832 raeburn 4457: }
1.867 raeburn 4458: }
1.937 raeburn 4459: if ($hidepriv) {
1.1219 raeburn 4460: my @privroles = ('dc','su');
1.999 raeburn 4461: if ($context eq 'userroles') {
1.1219 raeburn 4462: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4463: } else {
1.1219 raeburn 4464: my $possdoms = [$domain];
4465: if (ref($roledoms) eq 'ARRAY') {
4466: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4467: }
1.1219 raeburn 4468: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4469: if (!$nothide{$username.':'.$domain}) {
4470: next;
4471: }
4472: }
1.937 raeburn 4473: }
4474: }
1.933 raeburn 4475: if ($withsec) {
4476: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4477: $tstart.':'.$tend;
4478: } else {
4479: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4480: }
1.832 raeburn 4481: }
1.373 www 4482: return %returnhash;
1.399 www 4483: }
4484:
4485: # ----------------------------------------------------- Frontpage Announcements
4486: #
4487: #
4488:
4489: sub postannounce {
4490: my ($server,$text)=@_;
1.844 albertel 4491: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4492: unless ($text=~/\w/) { $text=''; }
4493: return &reply('setannounce:'.&escape($text),$server);
4494: }
4495:
4496: sub getannounce {
1.448 albertel 4497:
4498: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4499: my $announcement='';
1.800 albertel 4500: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4501: close($fh);
1.399 www 4502: if ($announcement=~/\w/) {
4503: return
4504: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4505: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4506: } else {
4507: return '';
4508: }
4509: } else {
4510: return '';
4511: }
1.351 www 4512: }
1.353 www 4513:
4514: # ---------------------------------------------------------- Course ID routines
4515: # Deal with domain's nohist_courseid.db files
4516: #
4517:
4518: sub courseidput {
1.921 raeburn 4519: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4520: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4521: my $outcome;
4522: if ($caller eq 'timeonly') {
4523: my $cids = '';
4524: foreach my $item (keys(%$storehash)) {
4525: $cids.=&escape($item).'&';
4526: }
4527: $cids=~s/\&$//;
4528: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4529: $coursehome);
4530: } else {
4531: my $items = '';
4532: foreach my $item (keys(%$storehash)) {
4533: $items.= &escape($item).'='.
4534: &freeze_escape($$storehash{$item}).'&';
4535: }
4536: $items=~s/\&$//;
4537: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4538: $coursehome);
1.918 raeburn 4539: }
4540: if ($outcome eq 'unknown_cmd') {
4541: my $what;
4542: foreach my $cid (keys(%$storehash)) {
4543: $what .= &escape($cid).'=';
1.921 raeburn 4544: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4545: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4546: }
4547: $what =~ s/\:$/&/;
4548: }
4549: $what =~ s/\&$//;
4550: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4551: } else {
4552: return $outcome;
4553: }
1.353 www 4554: }
4555:
4556: sub courseiddump {
1.921 raeburn 4557: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4558: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4559: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4560: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 4561: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4562: my $as_hash = 1;
4563: my %returnhash;
4564: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4565: my %libserv = &all_library();
4566: foreach my $tryserver (keys(%libserv)) {
4567: if ( ( $hostidflag == 1
4568: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4569: || (!defined($hostidflag)) ) {
4570:
1.918 raeburn 4571: if (($domfilter eq '') ||
4572: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4573: my $rep;
4574: if (grep { $_ eq $tryserver } current_machine_ids()) {
4575: $rep = LONCAPA::Lond::dump_course_id_handler(
4576: join(":", (&host_domain($tryserver), $sincefilter,
4577: &escape($descfilter), &escape($instcodefilter),
4578: &escape($ownerfilter), &escape($coursefilter),
4579: &escape($typefilter), &escape($regexp_ok),
4580: $as_hash, &escape($selfenrollonly),
4581: &escape($catfilter), $showhidden, $caller,
4582: &escape($cloner), &escape($cc_clone), $cloneonly,
4583: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 4584: &escape($creationcontext),$domcloner,$hasuniquecode,
4585: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 4586: } else {
4587: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4588: $sincefilter.':'.&escape($descfilter).':'.
4589: &escape($instcodefilter).':'.&escape($ownerfilter).
4590: ':'.&escape($coursefilter).':'.&escape($typefilter).
4591: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4592: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4593: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4594: &escape($cc_clone).':'.$cloneonly.':'.
4595: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 4596: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4597: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 4598: }
4599:
1.918 raeburn 4600: my @pairs=split(/\&/,$rep);
4601: foreach my $item (@pairs) {
4602: my ($key,$value)=split(/\=/,$item,2);
4603: $key = &unescape($key);
4604: next if ($key =~ /^error: 2 /);
4605: my $result = &thaw_unescape($value);
4606: if (ref($result) eq 'HASH') {
4607: $returnhash{$key}=$result;
4608: } else {
1.921 raeburn 4609: my @responses = split(/:/,$value);
4610: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4611: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4612: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4613: }
1.1008 raeburn 4614: }
1.353 www 4615: }
4616: }
4617: }
4618: }
4619: return %returnhash;
4620: }
4621:
1.1055 raeburn 4622: sub courselastaccess {
4623: my ($cdom,$cnum,$hostidref) = @_;
4624: my %returnhash;
4625: if ($cdom && $cnum) {
4626: my $chome = &homeserver($cnum,$cdom);
4627: if ($chome ne 'no_host') {
4628: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4629: &extract_lastaccess(\%returnhash,$rep);
4630: }
4631: } else {
4632: if (!$cdom) { $cdom=''; }
4633: my %libserv = &all_library();
4634: foreach my $tryserver (keys(%libserv)) {
4635: if (ref($hostidref) eq 'ARRAY') {
4636: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4637: }
4638: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4639: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4640: &extract_lastaccess(\%returnhash,$rep);
4641: }
4642: }
4643: }
4644: return %returnhash;
4645: }
4646:
4647: sub extract_lastaccess {
4648: my ($returnhash,$rep) = @_;
4649: if (ref($returnhash) eq 'HASH') {
4650: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4651: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4652: $rep eq '') {
4653: my @pairs=split(/\&/,$rep);
4654: foreach my $item (@pairs) {
4655: my ($key,$value)=split(/\=/,$item,2);
4656: $key = &unescape($key);
4657: next if ($key =~ /^error: 2 /);
4658: $returnhash->{$key} = &thaw_unescape($value);
4659: }
4660: }
4661: }
4662: return;
4663: }
4664:
1.658 raeburn 4665: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4666:
4667: sub dcmailput {
1.685 raeburn 4668: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4669: my $status = &Apache::lonnet::critical(
1.740 www 4670: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4671: &escape($message),$server);
1.662 raeburn 4672: return $status;
4673: }
4674:
1.658 raeburn 4675: sub dcmaildump {
4676: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4677: my %returnhash=();
1.846 albertel 4678:
4679: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4680: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4681: &escape($enddate).':';
4682: my @esc_senders=map { &escape($_)} @$senders;
4683: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4684: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4685: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4686: if (($key) && ($value)) {
4687: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4688: }
4689: }
4690: }
4691: return %returnhash;
4692: }
1.662 raeburn 4693: # ---------------------------------------------------------- Domain roles
4694:
4695: sub get_domain_roles {
4696: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4697: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4698: $startdate = '.';
4699: }
1.1018 raeburn 4700: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4701: $enddate = '.';
4702: }
1.922 raeburn 4703: my $rolelist;
4704: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4705: $rolelist = join('&',@{$roles});
1.922 raeburn 4706: }
1.662 raeburn 4707: my %personnel = ();
1.841 albertel 4708:
4709: my %servers = &get_servers($dom,'library');
4710: foreach my $tryserver (keys(%servers)) {
4711: %{$personnel{$tryserver}}=();
4712: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4713: &escape($startdate).':'.
4714: &escape($enddate).':'.
4715: &escape($rolelist), $tryserver))) {
4716: my ($key,$value) = split(/\=/,$line,2);
4717: if (($key) && ($value)) {
4718: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4719: }
4720: }
1.662 raeburn 4721: }
4722: return %personnel;
4723: }
1.658 raeburn 4724:
1.1057 www 4725: # ----------------------------------------------------------- Interval timing
1.149 www 4726:
1.1153 www 4727: {
4728: # Caches needed for speedup of navmaps
4729: # We don't want to cache this for very long at all (5 seconds at most)
4730: #
4731: # The user for whom we cache
4732: my $cachedkey='';
4733: # The cached times for this user
4734: my %cachedtimes=();
4735: # When this was last done
1.1282 raeburn 4736: my $cachedtime='';
1.1153 www 4737:
4738: sub load_all_first_access {
1.1308 raeburn 4739: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 4740: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 raeburn 4741: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
4742: (!$ignorecache)) {
1.1154 raeburn 4743: return;
4744: }
4745: $cachedtime=time;
4746: $cachedkey=$uname.':'.$udom;
4747: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4748: }
4749:
1.504 albertel 4750: sub get_first_access {
1.1308 raeburn 4751: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 4752: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4753: if ($argsymb) { $symb=$argsymb; }
4754: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4755: if ($argmap) { $map = $argmap; }
1.926 albertel 4756: if ($type eq 'course') {
4757: $res='course';
4758: } elsif ($type eq 'map') {
1.588 albertel 4759: $res=&symbread($map);
4760: } else {
4761: $res=$symb;
4762: }
1.1308 raeburn 4763: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 4764: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4765: }
4766:
4767: sub set_first_access {
1.1162 raeburn 4768: my ($type,$interval)=@_;
1.790 albertel 4769: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4770: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4771: if ($type eq 'course') {
4772: $res='course';
4773: } elsif ($type eq 'map') {
1.588 albertel 4774: $res=&symbread($map);
4775: } else {
4776: $res=$symb;
4777: }
1.1153 www 4778: $cachedkey='';
1.1162 raeburn 4779: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4780: if (!$firstaccess) {
1.1162 raeburn 4781: my $start = time;
4782: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4783: $udom,$uname);
4784: if ($putres eq 'ok') {
4785: &put('timerinterval',{"$courseid\0$res"=>$interval},
4786: $udom,$uname);
4787: &appenv(
4788: {
4789: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4790: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4791: }
4792: );
4793: }
4794: return $putres;
1.505 albertel 4795: }
4796: return 'already_set';
1.504 albertel 4797: }
1.1153 www 4798: }
1.1282 raeburn 4799:
1.110 www 4800: # --------------------------------------------- Set Expire Date for Spreadsheet
4801:
4802: sub expirespread {
4803: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4804: my $cid=$env{'request.course.id'};
1.110 www 4805: if ($cid) {
4806: my $now=time;
4807: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4808: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4809: $env{'course.'.$cid.'.num'}.
1.110 www 4810: ':nohist_expirationdates:'.
4811: &escape($key).'='.$now,
1.620 albertel 4812: $env{'course.'.$cid.'.home'})
1.110 www 4813: }
4814: return 'ok';
1.14 www 4815: }
4816:
1.109 www 4817: # ----------------------------------------------------- Devalidate Spreadsheets
4818:
4819: sub devalidate {
1.325 www 4820: my ($symb,$uname,$udom)=@_;
1.620 albertel 4821: my $cid=$env{'request.course.id'};
1.109 www 4822: if ($cid) {
1.391 matthew 4823: # delete the stored spreadsheets for
4824: # - the student level sheet of this user in course's homespace
4825: # - the assessment level sheet for this resource
4826: # for this user in user's homespace
1.553 albertel 4827: # - current conditional state info
1.325 www 4828: my $key=$uname.':'.$udom.':';
1.109 www 4829: my $status=
1.299 matthew 4830: &del('nohist_calculatedsheets',
1.391 matthew 4831: [$key.'studentcalc:'],
1.620 albertel 4832: $env{'course.'.$cid.'.domain'},
4833: $env{'course.'.$cid.'.num'})
1.133 albertel 4834: .' '.
4835: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4836: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4837: unless ($status eq 'ok ok') {
4838: &logthis('Could not devalidate spreadsheet '.
1.325 www 4839: $uname.' at '.$udom.' for '.
1.109 www 4840: $symb.': '.$status);
1.133 albertel 4841: }
1.553 albertel 4842: &delenv('user.state.'.$cid);
1.109 www 4843: }
4844: }
4845:
1.265 albertel 4846: sub get_scalar {
4847: my ($string,$end) = @_;
4848: my $value;
4849: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4850: $value = $1;
4851: } elsif ($$string =~ s/^([^&]*?)&//) {
4852: $value = $1;
4853: }
4854: return &unescape($value);
4855: }
4856:
4857: sub array2str {
4858: my (@array) = @_;
4859: my $result=&arrayref2str(\@array);
4860: $result=~s/^__ARRAY_REF__//;
4861: $result=~s/__END_ARRAY_REF__$//;
4862: return $result;
4863: }
4864:
1.204 albertel 4865: sub arrayref2str {
4866: my ($arrayref) = @_;
1.265 albertel 4867: my $result='__ARRAY_REF__';
1.204 albertel 4868: foreach my $elem (@$arrayref) {
1.265 albertel 4869: if(ref($elem) eq 'ARRAY') {
4870: $result.=&arrayref2str($elem).'&';
4871: } elsif(ref($elem) eq 'HASH') {
4872: $result.=&hashref2str($elem).'&';
4873: } elsif(ref($elem)) {
4874: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4875: } else {
4876: $result.=&escape($elem).'&';
4877: }
4878: }
4879: $result=~s/\&$//;
1.265 albertel 4880: $result .= '__END_ARRAY_REF__';
1.204 albertel 4881: return $result;
4882: }
4883:
1.168 albertel 4884: sub hash2str {
1.204 albertel 4885: my (%hash) = @_;
4886: my $result=&hashref2str(\%hash);
1.265 albertel 4887: $result=~s/^__HASH_REF__//;
4888: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4889: return $result;
4890: }
4891:
4892: sub hashref2str {
4893: my ($hashref)=@_;
1.265 albertel 4894: my $result='__HASH_REF__';
1.800 albertel 4895: foreach my $key (sort(keys(%$hashref))) {
4896: if (ref($key) eq 'ARRAY') {
4897: $result.=&arrayref2str($key).'=';
4898: } elsif (ref($key) eq 'HASH') {
4899: $result.=&hashref2str($key).'=';
4900: } elsif (ref($key)) {
1.265 albertel 4901: $result.='=';
1.800 albertel 4902: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4903: } else {
1.1132 raeburn 4904: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4905: }
4906:
1.800 albertel 4907: if(ref($hashref->{$key}) eq 'ARRAY') {
4908: $result.=&arrayref2str($hashref->{$key}).'&';
4909: } elsif(ref($hashref->{$key}) eq 'HASH') {
4910: $result.=&hashref2str($hashref->{$key}).'&';
4911: } elsif(ref($hashref->{$key})) {
1.265 albertel 4912: $result.='&';
1.800 albertel 4913: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4914: } else {
1.800 albertel 4915: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4916: }
4917: }
1.168 albertel 4918: $result=~s/\&$//;
1.265 albertel 4919: $result .= '__END_HASH_REF__';
1.168 albertel 4920: return $result;
4921: }
4922:
4923: sub str2hash {
1.265 albertel 4924: my ($string)=@_;
4925: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4926: return %$hash;
4927: }
4928:
4929: sub str2hashref {
1.168 albertel 4930: my ($string) = @_;
1.265 albertel 4931:
4932: my %hash;
4933:
4934: if($string !~ /^__HASH_REF__/) {
4935: if (! ($string eq '' || !defined($string))) {
4936: $hash{'error'}='Not hash reference';
4937: }
4938: return (\%hash, $string);
4939: }
4940:
4941: $string =~ s/^__HASH_REF__//;
4942:
4943: while($string !~ /^__END_HASH_REF__/) {
4944: #key
4945: my $key='';
4946: if($string =~ /^__HASH_REF__/) {
4947: ($key, $string)=&str2hashref($string);
4948: if(defined($key->{'error'})) {
4949: $hash{'error'}='Bad data';
4950: return (\%hash, $string);
4951: }
4952: } elsif($string =~ /^__ARRAY_REF__/) {
4953: ($key, $string)=&str2arrayref($string);
4954: if($key->[0] eq 'Array reference error') {
4955: $hash{'error'}='Bad data';
4956: return (\%hash, $string);
4957: }
4958: } else {
4959: $string =~ s/^(.*?)=//;
1.267 albertel 4960: $key=&unescape($1);
1.265 albertel 4961: }
4962: $string =~ s/^=//;
4963:
4964: #value
4965: my $value='';
4966: if($string =~ /^__HASH_REF__/) {
4967: ($value, $string)=&str2hashref($string);
4968: if(defined($value->{'error'})) {
4969: $hash{'error'}='Bad data';
4970: return (\%hash, $string);
4971: }
4972: } elsif($string =~ /^__ARRAY_REF__/) {
4973: ($value, $string)=&str2arrayref($string);
4974: if($value->[0] eq 'Array reference error') {
4975: $hash{'error'}='Bad data';
4976: return (\%hash, $string);
4977: }
4978: } else {
4979: $value=&get_scalar(\$string,'__END_HASH_REF__');
4980: }
4981: $string =~ s/^&//;
4982:
4983: $hash{$key}=$value;
1.204 albertel 4984: }
1.265 albertel 4985:
4986: $string =~ s/^__END_HASH_REF__//;
4987:
4988: return (\%hash, $string);
1.204 albertel 4989: }
4990:
4991: sub str2array {
1.265 albertel 4992: my ($string)=@_;
4993: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4994: return @$array;
4995: }
4996:
4997: sub str2arrayref {
1.204 albertel 4998: my ($string) = @_;
1.265 albertel 4999: my @array;
5000:
5001: if($string !~ /^__ARRAY_REF__/) {
5002: if (! ($string eq '' || !defined($string))) {
5003: $array[0]='Array reference error';
5004: }
5005: return (\@array, $string);
5006: }
5007:
5008: $string =~ s/^__ARRAY_REF__//;
5009:
5010: while($string !~ /^__END_ARRAY_REF__/) {
5011: my $value='';
5012: if($string =~ /^__HASH_REF__/) {
5013: ($value, $string)=&str2hashref($string);
5014: if(defined($value->{'error'})) {
5015: $array[0] ='Array reference error';
5016: return (\@array, $string);
5017: }
5018: } elsif($string =~ /^__ARRAY_REF__/) {
5019: ($value, $string)=&str2arrayref($string);
5020: if($value->[0] eq 'Array reference error') {
5021: $array[0] ='Array reference error';
5022: return (\@array, $string);
5023: }
5024: } else {
5025: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5026: }
5027: $string =~ s/^&//;
5028:
5029: push(@array, $value);
1.191 harris41 5030: }
1.265 albertel 5031:
5032: $string =~ s/^__END_ARRAY_REF__//;
5033:
5034: return (\@array, $string);
1.168 albertel 5035: }
5036:
1.167 albertel 5037: # -------------------------------------------------------------------Temp Store
5038:
1.168 albertel 5039: sub tmpreset {
5040: my ($symb,$namespace,$domain,$stuname) = @_;
5041: if (!$symb) {
5042: $symb=&symbread();
1.620 albertel 5043: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5044: }
5045: $symb=escape($symb);
5046:
1.620 albertel 5047: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5048: $namespace=~s/\//\_/g;
5049: $namespace=~s/\W//g;
5050:
1.620 albertel 5051: if (!$domain) { $domain=$env{'user.domain'}; }
5052: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5053: if ($domain eq 'public' && $stuname eq 'public') {
5054: $stuname=$ENV{'REMOTE_ADDR'};
5055: }
1.1117 foxr 5056: my $path=LONCAPA::tempdir();
1.168 albertel 5057: my %hash;
5058: if (tie(%hash,'GDBM_File',
5059: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5060: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5061: foreach my $key (keys(%hash)) {
1.180 albertel 5062: if ($key=~ /:$symb/) {
1.168 albertel 5063: delete($hash{$key});
5064: }
5065: }
5066: }
5067: }
5068:
1.167 albertel 5069: sub tmpstore {
1.168 albertel 5070: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5071:
5072: if (!$symb) {
5073: $symb=&symbread();
1.620 albertel 5074: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5075: }
5076: $symb=escape($symb);
5077:
5078: if (!$namespace) {
5079: # I don't think we would ever want to store this for a course.
5080: # it seems this will only be used if we don't have a course.
1.620 albertel 5081: #$namespace=$env{'request.course.id'};
1.168 albertel 5082: #if (!$namespace) {
1.620 albertel 5083: $namespace=$env{'request.state'};
1.168 albertel 5084: #}
5085: }
5086: $namespace=~s/\//\_/g;
5087: $namespace=~s/\W//g;
1.620 albertel 5088: if (!$domain) { $domain=$env{'user.domain'}; }
5089: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5090: if ($domain eq 'public' && $stuname eq 'public') {
5091: $stuname=$ENV{'REMOTE_ADDR'};
5092: }
1.168 albertel 5093: my $now=time;
5094: my %hash;
1.1117 foxr 5095: my $path=LONCAPA::tempdir();
1.168 albertel 5096: if (tie(%hash,'GDBM_File',
5097: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5098: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5099: $hash{"version:$symb"}++;
5100: my $version=$hash{"version:$symb"};
5101: my $allkeys='';
5102: foreach my $key (keys(%$storehash)) {
5103: $allkeys.=$key.':';
1.591 albertel 5104: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5105: }
5106: $hash{"$version:$symb:timestamp"}=$now;
5107: $allkeys.='timestamp';
5108: $hash{"$version:keys:$symb"}=$allkeys;
5109: if (untie(%hash)) {
5110: return 'ok';
5111: } else {
5112: return "error:$!";
5113: }
5114: } else {
5115: return "error:$!";
5116: }
5117: }
1.167 albertel 5118:
1.168 albertel 5119: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5120:
1.168 albertel 5121: sub tmprestore {
5122: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5123:
1.168 albertel 5124: if (!$symb) {
5125: $symb=&symbread();
1.620 albertel 5126: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5127: }
5128: $symb=escape($symb);
5129:
1.620 albertel 5130: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5131:
1.620 albertel 5132: if (!$domain) { $domain=$env{'user.domain'}; }
5133: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5134: if ($domain eq 'public' && $stuname eq 'public') {
5135: $stuname=$ENV{'REMOTE_ADDR'};
5136: }
1.168 albertel 5137: my %returnhash;
5138: $namespace=~s/\//\_/g;
5139: $namespace=~s/\W//g;
5140: my %hash;
1.1117 foxr 5141: my $path=LONCAPA::tempdir();
1.168 albertel 5142: if (tie(%hash,'GDBM_File',
5143: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5144: &GDBM_READER(),0640)) {
1.168 albertel 5145: my $version=$hash{"version:$symb"};
5146: $returnhash{'version'}=$version;
5147: my $scope;
5148: for ($scope=1;$scope<=$version;$scope++) {
5149: my $vkeys=$hash{"$scope:keys:$symb"};
5150: my @keys=split(/:/,$vkeys);
5151: my $key;
5152: $returnhash{"$scope:keys"}=$vkeys;
5153: foreach $key (@keys) {
1.591 albertel 5154: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5155: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5156: }
5157: }
1.168 albertel 5158: if (!(untie(%hash))) {
5159: return "error:$!";
5160: }
5161: } else {
5162: return "error:$!";
5163: }
5164: return %returnhash;
1.167 albertel 5165: }
5166:
1.9 www 5167: # ----------------------------------------------------------------------- Store
5168:
5169: sub store {
1.1269 raeburn 5170: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5171: my $home='';
5172:
1.168 albertel 5173: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5174:
1.213 www 5175: $symb=&symbclean($symb);
1.122 albertel 5176: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5177:
1.620 albertel 5178: if (!$domain) { $domain=$env{'user.domain'}; }
5179: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5180:
5181: &devalidate($symb,$stuname,$domain);
1.109 www 5182:
5183: $symb=escape($symb);
1.187 www 5184: if (!$namespace) {
1.620 albertel 5185: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5186: return '';
5187: }
5188: }
1.620 albertel 5189: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5190:
5191: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5192: $$storehash{'host'}=$perlvar{'lonHostID'};
5193:
1.12 www 5194: my $namevalue='';
1.800 albertel 5195: foreach my $key (keys(%$storehash)) {
5196: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5197: }
1.12 www 5198: $namevalue=~s/\&$//;
1.187 www 5199: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 5200: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5201: }
5202:
1.47 www 5203: # -------------------------------------------------------------- Critical Store
5204:
5205: sub cstore {
1.1269 raeburn 5206: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5207: my $home='';
5208:
1.168 albertel 5209: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5210:
1.213 www 5211: $symb=&symbclean($symb);
1.122 albertel 5212: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5213:
1.620 albertel 5214: if (!$domain) { $domain=$env{'user.domain'}; }
5215: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5216:
5217: &devalidate($symb,$stuname,$domain);
1.109 www 5218:
5219: $symb=escape($symb);
1.187 www 5220: if (!$namespace) {
1.620 albertel 5221: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5222: return '';
5223: }
5224: }
1.620 albertel 5225: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5226:
5227: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5228: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5229:
1.47 www 5230: my $namevalue='';
1.800 albertel 5231: foreach my $key (keys(%$storehash)) {
5232: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5233: }
1.47 www 5234: $namevalue=~s/\&$//;
1.187 www 5235: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5236: return critical
1.1269 raeburn 5237: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5238: }
5239:
1.9 www 5240: # --------------------------------------------------------------------- Restore
5241:
5242: sub restore {
1.124 www 5243: my ($symb,$namespace,$domain,$stuname) = @_;
5244: my $home='';
5245:
1.168 albertel 5246: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5247:
1.122 albertel 5248: if (!$symb) {
1.1224 raeburn 5249: return if ($namespace eq 'courserequests');
5250: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5251: } else {
1.1224 raeburn 5252: unless ($namespace eq 'courserequests') {
5253: $symb=&escape(&symbclean($symb));
5254: }
1.122 albertel 5255: }
1.188 www 5256: if (!$namespace) {
1.620 albertel 5257: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5258: return '';
5259: }
5260: }
1.620 albertel 5261: if (!$domain) { $domain=$env{'user.domain'}; }
5262: if (!$stuname) { $stuname=$env{'user.name'}; }
5263: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5264: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5265:
1.12 www 5266: my %returnhash=();
1.800 albertel 5267: foreach my $line (split(/\&/,$answer)) {
5268: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5269: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5270: }
1.75 www 5271: my $version;
5272: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5273: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5274: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5275: }
1.75 www 5276: }
1.13 www 5277: return %returnhash;
1.34 www 5278: }
5279:
5280: # ---------------------------------------------------------- Course Description
1.1118 foxr 5281: #
5282: #
1.34 www 5283:
5284: sub coursedescription {
1.731 albertel 5285: my ($courseid,$args)=@_;
1.34 www 5286: $courseid=~s/^\///;
1.49 www 5287: $courseid=~s/\_/\//g;
1.34 www 5288: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5289: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5290: my $normalid=$cdomain.'_'.$cnum;
5291: # need to always cache even if we get errors otherwise we keep
5292: # trying and trying and trying to get the course description.
5293: my %envhash=();
5294: my %returnhash=();
1.731 albertel 5295:
5296: my $expiretime=600;
5297: if ($env{'request.course.id'} eq $normalid) {
5298: $expiretime=120;
5299: }
5300:
5301: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5302: if (!$args->{'freshen_cache'}
5303: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5304: foreach my $key (keys(%env)) {
5305: next if ($key !~ /^\Q$prefix\E(.*)/);
5306: my ($setting) = $1;
5307: $returnhash{$setting} = $env{$key};
5308: }
5309: return %returnhash;
5310: }
5311:
1.1118 foxr 5312: # get the data again
5313:
1.731 albertel 5314: if (!$args->{'one_time'}) {
5315: $envhash{'course.'.$normalid.'.last_cache'}=time;
5316: }
1.811 albertel 5317:
1.34 www 5318: if ($chome ne 'no_host') {
1.302 albertel 5319: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5320: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5321: my $username = $env{'user.name'}; # Defult username
5322: if(defined $args->{'user'}) {
5323: $username = $args->{'user'};
5324: }
1.129 albertel 5325: $returnhash{'home'}= $chome;
5326: $returnhash{'domain'} = $cdomain;
5327: $returnhash{'num'} = $cnum;
1.741 raeburn 5328: if (!defined($returnhash{'type'})) {
5329: $returnhash{'type'} = 'Course';
5330: }
1.130 albertel 5331: while (my ($name,$value) = each %returnhash) {
1.53 www 5332: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5333: }
1.270 www 5334: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5335: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5336: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5337: $envhash{'course.'.$normalid.'.home'}=$chome;
5338: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5339: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5340: }
5341: }
1.731 albertel 5342: if (!$args->{'one_time'}) {
1.949 raeburn 5343: &appenv(\%envhash);
1.731 albertel 5344: }
1.302 albertel 5345: return %returnhash;
1.461 www 5346: }
5347:
1.1080 raeburn 5348: sub update_released_required {
5349: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5350: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5351: $cid = $env{'request.course.id'};
5352: $cdom = $env{'course.'.$cid.'.domain'};
5353: $cnum = $env{'course.'.$cid.'.num'};
5354: $chome = $env{'course.'.$cid.'.home'};
5355: }
5356: if ($needsrelease) {
5357: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5358: my $needsupdate;
5359: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5360: $needsupdate = 1;
5361: } else {
5362: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5363: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5364: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5365: $needsupdate = 1;
5366: }
5367: }
5368: if ($needsupdate) {
5369: my %needshash = (
5370: 'internal.releaserequired' => $needsrelease,
5371: );
5372: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5373: if ($putresult eq 'ok') {
5374: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5375: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5376: if (ref($crsinfo{$cid}) eq 'HASH') {
5377: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5378: &courseidput($cdom,\%crsinfo,$chome,'notime');
5379: }
5380: }
5381: }
5382: }
5383: return;
5384: }
5385:
1.461 www 5386: # -------------------------------------------------See if a user is privileged
5387:
5388: sub privileged {
1.1219 raeburn 5389: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5390: my $now = time;
1.1219 raeburn 5391: my $roles;
5392: if (ref($possroles) eq 'ARRAY') {
5393: $roles = $possroles;
5394: } else {
5395: $roles = ['dc','su'];
5396: }
5397: if (ref($possdomains) eq 'ARRAY') {
5398: my %privileged = &privileged_by_domain($possdomains,$roles);
5399: foreach my $dom (@{$possdomains}) {
5400: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5401: (ref($privileged{$dom}) eq 'HASH')) {
5402: foreach my $role (@{$roles}) {
5403: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5404: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5405: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5406: return 1 unless (($end && $end < $now) ||
5407: ($start && $start > $now));
5408: }
5409: }
5410: }
5411: }
5412: }
5413: } else {
5414: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5415: my $now = time;
1.1170 droeschl 5416:
1.1275 musolffc 5417: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5418: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5419: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5420: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5421: or ($tstart && $tstart > $now);
1.1170 droeschl 5422: }
1.1219 raeburn 5423: }
5424: }
5425: return 0;
5426: }
1.1170 droeschl 5427:
1.1219 raeburn 5428: sub privileged_by_domain {
5429: my ($domains,$roles) = @_;
5430: my %privileged = ();
5431: my $cachetime = 60*60*24;
5432: my $now = time;
5433: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5434: return %privileged;
5435: }
5436: foreach my $dom (@{$domains}) {
5437: next if (ref($privileged{$dom}) eq 'HASH');
5438: my $needroles;
5439: foreach my $role (@{$roles}) {
5440: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5441: if (defined($cached)) {
5442: if (ref($result) eq 'HASH') {
5443: $privileged{$dom}{$role} = $result;
5444: }
5445: } else {
5446: $needroles = 1;
5447: }
5448: }
5449: if ($needroles) {
5450: my %dompersonnel = &get_domain_roles($dom,$roles);
5451: $privileged{$dom} = {};
5452: foreach my $server (keys(%dompersonnel)) {
5453: if (ref($dompersonnel{$server}) eq 'HASH') {
5454: foreach my $item (keys(%{$dompersonnel{$server}})) {
5455: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5456: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5457: next if ($end && $end < $now);
5458: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5459: $dompersonnel{$server}{$item};
5460: }
5461: }
5462: }
5463: if (ref($privileged{$dom}) eq 'HASH') {
5464: foreach my $role (@{$roles}) {
5465: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5466: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5467: } else {
5468: my %hash = ();
5469: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5470: }
5471: }
5472: }
5473: }
5474: }
5475: return %privileged;
1.9 www 5476: }
1.1 albertel 5477:
1.103 harris41 5478: # -------------------------------------------------------- Get user privileges
1.11 www 5479:
5480: sub rolesinit {
1.1169 droeschl 5481: my ($domain, $username) = @_;
5482: my %userroles = ('user.login.time' => time);
5483: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5484:
5485: # firstaccess and timerinterval are related to timed maps/resources.
5486: # also, blocking can be triggered by an activating timer
5487: # it's saved in the user's %env.
5488: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5489: my %timerinterval = &dump('timerinterval', $domain, $username);
5490: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5491: %timerintchk, %timerintenv);
5492:
1.1162 raeburn 5493: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5494: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5495: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5496: }
1.1169 droeschl 5497:
1.1162 raeburn 5498: foreach my $key (keys(%timerinterval)) {
5499: my ($cid,$rest) = split(/\0/,$key);
5500: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5501: }
1.1169 droeschl 5502:
1.11 www 5503: my %allroles=();
1.1162 raeburn 5504: my %allgroups=();
1.11 www 5505:
1.1274 raeburn 5506: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5507: my $role = $rolesdump{$area};
5508: $area =~ s/\_\w\w$//;
5509:
5510: my ($trole, $tend, $tstart, $group_privs);
5511:
5512: if ($role =~ /^cr/) {
5513: # Custom role, defined by a user
5514: # e.g., user.role.cr/msu/smith/mynewrole
5515: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5516: $trole = $1;
5517: ($tend, $tstart) = split('_', $2);
5518: } else {
5519: $trole = $role;
5520: }
5521: } elsif ($role =~ m|^gr/|) {
5522: # Role of member in a group, defined within a course/community
5523: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5524: ($trole, $tend, $tstart) = split(/_/, $role);
5525: next if $tstart eq '-1';
5526: ($trole, $group_privs) = split(/\//, $trole);
5527: $group_privs = &unescape($group_privs);
5528: } else {
5529: # Just a normal role, defined in roles.tab
5530: ($trole, $tend, $tstart) = split(/_/,$role);
5531: }
5532:
5533: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5534: $username);
5535: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5536:
5537: # role expired or not available yet?
5538: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5539: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5540:
5541: next if $area eq '' or $trole eq '';
5542:
5543: my $spec = "$trole.$area";
5544: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5545:
5546: if ($trole =~ /^cr\//) {
5547: # Custom role, defined by a user
5548: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5549: } elsif ($trole eq 'gr') {
5550: # Role of a member in a group, defined within a course/community
5551: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5552: next;
5553: } else {
5554: # Normal role, defined in roles.tab
5555: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5556: }
5557:
5558: my $cid = $tdomain.'_'.$trest;
5559: unless ($firstaccchk{$cid}) {
5560: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5561: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5562: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5563: $coursetimerstarts{$cid}{$item};
5564: }
5565: }
5566: $firstaccchk{$cid} = 1;
5567: }
5568: unless ($timerintchk{$cid}) {
5569: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5570: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5571: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5572: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5573: }
1.12 www 5574: }
1.1169 droeschl 5575: $timerintchk{$cid} = 1;
1.191 harris41 5576: }
1.11 www 5577: }
1.1169 droeschl 5578:
5579: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5580: \%allroles, \%allgroups);
5581: $env{'user.adv'} = $userroles{'user.adv'};
5582:
1.1162 raeburn 5583: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5584: }
5585:
1.567 raeburn 5586: sub set_arearole {
1.1215 raeburn 5587: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5588: unless ($nolog) {
1.567 raeburn 5589: # log the associated role with the area
1.1215 raeburn 5590: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5591: }
1.743 albertel 5592: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5593: }
5594:
5595: sub custom_roleprivs {
5596: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5597: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 5598: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5599: if (&hostname($homsvr) ne '') {
1.567 raeburn 5600: my ($rdummy,$roledef)=
5601: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5602: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5603: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5604: if (defined($syspriv)) {
1.1043 raeburn 5605: if ($trest =~ /^$match_community$/) {
5606: $syspriv =~ s/bre\&S//;
5607: }
1.567 raeburn 5608: $$allroles{'cm./'}.=':'.$syspriv;
5609: $$allroles{$spec.'./'}.=':'.$syspriv;
5610: }
5611: if ($tdomain ne '') {
5612: if (defined($dompriv)) {
5613: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5614: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5615: }
5616: if (($trest ne '') && (defined($coursepriv))) {
5617: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5618: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5619: }
5620: }
5621: }
5622: }
5623: }
5624:
1.678 raeburn 5625: sub group_roleprivs {
5626: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5627: my $access = 1;
5628: my $now = time;
5629: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5630: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5631: if ($access) {
1.811 albertel 5632: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5633: $$allgroups{$course}{$group} .=':'.$group_privs;
5634: }
5635: }
1.567 raeburn 5636:
5637: sub standard_roleprivs {
5638: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5639: if (defined($pr{$trole.':s'})) {
5640: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5641: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5642: }
5643: if ($tdomain ne '') {
5644: if (defined($pr{$trole.':d'})) {
5645: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5646: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5647: }
5648: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5649: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5650: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5651: }
5652: }
5653: }
5654:
5655: sub set_userprivs {
1.1064 raeburn 5656: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5657: my $author=0;
5658: my $adv=0;
1.678 raeburn 5659: my %grouproles = ();
5660: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5661: my @groupkeys;
1.1000 raeburn 5662: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5663: push(@groupkeys,$role);
5664: }
5665: if (ref($groups_roles) eq 'HASH') {
5666: foreach my $key (keys(%{$groups_roles})) {
5667: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5668: push(@groupkeys,$key);
5669: }
5670: }
5671: }
5672: if (@groupkeys > 0) {
5673: foreach my $role (@groupkeys) {
5674: my ($trole,$area,$sec,$extendedarea);
5675: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5676: $trole = $1;
5677: $area = $2;
5678: $sec = $3;
5679: $extendedarea = $area.$sec;
5680: if (exists($$allgroups{$area})) {
5681: foreach my $group (keys(%{$$allgroups{$area}})) {
5682: my $spec = $trole.'.'.$extendedarea;
5683: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5684: $$allgroups{$area}{$group};
1.1064 raeburn 5685: }
1.678 raeburn 5686: }
5687: }
5688: }
5689: }
5690: }
1.800 albertel 5691: foreach my $group (keys(%grouproles)) {
5692: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5693: }
1.800 albertel 5694: foreach my $role (keys(%{$allroles})) {
5695: my %thesepriv;
1.941 raeburn 5696: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5697: foreach my $item (split(/:/,$$allroles{$role})) {
5698: if ($item ne '') {
5699: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5700: if ($restrictions eq '') {
5701: $thesepriv{$privilege}='F';
5702: } elsif ($thesepriv{$privilege} ne 'F') {
5703: $thesepriv{$privilege}.=$restrictions;
5704: }
5705: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5706: }
5707: }
5708: my $thesestr='';
1.1104 raeburn 5709: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5710: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5711: }
5712: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5713: }
5714: return ($author,$adv);
5715: }
5716:
1.994 raeburn 5717: sub role_status {
1.1104 raeburn 5718: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5719: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 5720: my ($one,$two) = split(m{\./},$rolekey,2);
5721: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5722: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 5723: $$where = '/'.$two;
1.994 raeburn 5724: $$trolecode=$$role.'.'.$$where;
5725: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5726: $$tstatus='is';
1.1104 raeburn 5727: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5728: $$tstatus='future';
1.1034 raeburn 5729: if ($$tstart<$now) {
5730: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5731: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5732: my (%allroles,%allgroups,$group_privs,
5733: %groups_roles,@rolecodes);
1.1002 raeburn 5734: my %userroles = (
5735: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5736: );
1.1064 raeburn 5737: @rolecodes = ('cm');
1.1002 raeburn 5738: my $spec=$$role.'.'.$$where;
5739: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5740: if ($$role =~ /^cr\//) {
5741: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5742: push(@rolecodes,'cr');
1.1002 raeburn 5743: } elsif ($$role eq 'gr') {
1.1064 raeburn 5744: push(@rolecodes,$$role);
1.1002 raeburn 5745: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5746: $env{'user.name'});
1.1064 raeburn 5747: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5748: (undef,my $group_privs) = split(/\//,$trole);
5749: $group_privs = &unescape($group_privs);
5750: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5751: 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 5752: &get_groups_roles($tdomain,$trest,
5753: \%course_roles,\@rolecodes,
5754: \%groups_roles);
1.1002 raeburn 5755: } else {
1.1064 raeburn 5756: push(@rolecodes,$$role);
1.1002 raeburn 5757: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5758: }
1.1064 raeburn 5759: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5760: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5761: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5762: }
5763: }
1.1034 raeburn 5764: $$tstatus = 'is';
1.1002 raeburn 5765: }
1.994 raeburn 5766: }
5767: if ($$tend) {
1.1104 raeburn 5768: if ($$tend<$update) {
1.994 raeburn 5769: $$tstatus='expired';
5770: } elsif ($$tend<$now) {
5771: $$tstatus='will_not';
5772: }
5773: }
5774: }
5775: }
5776: }
5777:
1.1104 raeburn 5778: sub get_groups_roles {
5779: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5780: return unless((ref($cdom_courseroles) eq 'HASH') &&
5781: (ref($rolecodes) eq 'ARRAY') &&
5782: (ref($groups_roles) eq 'HASH'));
5783: if (keys(%{$cdom_courseroles}) > 0) {
5784: my ($cnum) = ($rest =~ /^($match_courseid)/);
5785: if ($cdom ne '' && $cnum ne '') {
5786: foreach my $key (keys(%{$cdom_courseroles})) {
5787: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5788: my $crsrole = $1;
5789: my $crssec = $2;
5790: if ($crsrole =~ /^cr/) {
5791: unless (grep(/^cr$/,@{$rolecodes})) {
5792: push(@{$rolecodes},'cr');
5793: }
5794: } else {
5795: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5796: push(@{$rolecodes},$crsrole);
5797: }
5798: }
5799: my $rolekey = "$crsrole./$cdom/$cnum";
5800: if ($crssec ne '') {
5801: $rolekey .= "/$crssec";
5802: }
5803: $rolekey .= './';
5804: $groups_roles->{$rolekey} = $rolecodes;
5805: }
5806: }
5807: }
5808: }
5809: return;
5810: }
5811:
5812: sub delete_env_groupprivs {
5813: my ($where,$courseroles,$possroles) = @_;
5814: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5815: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5816: unless (ref($courseroles->{$udom}) eq 'HASH') {
5817: %{$courseroles->{$udom}} =
5818: &get_my_roles('','','userroles',['active'],
5819: $possroles,[$udom],1);
5820: }
5821: if (ref($courseroles->{$udom}) eq 'HASH') {
5822: foreach my $item (keys(%{$courseroles->{$udom}})) {
5823: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5824: my $area = '/'.$cdom.'/'.$cnum;
5825: my $privkey = "user.priv.$crsrole.$area";
5826: if ($crssec ne '') {
5827: $privkey .= '/'.$crssec;
5828: }
5829: $privkey .= ".$area/$group";
5830: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5831: }
5832: }
5833: return;
5834: }
5835:
1.994 raeburn 5836: sub check_adhoc_privs {
1.1104 raeburn 5837: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5838: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5839: my $setprivs;
1.994 raeburn 5840: if ($env{$cckey}) {
5841: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5842: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5843: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5844: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5845: $setprivs = 1;
1.994 raeburn 5846: }
5847: } else {
1.1088 raeburn 5848: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5849: $setprivs = 1;
1.994 raeburn 5850: }
1.1185 raeburn 5851: return $setprivs;
1.994 raeburn 5852: }
5853:
5854: sub set_adhoc_privileges {
1.1326 raeburn 5855: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1088 raeburn 5856: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5857: my $area = '/'.$dcdom.'/'.$pickedcourse;
5858: my $spec = $role.'.'.$area;
5859: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5860: $env{'user.name'},1);
1.1326 raeburn 5861: my %rolehash = ();
5862: if ($role =~ m{^cr/$dcdom/$dcdom\Q-domainconfig\E/}) {
5863: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
5864: } else {
5865: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
5866: }
5867: my ($author,$adv)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 5868: &appenv(\%userroles,[$role,'cm']);
5869: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5870: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5871: &appenv( {'request.role' => $spec,
5872: 'request.role.domain' => $dcdom,
5873: 'request.course.sec' => ''
5874: }
5875: );
5876: my $tadv=0;
5877: if (&allowed('adv') eq 'F') { $tadv=1; }
5878: &appenv({'request.role.adv' => $tadv});
5879: }
1.994 raeburn 5880: }
5881:
1.12 www 5882: # --------------------------------------------------------------- get interface
5883:
5884: sub get {
1.131 albertel 5885: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5886: my $items='';
1.800 albertel 5887: foreach my $item (@$storearr) {
5888: $items.=&escape($item).'&';
1.191 harris41 5889: }
1.12 www 5890: $items=~s/\&$//;
1.620 albertel 5891: if (!$udomain) { $udomain=$env{'user.domain'}; }
5892: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5893: my $uhome=&homeserver($uname,$udomain);
5894:
1.133 albertel 5895: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5896: my @pairs=split(/\&/,$rep);
1.273 albertel 5897: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5898: return @pairs;
5899: }
1.15 www 5900: my %returnhash=();
1.42 www 5901: my $i=0;
1.800 albertel 5902: foreach my $item (@$storearr) {
5903: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5904: $i++;
1.191 harris41 5905: }
1.15 www 5906: return %returnhash;
1.27 www 5907: }
5908:
5909: # --------------------------------------------------------------- del interface
5910:
5911: sub del {
1.133 albertel 5912: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5913: my $items='';
1.800 albertel 5914: foreach my $item (@$storearr) {
5915: $items.=&escape($item).'&';
1.191 harris41 5916: }
1.984 neumanie 5917:
1.27 www 5918: $items=~s/\&$//;
1.620 albertel 5919: if (!$udomain) { $udomain=$env{'user.domain'}; }
5920: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5921: my $uhome=&homeserver($uname,$udomain);
5922: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5923: }
5924:
5925: # -------------------------------------------------------------- dump interface
5926:
1.1180 droeschl 5927: sub unserialize {
5928: my ($rep, $escapedkeys) = @_;
5929:
5930: return {} if $rep =~ /^error/;
5931:
5932: my %returnhash=();
1.1252 raeburn 5933: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 5934: my ($key, $value) = split(/=/, $item, 2);
5935: $key = unescape($key) unless $escapedkeys;
5936: next if $key =~ /^error: 2 /;
1.1252 raeburn 5937: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 5938: }
5939: #return %returnhash;
5940: return \%returnhash;
5941: }
5942:
5943: # see Lond::dump_with_regexp
5944: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5945: sub dump {
1.1180 droeschl 5946: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5947: if (!$udomain) { $udomain=$env{'user.domain'}; }
5948: if (!$uname) { $uname=$env{'user.name'}; }
5949: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5950:
1.1266 raeburn 5951: if ($regexp) {
5952: $regexp=&escape($regexp);
5953: } else {
5954: $regexp='.';
5955: }
1.1180 droeschl 5956: if (grep { $_ eq $uhome } current_machine_ids()) {
5957: # user is hosted on this machine
1.1266 raeburn 5958: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5959: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5960: return %{unserialize($reply, $escapedkeys)};
5961: }
1.1166 raeburn 5962: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5963: my @pairs=split(/\&/,$rep);
5964: my %returnhash=();
1.1098 foxr 5965: if (!($rep =~ /^error/ )) {
5966: foreach my $item (@pairs) {
5967: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5968: $key = unescape($key) unless $escapedkeys;
5969: #$key = &unescape($key);
1.1098 foxr 5970: next if ($key =~ /^error: 2 /);
5971: $returnhash{$key}=&thaw_unescape($value);
5972: }
1.755 albertel 5973: }
5974: return %returnhash;
1.407 www 5975: }
5976:
1.1098 foxr 5977:
1.717 albertel 5978: # --------------------------------------------------------- dumpstore interface
5979:
5980: sub dumpstore {
5981: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5982: # same as dump but keys must be escaped. They may contain colon separated
5983: # lists of values that may themself contain colons (e.g. symbs).
5984: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5985: }
5986:
1.407 www 5987: # -------------------------------------------------------------- keys interface
5988:
5989: sub getkeys {
5990: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5991: if (!$udomain) { $udomain=$env{'user.domain'}; }
5992: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5993: my $uhome=&homeserver($uname,$udomain);
5994: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5995: my @keyarray=();
1.800 albertel 5996: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5997: next if ($key =~ /^error: 2 /);
1.800 albertel 5998: push(@keyarray,&unescape($key));
1.407 www 5999: }
6000: return @keyarray;
1.318 matthew 6001: }
6002:
1.319 matthew 6003: # --------------------------------------------------------------- currentdump
6004: sub currentdump {
1.328 matthew 6005: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6006: $courseid = $env{'request.course.id'} if (! defined($courseid));
6007: $sdom = $env{'user.domain'} if (! defined($sdom));
6008: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6009: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 6010: my $rep;
6011:
6012: if (grep { $_ eq $uhome } current_machine_ids()) {
6013: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6014: $courseid)));
6015: } else {
6016: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6017: }
6018:
1.318 matthew 6019: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6020: #
1.318 matthew 6021: my %returnhash=();
1.319 matthew 6022: #
6023: if ($rep eq "unknown_cmd") {
6024: # an old lond will not know currentdump
6025: # Do a dump and make it look like a currentdump
1.822 albertel 6026: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6027: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6028: my %hash = @tmp;
6029: @tmp=();
1.424 matthew 6030: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6031: } else {
6032: my @pairs=split(/\&/,$rep);
1.800 albertel 6033: foreach my $pair (@pairs) {
6034: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6035: my ($symb,$param) = split(/:/,$key);
6036: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6037: &thaw_unescape($value);
1.319 matthew 6038: }
1.191 harris41 6039: }
1.12 www 6040: return %returnhash;
1.424 matthew 6041: }
6042:
6043: sub convert_dump_to_currentdump{
6044: my %hash = %{shift()};
6045: my %returnhash;
6046: # Code ripped from lond, essentially. The only difference
6047: # here is the unescaping done by lonnet::dump(). Conceivably
6048: # we might run in to problems with parameter names =~ /^v\./
6049: while (my ($key,$value) = each(%hash)) {
6050: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 6051: $symb = &unescape($symb);
6052: $param = &unescape($param);
1.424 matthew 6053: next if ($v eq 'version' || $symb eq 'keys');
6054: next if (exists($returnhash{$symb}) &&
6055: exists($returnhash{$symb}->{$param}) &&
6056: $returnhash{$symb}->{'v.'.$param} > $v);
6057: $returnhash{$symb}->{$param}=$value;
6058: $returnhash{$symb}->{'v.'.$param}=$v;
6059: }
6060: #
6061: # Remove all of the keys in the hashes which keep track of
6062: # the version of the parameter.
6063: while (my ($symb,$param_hash) = each(%returnhash)) {
6064: # use a foreach because we are going to delete from the hash.
6065: foreach my $key (keys(%$param_hash)) {
6066: delete($param_hash->{$key}) if ($key =~ /^v\./);
6067: }
6068: }
6069: return \%returnhash;
1.12 www 6070: }
6071:
1.627 albertel 6072: # ------------------------------------------------------ critical inc interface
6073:
6074: sub cinc {
6075: return &inc(@_,'critical');
6076: }
6077:
1.449 matthew 6078: # --------------------------------------------------------------- inc interface
6079:
6080: sub inc {
1.627 albertel 6081: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 6082: if (!$udomain) { $udomain=$env{'user.domain'}; }
6083: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 6084: my $uhome=&homeserver($uname,$udomain);
6085: my $items='';
6086: if (! ref($store)) {
6087: # got a single value, so use that instead
6088: $items = &escape($store).'=&';
6089: } elsif (ref($store) eq 'SCALAR') {
6090: $items = &escape($$store).'=&';
6091: } elsif (ref($store) eq 'ARRAY') {
6092: $items = join('=&',map {&escape($_);} @{$store});
6093: } elsif (ref($store) eq 'HASH') {
6094: while (my($key,$value) = each(%{$store})) {
6095: $items.= &escape($key).'='.&escape($value).'&';
6096: }
6097: }
6098: $items=~s/\&$//;
1.627 albertel 6099: if ($critical) {
6100: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6101: } else {
6102: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6103: }
1.449 matthew 6104: }
6105:
1.12 www 6106: # --------------------------------------------------------------- put interface
6107:
6108: sub put {
1.134 albertel 6109: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6110: if (!$udomain) { $udomain=$env{'user.domain'}; }
6111: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6112: my $uhome=&homeserver($uname,$udomain);
1.12 www 6113: my $items='';
1.800 albertel 6114: foreach my $item (keys(%$storehash)) {
6115: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6116: }
1.12 www 6117: $items=~s/\&$//;
1.134 albertel 6118: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6119: }
6120:
1.631 albertel 6121: # ------------------------------------------------------------ newput interface
6122:
6123: sub newput {
6124: my ($namespace,$storehash,$udomain,$uname)=@_;
6125: if (!$udomain) { $udomain=$env{'user.domain'}; }
6126: if (!$uname) { $uname=$env{'user.name'}; }
6127: my $uhome=&homeserver($uname,$udomain);
6128: my $items='';
6129: foreach my $key (keys(%$storehash)) {
6130: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6131: }
6132: $items=~s/\&$//;
6133: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6134: }
6135:
6136: # --------------------------------------------------------- putstore interface
6137:
1.524 raeburn 6138: sub putstore {
1.1269 raeburn 6139: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6140: if (!$udomain) { $udomain=$env{'user.domain'}; }
6141: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6142: my $uhome=&homeserver($uname,$udomain);
6143: my $items='';
1.715 albertel 6144: foreach my $key (keys(%$storehash)) {
6145: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6146: }
1.715 albertel 6147: $items=~s/\&$//;
1.716 albertel 6148: my $esc_symb=&escape($symb);
6149: my $esc_v=&escape($version);
1.715 albertel 6150: my $reply =
1.716 albertel 6151: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6152: $uhome);
1.1269 raeburn 6153: if (($tolog) && ($reply eq 'ok')) {
6154: my $namevalue='';
6155: foreach my $key (keys(%{$storehash})) {
6156: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6157: }
6158: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6159: '&host='.&escape($perlvar{'lonHostID'}).
6160: '&version='.$esc_v.
6161: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6162: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6163: }
1.715 albertel 6164: if ($reply eq 'unknown_cmd') {
1.716 albertel 6165: # gfall back to way things use to be done
1.715 albertel 6166: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6167: $uname);
1.524 raeburn 6168: }
1.715 albertel 6169: return $reply;
6170: }
6171:
6172: sub old_putstore {
1.716 albertel 6173: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6174: if (!$udomain) { $udomain=$env{'user.domain'}; }
6175: if (!$uname) { $uname=$env{'user.name'}; }
6176: my $uhome=&homeserver($uname,$udomain);
6177: my %newstorehash;
1.800 albertel 6178: foreach my $item (keys(%$storehash)) {
6179: my $key = $version.':'.&escape($symb).':'.$item;
6180: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6181: }
6182: my $items='';
6183: my %allitems = ();
1.800 albertel 6184: foreach my $item (keys(%newstorehash)) {
6185: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6186: my $key = $1.':keys:'.$2;
6187: $allitems{$key} .= $3.':';
6188: }
1.800 albertel 6189: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6190: }
1.800 albertel 6191: foreach my $item (keys(%allitems)) {
6192: $allitems{$item} =~ s/\:$//;
6193: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6194: }
6195: $items=~s/\&$//;
6196: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6197: }
6198:
1.47 www 6199: # ------------------------------------------------------ critical put interface
6200:
6201: sub cput {
1.134 albertel 6202: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6203: if (!$udomain) { $udomain=$env{'user.domain'}; }
6204: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6205: my $uhome=&homeserver($uname,$udomain);
1.47 www 6206: my $items='';
1.800 albertel 6207: foreach my $item (keys(%$storehash)) {
6208: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6209: }
1.47 www 6210: $items=~s/\&$//;
1.134 albertel 6211: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6212: }
6213:
6214: # -------------------------------------------------------------- eget interface
6215:
6216: sub eget {
1.133 albertel 6217: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6218: my $items='';
1.800 albertel 6219: foreach my $item (@$storearr) {
6220: $items.=&escape($item).'&';
1.191 harris41 6221: }
1.12 www 6222: $items=~s/\&$//;
1.620 albertel 6223: if (!$udomain) { $udomain=$env{'user.domain'}; }
6224: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6225: my $uhome=&homeserver($uname,$udomain);
6226: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6227: my @pairs=split(/\&/,$rep);
6228: my %returnhash=();
1.42 www 6229: my $i=0;
1.800 albertel 6230: foreach my $item (@$storearr) {
6231: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6232: $i++;
1.191 harris41 6233: }
1.12 www 6234: return %returnhash;
6235: }
6236:
1.667 albertel 6237: # ------------------------------------------------------------ tmpput interface
6238: sub tmpput {
1.802 raeburn 6239: my ($storehash,$server,$context)=@_;
1.667 albertel 6240: my $items='';
1.800 albertel 6241: foreach my $item (keys(%$storehash)) {
6242: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6243: }
6244: $items=~s/\&$//;
1.802 raeburn 6245: if (defined($context)) {
6246: $items .= ':'.&escape($context);
6247: }
1.667 albertel 6248: return &reply("tmpput:$items",$server);
6249: }
6250:
6251: # ------------------------------------------------------------ tmpget interface
6252: sub tmpget {
1.688 albertel 6253: my ($token,$server)=@_;
6254: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6255: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6256: my %returnhash;
6257: foreach my $item (split(/\&/,$rep)) {
6258: my ($key,$value)=split(/=/,$item);
1.951 raeburn 6259: next if ($key =~ /^error: 2 /);
1.667 albertel 6260: $returnhash{&unescape($key)}=&thaw_unescape($value);
6261: }
6262: return %returnhash;
6263: }
6264:
1.1113 raeburn 6265: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6266: sub tmpdel {
6267: my ($token,$server)=@_;
6268: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6269: return &reply("tmpdel:$token",$server);
6270: }
6271:
1.1198 raeburn 6272: # ------------------------------------------------------------ get_timebased_id
6273:
6274: sub get_timebased_id {
6275: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6276: $maxtries) = @_;
6277: my ($newid,$error,$dellock);
6278: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6279: return ('','ok','invalid call to get suffix');
6280: }
6281:
6282: # set defaults for any optional args for which values were not supplied
6283: if ($who eq '') {
6284: $who = $env{'user.name'}.':'.$env{'user.domain'};
6285: }
6286: if (!$locktries) {
6287: $locktries = 3;
6288: }
6289: if (!$maxtries) {
6290: $maxtries = 10;
6291: }
6292:
6293: if (($cdom eq '') || ($cnum eq '')) {
6294: if ($env{'request.course.id'}) {
6295: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6296: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6297: }
6298: if (($cdom eq '') || ($cnum eq '')) {
6299: return ('','ok','call to get suffix not in course context');
6300: }
6301: }
6302:
6303: # construct locking item
6304: my $lockhash = {
6305: $prefix."\0".'locked_'.$keyid => $who,
6306: };
6307: my $tries = 0;
6308:
6309: # attempt to get lock on nohist_$namespace file
6310: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6311: while (($gotlock ne 'ok') && $tries <$locktries) {
6312: $tries ++;
6313: sleep 1;
6314: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6315: }
6316:
6317: # attempt to get unique identifier, based on current timestamp
6318: if ($gotlock eq 'ok') {
6319: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6320: my $id = time;
6321: $newid = $id;
1.1268 raeburn 6322: if ($idtype eq 'addcode') {
6323: $newid .= &sixnum_code();
6324: }
1.1198 raeburn 6325: my $idtries = 0;
6326: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6327: if ($idtype eq 'concat') {
6328: $newid = $id.$idtries;
1.1268 raeburn 6329: } elsif ($idtype eq 'addcode') {
6330: $newid = $newid.&sixnum_code();
1.1198 raeburn 6331: } else {
6332: $newid ++;
6333: }
6334: $idtries ++;
6335: }
6336: if (!exists($inuse{$prefix."\0".$newid})) {
6337: my %new_item = (
6338: $prefix."\0".$newid => $who,
6339: );
6340: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6341: $cdom,$cnum);
6342: if ($putresult ne 'ok') {
6343: undef($newid);
6344: $error = 'error saving new item: '.$putresult;
6345: }
6346: } else {
1.1268 raeburn 6347: undef($newid);
1.1198 raeburn 6348: $error = ('error: no unique suffix available for the new item ');
6349: }
6350: # remove lock
6351: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6352: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6353: } else {
6354: $error = "error: could not obtain lockfile\n";
6355: $dellock = 'ok';
1.1276 raeburn 6356: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6357: $dellock = 'nolock';
6358: }
1.1198 raeburn 6359: }
6360: return ($newid,$dellock,$error);
6361: }
6362:
1.1268 raeburn 6363: sub sixnum_code {
6364: my $code;
6365: for (0..6) {
6366: $code .= int( rand(9) );
6367: }
6368: return $code;
6369: }
6370:
1.765 albertel 6371: # -------------------------------------------------- portfolio access checking
6372:
6373: sub portfolio_access {
1.1270 raeburn 6374: my ($requrl,$clientip) = @_;
1.765 albertel 6375: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 6376: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6377: if ($result) {
6378: my %setters;
6379: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6380: my ($startblock,$endblock) =
6381: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6382: if ($startblock && $endblock) {
6383: return 'B';
6384: }
6385: } else {
6386: my ($startblock,$endblock) =
6387: &Apache::loncommon::blockcheck(\%setters,'port');
6388: if ($startblock && $endblock) {
6389: return 'B';
6390: }
6391: }
6392: }
1.765 albertel 6393: if ($result eq 'ok') {
1.766 albertel 6394: return 'F';
1.765 albertel 6395: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6396: return 'A';
1.765 albertel 6397: }
1.766 albertel 6398: return '';
1.765 albertel 6399: }
6400:
6401: sub get_portfolio_access {
1.1270 raeburn 6402: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6403:
6404: if (!ref($access_hash)) {
6405: my $current_perms = &get_portfile_permissions($udom,$unum);
6406: my %access_controls = &get_access_controls($current_perms,$group,
6407: $file_name);
6408: $access_hash = $access_controls{$file_name};
6409: }
6410:
1.1270 raeburn 6411: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6412: my $now = time;
6413: if (ref($access_hash) eq 'HASH') {
6414: foreach my $key (keys(%{$access_hash})) {
6415: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6416: if ($start > $now) {
6417: next;
6418: }
6419: if ($end && $end<$now) {
6420: next;
6421: }
6422: if ($scope eq 'public') {
6423: $public = $key;
6424: last;
6425: } elsif ($scope eq 'guest') {
6426: $guest = $key;
6427: } elsif ($scope eq 'domains') {
6428: push(@domains,$key);
6429: } elsif ($scope eq 'users') {
6430: push(@users,$key);
6431: } elsif ($scope eq 'course') {
6432: push(@courses,$key);
6433: } elsif ($scope eq 'group') {
6434: push(@groups,$key);
1.1270 raeburn 6435: } elsif ($scope eq 'ip') {
6436: push(@ips,$key);
1.765 albertel 6437: }
6438: }
6439: if ($public) {
6440: return 'ok';
1.1270 raeburn 6441: } elsif (@ips > 0) {
6442: my $allowed;
6443: foreach my $ipkey (@ips) {
6444: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6445: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6446: $allowed = 1;
6447: last;
6448: }
6449: }
6450: }
6451: if ($allowed) {
6452: return 'ok';
6453: }
1.765 albertel 6454: }
6455: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6456: if ($guest) {
6457: return $guest;
6458: }
6459: } else {
6460: if (@domains > 0) {
6461: foreach my $domkey (@domains) {
6462: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6463: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6464: return 'ok';
6465: }
6466: }
6467: }
6468: }
6469: if (@users > 0) {
6470: foreach my $userkey (@users) {
1.865 raeburn 6471: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6472: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6473: if (ref($item) eq 'HASH') {
6474: if (($item->{'uname'} eq $env{'user.name'}) &&
6475: ($item->{'udom'} eq $env{'user.domain'})) {
6476: return 'ok';
6477: }
6478: }
6479: }
6480: }
1.765 albertel 6481: }
6482: }
6483: my %roleshash;
6484: my @courses_and_groups = @courses;
6485: push(@courses_and_groups,@groups);
6486: if (@courses_and_groups > 0) {
6487: my (%allgroups,%allroles);
6488: my ($start,$end,$role,$sec,$group);
6489: foreach my $envkey (%env) {
1.1060 raeburn 6490: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6491: my $cid = $2.'_'.$3;
6492: if ($1 eq 'gr') {
6493: $group = $4;
6494: $allgroups{$cid}{$group} = $env{$envkey};
6495: } else {
6496: if ($4 eq '') {
6497: $sec = 'none';
6498: } else {
6499: $sec = $4;
6500: }
6501: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6502: }
1.811 albertel 6503: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6504: my $cid = $2.'_'.$3;
6505: if ($4 eq '') {
6506: $sec = 'none';
6507: } else {
6508: $sec = $4;
6509: }
6510: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6511: }
6512: }
6513: if (keys(%allroles) == 0) {
6514: return;
6515: }
6516: foreach my $key (@courses_and_groups) {
6517: my %content = %{$$access_hash{$key}};
6518: my $cnum = $content{'number'};
6519: my $cdom = $content{'domain'};
6520: my $cid = $cdom.'_'.$cnum;
6521: if (!exists($allroles{$cid})) {
6522: next;
6523: }
6524: foreach my $role_id (keys(%{$content{'roles'}})) {
6525: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6526: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6527: my @status = @{$content{'roles'}{$role_id}{'access'}};
6528: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6529: foreach my $role (keys(%{$allroles{$cid}})) {
6530: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6531: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6532: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6533: if (grep/^all$/,@sections) {
6534: return 'ok';
6535: } else {
6536: if (grep/^$sec$/,@sections) {
6537: return 'ok';
6538: }
6539: }
6540: }
6541: }
6542: if (keys(%{$allgroups{$cid}}) == 0) {
6543: if (grep/^none$/,@groups) {
6544: return 'ok';
6545: }
6546: } else {
6547: if (grep/^all$/,@groups) {
6548: return 'ok';
6549: }
6550: foreach my $group (keys(%{$allgroups{$cid}})) {
6551: if (grep/^$group$/,@groups) {
6552: return 'ok';
6553: }
6554: }
6555: }
6556: }
6557: }
6558: }
6559: }
6560: }
6561: if ($guest) {
6562: return $guest;
6563: }
6564: }
6565: }
6566: return;
6567: }
6568:
6569: sub course_group_datechecker {
6570: my ($dates,$now,$status) = @_;
6571: my ($start,$end) = split(/\./,$dates);
6572: if (!$start && !$end) {
6573: return 'ok';
6574: }
6575: if (grep/^active$/,@{$status}) {
6576: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6577: return 'ok';
6578: }
6579: }
6580: if (grep/^previous$/,@{$status}) {
6581: if ($end > $now ) {
6582: return 'ok';
6583: }
6584: }
6585: if (grep/^future$/,@{$status}) {
6586: if ($start > $now) {
6587: return 'ok';
6588: }
6589: }
6590: return;
6591: }
6592:
6593: sub parse_portfolio_url {
6594: my ($url) = @_;
6595:
6596: my ($type,$udom,$unum,$group,$file_name);
6597:
1.823 albertel 6598: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6599: $type = 1;
6600: $udom = $1;
6601: $unum = $2;
6602: $file_name = $3;
1.823 albertel 6603: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6604: $type = 2;
6605: $udom = $1;
6606: $unum = $2;
6607: $group = $3;
6608: $file_name = $3.'/'.$4;
6609: }
6610: if (wantarray) {
6611: return ($type,$udom,$unum,$file_name,$group);
6612: }
6613: return $type;
6614: }
6615:
6616: sub is_portfolio_url {
6617: my ($url) = @_;
6618: return scalar(&parse_portfolio_url($url));
6619: }
6620:
1.798 raeburn 6621: sub is_portfolio_file {
6622: my ($file) = @_;
1.820 raeburn 6623: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6624: return 1;
6625: }
6626: return;
6627: }
6628:
1.976 raeburn 6629: sub usertools_access {
1.1084 raeburn 6630: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6631: my ($access,%tools);
6632: if ($context eq '') {
6633: $context = 'tools';
6634: }
6635: if ($context eq 'requestcourses') {
6636: %tools = (
6637: official => 1,
6638: unofficial => 1,
1.1006 raeburn 6639: community => 1,
1.1246 raeburn 6640: textbook => 1,
1.1305 raeburn 6641: placement => 1,
1.985 raeburn 6642: );
1.1183 raeburn 6643: } elsif ($context eq 'requestauthor') {
6644: %tools = (
6645: requestauthor => 1,
6646: );
1.985 raeburn 6647: } else {
6648: %tools = (
6649: aboutme => 1,
6650: blog => 1,
1.1177 raeburn 6651: webdav => 1,
1.985 raeburn 6652: portfolio => 1,
6653: );
6654: }
1.976 raeburn 6655: return if (!defined($tools{$tool}));
6656:
1.1242 raeburn 6657: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6658: $udom = $env{'user.domain'};
6659: $uname = $env{'user.name'};
6660: }
6661:
1.978 raeburn 6662: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6663: if ($action ne 'reload') {
1.985 raeburn 6664: if ($context eq 'requestcourses') {
6665: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6666: } elsif ($context eq 'requestauthor') {
6667: return $env{'environment.canrequest.author'};
1.985 raeburn 6668: } else {
6669: return $env{'environment.availabletools.'.$tool};
6670: }
6671: }
1.976 raeburn 6672: }
6673:
1.1183 raeburn 6674: my ($toolstatus,$inststatus,$envkey);
6675: if ($context eq 'requestauthor') {
6676: $envkey = $context;
6677: } else {
6678: $envkey = $context.'.'.$tool;
6679: }
1.976 raeburn 6680:
1.985 raeburn 6681: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6682: ($action ne 'reload')) {
1.1183 raeburn 6683: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6684: $inststatus = $env{'environment.inststatus'};
6685: } else {
1.1084 raeburn 6686: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6687: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6688: $inststatus = $userenvref->{'inststatus'};
6689: } else {
1.1183 raeburn 6690: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6691: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6692: $inststatus = $userenv{'inststatus'};
6693: }
1.976 raeburn 6694: }
6695:
6696: if ($toolstatus ne '') {
6697: if ($toolstatus) {
6698: $access = 1;
6699: } else {
6700: $access = 0;
6701: }
6702: return $access;
6703: }
6704:
1.1084 raeburn 6705: my ($is_adv,%domdef);
6706: if (ref($is_advref) eq 'HASH') {
6707: $is_adv = $is_advref->{'is_adv'};
6708: } else {
6709: $is_adv = &is_advanced_user($udom,$uname);
6710: }
6711: if (ref($domdefref) eq 'HASH') {
6712: %domdef = %{$domdefref};
6713: } else {
6714: %domdef = &get_domain_defaults($udom);
6715: }
1.976 raeburn 6716: if (ref($domdef{$tool}) eq 'HASH') {
6717: if ($is_adv) {
6718: if ($domdef{$tool}{'_LC_adv'} ne '') {
6719: if ($domdef{$tool}{'_LC_adv'}) {
6720: $access = 1;
6721: } else {
6722: $access = 0;
6723: }
6724: return $access;
6725: }
6726: }
6727: if ($inststatus ne '') {
6728: my ($hasaccess,$hasnoaccess);
6729: foreach my $affiliation (split(/:/,$inststatus)) {
6730: if ($domdef{$tool}{$affiliation} ne '') {
6731: if ($domdef{$tool}{$affiliation}) {
6732: $hasaccess = 1;
6733: } else {
6734: $hasnoaccess = 1;
6735: }
6736: }
6737: }
6738: if ($hasaccess || $hasnoaccess) {
6739: if ($hasaccess) {
6740: $access = 1;
6741: } elsif ($hasnoaccess) {
6742: $access = 0;
6743: }
6744: return $access;
6745: }
6746: } else {
6747: if ($domdef{$tool}{'default'} ne '') {
6748: if ($domdef{$tool}{'default'}) {
6749: $access = 1;
6750: } elsif ($domdef{$tool}{'default'} == 0) {
6751: $access = 0;
6752: }
6753: return $access;
6754: }
6755: }
6756: } else {
1.1177 raeburn 6757: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6758: $access = 1;
6759: } else {
6760: $access = 0;
6761: }
1.976 raeburn 6762: return $access;
6763: }
6764: }
6765:
1.1050 raeburn 6766: sub is_course_owner {
6767: my ($cdom,$cnum,$udom,$uname) = @_;
6768: if (($udom eq '') || ($uname eq '')) {
6769: $udom = $env{'user.domain'};
6770: $uname = $env{'user.name'};
6771: }
6772: unless (($udom eq '') || ($uname eq '')) {
6773: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6774: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6775: return 1;
6776: } else {
6777: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6778: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6779: return 1;
6780: }
6781: }
6782: }
6783: }
6784: return;
6785: }
6786:
1.976 raeburn 6787: sub is_advanced_user {
6788: my ($udom,$uname) = @_;
1.1085 raeburn 6789: if ($udom ne '' && $uname ne '') {
6790: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6791: if (wantarray) {
6792: return ($env{'user.adv'},$env{'user.author'});
6793: } else {
6794: return $env{'user.adv'};
6795: }
1.1085 raeburn 6796: }
6797: }
1.976 raeburn 6798: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6799: my %allroles;
1.1128 raeburn 6800: my ($is_adv,$is_author);
1.976 raeburn 6801: foreach my $role (keys(%roleshash)) {
6802: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6803: my $area = '/'.$tdomain.'/'.$trest;
6804: if ($sec ne '') {
6805: $area .= '/'.$sec;
6806: }
6807: if (($area ne '') && ($trole ne '')) {
6808: my $spec=$trole.'.'.$area;
6809: if ($trole =~ /^cr\//) {
6810: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6811: } elsif ($trole ne 'gr') {
6812: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6813: }
1.1128 raeburn 6814: if ($trole eq 'au') {
6815: $is_author = 1;
6816: }
1.976 raeburn 6817: }
6818: }
6819: foreach my $role (keys(%allroles)) {
6820: last if ($is_adv);
6821: foreach my $item (split(/:/,$allroles{$role})) {
6822: if ($item ne '') {
6823: my ($privilege,$restrictions)=split(/&/,$item);
6824: if ($privilege eq 'adv') {
6825: $is_adv = 1;
6826: last;
6827: }
6828: }
6829: }
6830: }
1.1128 raeburn 6831: if (wantarray) {
6832: return ($is_adv,$is_author);
6833: }
1.976 raeburn 6834: return $is_adv;
6835: }
1.798 raeburn 6836:
1.1035 raeburn 6837: sub check_can_request {
1.1036 raeburn 6838: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6839: my $canreq = 0;
6840: my ($types,$typename) = &Apache::loncommon::course_types();
6841: my @options = ('approval','validate','autolimit');
6842: my $optregex = join('|',@options);
6843: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6844: foreach my $type (@{$types}) {
6845: if (&usertools_access($env{'user.name'},
6846: $env{'user.domain'},
6847: $type,undef,'requestcourses')) {
6848: $canreq ++;
1.1036 raeburn 6849: if (ref($request_domains) eq 'HASH') {
6850: push(@{$request_domains->{$type}},$env{'user.domain'});
6851: }
1.1035 raeburn 6852: if ($dom eq $env{'user.domain'}) {
6853: $can_request->{$type} = 1;
6854: }
6855: }
6856: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6857: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6858: if (@curr > 0) {
1.1036 raeburn 6859: foreach my $item (@curr) {
6860: if (ref($request_domains) eq 'HASH') {
6861: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6862: if ($otherdom ne '') {
6863: if (ref($request_domains->{$type}) eq 'ARRAY') {
6864: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6865: push(@{$request_domains->{$type}},$otherdom);
6866: }
6867: } else {
6868: push(@{$request_domains->{$type}},$otherdom);
6869: }
6870: }
6871: }
6872: }
6873: unless($dom eq $env{'user.domain'}) {
6874: $canreq ++;
1.1035 raeburn 6875: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6876: $can_request->{$type} = 1;
6877: }
6878: }
6879: }
6880: }
6881: }
6882: }
6883: return $canreq;
6884: }
6885:
1.341 www 6886: # ---------------------------------------------- Custom access rule evaluation
6887:
6888: sub customaccess {
6889: my ($priv,$uri)=@_;
1.807 albertel 6890: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6891: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6892: $udom = &LONCAPA::clean_domain($udom);
6893: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6894: my $access=0;
1.800 albertel 6895: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6896: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6897: if ($type eq 'user') {
6898: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6899: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6900: if ($tdom) {
6901: if ($tdom ne $env{'user.domain'}) { next; }
6902: }
1.896 albertel 6903: if ($tuname) {
6904: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6905: }
6906: $access=($effect eq 'allow');
6907: last;
6908: }
6909: } else {
6910: if ($role) {
6911: if ($role ne $urole) { next; }
6912: }
6913: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6914: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6915: if ($tdom) {
6916: if ($tdom ne $udom) { next; }
6917: }
6918: if ($tcrs) {
6919: if ($tcrs ne $ucrs) { next; }
6920: }
6921: if ($tsec) {
6922: if ($tsec ne $usec) { next; }
6923: }
6924: $access=($effect eq 'allow');
6925: last;
6926: }
6927: if ($realm eq '' && $role eq '') {
6928: $access=($effect eq 'allow');
6929: }
1.402 bowersj2 6930: }
1.341 www 6931: }
6932: return $access;
6933: }
6934:
1.103 harris41 6935: # ------------------------------------------------- Check for a user privilege
1.12 www 6936:
6937: sub allowed {
1.1281 raeburn 6938: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 6939: my $ver_orguri=$uri;
1.439 www 6940: $uri=&deversion($uri);
1.152 www 6941: my $orguri=$uri;
1.52 www 6942: $uri=&declutter($uri);
1.809 raeburn 6943:
1.810 raeburn 6944: if ($priv eq 'evb') {
6945: # Evade communication block restrictions for specified role in a course
6946: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6947: return $1;
6948: } else {
6949: return;
6950: }
6951: }
6952:
1.620 albertel 6953: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6954: # Free bre access to adm and meta resources
1.775 albertel 6955: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6956: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6957: && ($priv eq 'bre')) {
1.14 www 6958: return 'F';
1.159 www 6959: }
6960:
1.545 banghart 6961: # Free bre access to user's own portfolio contents
1.714 raeburn 6962: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6963: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6964: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6965: my %setters;
6966: my ($startblock,$endblock) =
6967: &Apache::loncommon::blockcheck(\%setters,'port');
6968: if ($startblock && $endblock) {
6969: return 'B';
6970: } else {
6971: return 'F';
6972: }
1.545 banghart 6973: }
6974:
1.762 raeburn 6975: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6976: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6977: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6978: if (exists($env{'request.course.id'})) {
6979: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6980: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6981: if (($domain eq $cdom) && ($name eq $cnum)) {
6982: my $courseprivid=$env{'request.course.id'};
6983: $courseprivid=~s/\_/\//;
6984: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6985: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6986: return $1;
1.762 raeburn 6987: } else {
6988: if ($env{'request.course.sec'}) {
6989: $courseprivid.='/'.$env{'request.course.sec'};
6990: }
6991: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6992: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6993: return $2;
6994: }
1.714 raeburn 6995: }
6996: }
6997: }
6998: }
6999:
1.159 www 7000: # Free bre to public access
7001:
7002: if ($priv eq 'bre') {
1.238 www 7003: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7004: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7005: return 'F';
7006: }
1.238 www 7007: if ($copyright eq 'priv') {
7008: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7009: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7010: return '';
7011: }
7012: }
7013: if ($copyright eq 'domain') {
7014: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7015: unless (($env{'user.domain'} eq $1) ||
7016: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7017: return '';
7018: }
1.262 matthew 7019: }
1.620 albertel 7020: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7021: # Library role, so allow browsing of resources in this domain.
7022: return 'F';
1.238 www 7023: }
1.341 www 7024: if ($copyright eq 'custom') {
7025: unless (&customaccess($priv,$uri)) { return ''; }
7026: }
1.14 www 7027: }
1.264 matthew 7028: # Domain coordinator is trying to create a course
1.620 albertel 7029: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7030: # uri is the requested domain in this case.
7031: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7032: # a role of dc for the domain in question.
1.620 albertel 7033: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7034: }
1.29 www 7035:
1.52 www 7036: my $thisallowed='';
7037: my $statecond=0;
7038: my $courseprivid='';
7039:
1.1039 raeburn 7040: my $ownaccess;
1.1043 raeburn 7041: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7042: if (($priv eq 'bro') && ($env{'user.author'})) {
7043: if ($uri eq '') {
7044: $ownaccess = 1;
7045: } else {
7046: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7047: my $udom = $env{'user.domain'};
7048: my $uname = $env{'user.name'};
7049: if ($uri =~ m{^\Q$udom\E/?$}) {
7050: $ownaccess = 1;
1.1040 raeburn 7051: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 7052: unless ($uri =~ m{\.\./}) {
7053: $ownaccess = 1;
7054: }
7055: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7056: my $now = time;
7057: if ($uri =~ m{^([^/]+)/?$}) {
7058: my $adom = $1;
7059: foreach my $key (keys(%env)) {
1.1042 raeburn 7060: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 7061: my ($start,$end) = split('.',$env{$key});
7062: if (($now >= $start) && (!$end || $end < $now)) {
7063: $ownaccess = 1;
7064: last;
7065: }
7066: }
7067: }
7068: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7069: my $adom = $1;
7070: my $aname = $2;
1.1042 raeburn 7071: foreach my $role ('ca','aa') {
7072: if ($env{"user.role.$role./$adom/$aname"}) {
7073: my ($start,$end) =
7074: split('.',$env{"user.role.$role./$adom/$aname"});
7075: if (($now >= $start) && (!$end || $end < $now)) {
7076: $ownaccess = 1;
7077: last;
7078: }
1.1039 raeburn 7079: }
7080: }
7081: }
7082: }
7083: }
7084: }
7085: }
7086:
1.52 www 7087: # Course
7088:
1.620 albertel 7089: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7090: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7091: $thisallowed.=$1;
7092: }
1.52 www 7093: }
1.29 www 7094:
1.52 www 7095: # Domain
7096:
1.620 albertel 7097: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7098: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7099: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7100: $thisallowed.=$1;
7101: }
1.12 www 7102: }
1.52 www 7103:
1.1141 raeburn 7104: # User who is not author or co-author might still be able to edit
7105: # resource of an author in the domain (e.g., if Domain Coordinator).
7106: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7107: (&allowed('mdc',$env{'request.course.id'}))) {
7108: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7109: $thisallowed.=$1;
7110: }
7111: }
7112:
1.52 www 7113: # Course: uri itself is a course
1.66 www 7114: my $courseuri=$uri;
7115: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 7116: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7117:
1.620 albertel 7118: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7119: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7120: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7121: $thisallowed.=$1;
7122: }
1.12 www 7123: }
1.29 www 7124:
1.665 albertel 7125: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7126: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7127: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7128: $thisallowed='';
1.671 raeburn 7129: my ($match)=&is_on_map($uri);
7130: if ($match) {
7131: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7132: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 7133: my $value = $1;
7134: if ($noblockcheck) {
7135: $thisallowed.=$value;
1.1162 raeburn 7136: } else {
1.1281 raeburn 7137: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7138: if (@blockers > 0) {
7139: $thisallowed = 'B';
7140: } else {
7141: $thisallowed.=$value;
7142: }
1.1162 raeburn 7143: }
1.671 raeburn 7144: }
7145: } else {
1.705 albertel 7146: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7147: if ($refuri) {
7148: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7149: $thisallowed='F';
1.671 raeburn 7150: } else {
7151: $refuri=&declutter($refuri);
7152: my ($match) = &is_on_map($refuri);
7153: if ($match) {
1.1281 raeburn 7154: if ($noblockcheck) {
7155: $thisallowed='F';
1.1162 raeburn 7156: } else {
1.1281 raeburn 7157: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7158: if (@blockers > 0) {
7159: $thisallowed = 'B';
7160: } else {
7161: $thisallowed='F';
7162: }
1.1162 raeburn 7163: }
1.671 raeburn 7164: }
1.669 raeburn 7165: }
1.671 raeburn 7166: }
7167: }
1.314 www 7168: }
1.492 albertel 7169:
1.766 albertel 7170: if ($priv eq 'bre'
7171: && $thisallowed ne 'F'
7172: && $thisallowed ne '2'
7173: && &is_portfolio_url($uri)) {
1.1270 raeburn 7174: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7175: }
1.1250 raeburn 7176:
1.52 www 7177: # Full access at system, domain or course-wide level? Exit.
1.29 www 7178: if ($thisallowed=~/F/) {
7179: return 'F';
7180: }
7181:
1.52 www 7182: # If this is generating or modifying users, exit with special codes
1.29 www 7183:
1.643 www 7184: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7185: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7186: my ($audom,$auname)=split('/',$uri);
1.643 www 7187: # no author name given, so this just checks on the general right to make a co-author in this domain
7188: unless ($auname) { return $thisallowed; }
7189: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7190: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7191: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7192: ($audom ne $env{'request.role.domain'}))) { return ''; }
7193: }
1.52 www 7194: return $thisallowed;
7195: }
7196: #
1.103 harris41 7197: # Gathered so far: system, domain and course wide privileges
1.52 www 7198: #
7199: # Course: See if uri or referer is an individual resource that is part of
7200: # the course
7201:
1.620 albertel 7202: if ($env{'request.course.id'}) {
1.232 www 7203:
1.620 albertel 7204: $courseprivid=$env{'request.course.id'};
7205: if ($env{'request.course.sec'}) {
7206: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7207: }
7208: $courseprivid=~s/\_/\//;
7209: my $checkreferer=1;
1.232 www 7210: my ($match,$cond)=&is_on_map($uri);
7211: if ($match) {
7212: $statecond=$cond;
1.620 albertel 7213: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7214: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7215: my $value = $1;
7216: if ($priv eq 'bre') {
1.1281 raeburn 7217: if ($noblockcheck) {
7218: $thisallowed.=$value;
1.1162 raeburn 7219: } else {
1.1281 raeburn 7220: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7221: if (@blockers > 0) {
7222: $thisallowed = 'B';
7223: } else {
7224: $thisallowed.=$value;
7225: }
1.1162 raeburn 7226: }
7227: } else {
7228: $thisallowed.=$value;
7229: }
1.52 www 7230: $checkreferer=0;
7231: }
1.29 www 7232: }
1.83 www 7233:
1.148 www 7234: if ($checkreferer) {
1.620 albertel 7235: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7236: unless ($refuri) {
1.800 albertel 7237: foreach my $key (keys(%env)) {
7238: if ($key=~/^httpref\..*\*/) {
7239: my $pattern=$key;
1.156 www 7240: $pattern=~s/^httpref\.\/res\///;
1.148 www 7241: $pattern=~s/\*/\[\^\/\]\+/g;
7242: $pattern=~s/\//\\\//g;
1.152 www 7243: if ($orguri=~/$pattern/) {
1.800 albertel 7244: $refuri=$env{$key};
1.148 www 7245: }
7246: }
1.191 harris41 7247: }
1.148 www 7248: }
1.232 www 7249:
1.148 www 7250: if ($refuri) {
1.152 www 7251: $refuri=&declutter($refuri);
1.232 www 7252: my ($match,$cond)=&is_on_map($refuri);
7253: if ($match) {
7254: my $refstatecond=$cond;
1.620 albertel 7255: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7256: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7257: my $value = $1;
7258: if ($priv eq 'bre') {
1.1281 raeburn 7259: if ($noblockcheck) {
7260: $thisallowed.=$value;
1.1162 raeburn 7261: } else {
1.1281 raeburn 7262: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7263: if (@blockers > 0) {
7264: $thisallowed = 'B';
7265: } else {
7266: $thisallowed.=$value;
7267: }
1.1162 raeburn 7268: }
7269: } else {
7270: $thisallowed.=$value;
7271: }
1.53 www 7272: $uri=$refuri;
7273: $statecond=$refstatecond;
1.52 www 7274: }
7275: }
1.148 www 7276: }
1.29 www 7277: }
1.52 www 7278: }
1.29 www 7279:
1.52 www 7280: #
1.103 harris41 7281: # Gathered now: all privileges that could apply, and condition number
1.52 www 7282: #
7283: #
7284: # Full or no access?
7285: #
1.29 www 7286:
1.52 www 7287: if ($thisallowed=~/F/) {
7288: return 'F';
7289: }
1.29 www 7290:
1.52 www 7291: unless ($thisallowed) {
7292: return '';
7293: }
1.29 www 7294:
1.52 www 7295: # Restrictions exist, deal with them
7296: #
7297: # C:according to course preferences
7298: # R:according to resource settings
7299: # L:unless locked
7300: # X:according to user session state
7301: #
7302:
7303: # Possibly locked functionality, check all courses
1.54 www 7304: # Locks might take effect only after 10 minutes cache expiration for other
7305: # courses, and 2 minutes for current course
1.52 www 7306:
7307: my $envkey;
7308: if ($thisallowed=~/L/) {
1.1000 raeburn 7309: foreach $envkey (keys(%env)) {
1.54 www 7310: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7311: my $courseid=$2;
7312: my $roleid=$1.'.'.$2;
1.92 www 7313: $courseid=~s/^\///;
1.54 www 7314: my $expiretime=600;
1.620 albertel 7315: if ($env{'request.role'} eq $roleid) {
1.54 www 7316: $expiretime=120;
7317: }
7318: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7319: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7320: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7321: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7322: }
1.620 albertel 7323: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7324: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7325: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7326: &log($env{'user.domain'},$env{'user.name'},
7327: $env{'user.home'},
1.57 www 7328: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7329: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7330: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7331: return '';
7332: }
7333: }
1.620 albertel 7334: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7335: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7336: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7337: &log($env{'user.domain'},$env{'user.name'},
7338: $env{'user.home'},
1.57 www 7339: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7340: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7341: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7342: return '';
7343: }
7344: }
7345: }
1.29 www 7346: }
1.52 www 7347: }
7348:
7349: #
7350: # Rest of the restrictions depend on selected course
7351: #
7352:
1.620 albertel 7353: unless ($env{'request.course.id'}) {
1.766 albertel 7354: if ($thisallowed eq 'A') {
7355: return 'A';
1.814 raeburn 7356: } elsif ($thisallowed eq 'B') {
7357: return 'B';
1.766 albertel 7358: } else {
7359: return '1';
7360: }
1.52 www 7361: }
1.29 www 7362:
1.52 www 7363: #
7364: # Now user is definitely in a course
7365: #
1.53 www 7366:
7367:
7368: # Course preferences
7369:
7370: if ($thisallowed=~/C/) {
1.620 albertel 7371: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7372: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7373: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7374: =~/\Q$rolecode\E/) {
1.1304 raeburn 7375: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7376: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7377: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7378: $env{'request.course.id'});
7379: }
1.237 www 7380: return '';
7381: }
7382:
1.620 albertel 7383: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7384: =~/\Q$unamedom\E/) {
1.1304 raeburn 7385: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7386: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7387: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7388: $env{'request.course.id'});
7389: }
1.54 www 7390: return '';
7391: }
1.53 www 7392: }
7393:
7394: # Resource preferences
7395:
7396: if ($thisallowed=~/R/) {
1.620 albertel 7397: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7398: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7399: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7400: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7401: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7402: }
7403: return '';
1.54 www 7404: }
1.53 www 7405: }
1.30 www 7406:
1.246 www 7407: # Restricted by state or randomout?
1.30 www 7408:
1.52 www 7409: if ($thisallowed=~/X/) {
1.620 albertel 7410: if ($env{'acc.randomout'}) {
1.579 albertel 7411: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7412: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7413: return '';
7414: }
1.247 www 7415: }
7416: if (&condval($statecond)) {
1.52 www 7417: return '2';
7418: } else {
7419: return '';
7420: }
7421: }
1.30 www 7422:
1.766 albertel 7423: if ($thisallowed eq 'A') {
7424: return 'A';
1.814 raeburn 7425: } elsif ($thisallowed eq 'B') {
7426: return 'B';
1.766 albertel 7427: }
1.52 www 7428: return 'F';
1.232 www 7429: }
1.1162 raeburn 7430:
1.1192 raeburn 7431: # ------------------------------------------- Check construction space access
7432:
7433: sub constructaccess {
7434: my ($url,$setpriv)=@_;
7435:
7436: # We do not allow editing of previous versions of files
7437: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7438:
7439: # Get username and domain from URL
7440: my ($ownername,$ownerdomain,$ownerhome);
7441:
7442: ($ownerdomain,$ownername) =
1.1325 raeburn 7443: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192 raeburn 7444:
7445: # The URL does not really point to any authorspace, forget it
7446: unless (($ownername) && ($ownerdomain)) { return ''; }
7447:
7448: # Now we need to see if the user has access to the authorspace of
7449: # $ownername at $ownerdomain
7450:
7451: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7452: # Real author for this?
7453: $ownerhome = $env{'user.home'};
7454: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7455: return ($ownername,$ownerdomain,$ownerhome);
7456: }
7457: } else {
7458: # Co-author for this?
7459: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7460: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7461: $ownerhome = &homeserver($ownername,$ownerdomain);
7462: return ($ownername,$ownerdomain,$ownerhome);
7463: }
1.1312 raeburn 7464: if ($env{'request.course.id'}) {
7465: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
7466: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
7467: if (&allowed('mdc',$env{'request.course.id'})) {
7468: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
7469: return ($ownername,$ownerdomain,$ownerhome);
7470: }
7471: }
7472: }
1.1192 raeburn 7473: }
7474:
7475: # We don't have any access right now. If we are not possibly going to do anything about this,
7476: # we might as well leave
7477: unless ($setpriv) { return ''; }
7478:
7479: # Backdoor access?
7480: my $allowed=&allowed('eco',$ownerdomain);
7481: # Nope
7482: unless ($allowed) { return ''; }
7483: # Looks like we may have access, but could be locked by the owner of the construction space
7484: if ($allowed eq 'U') {
7485: my %blocked=&get('environment',['domcoord.author'],
7486: $ownerdomain,$ownername);
7487: # Is blocked by owner
7488: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7489: }
7490: if (($allowed eq 'F') || ($allowed eq 'U')) {
7491: # Grant temporary access
7492: my $then=$env{'user.login.time'};
1.1209 raeburn 7493: my $update=$env{'user.update.time'};
1.1192 raeburn 7494: if (!$update) { $update = $then; }
7495: my $refresh=$env{'user.refresh.time'};
7496: if (!$refresh) { $refresh = $update; }
7497: my $now = time;
7498: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7499: $now,'ca','constructaccess');
7500: $ownerhome = &homeserver($ownername,$ownerdomain);
7501: return($ownername,$ownerdomain,$ownerhome);
7502: }
7503: # No business here
7504: return '';
7505: }
7506:
1.1282 raeburn 7507: # ----------------------------------------------------------- Content Blocking
7508:
7509: {
7510: # Caches for faster Course Contents display where content blocking
7511: # is in operation (i.e., interval param set) for timed quiz.
7512: #
7513: # User for whom data are being temporarily cached.
7514: my $cacheduser='';
7515: # Cached blockers for this user (a hash of blocking items).
7516: my %cachedblockers=();
7517: # When the data were last cached.
7518: my $cachedlast='';
7519:
7520: sub load_all_blockers {
7521: my ($uname,$udom,$blocks)=@_;
7522: if (($uname ne '') && ($udom ne '')) {
7523: if (($cacheduser eq $uname.':'.$udom) &&
7524: (abs($cachedlast-time)<5)) {
7525: return;
7526: }
7527: }
7528: $cachedlast=time;
7529: $cacheduser=$uname.':'.$udom;
7530: %cachedblockers = &get_commblock_resources($blocks);
7531: }
7532:
1.1162 raeburn 7533: sub get_comm_blocks {
7534: my ($cdom,$cnum) = @_;
7535: if ($cdom eq '' || $cnum eq '') {
7536: return unless ($env{'request.course.id'});
7537: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7538: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7539: }
7540: my %commblocks;
7541: my $hashid=$cdom.'_'.$cnum;
7542: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7543: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7544: %commblocks = %{$blocksref};
7545: } else {
7546: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7547: my $cachetime = 600;
7548: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7549: }
7550: return %commblocks;
7551: }
7552:
1.1282 raeburn 7553: sub get_commblock_resources {
7554: my ($blocks) = @_;
7555: my %blockers = ();
7556: return %blockers unless ($env{'request.course.id'});
7557: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7558: my %commblocks;
7559: if (ref($blocks) eq 'HASH') {
7560: %commblocks = %{$blocks};
7561: } else {
7562: %commblocks = &get_comm_blocks();
7563: }
1.1282 raeburn 7564: return %blockers unless (keys(%commblocks) > 0);
7565: my $navmap = Apache::lonnavmaps::navmap->new();
7566: return %blockers unless (ref($navmap));
1.1162 raeburn 7567: my $now = time;
7568: foreach my $block (keys(%commblocks)) {
7569: if ($block =~ /^(\d+)____(\d+)$/) {
7570: my ($start,$end) = ($1,$2);
7571: if ($start <= $now && $end >= $now) {
7572: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7573: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7574: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 7575: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7576: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7577: }
7578: }
7579: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 7580: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7581: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7582: }
7583: }
7584: }
7585: }
7586: }
7587: } elsif ($block =~ /^firstaccess____(.+)$/) {
7588: my $item = $1;
1.1163 raeburn 7589: my @to_test;
1.1162 raeburn 7590: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7591: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282 raeburn 7592: my @interval;
7593: my $type = 'map';
7594: if ($item eq 'course') {
7595: $type = 'course';
7596: @interval=&EXT("resource.0.interval");
7597: } else {
7598: if ($item =~ /___\d+___/) {
7599: $type = 'resource';
7600: @interval=&EXT("resource.0.interval",$item);
7601: if (ref($navmap)) {
7602: my $res = $navmap->getBySymb($item);
7603: push(@to_test,$res);
7604: }
1.1162 raeburn 7605: } else {
1.1282 raeburn 7606: my $mapsymb = &symbread($item,1);
7607: if ($mapsymb) {
7608: if (ref($navmap)) {
7609: my $mapres = $navmap->getBySymb($mapsymb);
7610: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7611: foreach my $res (@to_test) {
7612: my $symb = $res->symb();
7613: next if ($symb eq $mapsymb);
7614: if ($symb ne '') {
7615: @interval=&EXT("resource.0.interval",$symb);
7616: if ($interval[1] eq 'map') {
7617: last;
1.1162 raeburn 7618: }
7619: }
7620: }
7621: }
7622: }
7623: }
1.1282 raeburn 7624: }
1.1310 raeburn 7625: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 7626: my $timelimit = $1;
1.1282 raeburn 7627: my $first_access;
7628: if ($type eq 'resource') {
7629: $first_access=&get_first_access($interval[1],$item);
7630: } elsif ($type eq 'map') {
7631: $first_access=&get_first_access($interval[1],undef,$item);
7632: } else {
7633: $first_access=&get_first_access($interval[1]);
7634: }
7635: if ($first_access) {
1.1292 raeburn 7636: my $timesup = $first_access+$timelimit;
1.1282 raeburn 7637: if ($timesup > $now) {
7638: my $activeblock;
7639: foreach my $res (@to_test) {
1.1283 raeburn 7640: if ($res->answerable()) {
1.1282 raeburn 7641: $activeblock = 1;
7642: last;
7643: }
7644: }
7645: if ($activeblock) {
7646: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7647: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7648: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7649: }
7650: }
7651: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7652: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7653: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7654: }
1.1162 raeburn 7655: }
7656: }
7657: }
7658: }
7659: }
7660: }
7661: }
7662: }
7663: }
1.1282 raeburn 7664: return %blockers;
1.1162 raeburn 7665: }
7666:
1.1282 raeburn 7667: sub has_comm_blocking {
7668: my ($priv,$symb,$uri,$blocks) = @_;
7669: my @blockers;
7670: return unless ($env{'request.course.id'});
7671: return unless ($priv eq 'bre');
7672: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7673: return if ($env{'request.state'} eq 'construct');
7674: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7675: return unless (keys(%cachedblockers) > 0);
7676: my (%possibles,@symbs);
7677: if (!$symb) {
7678: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7679: }
1.1282 raeburn 7680: if ($symb) {
7681: @symbs = ($symb);
7682: } elsif (keys(%possibles)) {
7683: @symbs = keys(%possibles);
7684: }
7685: my $noblock;
7686: foreach my $symb (@symbs) {
7687: last if ($noblock);
7688: my ($map,$resid,$resurl)=&decode_symb($symb);
7689: foreach my $block (keys(%cachedblockers)) {
7690: if ($block =~ /^firstaccess____(.+)$/) {
7691: my $item = $1;
7692: if (($item eq $map) || ($item eq $symb)) {
7693: $noblock = 1;
7694: last;
7695: }
7696: }
7697: if (ref($cachedblockers{$block}) eq 'HASH') {
7698: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7699: if ($cachedblockers{$block}{'resources'}{$symb}) {
7700: unless (grep(/^\Q$block\E$/,@blockers)) {
7701: push(@blockers,$block);
7702: }
7703: }
7704: }
1.1162 raeburn 7705: }
1.1282 raeburn 7706: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7707: if ($cachedblockers{$block}{'maps'}{$map}) {
7708: unless (grep(/^\Q$block\E$/,@blockers)) {
7709: push(@blockers,$block);
7710: }
7711: }
1.1162 raeburn 7712: }
7713: }
7714: }
1.1282 raeburn 7715: return if ($noblock);
7716: return @blockers;
7717: }
1.1162 raeburn 7718: }
7719:
1.1282 raeburn 7720: # -------------------------------- Deversion and split uri into path an filename
7721:
1.1133 foxr 7722: #
1.1282 raeburn 7723: # Removes the version from a URI and
1.1133 foxr 7724: # splits it in to its filename and path to the filename.
7725: # Seems like File::Basename could have done this more clearly.
7726: # Parameters:
7727: # $uri - input URI
7728: # Returns:
7729: # Two element list consisting of
7730: # $pathname - the URI up to and excluding the trailing /
7731: # $filename - The part of the URI following the last /
7732: # NOTE:
7733: # Another realization of this is simply:
7734: # use File::Basename;
7735: # ...
7736: # $uri = shift;
7737: # $filename = basename($uri);
7738: # $path = dirname($uri);
7739: # return ($filename, $path);
7740: #
7741: # The implementation below is probably faster however.
7742: #
1.710 albertel 7743: sub split_uri_for_cond {
7744: my $uri=&deversion(&declutter(shift));
7745: my @uriparts=split(/\//,$uri);
7746: my $filename=pop(@uriparts);
7747: my $pathname=join('/',@uriparts);
7748: return ($pathname,$filename);
7749: }
1.232 www 7750: # --------------------------------------------------- Is a resource on the map?
7751:
7752: sub is_on_map {
1.710 albertel 7753: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7754: #Trying to find the conditional for the file
1.620 albertel 7755: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7756: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7757: if ($match) {
1.289 bowersj2 7758: return (1,$1);
7759: } else {
1.434 www 7760: return (0,0);
1.289 bowersj2 7761: }
1.12 www 7762: }
7763:
1.427 www 7764: # --------------------------------------------------------- Get symb from alias
7765:
7766: sub get_symb_from_alias {
7767: my $symb=shift;
7768: my ($map,$resid,$url)=&decode_symb($symb);
7769: # Already is a symb
7770: if ($url) { return $symb; }
7771: # Must be an alias
7772: my $aliassymb='';
7773: my %bighash;
1.620 albertel 7774: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7775: &GDBM_READER(),0640)) {
7776: my $rid=$bighash{'mapalias_'.$symb};
7777: if ($rid) {
7778: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7779: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7780: $resid,$bighash{'src_'.$rid});
1.427 www 7781: }
7782: untie %bighash;
7783: }
7784: return $aliassymb;
7785: }
7786:
1.12 www 7787: # ----------------------------------------------------------------- Define Role
7788:
7789: sub definerole {
7790: if (allowed('mcr','/')) {
1.1326 raeburn 7791: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 7792: foreach my $role (split(':',$sysrole)) {
7793: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7794: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7795: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7796: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7797: return "refused:s:$crole&$cqual";
7798: }
7799: }
1.191 harris41 7800: }
1.800 albertel 7801: foreach my $role (split(':',$domrole)) {
7802: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7803: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7804: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7805: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7806: return "refused:d:$crole&$cqual";
7807: }
7808: }
1.191 harris41 7809: }
1.800 albertel 7810: foreach my $role (split(':',$courole)) {
7811: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7812: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7813: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7814: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7815: return "refused:c:$crole&$cqual";
7816: }
7817: }
1.191 harris41 7818: }
1.1326 raeburn 7819: my $uhome;
7820: if (($uname ne '') && ($udom ne '')) {
7821: $uhome = &homeserver($uname,$udom);
7822: return $uhome if ($uhome eq 'no_host');
7823: } else {
7824: $uname = $env{'user.name'};
7825: $udom = $env{'user.domain'};
7826: $uhome = $env{'user.home'};
7827: }
1.620 albertel 7828: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326 raeburn 7829: "$udom:$uname:rolesdef_$rolename=".
1.21 www 7830: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326 raeburn 7831: return reply($command,$uhome);
1.12 www 7832: } else {
7833: return 'refused';
7834: }
1.105 harris41 7835: }
7836:
7837: # ---------------- Make a metadata query against the network of library servers
7838:
7839: sub metadata_query {
1.1237 raeburn 7840: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7841: my %rhash;
1.845 albertel 7842: my %libserv = &all_library();
1.244 matthew 7843: my @server_list = (defined($server_array) ? @$server_array
7844: : keys(%libserv) );
7845: for my $server (@server_list) {
1.1237 raeburn 7846: my $domains = '';
7847: if (ref($domains_hash) eq 'HASH') {
7848: $domains = $domains_hash->{$server};
7849: }
1.118 harris41 7850: unless ($custom or $customshow) {
1.1237 raeburn 7851: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7852: $rhash{$server}=$reply;
7853: }
7854: else {
7855: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7856: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7857: $server);
7858: $rhash{$server}=$reply;
7859: }
1.112 harris41 7860: }
1.118 harris41 7861: return \%rhash;
1.240 www 7862: }
7863:
7864: # ----------------------------------------- Send log queries and wait for reply
7865:
7866: sub log_query {
7867: my ($uname,$udom,$query,%filters)=@_;
7868: my $uhome=&homeserver($uname,$udom);
7869: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7870: my $uhost=&hostname($uhome);
1.800 albertel 7871: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7872: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7873: $uhome);
1.479 albertel 7874: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7875: return get_query_reply($queryid);
7876: }
7877:
1.818 raeburn 7878: # -------------------------- Update MySQL table for portfolio file
7879:
7880: sub update_portfolio_table {
1.821 raeburn 7881: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7882: if ($group ne '') {
7883: $file_name =~s /^\Q$group\E//;
7884: }
1.818 raeburn 7885: my $homeserver = &homeserver($uname,$udom);
7886: my $queryid=
1.821 raeburn 7887: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7888: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7889: my $reply = &get_query_reply($queryid);
7890: return $reply;
7891: }
7892:
1.899 raeburn 7893: # -------------------------- Update MySQL allusers table
7894:
7895: sub update_allusers_table {
7896: my ($uname,$udom,$names) = @_;
7897: my $homeserver = &homeserver($uname,$udom);
7898: my $queryid=
7899: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7900: 'lastname='.&escape($names->{'lastname'}).'%%'.
7901: 'firstname='.&escape($names->{'firstname'}).'%%'.
7902: 'middlename='.&escape($names->{'middlename'}).'%%'.
7903: 'generation='.&escape($names->{'generation'}).'%%'.
7904: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7905: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7906: return;
1.899 raeburn 7907: }
7908:
1.508 raeburn 7909: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7910:
7911: sub fetch_enrollment_query {
1.511 raeburn 7912: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 raeburn 7913: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 7914: my $maxtries = 1;
1.508 raeburn 7915: if ($context eq 'automated') {
7916: $homeserver = $perlvar{'lonHostID'};
1.1317 raeburn 7917: $sleep = 2;
7918: $loopmax = 100;
1.547 raeburn 7919: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7920: } else {
7921: $homeserver = &homeserver($cnum,$dom);
7922: }
1.838 albertel 7923: my $host=&hostname($homeserver);
1.506 raeburn 7924: my $cmd = '';
1.1000 raeburn 7925: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7926: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7927: }
7928: $cmd =~ s/%%$//;
7929: $cmd = &escape($cmd);
7930: my $query = 'fetchenrollment';
1.620 albertel 7931: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7932: unless ($queryid=~/^\Q$host\E\_/) {
7933: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7934: return 'error: '.$queryid;
7935: }
1.1317 raeburn 7936: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 7937: my $tries = 1;
7938: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 raeburn 7939: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 7940: $tries ++;
7941: }
1.526 raeburn 7942: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7943: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7944: } else {
1.901 albertel 7945: my @responses = split(/:/,$reply);
1.1322 raeburn 7946: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 7947: foreach my $line (@responses) {
7948: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7949: $$replyref{$key} = $value;
7950: }
7951: } else {
1.1117 foxr 7952: my $pathname = LONCAPA::tempdir();
1.800 albertel 7953: foreach my $line (@responses) {
7954: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7955: $$replyref{$key} = $value;
7956: if ($value > 0) {
1.800 albertel 7957: foreach my $item (@{$$affiliatesref{$key}}) {
7958: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7959: my $destname = $pathname.'/'.$filename;
7960: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7961: if ($xml_classlist =~ /^error/) {
7962: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7963: } else {
1.506 raeburn 7964: if ( open(FILE,">$destname") ) {
7965: print FILE &unescape($xml_classlist);
7966: close(FILE);
1.526 raeburn 7967: } else {
7968: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7969: }
7970: }
7971: }
7972: }
7973: }
7974: }
7975: return 'ok';
7976: }
7977: return 'error';
7978: }
7979:
1.242 www 7980: sub get_query_reply {
1.1317 raeburn 7981: my ($queryid,$sleep,$loopmax) = @_;;
7982: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
7983: $sleep = 0.2;
7984: }
7985: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
7986: $loopmax = 100;
7987: }
1.1117 foxr 7988: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7989: my $reply='';
1.1317 raeburn 7990: for (1..$loopmax) {
7991: sleep($sleep);
1.240 www 7992: if (-e $replyfile.'.end') {
1.448 albertel 7993: if (open(my $fh,$replyfile)) {
1.904 albertel 7994: $reply = join('',<$fh>);
7995: close($fh);
1.240 www 7996: } else { return 'error: reply_file_error'; }
1.242 www 7997: return &unescape($reply);
7998: }
1.240 www 7999: }
1.242 www 8000: return 'timeout:'.$queryid;
1.240 www 8001: }
8002:
8003: sub courselog_query {
1.241 www 8004: #
8005: # possible filters:
8006: # url: url or symb
8007: # username
8008: # domain
8009: # action: view, submit, grade
8010: # start: timestamp
8011: # end: timestamp
8012: #
1.240 www 8013: my (%filters)=@_;
1.620 albertel 8014: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 8015: if ($filters{'url'}) {
8016: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8017: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8018: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8019: }
1.620 albertel 8020: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8021: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 8022: return &log_query($cname,$cdom,'courselog',%filters);
8023: }
8024:
8025: sub userlog_query {
1.858 raeburn 8026: #
8027: # possible filters:
8028: # action: log check role
8029: # start: timestamp
8030: # end: timestamp
8031: #
1.240 www 8032: my ($uname,$udom,%filters)=@_;
8033: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 8034: }
8035:
1.506 raeburn 8036: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8037:
8038: sub auto_run {
1.508 raeburn 8039: my ($cnum,$cdom) = @_;
1.876 raeburn 8040: my $response = 0;
8041: my $settings;
8042: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8043: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8044: $settings = $domconfig{'autoenroll'};
8045: if ($settings->{'run'} eq '1') {
8046: $response = 1;
8047: }
8048: } else {
1.934 raeburn 8049: my $homeserver;
8050: if (&is_course($cdom,$cnum)) {
8051: $homeserver = &homeserver($cnum,$cdom);
8052: } else {
8053: $homeserver = &domain($cdom,'primary');
8054: }
8055: if ($homeserver ne 'no_host') {
8056: $response = &reply('autorun:'.$cdom,$homeserver);
8057: }
1.876 raeburn 8058: }
1.506 raeburn 8059: return $response;
8060: }
1.776 albertel 8061:
1.506 raeburn 8062: sub auto_get_sections {
1.508 raeburn 8063: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 8064: my $homeserver;
8065: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8066: $homeserver = &homeserver($cnum,$cdom);
8067: }
8068: if (!defined($homeserver)) {
8069: if ($cdom =~ /^$match_domain$/) {
8070: $homeserver = &domain($cdom,'primary');
8071: }
8072: }
8073: my @secs;
8074: if (defined($homeserver)) {
8075: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8076: unless ($response eq 'refused') {
8077: @secs = split(/:/,$response);
8078: }
1.506 raeburn 8079: }
8080: return @secs;
8081: }
1.776 albertel 8082:
1.506 raeburn 8083: sub auto_new_course {
1.1099 raeburn 8084: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 8085: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 8086: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 8087: return $response;
8088: }
1.776 albertel 8089:
1.506 raeburn 8090: sub auto_validate_courseID {
1.508 raeburn 8091: my ($cnum,$cdom,$inst_course_id) = @_;
8092: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 8093: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 8094: return $response;
8095: }
1.776 albertel 8096:
1.1007 raeburn 8097: sub auto_validate_instcode {
1.1020 raeburn 8098: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 8099: my ($homeserver,$response);
8100: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8101: $homeserver = &homeserver($cnum,$cdom);
8102: }
8103: if (!defined($homeserver)) {
8104: if ($cdom =~ /^$match_domain$/) {
8105: $homeserver = &domain($cdom,'primary');
8106: }
8107: }
1.1065 raeburn 8108: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8109: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 8110: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
8111: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 8112: }
8113:
1.506 raeburn 8114: sub auto_create_password {
1.873 raeburn 8115: my ($cnum,$cdom,$authparam,$udom) = @_;
8116: my ($homeserver,$response);
1.506 raeburn 8117: my $create_passwd = 0;
8118: my $authchk = '';
1.873 raeburn 8119: if ($udom =~ /^$match_domain$/) {
8120: $homeserver = &domain($udom,'primary');
8121: }
8122: if ($homeserver eq '') {
8123: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8124: $homeserver = &homeserver($cnum,$cdom);
8125: }
8126: }
8127: if ($homeserver eq '') {
8128: $authchk = 'nodomain';
1.506 raeburn 8129: } else {
1.873 raeburn 8130: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8131: if ($response eq 'refused') {
8132: $authchk = 'refused';
8133: } else {
1.901 albertel 8134: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8135: }
1.506 raeburn 8136: }
8137: return ($authparam,$create_passwd,$authchk);
8138: }
8139:
1.706 raeburn 8140: sub auto_photo_permission {
8141: my ($cnum,$cdom,$students) = @_;
8142: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8143: my ($outcome,$perm_reqd,$conditions) =
8144: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8145: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8146: return (undef,undef);
8147: }
1.706 raeburn 8148: return ($outcome,$perm_reqd,$conditions);
8149: }
8150:
8151: sub auto_checkphotos {
8152: my ($uname,$udom,$pid) = @_;
8153: my $homeserver = &homeserver($uname,$udom);
8154: my ($result,$resulttype);
8155: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8156: &escape($uname).':'.&escape($pid),
8157: $homeserver));
1.709 albertel 8158: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8159: return (undef,undef);
8160: }
1.706 raeburn 8161: if ($outcome) {
8162: ($result,$resulttype) = split(/:/,$outcome);
8163: }
8164: return ($result,$resulttype);
8165: }
8166:
8167: sub auto_photochoice {
8168: my ($cnum,$cdom) = @_;
8169: my $homeserver = &homeserver($cnum,$cdom);
8170: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8171: &escape($cdom),
8172: $homeserver)));
1.709 albertel 8173: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8174: return (undef,undef);
8175: }
1.706 raeburn 8176: return ($update,$comment);
8177: }
8178:
8179: sub auto_photoupdate {
8180: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8181: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8182: my $host=&hostname($homeserver);
1.706 raeburn 8183: my $cmd = '';
8184: my $maxtries = 1;
1.800 albertel 8185: foreach my $affiliate (keys(%{$affiliatesref})) {
8186: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8187: }
8188: $cmd =~ s/%%$//;
8189: $cmd = &escape($cmd);
8190: my $query = 'institutionalphotos';
8191: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8192: unless ($queryid=~/^\Q$host\E\_/) {
8193: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8194: return 'error: '.$queryid;
8195: }
8196: my $reply = &get_query_reply($queryid);
8197: my $tries = 1;
8198: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8199: $reply = &get_query_reply($queryid);
8200: $tries ++;
8201: }
8202: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8203: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8204: } else {
8205: my @responses = split(/:/,$reply);
8206: my $outcome = shift(@responses);
8207: foreach my $item (@responses) {
8208: my ($key,$value) = split(/=/,$item);
8209: $$photo{$key} = $value;
8210: }
8211: return $outcome;
8212: }
8213: return 'error';
8214: }
8215:
1.521 raeburn 8216: sub auto_instcode_format {
1.793 albertel 8217: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8218: $cat_order) = @_;
1.521 raeburn 8219: my $courses = '';
1.772 raeburn 8220: my @homeservers;
1.521 raeburn 8221: if ($caller eq 'global') {
1.841 albertel 8222: my %servers = &get_servers($codedom,'library');
8223: foreach my $tryserver (keys(%servers)) {
8224: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8225: push(@homeservers,$tryserver);
8226: }
1.584 raeburn 8227: }
1.1022 raeburn 8228: } elsif ($caller eq 'requests') {
8229: if ($codedom =~ /^$match_domain$/) {
8230: my $chome = &domain($codedom,'primary');
8231: unless ($chome eq 'no_host') {
8232: push(@homeservers,$chome);
8233: }
8234: }
1.521 raeburn 8235: } else {
1.772 raeburn 8236: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8237: }
1.793 albertel 8238: foreach my $code (keys(%{$instcodes})) {
8239: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8240: }
8241: chop($courses);
1.772 raeburn 8242: my $ok_response = 0;
8243: my $response;
8244: while (@homeservers > 0 && $ok_response == 0) {
8245: my $server = shift(@homeservers);
8246: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8247: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8248: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8249: split(/:/,$response);
1.772 raeburn 8250: %{$codes} = (%{$codes},&str2hash($codes_str));
8251: push(@{$codetitles},&str2array($codetitles_str));
8252: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8253: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8254: $ok_response = 1;
8255: }
8256: }
8257: if ($ok_response) {
1.521 raeburn 8258: return 'ok';
1.772 raeburn 8259: } else {
8260: return $response;
1.521 raeburn 8261: }
8262: }
8263:
1.792 raeburn 8264: sub auto_instcode_defaults {
8265: my ($domain,$returnhash,$code_order) = @_;
8266: my @homeservers;
1.841 albertel 8267:
8268: my %servers = &get_servers($domain,'library');
8269: foreach my $tryserver (keys(%servers)) {
8270: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8271: push(@homeservers,$tryserver);
8272: }
1.792 raeburn 8273: }
1.841 albertel 8274:
1.792 raeburn 8275: my $response;
1.841 albertel 8276: foreach my $server (@homeservers) {
1.792 raeburn 8277: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8278: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8279:
8280: foreach my $pair (split(/\&/,$response)) {
8281: my ($name,$value)=split(/\=/,$pair);
8282: if ($name eq 'code_order') {
8283: @{$code_order} = split(/\&/,&unescape($value));
8284: } else {
8285: $returnhash->{&unescape($name)}=&unescape($value);
8286: }
8287: }
8288: return 'ok';
1.792 raeburn 8289: }
1.841 albertel 8290:
8291: return $response;
1.1003 raeburn 8292: }
8293:
8294: sub auto_possible_instcodes {
1.1007 raeburn 8295: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8296: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8297: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8298: return;
8299: }
1.1003 raeburn 8300: my (@homeservers,$uhome);
8301: if (defined(&domain($domain,'primary'))) {
8302: $uhome=&domain($domain,'primary');
8303: push(@homeservers,&domain($domain,'primary'));
8304: } else {
8305: my %servers = &get_servers($domain,'library');
8306: foreach my $tryserver (keys(%servers)) {
8307: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8308: push(@homeservers,$tryserver);
8309: }
8310: }
8311: }
8312: my $response;
8313: foreach my $server (@homeservers) {
8314: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8315: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8316: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8317: split(':',$response);
8318: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8319: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8320: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8321: my ($name,$value)=split('=',$item);
8322: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8323: }
8324: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8325: my ($name,$value)=split('=',$item);
8326: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8327: }
8328: return 'ok';
8329: }
8330: return $response;
8331: }
1.792 raeburn 8332:
1.1010 raeburn 8333: sub auto_courserequest_checks {
8334: my ($dom) = @_;
1.1020 raeburn 8335: my ($homeserver,%validations);
8336: if ($dom =~ /^$match_domain$/) {
8337: $homeserver = &domain($dom,'primary');
8338: }
8339: unless ($homeserver eq 'no_host') {
8340: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8341: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8342: my @items = split(/&/,$response);
8343: foreach my $item (@items) {
8344: my ($key,$value) = split('=',$item);
8345: $validations{&unescape($key)} = &thaw_unescape($value);
8346: }
8347: }
8348: }
1.1010 raeburn 8349: return %validations;
8350: }
8351:
1.1020 raeburn 8352: sub auto_courserequest_validation {
1.1255 raeburn 8353: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8354: my ($homeserver,$response);
8355: if ($dom =~ /^$match_domain$/) {
8356: $homeserver = &domain($dom,'primary');
8357: }
1.1255 raeburn 8358: unless ($homeserver eq 'no_host') {
8359: my $customdata;
8360: if (ref($custominfo) eq 'HASH') {
8361: $customdata = &freeze_escape($custominfo);
8362: }
1.1020 raeburn 8363: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8364: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 8365: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8366: $customdata,$homeserver));
1.1020 raeburn 8367: }
8368: return $response;
8369: }
8370:
1.777 albertel 8371: sub auto_validate_class_sec {
1.918 raeburn 8372: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8373: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8374: my $ownerlist;
8375: if (ref($owners) eq 'ARRAY') {
8376: $ownerlist = join(',',@{$owners});
8377: } else {
8378: $ownerlist = $owners;
8379: }
1.773 raeburn 8380: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8381: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8382: return $response;
8383: }
8384:
1.1248 raeburn 8385: sub auto_crsreq_update {
8386: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 8387: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 8388: my ($homeserver,%crsreqresponse);
8389: if ($cdom =~ /^$match_domain$/) {
8390: $homeserver = &domain($cdom,'primary');
8391: }
8392: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8393: my $info;
8394: if (ref($inbound) eq 'HASH') {
8395: $info = &freeze_escape($inbound);
8396: }
8397: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8398: ':'.&escape($action).':'.&escape($ownername).':'.
8399: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 8400: &escape($title).':'.&escape($code).':'.
8401: &escape($accessstart).':'.&escape($accessend).':'.$info,
8402: $homeserver);
1.1248 raeburn 8403: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8404: my @items = split(/&/,$response);
8405: foreach my $item (@items) {
8406: my ($key,$value) = split('=',$item);
8407: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8408: }
8409: }
8410: }
8411: return \%crsreqresponse;
8412: }
8413:
1.1305 raeburn 8414: sub auto_export_grades {
1.1309 raeburn 8415: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8416: my ($homeserver,%exportresponse);
8417: if ($cdom =~ /^$match_domain$/) {
8418: $homeserver = &domain($cdom,'primary');
8419: }
8420: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8421: my $info;
8422: if (ref($inforef) eq 'HASH') {
8423: $info = &freeze_escape($inforef);
8424: }
8425: if (ref($gradesref) eq 'HASH') {
8426: my $grades = &freeze_escape($gradesref);
8427: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8428: $info.':'.$grades,$homeserver);
8429: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8430: my @items = split(/&/,$response);
8431: foreach my $item (@items) {
8432: my ($key,$value) = split('=',$item);
8433: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8434: }
8435: }
8436: }
8437: }
8438: return \%exportresponse;
1.1305 raeburn 8439: }
8440:
1.1287 raeburn 8441: sub check_instcode_cloning {
8442: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8443: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8444: return;
8445: }
8446: my $canclone;
8447: if (@{$code_order} > 0) {
8448: my $instcoderegexp ='^';
8449: my @clonecodes = split(/\&/,$cloner);
8450: foreach my $item (@{$code_order}) {
8451: if (grep(/^\Q$item\E=/,@clonecodes)) {
8452: foreach my $pair (@clonecodes) {
8453: my ($key,$val) = split(/\=/,$pair,2);
8454: $val = &unescape($val);
8455: if ($key eq $item) {
8456: $instcoderegexp .= '('.$val.')';
8457: last;
8458: }
8459: }
8460: } else {
8461: $instcoderegexp .= $codedefaults->{$item};
8462: }
8463: }
8464: $instcoderegexp .= '$';
8465: my (@from,@to);
8466: eval {
8467: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8468: (@to) = ($clonetocode =~ /$instcoderegexp/);
8469: };
8470: if ((@from > 0) && (@to > 0)) {
8471: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8472: if (!@diffs) {
8473: $canclone = 1;
8474: }
8475: }
8476: }
8477: return $canclone;
8478: }
8479:
8480: sub default_instcode_cloning {
8481: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8482: my (%codedefaults,@code_order,$canclone);
8483: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8484: %codedefaults = %{$codedefaultsref};
8485: @code_order = @{$codeorderref};
8486: } elsif ($clonedom) {
8487: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8488: }
8489: if (($domdefclone) && (@code_order)) {
8490: my @clonecodes = split(/\+/,$domdefclone);
8491: my $instcoderegexp ='^';
8492: foreach my $item (@code_order) {
8493: if (grep(/^\Q$item\E$/,@clonecodes)) {
8494: $instcoderegexp .= '('.$codedefaults{$item}.')';
8495: } else {
8496: $instcoderegexp .= $codedefaults{$item};
8497: }
8498: }
8499: $instcoderegexp .= '$';
8500: my (@from,@to);
8501: eval {
8502: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8503: (@to) = ($clonetocode =~ /$instcoderegexp/);
8504: };
8505: if ((@from > 0) && (@to > 0)) {
8506: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8507: if (!@diffs) {
8508: $canclone = 1;
8509: }
8510: }
8511: }
8512: return $canclone;
8513: }
8514:
1.679 raeburn 8515: # ------------------------------------------------------- Course Group routines
8516:
8517: sub get_coursegroups {
1.809 raeburn 8518: my ($cdom,$cnum,$group,$namespace) = @_;
8519: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8520: }
8521:
1.679 raeburn 8522: sub modify_coursegroup {
8523: my ($cdom,$cnum,$groupsettings) = @_;
8524: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8525: }
8526:
1.809 raeburn 8527: sub toggle_coursegroup_status {
8528: my ($cdom,$cnum,$group,$action) = @_;
8529: my ($from_namespace,$to_namespace);
8530: if ($action eq 'delete') {
8531: $from_namespace = 'coursegroups';
8532: $to_namespace = 'deleted_groups';
8533: } else {
8534: $from_namespace = 'deleted_groups';
8535: $to_namespace = 'coursegroups';
8536: }
8537: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8538: if (my $tmp = &error(%curr_group)) {
8539: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8540: return ('read error',$tmp);
8541: } else {
8542: my %savedsettings = %curr_group;
1.809 raeburn 8543: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8544: my $deloutcome;
8545: if ($result eq 'ok') {
1.809 raeburn 8546: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8547: } else {
8548: return ('write error',$result);
8549: }
8550: if ($deloutcome eq 'ok') {
8551: return 'ok';
8552: } else {
8553: return ('delete error',$deloutcome);
8554: }
8555: }
8556: }
8557:
1.679 raeburn 8558: sub modify_group_roles {
1.957 raeburn 8559: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8560: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8561: my $role = 'gr/'.&escape($userprivs);
8562: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8563: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8564: if ($result eq 'ok') {
8565: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8566: }
1.679 raeburn 8567: return $result;
8568: }
8569:
8570: sub modify_coursegroup_membership {
8571: my ($cdom,$cnum,$membership) = @_;
8572: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8573: return $result;
8574: }
8575:
1.682 raeburn 8576: sub get_active_groups {
8577: my ($udom,$uname,$cdom,$cnum) = @_;
8578: my $now = time;
8579: my %groups = ();
8580: foreach my $key (keys(%env)) {
1.811 albertel 8581: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8582: my ($start,$end) = split(/\./,$env{$key});
8583: if (($end!=0) && ($end<$now)) { next; }
8584: if (($start!=0) && ($start>$now)) { next; }
8585: if ($1 eq $cdom && $2 eq $cnum) {
8586: $groups{$3} = $env{$key} ;
8587: }
8588: }
8589: }
8590: return %groups;
8591: }
8592:
1.683 raeburn 8593: sub get_group_membership {
8594: my ($cdom,$cnum,$group) = @_;
8595: return(&dump('groupmembership',$cdom,$cnum,$group));
8596: }
8597:
8598: sub get_users_groups {
8599: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8600: my @usersgroups;
1.683 raeburn 8601: my $cachetime=1800;
8602:
8603: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8604: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8605: if (defined($cached)) {
1.734 albertel 8606: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8607: } else {
8608: $grouplist = '';
1.816 raeburn 8609: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8610: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8611: my $access_end = $env{'course.'.$courseid.
8612: '.default_enrollment_end_date'};
8613: my $now = time;
8614: foreach my $key (keys(%roleshash)) {
8615: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8616: my $group = $1;
8617: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8618: my $start = $2;
8619: my $end = $1;
8620: if ($start == -1) { next; } # deleted from group
8621: if (($start!=0) && ($start>$now)) { next; }
8622: if (($end!=0) && ($end<$now)) {
8623: if ($access_end && $access_end < $now) {
8624: if ($access_end - $end < 86400) {
8625: push(@usersgroups,$group);
1.733 raeburn 8626: }
8627: }
1.817 raeburn 8628: next;
1.733 raeburn 8629: }
1.817 raeburn 8630: push(@usersgroups,$group);
1.683 raeburn 8631: }
8632: }
8633: }
1.817 raeburn 8634: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8635: $grouplist = join(':',@usersgroups);
8636: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8637: }
1.733 raeburn 8638: return @usersgroups;
1.683 raeburn 8639: }
8640:
8641: sub devalidate_getgroups_cache {
8642: my ($udom,$uname,$cdom,$cnum)=@_;
8643: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8644:
1.683 raeburn 8645: my $hashid="$udom:$uname:$courseid";
8646: &devalidate_cache_new('getgroups',$hashid);
8647: }
8648:
1.12 www 8649: # ------------------------------------------------------------------ Plain Text
8650:
8651: sub plaintext {
1.988 raeburn 8652: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8653: if ($short =~ m{^cr/}) {
1.758 albertel 8654: return (split('/',$short))[-1];
8655: }
1.742 raeburn 8656: if (!defined($cid)) {
8657: $cid = $env{'request.course.id'};
8658: }
8659: my %rolenames = (
1.1008 raeburn 8660: Course => 'std',
8661: Community => 'alt1',
1.1305 raeburn 8662: Placement => 'std',
1.742 raeburn 8663: );
1.1037 raeburn 8664: if ($cid ne '') {
8665: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8666: unless ($forcedefault) {
8667: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8668: &Apache::lonlocal::mt_escape(\$roletext);
8669: return &Apache::lonlocal::mt($roletext);
8670: }
8671: }
8672: }
8673: if ((defined($type)) && (defined($rolenames{$type})) &&
8674: (defined($rolenames{$type})) &&
8675: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8676: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8677: } elsif ($cid ne '') {
8678: my $crstype = $env{'course.'.$cid.'.type'};
8679: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8680: (defined($prp{$short}{$rolenames{$crstype}}))) {
8681: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8682: }
1.742 raeburn 8683: }
1.1037 raeburn 8684: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8685: }
8686:
8687: # ----------------------------------------------------------------- Assign Role
8688:
8689: sub assignrole {
1.957 raeburn 8690: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8691: $context)=@_;
1.21 www 8692: my $mrole;
8693: if ($role =~ /^cr\//) {
1.393 www 8694: my $cwosec=$url;
1.811 albertel 8695: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8696: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8697: my $refused = 1;
8698: if ($context eq 'requestcourses') {
8699: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8700: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8701: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8702: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8703: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8704: if ($crsenv{'internal.courseowner'} eq
8705: $env{'user.name'}.':'.$env{'user.domain'}) {
8706: $refused = '';
8707: }
8708: }
8709: }
8710: }
8711: }
8712: if ($refused) {
8713: &logthis('Refused custom assignrole: '.
8714: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8715: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8716: return 'refused';
8717: }
1.104 www 8718: }
1.21 www 8719: $mrole='cr';
1.678 raeburn 8720: } elsif ($role =~ /^gr\//) {
8721: my $cwogrp=$url;
1.811 albertel 8722: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8723: unless (&allowed('mdg',$cwogrp)) {
8724: &logthis('Refused group assignrole: '.
8725: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8726: $env{'user.name'}.' at '.$env{'user.domain'});
8727: return 'refused';
8728: }
8729: $mrole='gr';
1.21 www 8730: } else {
1.82 www 8731: my $cwosec=$url;
1.811 albertel 8732: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8733: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8734: my $refused;
8735: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8736: if (!(&allowed('c'.$role,$url))) {
8737: $refused = 1;
8738: }
8739: } else {
8740: $refused = 1;
8741: }
1.947 raeburn 8742: if ($refused) {
1.1045 raeburn 8743: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8744: if (!$selfenroll && $context eq 'course') {
8745: my %crsenv;
8746: if ($role eq 'cc' || $role eq 'co') {
8747: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8748: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8749: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8750: if ($crsenv{'internal.courseowner'} eq
8751: $env{'user.name'}.':'.$env{'user.domain'}) {
8752: $refused = '';
8753: }
8754: }
8755: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8756: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8757: if ($crsenv{'internal.courseowner'} eq
8758: $env{'user.name'}.':'.$env{'user.domain'}) {
8759: $refused = '';
8760: }
8761: }
8762: }
8763: }
8764: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8765: $refused = '';
1.1017 raeburn 8766: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8767: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8768: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8769: my $wrongcc;
8770: if ($cnum =~ /^$match_community$/) {
8771: $wrongcc = 1 if ($role eq 'cc');
8772: } else {
8773: $wrongcc = 1 if ($role eq 'co');
8774: }
8775: unless ($wrongcc) {
8776: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8777: if ($crsenv{'internal.courseowner'} eq
8778: $env{'user.name'}.':'.$env{'user.domain'}) {
8779: $refused = '';
8780: }
1.1017 raeburn 8781: }
8782: }
1.1183 raeburn 8783: } elsif ($context eq 'requestauthor') {
8784: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8785: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8786: if ($env{'environment.requestauthor'} eq 'automatic') {
8787: $refused = '';
8788: } else {
8789: my %domdefaults = &get_domain_defaults($udom);
8790: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8791: my $checkbystatus;
8792: if ($env{'user.adv'}) {
8793: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8794: if ($disposition eq 'automatic') {
8795: $refused = '';
8796: } elsif ($disposition eq '') {
8797: $checkbystatus = 1;
8798: }
8799: } else {
8800: $checkbystatus = 1;
8801: }
8802: if ($checkbystatus) {
8803: if ($env{'environment.inststatus'}) {
8804: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8805: foreach my $type (@inststatuses) {
8806: if (($type ne '') &&
8807: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8808: $refused = '';
8809: }
8810: }
8811: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8812: $refused = '';
8813: }
8814: }
8815: }
8816: }
8817: }
1.1017 raeburn 8818: }
8819: if ($refused) {
1.947 raeburn 8820: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8821: ' '.$role.' '.$end.' '.$start.' by '.
8822: $env{'user.name'}.' at '.$env{'user.domain'});
8823: return 'refused';
8824: }
1.932 raeburn 8825: }
1.1131 raeburn 8826: } elsif ($role eq 'au') {
8827: if ($url ne '/'.$udom.'/') {
8828: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8829: ' to assign author role for '.$uname.':'.$udom.
8830: ' in domain: '.$url.' refused (wrong domain).');
8831: return 'refused';
8832: }
1.104 www 8833: }
1.21 www 8834: $mrole=$role;
8835: }
1.620 albertel 8836: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8837: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8838: if ($end) { $command.='_'.$end; }
1.21 www 8839: if ($start) {
8840: if ($end) {
1.81 www 8841: $command.='_'.$start;
1.21 www 8842: } else {
1.81 www 8843: $command.='_0_'.$start;
1.21 www 8844: }
8845: }
1.739 raeburn 8846: my $origstart = $start;
8847: my $origend = $end;
1.957 raeburn 8848: my $delflag;
1.357 www 8849: # actually delete
8850: if ($deleteflag) {
1.373 www 8851: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8852: # modify command to delete the role
1.620 albertel 8853: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8854: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8855: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8856: # set start and finish to negative values for userrolelog
8857: $start=-1;
8858: $end=-1;
1.957 raeburn 8859: $delflag = 1;
1.357 www 8860: }
8861: }
8862: # send command
1.349 www 8863: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8864: # log new user role if status is ok
1.349 www 8865: if ($answer eq 'ok') {
1.663 raeburn 8866: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8867: if (($role eq 'cc') || ($role eq 'in') ||
8868: ($role eq 'ep') || ($role eq 'ad') ||
8869: ($role eq 'ta') || ($role eq 'st') ||
8870: ($role=~/^cr/) || ($role eq 'gr') ||
8871: ($role eq 'co')) {
1.1200 raeburn 8872: # for course roles, perform group memberships changes triggered by role change.
8873: unless ($role =~ /^gr/) {
8874: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8875: $origstart,$selfenroll,$context);
8876: }
1.1184 raeburn 8877: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8878: $selfenroll,$context);
8879: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1327 ! raeburn 8880: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh')) {
1.1184 raeburn 8881: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8882: $context);
8883: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8884: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8885: $context);
8886: }
1.1053 raeburn 8887: if ($role eq 'cc') {
8888: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8889: }
1.349 www 8890: }
8891: return $answer;
1.169 harris41 8892: }
8893:
1.1053 raeburn 8894: sub autoupdate_coowners {
8895: my ($url,$end,$start,$uname,$udom) = @_;
8896: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8897: if (($cdom ne '') && ($cnum ne '')) {
8898: my $now = time;
8899: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8900: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8901: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8902: my $instcode = $coursehash{'internal.coursecode'};
8903: if ($instcode ne '') {
1.1056 raeburn 8904: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8905: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8906: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8907: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8908: if ($result eq 'valid') {
8909: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8910: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8911: push(@newcoowners,$coowner);
8912: }
8913: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8914: push(@newcoowners,$uname.':'.$udom);
8915: }
8916: @newcoowners = sort(@newcoowners);
8917: } else {
8918: push(@newcoowners,$uname.':'.$udom);
8919: }
8920: } else {
8921: if ($coursehash{'internal.co-owners'}) {
8922: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8923: unless ($coowner eq $uname.':'.$udom) {
8924: push(@newcoowners,$coowner);
8925: }
8926: }
8927: unless (@newcoowners > 0) {
8928: $delcoowners = 1;
8929: $coowners = '';
8930: }
8931: }
8932: }
8933: if (@newcoowners || $delcoowners) {
8934: &store_coowners($cdom,$cnum,$coursehash{'home'},
8935: $delcoowners,@newcoowners);
8936: }
8937: }
8938: }
8939: }
8940: }
8941: }
8942: }
8943:
8944: sub store_coowners {
8945: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8946: my $cid = $cdom.'_'.$cnum;
8947: my ($coowners,$delresult,$putresult);
8948: if (@newcoowners) {
8949: $coowners = join(',',@newcoowners);
8950: my %coownershash = (
8951: 'internal.co-owners' => $coowners,
8952: );
8953: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8954: if ($putresult eq 'ok') {
8955: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8956: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8957: }
8958: }
8959: }
8960: if ($delcoowners) {
8961: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8962: if ($delresult eq 'ok') {
8963: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8964: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8965: }
8966: }
8967: }
8968: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8969: my %crsinfo =
8970: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8971: if (ref($crsinfo{$cid}) eq 'HASH') {
8972: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8973: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8974: }
8975: }
8976: }
8977:
1.169 harris41 8978: # -------------------------------------------------- Modify user authentication
1.197 www 8979: # Overrides without validation
8980:
1.169 harris41 8981: sub modifyuserauth {
8982: my ($udom,$uname,$umode,$upass)=@_;
8983: my $uhome=&homeserver($uname,$udom);
1.197 www 8984: unless (&allowed('mau',$udom)) { return 'refused'; }
8985: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8986: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8987: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8988: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8989: &escape($upass),$uhome);
1.620 albertel 8990: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8991: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8992: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8993: &log($udom,,$uname,$uhome,
1.620 albertel 8994: 'Authentication changed by '.$env{'user.domain'}.', '.
8995: $env{'user.name'}.', '.$umode.
1.197 www 8996: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8997: unless ($reply eq 'ok') {
1.197 www 8998: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8999: return 'error: '.$reply;
9000: }
1.170 harris41 9001: return 'ok';
1.80 www 9002: }
9003:
1.81 www 9004: # --------------------------------------------------------------- Modify a user
1.80 www 9005:
1.81 www 9006: sub modifyuser {
1.206 matthew 9007: my ($udom, $uname, $uid,
9008: $umode, $upass, $first,
9009: $middle, $last, $gene,
1.1058 raeburn 9010: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 9011: $udom= &LONCAPA::clean_domain($udom);
9012: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 9013: my $showcandelete = 'none';
9014: if (ref($candelete) eq 'ARRAY') {
9015: if (@{$candelete} > 0) {
9016: $showcandelete = join(', ',@{$candelete});
9017: }
9018: }
1.81 www 9019: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 9020: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 9021: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 9022: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9023: ' desiredhome not specified').
1.620 albertel 9024: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9025: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 9026: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 9027: my $newuser;
9028: if ($uhome eq 'no_host') {
9029: $newuser = 1;
9030: }
1.80 www 9031: # ----------------------------------------------------------------- Create User
1.406 albertel 9032: if (($uhome eq 'no_host') &&
9033: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 9034: my $unhome='';
1.844 albertel 9035: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 9036: $unhome = $desiredhome;
1.620 albertel 9037: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9038: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 9039: } else { # load balancing routine for determining $unhome
1.81 www 9040: my $loadm=10000000;
1.841 albertel 9041: my %servers = &get_servers($udom,'library');
9042: foreach my $tryserver (keys(%servers)) {
9043: my $answer=reply('load',$tryserver);
9044: if (($answer=~/\d+/) && ($answer<$loadm)) {
9045: $loadm=$answer;
9046: $unhome=$tryserver;
9047: }
1.80 www 9048: }
9049: }
9050: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 9051: return 'error: unable to find a home server for '.$uname.
9052: ' in domain '.$udom;
1.80 www 9053: }
9054: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9055: &escape($upass),$unhome);
9056: unless ($reply eq 'ok') {
9057: return 'error: '.$reply;
9058: }
1.230 stredwic 9059: $uhome=&homeserver($uname,$udom,'true');
1.80 www 9060: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 9061: return 'error: unable verify users home machine.';
1.80 www 9062: }
1.209 matthew 9063: } # End of creation of new user
1.80 www 9064: # ---------------------------------------------------------------------- Add ID
9065: if ($uid) {
9066: $uid=~tr/A-Z/a-z/;
9067: my %uidhash=&idrget($udom,$uname);
1.196 www 9068: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
9069: && (!$forceid)) {
1.80 www 9070: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 9071: return 'error: user id "'.$uid.'" does not match '.
9072: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 9073: }
9074: } else {
1.1300 raeburn 9075: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 9076: }
9077: }
9078: # -------------------------------------------------------------- Add names, etc
1.313 matthew 9079: my @tmp=&get('environment',
1.899 raeburn 9080: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 9081: 'permanentemail','inststatus'],
1.134 albertel 9082: $udom,$uname);
1.1075 raeburn 9083: my (%names,%oldnames);
1.313 matthew 9084: if ($tmp[0] =~ m/^error:.*/) {
9085: %names=();
9086: } else {
9087: %names = @tmp;
1.1075 raeburn 9088: %oldnames = %names;
1.313 matthew 9089: }
1.388 www 9090: #
1.1058 raeburn 9091: # If name, email and/or uid are blank (e.g., because an uploaded file
9092: # of users did not contain them), do not overwrite existing values
9093: # unless field is in $candelete array ref.
9094: #
9095:
9096: my @fields = ('firstname','middlename','lastname','generation',
9097: 'permanentemail','id');
9098: my %newvalues;
9099: if (ref($candelete) eq 'ARRAY') {
9100: foreach my $field (@fields) {
9101: if (grep(/^\Q$field\E$/,@{$candelete})) {
9102: if ($field eq 'firstname') {
9103: $names{$field} = $first;
9104: } elsif ($field eq 'middlename') {
9105: $names{$field} = $middle;
9106: } elsif ($field eq 'lastname') {
9107: $names{$field} = $last;
9108: } elsif ($field eq 'generation') {
9109: $names{$field} = $gene;
9110: } elsif ($field eq 'permanentemail') {
9111: $names{$field} = $email;
9112: } elsif ($field eq 'id') {
9113: $names{$field} = $uid;
9114: }
9115: }
9116: }
9117: }
1.388 www 9118: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 9119: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 9120: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 9121: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 9122: if ($email) {
9123: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 9124: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 9125: }
1.899 raeburn 9126: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 9127: if (defined($inststatus)) {
9128: $names{'inststatus'} = '';
9129: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9130: if (ref($usertypes) eq 'HASH') {
9131: my @okstatuses;
9132: foreach my $item (split(/:/,$inststatus)) {
9133: if (defined($usertypes->{$item})) {
9134: push(@okstatuses,$item);
9135: }
9136: }
9137: if (@okstatuses) {
9138: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9139: }
9140: }
9141: }
1.1075 raeburn 9142: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 9143: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 9144: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 9145: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9146: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9147: } else {
9148: $logmsg .= ' during self creation';
9149: }
1.1075 raeburn 9150: my $changed;
9151: if ($newuser) {
9152: $changed = 1;
9153: } else {
9154: foreach my $field (@fields) {
9155: if ($names{$field} ne $oldnames{$field}) {
9156: $changed = 1;
9157: last;
9158: }
9159: }
9160: }
9161: unless ($changed) {
9162: $logmsg = 'No changes in user information needed for: '.$logmsg;
9163: &logthis($logmsg);
9164: return 'ok';
9165: }
9166: my $reply = &put('environment', \%names, $udom,$uname);
9167: if ($reply ne 'ok') {
9168: return 'error: '.$reply;
9169: }
1.1087 raeburn 9170: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9171: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9172: }
1.1075 raeburn 9173: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9174: &devalidate_cache_new('namescache',$uname.':'.$udom);
9175: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9176: &logthis($logmsg);
1.134 albertel 9177: return 'ok';
1.80 www 9178: }
9179:
1.81 www 9180: # -------------------------------------------------------------- Modify student
1.80 www 9181:
1.81 www 9182: sub modifystudent {
9183: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9184: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 9185: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 9186: if (!$cid) {
1.620 albertel 9187: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9188: return 'not_in_class';
9189: }
1.80 www 9190: }
9191: # --------------------------------------------------------------- Make the user
1.81 www 9192: my $reply=&modifyuser
1.209 matthew 9193: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9194: $desiredhome,$email,$inststatus);
1.80 www 9195: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9196: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 9197: # student's environment
1.297 matthew 9198: $uid = undef if (!$forceid);
1.455 albertel 9199: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 9200: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 9201: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 9202: return $reply;
9203: }
9204:
9205: sub modify_student_enrollment {
1.1216 raeburn 9206: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314 raeburn 9207: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 9208: my ($cdom,$cnum,$chome);
9209: if (!$cid) {
1.620 albertel 9210: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9211: return 'not_in_class';
9212: }
1.620 albertel 9213: $cdom=$env{'course.'.$cid.'.domain'};
9214: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9215: } else {
9216: ($cdom,$cnum)=split(/_/,$cid);
9217: }
1.620 albertel 9218: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9219: if (!$chome) {
1.457 raeburn 9220: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9221: }
1.455 albertel 9222: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9223: # Make sure the user exists
1.81 www 9224: my $uhome=&homeserver($uname,$udom);
9225: if (($uhome eq '') || ($uhome eq 'no_host')) {
9226: return 'error: no such user';
9227: }
1.297 matthew 9228: # Get student data if we were not given enough information
9229: if (!defined($first) || $first eq '' ||
9230: !defined($last) || $last eq '' ||
9231: !defined($uid) || $uid eq '' ||
9232: !defined($middle) || $middle eq '' ||
9233: !defined($gene) || $gene eq '') {
1.294 matthew 9234: # They did not supply us with enough data to enroll the student, so
9235: # we need to pick up more information.
1.297 matthew 9236: my %tmp = &get('environment',
1.294 matthew 9237: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9238: ,$udom,$uname);
9239:
1.800 albertel 9240: #foreach my $key (keys(%tmp)) {
9241: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9242: #}
1.294 matthew 9243: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9244: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9245: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9246: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9247: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9248: }
1.556 albertel 9249: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9250: my $user = "$uname:$udom";
9251: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9252: my $reply=cput('classlist',
1.1148 raeburn 9253: {$user =>
1.1314 raeburn 9254: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 9255: $cdom,$cnum);
1.1148 raeburn 9256: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9257: &devalidate_getsection_cache($udom,$uname,$cid);
9258: } else {
1.81 www 9259: return 'error: '.$reply;
9260: }
1.297 matthew 9261: # Add student role to user
1.83 www 9262: my $uurl='/'.$cid;
1.81 www 9263: $uurl=~s/\_/\//g;
9264: if ($usec) {
9265: $uurl.='/'.$usec;
9266: }
1.1148 raeburn 9267: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9268: $selfenroll,$context);
9269: if ($result ne 'ok') {
9270: if ($old_entry{$user} ne '') {
9271: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9272: } else {
9273: $reply = &del('classlist',[$user],$cdom,$cnum);
9274: }
9275: }
9276: return $result;
1.21 www 9277: }
9278:
1.556 albertel 9279: sub format_name {
9280: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9281: my $name;
9282: if ($first ne 'lastname') {
9283: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9284: } else {
9285: if ($lastname=~/\S/) {
9286: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9287: $name=~s/\s+,/,/;
9288: } else {
9289: $name.= $firstname.' '.$middlename.' '.$generation;
9290: }
9291: }
9292: $name=~s/^\s+//;
9293: $name=~s/\s+$//;
9294: $name=~s/\s+/ /g;
9295: return $name;
9296: }
9297:
1.84 www 9298: # ------------------------------------------------- Write to course preferences
9299:
9300: sub writecoursepref {
9301: my ($courseid,%prefs)=@_;
9302: $courseid=~s/^\///;
9303: $courseid=~s/\_/\//g;
9304: my ($cdomain,$cnum)=split(/\//,$courseid);
9305: my $chome=homeserver($cnum,$cdomain);
9306: if (($chome eq '') || ($chome eq 'no_host')) {
9307: return 'error: no such course';
9308: }
9309: my $cstring='';
1.800 albertel 9310: foreach my $pref (keys(%prefs)) {
9311: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9312: }
1.84 www 9313: $cstring=~s/\&$//;
9314: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9315: }
9316:
9317: # ---------------------------------------------------------- Make/modify course
9318:
9319: sub createcourse {
1.741 raeburn 9320: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9321: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9322: $url=&declutter($url);
9323: my $cid='';
1.1028 raeburn 9324: if ($context eq 'requestcourses') {
9325: my $can_create = 0;
9326: my ($ownername,$ownerdom) = split(':',$course_owner);
9327: if ($udom eq $ownerdom) {
9328: if (&usertools_access($ownername,$ownerdom,$category,undef,
9329: $context)) {
9330: $can_create = 1;
9331: }
9332: } else {
9333: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9334: $category);
9335: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9336: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9337: if (@curr > 0) {
9338: my @options = qw(approval validate autolimit);
9339: my $optregex = join('|',@options);
9340: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9341: $can_create = 1;
9342: }
9343: }
9344: }
9345: }
9346: if ($can_create) {
9347: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9348: unless (&allowed('ccc',$udom)) {
9349: return 'refused';
9350: }
1.1017 raeburn 9351: }
9352: } else {
9353: return 'refused';
9354: }
1.1028 raeburn 9355: } elsif (!&allowed('ccc',$udom)) {
9356: return 'refused';
1.84 www 9357: }
1.1011 raeburn 9358: # --------------------------------------------------------------- Get Unique ID
9359: my $uname;
9360: if ($cnum =~ /^$match_courseid$/) {
9361: my $chome=&homeserver($cnum,$udom,'true');
9362: if (($chome eq '') || ($chome eq 'no_host')) {
9363: $uname = $cnum;
9364: } else {
1.1038 raeburn 9365: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9366: }
9367: } else {
1.1038 raeburn 9368: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9369: }
9370: return $uname if ($uname =~ /^error/);
9371: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9372: if (!defined($course_server)) {
9373: if (defined(&domain($udom,'primary'))) {
9374: $course_server = &domain($udom,'primary');
9375: } else {
9376: $course_server = $env{'user.home'};
9377: }
9378: }
9379: my %host_servers =
9380: &Apache::lonnet::get_servers($udom,'library');
9381: unless ($host_servers{$course_server}) {
9382: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9383: }
1.84 www 9384: # ------------------------------------------------------------- Make the course
9385: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9386: $course_server);
1.84 www 9387: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9388: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9389: if (($uhome eq '') || ($uhome eq 'no_host')) {
9390: return 'error: no such course';
9391: }
1.271 www 9392: # ----------------------------------------------------------------- Course made
1.516 raeburn 9393: # log existence
1.1029 raeburn 9394: my $now = time;
1.918 raeburn 9395: my $newcourse = {
9396: $udom.'_'.$uname => {
1.921 raeburn 9397: description => $description,
9398: inst_code => $inst_code,
9399: owner => $course_owner,
9400: type => $crstype,
1.1029 raeburn 9401: creator => $env{'user.name'}.':'.
9402: $env{'user.domain'},
9403: created => $now,
9404: context => $context,
1.918 raeburn 9405: },
9406: };
1.921 raeburn 9407: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9408: # set toplevel url
1.271 www 9409: my $topurl=$url;
9410: unless ($nonstandard) {
9411: # ------------------------------------------ For standard courses, make top url
9412: my $mapurl=&clutter($url);
1.278 www 9413: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9414: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9415: <map>
9416: <resource id="1" type="start"></resource>
9417: <resource id="2" src="$mapurl"></resource>
9418: <resource id="3" type="finish"></resource>
9419: <link index="1" from="1" to="2"></link>
9420: <link index="2" from="2" to="3"></link>
9421: </map>
9422: ENDINITMAP
9423: $topurl=&declutter(
1.638 albertel 9424: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9425: );
9426: }
9427: # ----------------------------------------------------------- Write preferences
1.84 www 9428: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9429: ('description' => $description,
9430: 'url' => $topurl,
9431: 'internal.creator' => $env{'user.name'}.':'.
9432: $env{'user.domain'},
9433: 'internal.created' => $now,
9434: 'internal.creationcontext' => $context)
9435: );
1.84 www 9436: return '/'.$udom.'/'.$uname;
9437: }
9438:
1.1011 raeburn 9439: # ------------------------------------------------------------------- Create ID
9440: sub generate_coursenum {
1.1038 raeburn 9441: my ($udom,$crstype) = @_;
1.1011 raeburn 9442: my $domdesc = &domain($udom);
9443: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9444: my $first;
9445: if ($crstype eq 'Community') {
9446: $first = '0';
9447: } else {
9448: $first = int(1+rand(9));
9449: }
9450: my $uname=$first.
1.1011 raeburn 9451: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9452: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9453: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9454: # ----------------------------------------------- Make sure that does not exist
9455: my $uhome=&homeserver($uname,$udom,'true');
9456: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9457: if ($crstype eq 'Community') {
9458: $first = '0';
9459: } else {
9460: $first = int(1+rand(9));
9461: }
9462: $uname=$first.
1.1011 raeburn 9463: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9464: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9465: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9466: $uhome=&homeserver($uname,$udom,'true');
9467: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9468: return 'error: unable to generate unique course-ID';
9469: }
9470: }
9471: return $uname;
9472: }
9473:
1.813 albertel 9474: sub is_course {
1.1167 droeschl 9475: my ($cdom, $cnum) = scalar(@_) == 1 ?
9476: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9477:
9478: return unless $cdom and $cnum;
9479:
9480: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9481: '.');
9482:
1.1219 raeburn 9483: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9484: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9485: }
9486:
1.1015 raeburn 9487: sub store_userdata {
9488: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9489: my $result;
1.1016 raeburn 9490: if ($datakey ne '') {
1.1013 raeburn 9491: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9492: if ($udom eq '' || $uname eq '') {
9493: $udom = $env{'user.domain'};
9494: $uname = $env{'user.name'};
9495: }
9496: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9497: if (($uhome eq '') || ($uhome eq 'no_host')) {
9498: $result = 'error: no_host';
9499: } else {
9500: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9501: $storehash->{'host'} = $perlvar{'lonHostID'};
9502:
9503: my $namevalue='';
9504: foreach my $key (keys(%{$storehash})) {
9505: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9506: }
9507: $namevalue=~s/\&$//;
1.1224 raeburn 9508: unless ($namespace eq 'courserequests') {
9509: $datakey = &escape($datakey);
9510: }
1.1105 raeburn 9511: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9512: $namevalue,$uhome);
1.1013 raeburn 9513: }
9514: } else {
9515: $result = 'error: data to store was not a hash reference';
9516: }
9517: } else {
9518: $result= 'error: invalid requestkey';
9519: }
9520: return $result;
9521: }
9522:
1.21 www 9523: # ---------------------------------------------------------- Assign Custom Role
9524:
9525: sub assigncustomrole {
1.957 raeburn 9526: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9527: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9528: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9529: }
9530:
9531: # ----------------------------------------------------------------- Revoke Role
9532:
9533: sub revokerole {
1.957 raeburn 9534: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9535: my $now=time;
1.965 raeburn 9536: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9537: }
9538:
9539: # ---------------------------------------------------------- Revoke Custom Role
9540:
9541: sub revokecustomrole {
1.957 raeburn 9542: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9543: my $now=time;
1.357 www 9544: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9545: $deleteflag,$selfenroll,$context);
1.17 www 9546: }
9547:
1.533 banghart 9548: # ------------------------------------------------------------ Disk usage
1.535 albertel 9549: sub diskusage {
1.955 raeburn 9550: my ($udom,$uname,$directorypath,$getpropath)=@_;
9551: $directorypath =~ s/\/$//;
9552: my $listing=&reply('du2:'.&escape($directorypath).':'
9553: .&escape($getpropath).':'.&escape($uname).':'
9554: .&escape($udom),homeserver($uname,$udom));
9555: if ($listing eq 'unknown_cmd') {
9556: if ($getpropath) {
9557: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9558: }
9559: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9560: }
1.514 albertel 9561: return $listing;
1.512 banghart 9562: }
9563:
1.566 banghart 9564: sub is_locked {
1.1096 raeburn 9565: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9566: my @check;
9567: my $is_locked;
1.1093 raeburn 9568: push (@check,$file_name);
1.613 albertel 9569: my %locked = &get('file_permissions',\@check,
1.620 albertel 9570: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9571: my ($tmp)=keys(%locked);
9572: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9573:
1.566 banghart 9574: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9575: $is_locked = 'false';
9576: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9577: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9578: $is_locked = 'true';
1.1096 raeburn 9579: if (ref($which) eq 'ARRAY') {
9580: push(@{$which},$entry);
9581: } else {
9582: last;
9583: }
1.745 raeburn 9584: }
9585: }
1.566 banghart 9586: } else {
9587: $is_locked = 'false';
9588: }
1.1093 raeburn 9589: return $is_locked;
1.566 banghart 9590: }
9591:
1.759 albertel 9592: sub declutter_portfile {
9593: my ($file) = @_;
1.833 albertel 9594: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9595: return $file;
9596: }
9597:
1.559 banghart 9598: # ------------------------------------------------------------- Mark as Read Only
9599:
9600: sub mark_as_readonly {
9601: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9602: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9603: my ($tmp)=keys(%current_permissions);
9604: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9605: foreach my $file (@{$files}) {
1.759 albertel 9606: $file = &declutter_portfile($file);
1.561 banghart 9607: push(@{$current_permissions{$file}},$what);
1.559 banghart 9608: }
1.613 albertel 9609: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9610: return;
9611: }
9612:
1.572 banghart 9613: # ------------------------------------------------------------Save Selected Files
9614:
9615: sub save_selected_files {
9616: my ($user, $path, @files) = @_;
9617: my $filename = $user."savedfiles";
1.573 banghart 9618: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9619: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9620: foreach my $file (@files) {
1.620 albertel 9621: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9622: }
9623: foreach my $file (@other_files) {
1.574 banghart 9624: print (OUT $file."\n");
1.572 banghart 9625: }
1.574 banghart 9626: close (OUT);
1.572 banghart 9627: return 'ok';
9628: }
9629:
1.574 banghart 9630: sub clear_selected_files {
9631: my ($user) = @_;
9632: my $filename = $user."savedfiles";
1.1117 foxr 9633: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9634: print (OUT undef);
9635: close (OUT);
9636: return ("ok");
9637: }
9638:
1.572 banghart 9639: sub files_in_path {
9640: my ($user, $path) = @_;
9641: my $filename = $user."savedfiles";
9642: my %return_files;
1.1117 foxr 9643: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9644: while (my $line_in = <IN>) {
1.574 banghart 9645: chomp ($line_in);
9646: my @paths_and_file = split (m!/!, $line_in);
9647: my $file_part = pop (@paths_and_file);
9648: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9649: $path_part.='/';
9650: my $path_and_file = $path_part.$file_part;
9651: if ($path_part eq $path) {
9652: $return_files{$file_part}= 'selected';
9653: }
9654: }
1.574 banghart 9655: close (IN);
9656: return (\%return_files);
1.572 banghart 9657: }
9658:
9659: # called in portfolio select mode, to show files selected NOT in current directory
9660: sub files_not_in_path {
9661: my ($user, $path) = @_;
9662: my $filename = $user."savedfiles";
9663: my @return_files;
9664: my $path_part;
1.1117 foxr 9665: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9666: while (my $line = <IN>) {
1.572 banghart 9667: #ok, I know it's clunky, but I want it to work
1.800 albertel 9668: my @paths_and_file = split(m|/|, $line);
9669: my $file_part = pop(@paths_and_file);
9670: chomp($file_part);
9671: my $path_part = join('/', @paths_and_file);
1.572 banghart 9672: $path_part .= '/';
9673: my $path_and_file = $path_part.$file_part;
9674: if ($path_part ne $path) {
1.800 albertel 9675: push(@return_files, ($path_and_file));
1.572 banghart 9676: }
9677: }
1.800 albertel 9678: close(OUT);
1.574 banghart 9679: return (@return_files);
1.572 banghart 9680: }
9681:
1.1273 raeburn 9682: #------------------------------Submitted/Handedback Portfolio Files Versioning
9683:
9684: sub portfiles_versioning {
9685: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
9686: my $portfolio_root = '/userfiles/portfolio';
9687: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
9688: foreach my $file (@{$portfiles}) {
9689: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
9690: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
9691: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
9692: my $getpropath = 1;
9693: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
9694: $stu_name,$getpropath);
9695: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
9696: my $new_answer =
9697: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
9698: if ($new_answer ne 'problem getting file') {
9699: push(@{$versioned_portfiles}, $directory.$new_answer);
9700: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
9701: [$symb,$env{'request.course.id'},'graded']);
9702: }
9703: }
9704: }
9705:
9706: sub get_next_version {
9707: my ($answer_name, $answer_ext, $dir_list) = @_;
9708: my $version;
9709: if (ref($dir_list) eq 'ARRAY') {
9710: foreach my $row (@{$dir_list}) {
9711: my ($file) = split(/\&/,$row,2);
9712: my ($file_name,$file_version,$file_ext) =
9713: &file_name_version_ext($file);
9714: if (($file_name eq $answer_name) &&
9715: ($file_ext eq $answer_ext)) {
9716: # gets here if filename and extension match,
9717: # regardless of version
9718: if ($file_version ne '') {
9719: # a versioned file is found so save it for later
9720: if ($file_version > $version) {
9721: $version = $file_version;
9722: }
9723: }
9724: }
9725: }
9726: }
9727: $version ++;
9728: return($version);
9729: }
9730:
9731: sub version_selected_portfile {
9732: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
9733: my ($answer_name,$answer_ver,$answer_ext) =
9734: &file_name_version_ext($file_name);
9735: my $new_answer;
9736: $env{'form.copy'} =
9737: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
9738: if($env{'form.copy'} eq '-1') {
9739: $new_answer = 'problem getting file';
9740: } else {
9741: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
9742: my $copy_result =
9743: &finishuserfileupload($stu_name,$domain,'copy',
9744: '/portfolio'.$directory.$new_answer);
9745: }
9746: undef($env{'form.copy'});
9747: return ($new_answer);
9748: }
9749:
9750: sub file_name_version_ext {
9751: my ($file)=@_;
9752: my @file_parts = split(/\./, $file);
9753: my ($name,$version,$ext);
9754: if (@file_parts > 1) {
9755: $ext=pop(@file_parts);
9756: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
9757: $version=pop(@file_parts);
9758: }
9759: $name=join('.',@file_parts);
9760: } else {
9761: $name=join('.',@file_parts);
9762: }
9763: return($name,$version,$ext);
9764: }
9765:
1.745 raeburn 9766: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9767:
1.745 raeburn 9768: sub get_portfile_permissions {
9769: my ($domain,$user) = @_;
1.613 albertel 9770: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9771: my ($tmp)=keys(%current_permissions);
9772: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9773: return \%current_permissions;
9774: }
9775:
9776: #---------------------------------------------Get portfolio file access controls
9777:
1.749 raeburn 9778: sub get_access_controls {
1.745 raeburn 9779: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9780: my %access;
9781: my $real_file = $file;
9782: $file =~ s/\.meta$//;
1.745 raeburn 9783: if (defined($file)) {
1.749 raeburn 9784: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9785: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9786: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9787: }
9788: }
1.745 raeburn 9789: } else {
1.749 raeburn 9790: foreach my $key (keys(%{$current_permissions})) {
9791: if ($key =~ /\0accesscontrol$/) {
9792: if (defined($group)) {
9793: if ($key !~ m-^\Q$group\E/-) {
9794: next;
9795: }
9796: }
9797: my ($fullpath) = split(/\0/,$key);
9798: if (ref($$current_permissions{$key}) eq 'HASH') {
9799: foreach my $control (keys(%{$$current_permissions{$key}})) {
9800: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9801: }
9802: }
9803: }
9804: }
9805: }
9806: return %access;
9807: }
9808:
9809: sub modify_access_controls {
9810: my ($file_name,$changes,$domain,$user)=@_;
9811: my ($outcome,$deloutcome);
9812: my %store_permissions;
9813: my %new_values;
9814: my %new_control;
9815: my %translation;
9816: my @deletions = ();
9817: my $now = time;
9818: if (exists($$changes{'activate'})) {
9819: if (ref($$changes{'activate'}) eq 'HASH') {
9820: my @newitems = sort(keys(%{$$changes{'activate'}}));
9821: my $numnew = scalar(@newitems);
9822: for (my $i=0; $i<$numnew; $i++) {
9823: my $newkey = $newitems[$i];
9824: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9825: if ($newkey =~ /^\d+:/) {
9826: $newkey =~ s/^(\d+)/$newid/;
9827: $translation{$1} = $newid;
9828: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9829: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9830: $translation{$1} = $newid;
9831: }
1.749 raeburn 9832: $new_values{$file_name."\0".$newkey} =
9833: $$changes{'activate'}{$newitems[$i]};
9834: $new_control{$newkey} = $now;
9835: }
9836: }
9837: }
9838: my %todelete;
9839: my %changed_items;
9840: foreach my $action ('delete','update') {
9841: if (exists($$changes{$action})) {
9842: if (ref($$changes{$action}) eq 'HASH') {
9843: foreach my $key (keys(%{$$changes{$action}})) {
9844: my ($itemnum) = ($key =~ /^([^:]+):/);
9845: if ($action eq 'delete') {
9846: $todelete{$itemnum} = 1;
9847: } else {
9848: $changed_items{$itemnum} = $key;
9849: }
9850: }
1.745 raeburn 9851: }
9852: }
1.749 raeburn 9853: }
9854: # get lock on access controls for file.
9855: my $lockhash = {
9856: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9857: ':'.$env{'user.domain'},
9858: };
9859: my $tries = 0;
9860: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9861:
1.1288 damieng 9862: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 9863: $tries ++;
1.1289 damieng 9864: sleep(0.1);
1.749 raeburn 9865: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9866: }
9867: if ($gotlock eq 'ok') {
9868: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9869: my ($tmp)=keys(%curr_permissions);
9870: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9871: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9872: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9873: if (ref($curr_controls) eq 'HASH') {
9874: foreach my $control_item (keys(%{$curr_controls})) {
9875: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9876: if (defined($todelete{$itemnum})) {
9877: push(@deletions,$file_name."\0".$control_item);
9878: } else {
9879: if (defined($changed_items{$itemnum})) {
9880: $new_control{$changed_items{$itemnum}} = $now;
9881: push(@deletions,$file_name."\0".$control_item);
9882: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9883: } else {
9884: $new_control{$control_item} = $$curr_controls{$control_item};
9885: }
9886: }
1.745 raeburn 9887: }
9888: }
9889: }
1.970 raeburn 9890: my ($group);
9891: if (&is_course($domain,$user)) {
9892: ($group,my $file) = split(/\//,$file_name,2);
9893: }
1.749 raeburn 9894: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9895: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9896: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9897: # remove lock
9898: my @del_lock = ($file_name."\0".'locked_access_records');
9899: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9900: my $sqlresult =
1.970 raeburn 9901: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9902: $group);
1.749 raeburn 9903: } else {
9904: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9905: }
1.749 raeburn 9906: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9907: }
9908:
1.827 raeburn 9909: sub make_public_indefinitely {
1.1271 raeburn 9910: my (@requrl) = @_;
9911: return &automated_portfile_access('public',\@requrl);
9912: }
9913:
9914: sub automated_portfile_access {
9915: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 9916: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
9917: return 'invalid';
9918: }
1.1271 raeburn 9919: my %urls;
9920: if (ref($addsref) eq 'ARRAY') {
9921: foreach my $requrl (@{$addsref}) {
9922: if (&is_portfolio_url($requrl)) {
9923: unless (exists($urls{$requrl})) {
9924: $urls{$requrl} = 'add';
9925: }
9926: }
9927: }
9928: }
9929: if (ref($delsref) eq 'ARRAY') {
9930: foreach my $requrl (@{$delsref}) {
9931: if (&is_portfolio_url($requrl)) {
9932: unless (exists($urls{$requrl})) {
9933: $urls{$requrl} = 'delete';
9934: }
9935: }
9936: }
9937: }
9938: unless (keys(%urls)) {
9939: return 'invalid';
9940: }
9941: my $ip;
9942: if ($accesstype eq 'ip') {
9943: if (ref($info) eq 'HASH') {
9944: if ($info->{'ip'} ne '') {
9945: $ip = $info->{'ip'};
9946: }
9947: }
9948: if ($ip eq '') {
9949: return 'invalid';
9950: }
9951: }
9952: my $errors;
1.827 raeburn 9953: my $now = time;
1.1271 raeburn 9954: my %current_perms;
9955: foreach my $requrl (sort(keys(%urls))) {
9956: my $action;
9957: if ($urls{$requrl} eq 'add') {
9958: $action = 'activate';
9959: } else {
9960: $action = 'none';
9961: }
9962: my $aclnum = 0;
1.827 raeburn 9963: my (undef,$udom,$unum,$file_name,$group) =
9964: &parse_portfolio_url($requrl);
1.1271 raeburn 9965: unless (exists($current_perms{$unum.':'.$udom})) {
9966: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
9967: }
9968: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 9969: $group,$file_name);
9970: foreach my $key (keys(%{$access_controls{$file_name}})) {
9971: my ($num,$scope,$end,$start) =
9972: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 9973: if ($scope eq $accesstype) {
9974: if (($start <= $now) && ($end == 0)) {
9975: if ($accesstype eq 'ip') {
9976: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
9977: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
9978: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
9979: if ($urls{$requrl} eq 'add') {
9980: $action = 'none';
9981: last;
9982: } else {
9983: $action = 'delete';
9984: $aclnum = $num;
9985: last;
9986: }
9987: }
9988: }
9989: }
9990: } elsif ($accesstype eq 'public') {
9991: if ($urls{$requrl} eq 'add') {
9992: $action = 'none';
9993: last;
9994: } else {
9995: $action = 'delete';
9996: $aclnum = $num;
9997: last;
9998: }
9999: }
10000: } elsif ($accesstype eq 'public') {
1.827 raeburn 10001: $action = 'update';
10002: $aclnum = $num;
1.1271 raeburn 10003: last;
1.827 raeburn 10004: }
10005: }
10006: }
10007: if ($action eq 'none') {
1.1271 raeburn 10008: next;
1.827 raeburn 10009: } else {
10010: my %changes;
10011: my $newend = 0;
10012: my $newstart = $now;
1.1271 raeburn 10013: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 10014: $changes{$action}{$newkey} = {
1.1271 raeburn 10015: type => $accesstype,
1.827 raeburn 10016: time => {
10017: start => $newstart,
10018: end => $newend,
10019: },
10020: };
1.1271 raeburn 10021: if ($accesstype eq 'ip') {
10022: $changes{$action}{$newkey}{'ip'} = [$ip];
10023: }
1.827 raeburn 10024: my ($outcome,$deloutcome,$new_values,$translation) =
10025: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 10026: unless ($outcome eq 'ok') {
10027: $errors .= $outcome.' ';
10028: }
1.827 raeburn 10029: }
1.1271 raeburn 10030: }
10031: if ($errors) {
10032: $errors =~ s/\s$//;
10033: return $errors;
1.827 raeburn 10034: } else {
1.1271 raeburn 10035: return 'ok';
1.827 raeburn 10036: }
10037: }
10038:
1.745 raeburn 10039: #------------------------------------------------------Get Marked as Read Only
10040:
10041: sub get_marked_as_readonly {
10042: my ($domain,$user,$what,$group) = @_;
10043: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 10044: my @readonly_files;
1.629 banghart 10045: my $cmp1=$what;
10046: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10047: while (my ($file_name,$value) = each(%{$current_permissions})) {
10048: if (defined($group)) {
10049: if ($file_name !~ m-^\Q$group\E/-) {
10050: next;
10051: }
10052: }
1.561 banghart 10053: if (ref($value) eq "ARRAY"){
10054: foreach my $stored_what (@{$value}) {
1.629 banghart 10055: my $cmp2=$stored_what;
1.759 albertel 10056: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 10057: $cmp2=join('',@{$stored_what});
1.745 raeburn 10058: }
1.629 banghart 10059: if ($cmp1 eq $cmp2) {
1.561 banghart 10060: push(@readonly_files, $file_name);
1.745 raeburn 10061: last;
1.563 banghart 10062: } elsif (!defined($what)) {
10063: push(@readonly_files, $file_name);
1.745 raeburn 10064: last;
1.561 banghart 10065: }
10066: }
1.745 raeburn 10067: }
1.561 banghart 10068: }
10069: return @readonly_files;
10070: }
1.577 banghart 10071: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 10072:
1.577 banghart 10073: sub get_marked_as_readonly_hash {
1.745 raeburn 10074: my ($current_permissions,$group,$what) = @_;
1.577 banghart 10075: my %readonly_files;
1.745 raeburn 10076: while (my ($file_name,$value) = each(%{$current_permissions})) {
10077: if (defined($group)) {
10078: if ($file_name !~ m-^\Q$group\E/-) {
10079: next;
10080: }
10081: }
1.577 banghart 10082: if (ref($value) eq "ARRAY"){
10083: foreach my $stored_what (@{$value}) {
1.745 raeburn 10084: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 10085: foreach my $lock_descriptor(@{$stored_what}) {
10086: if ($lock_descriptor eq 'graded') {
10087: $readonly_files{$file_name} = 'graded';
10088: } elsif ($lock_descriptor eq 'handback') {
10089: $readonly_files{$file_name} = 'handback';
10090: } else {
10091: if (!exists($readonly_files{$file_name})) {
10092: $readonly_files{$file_name} = 'locked';
10093: }
10094: }
1.745 raeburn 10095: }
1.750 banghart 10096: }
1.577 banghart 10097: }
10098: }
10099: }
10100: return %readonly_files;
10101: }
1.559 banghart 10102: # ------------------------------------------------------------ Unmark as Read Only
10103:
10104: sub unmark_as_readonly {
1.629 banghart 10105: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10106: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 10107: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 10108: $file_name = &declutter_portfile($file_name);
1.634 albertel 10109: my $symb_crs = $what;
10110: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 10111: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 10112: my ($tmp)=keys(%current_permissions);
10113: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10114: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 10115: foreach my $file (@readonly_files) {
1.759 albertel 10116: my $clean_file = &declutter_portfile($file);
10117: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 10118: my $current_locks = $current_permissions{$file};
1.563 banghart 10119: my @new_locks;
10120: my @del_keys;
10121: if (ref($current_locks) eq "ARRAY"){
10122: foreach my $locker (@{$current_locks}) {
1.632 albertel 10123: my $compare=$locker;
1.749 raeburn 10124: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 10125: $compare=join('',@{$locker});
1.746 raeburn 10126: if ($compare ne $symb_crs) {
10127: push(@new_locks, $locker);
10128: }
1.563 banghart 10129: }
10130: }
1.650 albertel 10131: if (scalar(@new_locks) > 0) {
1.563 banghart 10132: $current_permissions{$file} = \@new_locks;
10133: } else {
10134: push(@del_keys, $file);
1.613 albertel 10135: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 10136: delete($current_permissions{$file});
1.563 banghart 10137: }
10138: }
1.561 banghart 10139: }
1.613 albertel 10140: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10141: return;
10142: }
1.512 banghart 10143:
1.17 www 10144: # ------------------------------------------------------------ Directory lister
10145:
10146: sub dirlist {
1.955 raeburn 10147: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10148: $uri=~s/^\///;
10149: $uri=~s/\/$//;
1.253 stredwic 10150: my ($udom, $uname);
1.955 raeburn 10151: if ($getuserdir) {
1.253 stredwic 10152: $udom = $userdomain;
10153: $uname = $username;
1.955 raeburn 10154: } else {
10155: (undef,$udom,$uname)=split(/\//,$uri);
10156: if(defined($userdomain)) {
10157: $udom = $userdomain;
10158: }
10159: if(defined($username)) {
10160: $uname = $username;
10161: }
1.253 stredwic 10162: }
1.955 raeburn 10163: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10164:
1.955 raeburn 10165: $dirRoot = $perlvar{'lonDocRoot'};
10166: if (defined($getpropath)) {
10167: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10168: $dirRoot =~ s/\/$//;
1.955 raeburn 10169: } elsif (defined($getuserdir)) {
10170: my $subdir=$uname.'__';
10171: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10172: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10173: ."/$udom/$subdir/$uname";
10174: } elsif (defined($alternateRoot)) {
10175: $dirRoot = $alternateRoot;
1.751 banghart 10176: }
1.253 stredwic 10177:
10178: if($udom) {
10179: if($uname) {
1.1135 raeburn 10180: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10181: if ($uhome eq 'no_host') {
10182: return ([],'no_host');
10183: }
1.955 raeburn 10184: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10185: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10186: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10187: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10188: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10189: } else {
10190: @listing_results = map { &unescape($_); } split(/:/,$listing);
10191: }
1.605 matthew 10192: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10193: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10194: @listing_results = split(/:/,$listing);
10195: } else {
10196: @listing_results = map { &unescape($_); } split(/:/,$listing);
10197: }
1.1135 raeburn 10198: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10199: ($listing eq 'rejected') || ($listing eq 'refused') ||
10200: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10201: return ([],$listing);
10202: } else {
10203: return (\@listing_results);
1.1135 raeburn 10204: }
1.955 raeburn 10205: } elsif(!$alternateRoot) {
1.1136 raeburn 10206: my (%allusers,%listerror);
1.841 albertel 10207: my %servers = &get_servers($udom,'library');
1.955 raeburn 10208: foreach my $tryserver (keys(%servers)) {
10209: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10210: &escape($udom),$tryserver);
10211: if ($listing eq 'unknown_cmd') {
10212: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10213: $udom, $tryserver);
10214: } else {
10215: @listing_results = map { &unescape($_); } split(/:/,$listing);
10216: }
1.841 albertel 10217: if ($listing eq 'unknown_cmd') {
10218: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10219: $udom, $tryserver);
10220: @listing_results = split(/:/,$listing);
10221: } else {
10222: @listing_results =
10223: map { &unescape($_); } split(/:/,$listing);
10224: }
1.1136 raeburn 10225: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10226: ($listing eq 'rejected') || ($listing eq 'refused') ||
10227: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10228: $listerror{$tryserver} = $listing;
10229: } else {
1.841 albertel 10230: foreach my $line (@listing_results) {
10231: my ($entry) = split(/&/,$line,2);
10232: $allusers{$entry} = 1;
10233: }
10234: }
1.253 stredwic 10235: }
1.1136 raeburn 10236: my @alluserslist=();
1.800 albertel 10237: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 10238: push(@alluserslist,$user.'&user');
1.253 stredwic 10239: }
1.1318 droeschl 10240:
10241: if (!%listerror) {
10242: # no errors
10243: return (\@alluserslist);
10244: } elsif (scalar(keys(%servers)) == 1) {
10245: # one library server, one error
10246: my ($key) = keys(%listerror);
10247: return (\@alluserslist, $listerror{$key});
10248: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10249: # con_lost indicates that we might miss data from at least one
10250: # library server
10251: return (\@alluserslist, 'con_lost');
10252: } else {
10253: # multiple library servers and no con_lost -> data should be
10254: # complete.
10255: return (\@alluserslist);
10256: }
10257:
1.253 stredwic 10258: } else {
1.1136 raeburn 10259: return ([],'missing username');
1.253 stredwic 10260: }
1.955 raeburn 10261: } elsif(!defined($getpropath)) {
1.1136 raeburn 10262: my $path = $perlvar{'lonDocRoot'}.'/res/';
10263: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10264: return (\@all_domains);
1.955 raeburn 10265: } else {
1.1136 raeburn 10266: return ([],'missing domain');
1.275 stredwic 10267: }
10268: }
10269:
10270: # --------------------------------------------- GetFileTimestamp
10271: # This function utilizes dirlist and returns the date stamp for
10272: # when it was last modified. It will also return an error of -1
10273: # if an error occurs
10274:
10275: sub GetFileTimestamp {
1.955 raeburn 10276: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 10277: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10278: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 10279: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10280: undef,$getuserdir);
10281: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10282: return -1;
10283: }
10284: if (ref($fileref) eq 'ARRAY') {
10285: my @stats = split('&',$fileref->[0]);
1.375 matthew 10286: # @stats contains first the filename, then the stat output
10287: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 10288: } else {
10289: return -1;
1.253 stredwic 10290: }
1.26 www 10291: }
10292:
1.712 albertel 10293: sub stat_file {
10294: my ($uri) = @_;
1.787 albertel 10295: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 10296:
1.955 raeburn 10297: my ($udom,$uname,$file);
1.712 albertel 10298: if ($uri =~ m-^/(uploaded|editupload)/-) {
10299: ($udom,$uname,$file) =
1.811 albertel 10300: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 10301: $file = 'userfiles/'.$file;
10302: }
10303: if ($uri =~ m-^/res/-) {
10304: ($udom,$uname) =
1.807 albertel 10305: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 10306: $file = $uri;
10307: }
10308:
10309: if (!$udom || !$uname || !$file) {
10310: # unable to handle the uri
10311: return ();
10312: }
1.956 raeburn 10313: my $getpropath;
10314: if ($file =~ /^userfiles\//) {
10315: $getpropath = 1;
10316: }
1.1136 raeburn 10317: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10318: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10319: return ();
10320: } else {
10321: if (ref($listref) eq 'ARRAY') {
10322: my @stats = split('&',$listref->[0]);
10323: shift(@stats); #filename is first
10324: return @stats;
10325: }
1.712 albertel 10326: }
10327: return ();
10328: }
10329:
1.1313 raeburn 10330: # --------------------------------------------------------- recursedirs
10331: # Recursive function to traverse either a specific user's Authoring Space
10332: # or corresponding Published Resource Space, and populate the hash ref:
10333: # $dirhashref with URLs of all directories, and if $filehashref hash
10334: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
10335: # or .rights files in resource space, and .meta, .save, .log, and .bak
10336: # files in Authoring Space.
10337: #
10338: # Inputs:
10339: #
10340: # $is_home - true if current server is home server for user's space
10341: # $context - either: priv, or res respectively for Authoring or Resource Space.
10342: # $docroot - Document root (i.e., /home/httpd/html
10343: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
10344: # $relpath - Current path (relative to top level).
10345: # $dirhashref - reference to hash to populate with URLs of directories (Required)
10346: # $filehashref - reference to hash to populate with URLs of files (Optional)
10347: #
10348: # Returns: nothing
10349: #
10350: # Side Effects: populates $dirhashref, and $filehashref (if provided).
10351: #
10352: # Currently used by interface/londocs.pm to create linked select boxes for
10353: # directory and filename to import a Course "Author" resource into a course, and
10354: # also to create linked select boxes for Authoring Space and Directory to choose
10355: # save location for creation of a new "standard" problem from the Course Editor.
10356: #
10357:
10358: sub recursedirs {
10359: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
10360: return unless (ref($dirhashref) eq 'HASH');
10361: my $currpath = $docroot.$toppath;
10362: if ($relpath) {
10363: $currpath .= "/$relpath";
10364: }
10365: my $savefile;
10366: if (ref($filehashref)) {
10367: $savefile = 1;
10368: }
10369: if ($is_home) {
10370: if (opendir(my $dirh,$currpath)) {
10371: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
10372: next if ($item eq '');
10373: if (-d "$currpath/$item") {
10374: my $newpath;
10375: if ($relpath) {
10376: $newpath = "$relpath/$item";
10377: } else {
10378: $newpath = $item;
10379: }
10380: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10381: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10382: } elsif ($savefile) {
10383: if ($context eq 'priv') {
10384: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10385: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10386: }
10387: } else {
10388: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
10389: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10390: }
10391: }
10392: }
10393: }
10394: closedir($dirh);
10395: }
10396: } else {
10397: my ($dirlistref,$listerror) =
10398: &dirlist($toppath.$relpath);
10399: my @dir_lines;
10400: my $dirptr=16384;
10401: if (ref($dirlistref) eq 'ARRAY') {
10402: foreach my $dir_line (sort
10403: {
10404: my ($afile)=split('&',$a,2);
10405: my ($bfile)=split('&',$b,2);
10406: return (lc($afile) cmp lc($bfile));
10407: } (@{$dirlistref})) {
10408: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
10409: split(/\&/,$dir_line,16);
10410: $item =~ s/\s+$//;
10411: next if (($item =~ /^\.\.?$/) || ($obs));
10412: if ($dirptr&$testdir) {
10413: my $newpath;
10414: if ($relpath) {
10415: $newpath = "$relpath/$item";
10416: } else {
10417: $relpath = '/';
10418: $newpath = $item;
10419: }
10420: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10421: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10422: } elsif ($savefile) {
10423: if ($context eq 'priv') {
10424: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10425: $filehashref->{$relpath}{$item} = 1;
10426: }
10427: } else {
10428: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
10429: $filehashref->{$relpath}{$item} = 1;
10430: }
10431: }
10432: }
10433: }
10434: }
10435: }
10436: return;
10437: }
10438:
1.26 www 10439: # -------------------------------------------------------- Value of a Condition
10440:
1.713 albertel 10441: # gets the value of a specific preevaluated condition
10442: # stored in the string $env{user.state.<cid>}
10443: # or looks up a condition reference in the bighash and if if hasn't
10444: # already been evaluated recurses into docondval to get the value of
10445: # the condition, then memoizing it to
10446: # $env{user.state.<cid>.<condition>}
1.40 www 10447: sub directcondval {
10448: my $number=shift;
1.620 albertel 10449: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10450: &Apache::lonuserstate::evalstate();
10451: }
1.713 albertel 10452: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10453: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10454: } elsif ($number =~ /^_/) {
10455: my $sub_condition;
10456: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10457: &GDBM_READER(),0640)) {
10458: $sub_condition=$bighash{'conditions'.$number};
10459: untie(%bighash);
10460: }
10461: my $value = &docondval($sub_condition);
1.949 raeburn 10462: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10463: return $value;
10464: }
1.620 albertel 10465: if ($env{'user.state.'.$env{'request.course.id'}}) {
10466: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10467: } else {
10468: return 2;
10469: }
10470: }
10471:
1.713 albertel 10472: # get the collection of conditions for this resource
1.26 www 10473: sub condval {
10474: my $condidx=shift;
1.54 www 10475: my $allpathcond='';
1.713 albertel 10476: foreach my $cond (split(/\|/,$condidx)) {
10477: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10478: $allpathcond.=
10479: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10480: }
1.191 harris41 10481: }
1.54 www 10482: $allpathcond=~s/\|$//;
1.713 albertel 10483: return &docondval($allpathcond);
10484: }
10485:
10486: #evaluates an expression of conditions
10487: sub docondval {
10488: my ($allpathcond) = @_;
10489: my $result=0;
10490: if ($env{'request.course.id'}
10491: && defined($allpathcond)) {
10492: my $operand='|';
10493: my @stack;
10494: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10495: if ($chunk eq '(') {
10496: push @stack,($operand,$result);
10497: } elsif ($chunk eq ')') {
10498: my $before=pop @stack;
10499: if (pop @stack eq '&') {
10500: $result=$result>$before?$before:$result;
10501: } else {
10502: $result=$result>$before?$result:$before;
10503: }
10504: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10505: $operand=$chunk;
10506: } else {
10507: my $new=directcondval($chunk);
10508: if ($operand eq '&') {
10509: $result=$result>$new?$new:$result;
10510: } else {
10511: $result=$result>$new?$result:$new;
10512: }
10513: }
10514: }
1.26 www 10515: }
10516: return $result;
1.421 albertel 10517: }
10518:
10519: # ---------------------------------------------------- Devalidate courseresdata
10520:
10521: sub devalidatecourseresdata {
10522: my ($coursenum,$coursedomain)=@_;
10523: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10524: &devalidate_cache_new('courseres',$hashid);
1.28 www 10525: }
10526:
1.763 www 10527:
1.200 www 10528: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10529: #
10530: # Parameters:
10531: # $coursenum - Number of the course.
10532: # $coursedomain - Domain at which the course was created.
10533: # Returns:
10534: # A hash of the course parameters along (I think) with timestamps
10535: # and version info.
1.877 foxr 10536:
1.624 albertel 10537: sub get_courseresdata {
10538: my ($coursenum,$coursedomain)=@_;
1.200 www 10539: my $coursehom=&homeserver($coursenum,$coursedomain);
10540: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10541: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10542: my %dumpreply;
1.417 albertel 10543: unless (defined($cached)) {
1.624 albertel 10544: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10545: $result=\%dumpreply;
1.251 albertel 10546: my ($tmp) = keys(%dumpreply);
10547: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10548: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10549: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10550: return $tmp;
1.416 albertel 10551: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10552: $result=undef;
1.599 albertel 10553: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10554: }
10555: }
1.624 albertel 10556: return $result;
10557: }
10558:
1.633 albertel 10559: sub devalidateuserresdata {
10560: my ($uname,$udom)=@_;
10561: my $hashid="$udom:$uname";
10562: &devalidate_cache_new('userres',$hashid);
10563: }
10564:
1.624 albertel 10565: sub get_userresdata {
10566: my ($uname,$udom)=@_;
10567: #most student don\'t have any data set, check if there is some data
10568: if (&EXT_cache_status($udom,$uname)) { return undef; }
10569:
10570: my $hashid="$udom:$uname";
10571: my ($result,$cached)=&is_cached_new('userres',$hashid);
10572: if (!defined($cached)) {
10573: my %resourcedata=&dump('resourcedata',$udom,$uname);
10574: $result=\%resourcedata;
10575: &do_cache_new('userres',$hashid,$result,600);
10576: }
10577: my ($tmp)=keys(%$result);
10578: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10579: return $result;
10580: }
10581: #error 2 occurs when the .db doesn't exist
10582: if ($tmp!~/error: 2 /) {
1.1294 raeburn 10583: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10584: &logthis("<font color=\"blue\">WARNING:".
10585: " Trying to get resource data for ".
10586: $uname." at ".$udom.": ".
10587: $tmp."</font>");
10588: }
1.624 albertel 10589: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10590: #&EXT_cache_set($udom,$uname);
10591: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10592: undef($tmp); # not really an error so don't send it back
1.624 albertel 10593: }
10594: return $tmp;
10595: }
1.879 foxr 10596: #----------------------------------------------- resdata - return resource data
10597: # Purpose:
10598: # Return resource data for either users or for a course.
10599: # Parameters:
10600: # $name - Course/user name.
10601: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 10602: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 10603: # $mapp - decluttered URL of enclosing map
10604: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
10605: # $recurseup - Ref to array of map URLs, starting with map containing
10606: # $mapp up through hierarchy of nested maps to top level map.
10607: # $courseid - CourseID (first part of param identifier).
10608: # $modifier - Middle part of param identifier.
10609: # $what - Last part of param identifier.
1.879 foxr 10610: # @which - Array of names of resources desired.
10611: # Returns:
10612: # The value of the first reasource in @which that is found in the
10613: # resource hash.
10614: # Exceptional Conditions:
10615: # If the $type passed in is not valid (not the string 'course' or
10616: # 'user', an undefined reference is returned.
10617: # If none of the resources are found, an undef is returned
1.624 albertel 10618: sub resdata {
1.1301 raeburn 10619: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
10620: $modifier,$what,@which)=@_;
1.624 albertel 10621: my $result;
10622: if ($type eq 'course') {
10623: $result=&get_courseresdata($name,$domain);
10624: } elsif ($type eq 'user') {
10625: $result=&get_userresdata($name,$domain);
10626: }
10627: if (!ref($result)) { return $result; }
1.251 albertel 10628: foreach my $item (@which) {
1.1301 raeburn 10629: if ($item->[1] eq 'course') {
10630: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
10631: unless ($$recursed) {
1.1302 raeburn 10632: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 10633: $$recursed = 1;
10634: }
10635: foreach my $item (@${recurseup}) {
10636: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
10637: last if (defined($result->{$norecursechk}));
10638: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
10639: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
10640: }
10641: }
10642: }
10643: if (defined($result->{$item->[0]})) {
1.927 albertel 10644: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10645: }
1.250 albertel 10646: }
1.291 albertel 10647: return undef;
1.200 www 10648: }
10649:
1.1298 raeburn 10650: sub get_domain_ltitools {
10651: my ($cdom) = @_;
10652: my %ltitools;
10653: my ($result,$cached)=&is_cached_new('ltitools',$cdom);
10654: if (defined($cached)) {
10655: if (ref($result) eq 'HASH') {
10656: %ltitools = %{$result};
10657: }
10658: } else {
10659: my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
10660: if (ref($domconfig{'ltitools'}) eq 'HASH') {
10661: %ltitools = %{$domconfig{'ltitools'}};
10662: }
10663: my $cachetime = 24*60*60;
10664: &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
10665: }
10666: return %ltitools;
10667: }
10668:
1.1236 raeburn 10669: sub get_numsuppfiles {
10670: my ($cnum,$cdom,$ignorecache)=@_;
10671: my $hashid=$cnum.':'.$cdom;
10672: my ($suppcount,$cached);
10673: unless ($ignorecache) {
10674: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10675: }
10676: unless (defined($cached)) {
10677: my $chome=&homeserver($cnum,$cdom);
10678: unless ($chome eq 'no_host') {
10679: ($suppcount,my $errors) = (0,0);
10680: my $suppmap = 'supplemental.sequence';
10681: ($suppcount,$errors) =
10682: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10683: }
10684: &do_cache_new('suppcount',$hashid,$suppcount,600);
10685: }
10686: return $suppcount;
10687: }
10688:
1.379 matthew 10689: #
10690: # EXT resource caching routines
10691: #
10692:
1.1302 raeburn 10693: {
10694: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
10695: #
10696: # The course for which we cache
10697: my $cachedmapkey='';
10698: # The cached recursive maps for this course
10699: my %cachedmaps=();
10700: # When this was last done
10701: my $cachedmaptime='';
10702:
1.379 matthew 10703: sub clear_EXT_cache_status {
1.383 albertel 10704: &delenv('cache.EXT.');
1.379 matthew 10705: }
10706:
10707: sub EXT_cache_status {
10708: my ($target_domain,$target_user) = @_;
1.383 albertel 10709: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 10710: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 10711: # We know already the user has no data
10712: return 1;
10713: } else {
10714: return 0;
10715: }
10716: }
10717:
10718: sub EXT_cache_set {
10719: my ($target_domain,$target_user) = @_;
1.383 albertel 10720: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 10721: #&appenv({$cachename => time});
1.379 matthew 10722: }
10723:
1.28 www 10724: # --------------------------------------------------------- Value of a Variable
1.58 www 10725: sub EXT {
1.715 albertel 10726:
1.1228 raeburn 10727: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 10728: unless ($varname) { return ''; }
1.218 albertel 10729: #get real user name/domain, courseid and symb
10730: my $courseid;
1.359 albertel 10731: my $publicuser;
1.427 www 10732: if ($symbparm) {
10733: $symbparm=&get_symb_from_alias($symbparm);
10734: }
1.218 albertel 10735: if (!($uname && $udom)) {
1.790 albertel 10736: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 10737: if (!$symbparm) { $symbparm=$cursymb; }
10738: } else {
1.620 albertel 10739: $courseid=$env{'request.course.id'};
1.218 albertel 10740: }
1.48 www 10741: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10742: my $rest;
1.320 albertel 10743: if (defined($therest[0])) {
1.48 www 10744: $rest=join('.',@therest);
10745: } else {
10746: $rest='';
10747: }
1.320 albertel 10748:
1.57 www 10749: my $qualifierrest=$qualifier;
10750: if ($rest) { $qualifierrest.='.'.$rest; }
10751: my $spacequalifierrest=$space;
10752: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 10753: if ($realm eq 'user') {
1.48 www 10754: # --------------------------------------------------------------- user.resource
10755: if ($space eq 'resource') {
1.651 albertel 10756: if ( (defined($Apache::lonhomework::parsing_a_problem)
10757: || defined($Apache::lonhomework::parsing_a_task))
10758: &&
1.744 albertel 10759: ($symbparm eq &symbread()) ) {
10760: # if we are in the middle of processing the resource the
10761: # get the value we are planning on committing
10762: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10763: return $Apache::lonhomework::results{$qualifierrest};
10764: } else {
10765: return $Apache::lonhomework::history{$qualifierrest};
10766: }
1.335 albertel 10767: } else {
1.359 albertel 10768: my %restored;
1.620 albertel 10769: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 10770: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10771: } else {
10772: %restored=&restore($symbparm,$courseid,$udom,$uname);
10773: }
1.335 albertel 10774: return $restored{$qualifierrest};
10775: }
1.48 www 10776: # ----------------------------------------------------------------- user.access
10777: } elsif ($space eq 'access') {
1.218 albertel 10778: # FIXME - not supporting calls for a specific user
1.48 www 10779: return &allowed($qualifier,$rest);
10780: # ------------------------------------------ user.preferences, user.environment
10781: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 10782: if (($uname eq $env{'user.name'}) &&
10783: ($udom eq $env{'user.domain'})) {
10784: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 10785: } else {
1.359 albertel 10786: my %returnhash;
10787: if (!$publicuser) {
10788: %returnhash=&userenvironment($udom,$uname,
10789: $qualifierrest);
10790: }
1.218 albertel 10791: return $returnhash{$qualifierrest};
10792: }
1.48 www 10793: # ----------------------------------------------------------------- user.course
10794: } elsif ($space eq 'course') {
1.218 albertel 10795: # FIXME - not supporting calls for a specific user
1.620 albertel 10796: return $env{join('.',('request.course',$qualifier))};
1.48 www 10797: # ------------------------------------------------------------------- user.role
10798: } elsif ($space eq 'role') {
1.218 albertel 10799: # FIXME - not supporting calls for a specific user
1.620 albertel 10800: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 10801: if ($qualifier eq 'value') {
10802: return $role;
10803: } elsif ($qualifier eq 'extent') {
10804: return $where;
10805: }
10806: # ----------------------------------------------------------------- user.domain
10807: } elsif ($space eq 'domain') {
1.218 albertel 10808: return $udom;
1.48 www 10809: # ------------------------------------------------------------------- user.name
10810: } elsif ($space eq 'name') {
1.218 albertel 10811: return $uname;
1.48 www 10812: # ---------------------------------------------------- Any other user namespace
1.29 www 10813: } else {
1.359 albertel 10814: my %reply;
10815: if (!$publicuser) {
10816: %reply=&get($space,[$qualifierrest],$udom,$uname);
10817: }
10818: return $reply{$qualifierrest};
1.48 www 10819: }
1.236 www 10820: } elsif ($realm eq 'query') {
10821: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 10822: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10823: [$spacequalifierrest]);
1.620 albertel 10824: return $env{'form.'.$spacequalifierrest};
1.236 www 10825: } elsif ($realm eq 'request') {
1.48 www 10826: # ------------------------------------------------------------- request.browser
10827: if ($space eq 'browser') {
1.1145 bisitz 10828: return $env{'browser.'.$qualifier};
1.57 www 10829: # ------------------------------------------------------------ request.filename
10830: } else {
1.620 albertel 10831: return $env{'request.'.$spacequalifierrest};
1.29 www 10832: }
1.28 www 10833: } elsif ($realm eq 'course') {
1.48 www 10834: # ---------------------------------------------------------- course.description
1.620 albertel 10835: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 10836: } elsif ($realm eq 'resource') {
1.165 www 10837:
1.620 albertel 10838: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 10839: if (!$symbparm) { $symbparm=&symbread(); }
10840: }
1.693 albertel 10841:
1.1232 raeburn 10842: if ($qualifier eq '') {
10843: if ($space eq 'title') {
10844: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10845: return &gettitle($symbparm);
10846: }
1.693 albertel 10847:
1.1232 raeburn 10848: if ($space eq 'map') {
10849: my ($map) = &decode_symb($symbparm);
10850: return &symbread($map);
10851: }
10852: if ($space eq 'maptitle') {
10853: my ($map) = &decode_symb($symbparm);
10854: return &gettitle($map);
10855: }
10856: if ($space eq 'filename') {
10857: if ($symbparm) {
10858: return &clutter((&decode_symb($symbparm))[2]);
10859: }
10860: return &hreflocation('',$env{'request.filename'});
1.905 albertel 10861: }
1.1232 raeburn 10862:
1.1233 raeburn 10863: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10864: if ($space eq 'visibleparts') {
10865: my $navmap = Apache::lonnavmaps::navmap->new();
10866: my $item;
10867: if (ref($navmap)) {
10868: my $res = $navmap->getBySymb($symbparm);
10869: my $parts = $res->parts();
10870: if (ref($parts) eq 'ARRAY') {
10871: $item = join(',',@{$parts});
10872: }
10873: undef($navmap);
1.1232 raeburn 10874: }
1.1233 raeburn 10875: return $item;
1.1232 raeburn 10876: }
10877: }
10878: }
1.693 albertel 10879:
1.1301 raeburn 10880: my ($section, $group, @groups, @recurseup, $recursed);
10881: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 10882: if (($courseid eq '') && ($cid)) {
10883: $courseid = $cid;
10884: }
10885: if (($symbparm && $courseid) &&
10886: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 10887:
1.218 albertel 10888: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 10889:
1.60 www 10890: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 10891: my $symbp=$symbparm;
1.1301 raeburn 10892: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 10893: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 10894: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 10895: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 10896: if (($env{'user.name'} eq $uname) &&
10897: ($env{'user.domain'} eq $udom)) {
10898: $section=$env{'request.course.sec'};
1.733 raeburn 10899: @groups = split(/:/,$env{'request.course.groups'});
10900: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 10901: } else {
1.539 albertel 10902: if (! defined($usection)) {
1.551 albertel 10903: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 10904: } else {
10905: $section = $usection;
10906: }
1.733 raeburn 10907: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 10908: }
10909:
10910: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10911: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 10912: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 10913: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10914:
1.593 albertel 10915: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 10916: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 10917: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 10918: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 10919:
1.60 www 10920: # ----------------------------------------------------------- first, check user
1.624 albertel 10921:
1.1301 raeburn 10922: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
10923: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 10924: ([$courselevelr,'resource'],
10925: [$courselevelm,'map' ],
1.1301 raeburn 10926: [$courseleveli,'map' ],
1.927 albertel 10927: [$courselevel, 'course' ]));
1.931 albertel 10928: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 10929:
1.594 albertel 10930: # ------------------------------------------------ second, check some of course
1.684 raeburn 10931: my $coursereply;
1.691 raeburn 10932: if (@groups > 0) {
10933: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 10934: $recurseparm,$mapparm,$spacequalifierrest,
10935: $mapp,\$recursed,\@recurseup);
10936: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 10937: }
1.96 www 10938:
1.684 raeburn 10939: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 10940: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 10941: 'course',$mapp,\$recursed,\@recurseup,
10942: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 10943: ([$seclevelr, 'resource'],
10944: [$seclevelm, 'map' ],
1.1301 raeburn 10945: [$secleveli, 'map' ],
1.927 albertel 10946: [$seclevel, 'course' ],
10947: [$courselevelr,'resource']));
10948: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10949:
1.60 www 10950: # ------------------------------------------------------ third, check map parms
1.218 albertel 10951: my %parmhash=();
10952: my $thisparm='';
10953: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10954: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10955: &GDBM_READER(),0640)) {
1.218 albertel 10956: $thisparm=$parmhash{$symbparm};
10957: untie(%parmhash);
10958: }
1.927 albertel 10959: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10960: }
1.594 albertel 10961: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 10962:
10963: my $what = $spacequalifierrest;
10964: $what=~s/\./\_/;
1.282 albertel 10965: my $filename;
10966: if (!$symbparm) { $symbparm=&symbread(); }
10967: if ($symbparm) {
1.409 www 10968: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10969: } else {
1.620 albertel 10970: $filename=$env{'request.filename'};
1.282 albertel 10971: }
1.1301 raeburn 10972: my $metadata=&metadata($filename,$what);
1.927 albertel 10973: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301 raeburn 10974: $metadata=&metadata($filename,'parameter_'.$what);
1.927 albertel 10975: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10976:
1.1301 raeburn 10977: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 10978: if ($symbparm && defined($courseid) &&
1.620 albertel 10979: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10980: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10981: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 10982: 'course',$mapp,\$recursed,\@recurseup,
10983: $courseid,'.',$spacequalifierrest,
1.927 albertel 10984: ([$courselevelm,'map' ],
1.1301 raeburn 10985: [$courseleveli,'map' ],
1.927 albertel 10986: [$courselevel, 'course']));
10987: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10988: }
1.145 www 10989: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10990: unless ($space eq '0') {
1.336 albertel 10991: my @parts=split(/_/,$space);
10992: my $id=pop(@parts);
10993: my $part=join('_',@parts);
10994: if ($part eq '') { $part='0'; }
1.927 albertel 10995: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10996: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10997: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10998: }
1.395 albertel 10999: if ($recurse) { return undef; }
11000: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 11001: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 11002: # ---------------------------------------------------- Any other user namespace
11003: } elsif ($realm eq 'environment') {
11004: # ----------------------------------------------------------------- environment
1.620 albertel 11005: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11006: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 11007: } else {
1.770 albertel 11008: if ($uname eq 'anonymous' && $udom eq '') {
11009: return '';
11010: }
1.219 albertel 11011: my %returnhash=&userenvironment($udom,$uname,
11012: $spacequalifierrest);
11013: return $returnhash{$spacequalifierrest};
11014: }
1.28 www 11015: } elsif ($realm eq 'system') {
1.48 www 11016: # ----------------------------------------------------------------- system.time
11017: if ($space eq 'time') {
11018: return time;
11019: }
1.696 albertel 11020: } elsif ($realm eq 'server') {
11021: # ----------------------------------------------------------------- system.time
11022: if ($space eq 'name') {
11023: return $ENV{'SERVER_NAME'};
11024: }
1.28 www 11025: }
1.48 www 11026: return '';
1.61 www 11027: }
11028:
1.927 albertel 11029: sub get_reply {
11030: my ($reply_value) = @_;
1.940 raeburn 11031: if (ref($reply_value) eq 'ARRAY') {
11032: if (wantarray) {
11033: return @$reply_value;
11034: }
11035: return $reply_value->[0];
11036: } else {
11037: return $reply_value;
1.927 albertel 11038: }
11039: }
11040:
1.691 raeburn 11041: sub check_group_parms {
1.1301 raeburn 11042: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11043: $recursed,$recurseupref) = @_;
11044: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11045: [$what,'course']);
11046: my $coursereply;
1.691 raeburn 11047: foreach my $group (@{$groups}) {
1.1301 raeburn 11048: my @groupitems = ();
1.691 raeburn 11049: foreach my $level (@levels) {
1.927 albertel 11050: my $item = $courseid.'.['.$group.'].'.$level->[0];
11051: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11052: }
1.1301 raeburn 11053: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11054: $env{'course.'.$courseid.'.domain'},
11055: 'course',$mapp,$recursed,$recurseupref,
11056: $courseid,'.['.$group.'].',$what,
11057: @groupitems);
11058: last if (defined($coursereply));
1.691 raeburn 11059: }
11060: return $coursereply;
11061: }
11062:
1.1301 raeburn 11063: sub get_map_hierarchy {
1.1302 raeburn 11064: my ($mapname,$courseid) = @_;
11065: my @recurseup = ();
1.1301 raeburn 11066: if ($mapname) {
1.1302 raeburn 11067: if (($cachedmapkey eq $courseid) &&
11068: (abs($cachedmaptime-time)<5)) {
11069: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11070: return @{$cachedmaps{$mapname}};
11071: }
11072: }
1.1301 raeburn 11073: my $navmap = Apache::lonnavmaps::navmap->new();
11074: if (ref($navmap)) {
11075: @recurseup = $navmap->recurseup_maps($mapname);
11076: undef($navmap);
1.1302 raeburn 11077: $cachedmaps{$mapname} = \@recurseup;
11078: $cachedmaptime=time;
11079: $cachedmapkey=$courseid;
1.1301 raeburn 11080: }
11081: }
11082: return @recurseup;
11083: }
11084:
1.1302 raeburn 11085: }
11086:
1.691 raeburn 11087: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11088: my ($courseid,@groups) = @_;
11089: @groups = sort(@groups);
1.691 raeburn 11090: return @groups;
11091: }
11092:
1.395 albertel 11093: sub packages_tab_default {
11094: my ($uri,$varname)=@_;
11095: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11096:
11097: my (@extension,@specifics,$do_default);
11098: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11099: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11100: if ($pack_type eq 'default') {
11101: $do_default=1;
11102: } elsif ($pack_type eq 'extension') {
11103: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11104: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11105: # only look at packages defaults for packages that this id is
1.738 albertel 11106: push(@specifics,[$package,$pack_type,$pack_part]);
11107: }
11108: }
11109: # first look for a package that matches the requested part id
11110: foreach my $package (@specifics) {
11111: my (undef,$pack_type,$pack_part)=@{$package};
11112: next if ($pack_part ne $part);
11113: if (defined($packagetab{"$pack_type&$name&default"})) {
11114: return $packagetab{"$pack_type&$name&default"};
11115: }
11116: }
11117: # look for any possible matching non extension_ package
11118: foreach my $package (@specifics) {
11119: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11120: if (defined($packagetab{"$pack_type&$name&default"})) {
11121: return $packagetab{"$pack_type&$name&default"};
11122: }
1.585 albertel 11123: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11124: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11125: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11126: }
11127: }
1.738 albertel 11128: # look for any posible extension_ match
11129: foreach my $package (@extension) {
11130: my ($package,$pack_type)=@{$package};
11131: if (defined($packagetab{"$pack_type&$name&default"})) {
11132: return $packagetab{"$pack_type&$name&default"};
11133: }
11134: if (defined($packagetab{$package."&$name&default"})) {
11135: return $packagetab{$package."&$name&default"};
11136: }
11137: }
11138: # look for a global default setting
11139: if ($do_default && defined($packagetab{"default&$name&default"})) {
11140: return $packagetab{"default&$name&default"};
11141: }
1.395 albertel 11142: return undef;
11143: }
11144:
1.334 albertel 11145: sub add_prefix_and_part {
11146: my ($prefix,$part)=@_;
11147: my $keyroot;
11148: if (defined($prefix) && $prefix !~ /^__/) {
11149: # prefix that has a part already
11150: $keyroot=$prefix;
11151: } elsif (defined($prefix)) {
11152: # prefix that is missing a part
11153: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11154: } else {
11155: # no prefix at all
11156: if (defined($part)) { $keyroot='_'.$part; }
11157: }
11158: return $keyroot;
11159: }
11160:
1.71 www 11161: # ---------------------------------------------------------------- Get metadata
11162:
1.599 albertel 11163: my %metaentry;
1.1070 www 11164: my %importedpartids;
1.71 www 11165: sub metadata {
1.176 www 11166: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11167: $uri=&declutter($uri);
1.288 albertel 11168: # if it is a non metadata possible uri return quickly
1.529 albertel 11169: if (($uri eq '') ||
11170: (($uri =~ m|^/*adm/|) &&
1.1298 raeburn 11171: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108 raeburn 11172: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11173: return undef;
11174: }
1.1261 raeburn 11175: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11176: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11177: return undef;
1.288 albertel 11178: }
1.73 www 11179: my $filename=$uri;
11180: $uri=~s/\.meta$//;
1.172 www 11181: #
11182: # Is the metadata already cached?
1.177 www 11183: # Look at timestamp of caching
1.172 www 11184: # Everything is cached by the main uri, libraries are never directly cached
11185: #
1.428 albertel 11186: if (!defined($liburi)) {
1.599 albertel 11187: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11188: if (defined($cached)) { return $result->{':'.$what}; }
11189: }
11190: {
1.1069 www 11191: # Imported parts would go here
1.1070 www 11192: my %importedids=();
11193: my @origfileimportpartids=();
1.1069 www 11194: my $importedparts=0;
1.172 www 11195: #
11196: # Is this a recursive call for a library?
11197: #
1.599 albertel 11198: # if (! exists($metacache{$uri})) {
11199: # $metacache{$uri}={};
11200: # }
1.924 albertel 11201: my $cachetime = 60*60;
1.171 www 11202: if ($liburi) {
11203: $liburi=&declutter($liburi);
11204: $filename=$liburi;
1.401 bowersj2 11205: } else {
1.599 albertel 11206: &devalidate_cache_new('meta',$uri);
11207: undef(%metaentry);
1.401 bowersj2 11208: }
1.140 www 11209: my %metathesekeys=();
1.73 www 11210: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 11211: my $metastring;
1.1140 www 11212: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 11213: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 11214: $metastring =
1.929 albertel 11215: &Apache::lonnet::ssi_body($which,
1.924 albertel 11216: ('grade_target' => 'meta'));
11217: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 11218: } elsif (($uri !~ m -^(editupload)/-) &&
11219: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 11220: my $file=&filelocation('',&clutter($filename));
1.599 albertel 11221: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 11222: $metastring=&getfile($file);
1.489 albertel 11223: }
1.208 albertel 11224: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 11225: my $token;
1.140 www 11226: undef %metathesekeys;
1.71 www 11227: while ($token=$parser->get_token) {
1.339 albertel 11228: if ($token->[0] eq 'S') {
11229: if (defined($token->[2]->{'package'})) {
1.172 www 11230: #
11231: # This is a package - get package info
11232: #
1.339 albertel 11233: my $package=$token->[2]->{'package'};
11234: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11235: if (defined($token->[2]->{'id'})) {
11236: $keyroot.='_'.$token->[2]->{'id'};
11237: }
1.599 albertel 11238: if ($metaentry{':packages'}) {
11239: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 11240: } else {
1.599 albertel 11241: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 11242: }
1.736 albertel 11243: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 11244: my $part=$keyroot;
11245: $part=~s/^\_//;
1.736 albertel 11246: if ($pack_entry=~/^\Q$package\E\&/ ||
11247: $pack_entry=~/^\Q$package\E_0\&/) {
11248: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11249: # ignore package.tab specified default values
11250: # here &package_tab_default() will fetch those
11251: if ($subp eq 'default') { next; }
1.736 albertel 11252: my $value=$packagetab{$pack_entry};
1.432 albertel 11253: my $unikey;
11254: if ($pack =~ /_0$/) {
11255: $unikey='parameter_0_'.$name;
11256: $part=0;
11257: } else {
11258: $unikey='parameter'.$keyroot.'_'.$name;
11259: }
1.339 albertel 11260: if ($subp eq 'display') {
11261: $value.=' [Part: '.$part.']';
11262: }
1.599 albertel 11263: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11264: $metathesekeys{$unikey}=1;
1.599 albertel 11265: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11266: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11267: }
1.599 albertel 11268: if (defined($metaentry{':'.$unikey.'.default'})) {
11269: $metaentry{':'.$unikey}=
11270: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11271: }
1.339 albertel 11272: }
11273: }
11274: } else {
1.172 www 11275: #
11276: # This is not a package - some other kind of start tag
1.339 albertel 11277: #
11278: my $entry=$token->[1];
1.1068 www 11279: my $unikey='';
1.175 www 11280:
1.339 albertel 11281: if ($entry eq 'import') {
1.175 www 11282: #
11283: # Importing a library here
1.339 albertel 11284: #
1.1067 www 11285: my $location=$parser->get_text('/import');
11286: my $dir=$filename;
11287: $dir=~s|[^/]*$||;
11288: $location=&filelocation($dir,$location);
1.1069 www 11289:
1.1068 www 11290: my $importmode=$token->[2]->{'importmode'};
11291: if ($importmode eq 'problem') {
1.1069 www 11292: # Import as problem/response
1.1068 www 11293: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11294: } elsif ($importmode eq 'part') {
11295: # Import as part(s)
1.1069 www 11296: $importedparts=1;
11297: # We need to get the original file and the imported file to get the part order correct
11298: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11299: # Load and inspect original file
1.1070 www 11300: if ($#origfileimportpartids<0) {
11301: undef(%importedpartids);
11302: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11303: my $origfile=&getfile($origfilelocation);
11304: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11305: }
11306:
1.1069 www 11307: # Load and inspect imported file
11308: my $impfile=&getfile($location);
11309: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11310: if ($#impfilepartids>=0) {
11311: # This problem had parts
1.1070 www 11312: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11313: } else {
11314: # Importing by turning a single problem into a problem part
11315: # It gets the import-tags ID as part-ID
11316: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11317: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11318: }
1.1068 www 11319: } else {
11320: # Normal import
11321: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11322: if (defined($token->[2]->{'id'})) {
11323: $unikey.='_'.$token->[2]->{'id'};
11324: }
1.1067 www 11325: }
11326:
1.339 albertel 11327: if ($depthcount<20) {
1.736 albertel 11328: my $metadata =
11329: &metadata($uri,'keys', $location,$unikey,
11330: $depthcount+1);
11331: foreach my $meta (split(',',$metadata)) {
11332: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11333: $metathesekeys{$meta}=1;
1.339 albertel 11334: }
1.1068 www 11335:
11336: }
1.1067 www 11337: } else {
11338: #
11339: # Not importing, some other kind of non-package, non-library start tag
11340: #
11341: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11342: if (defined($token->[2]->{'id'})) {
11343: $unikey.='_'.$token->[2]->{'id'};
11344: }
1.339 albertel 11345: if (defined($token->[2]->{'name'})) {
11346: $unikey.='_'.$token->[2]->{'name'};
11347: }
11348: $metathesekeys{$unikey}=1;
1.736 albertel 11349: foreach my $param (@{$token->[3]}) {
11350: $metaentry{':'.$unikey.'.'.$param} =
11351: $token->[2]->{$param};
1.339 albertel 11352: }
11353: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11354: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11355: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11356: # only ws inside the tag, and not in default, so use default
11357: # as value
1.599 albertel 11358: $metaentry{':'.$unikey}=$default;
1.908 albertel 11359: } elsif ( $internaltext =~ /\S/ ) {
11360: # something interesting inside the tag
11361: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11362: } else {
1.908 albertel 11363: # no interesting values, don't set a default
1.339 albertel 11364: }
1.172 www 11365: # end of not-a-package not-a-library import
1.339 albertel 11366: }
1.172 www 11367: # end of not-a-package start tag
1.339 albertel 11368: }
1.172 www 11369: # the next is the end of "start tag"
1.339 albertel 11370: }
11371: }
1.483 albertel 11372: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11373: $extension = lc($extension);
11374: if ($extension eq 'htm') { $extension='html'; }
11375:
1.737 albertel 11376: foreach my $key (keys(%packagetab)) {
1.483 albertel 11377: #no specific packages #how's our extension
11378: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11379: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11380: \%metathesekeys);
11381: }
1.883 albertel 11382:
11383: if (!exists($metaentry{':packages'})
11384: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11385: foreach my $key (keys(%packagetab)) {
1.483 albertel 11386: #no specific packages well let's get default then
11387: if ($key!~/^default&/) { next; }
1.488 albertel 11388: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 11389: \%metathesekeys);
11390: }
11391: }
1.338 www 11392: # are there custom rights to evaluate
1.599 albertel 11393: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 11394:
1.338 www 11395: #
11396: # Importing a rights file here
1.339 albertel 11397: #
11398: unless ($depthcount) {
1.599 albertel 11399: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 11400: my $dir=$filename;
11401: $dir=~s|[^/]*$||;
11402: $location=&filelocation($dir,$location);
1.736 albertel 11403: my $rights_metadata =
11404: &metadata($uri,'keys',$location,'_rights',
11405: $depthcount+1);
11406: foreach my $rights (split(',',$rights_metadata)) {
11407: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11408: $metathesekeys{$rights}=1;
1.339 albertel 11409: }
11410: }
11411: }
1.737 albertel 11412: # uniqifiy package listing
11413: my %seen;
11414: my @uniq_packages =
11415: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11416: $metaentry{':packages'} = join(',',@uniq_packages);
11417:
1.1070 www 11418: if ($importedparts) {
11419: # We had imported parts and need to rebuild partorder
11420: $metaentry{':partorder'}='';
11421: $metathesekeys{'partorder'}=1;
11422: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11423: if ($origfileimportpartids[$index] eq 'part') {
11424: # original part, part of the problem
11425: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11426: } else {
11427: # we have imported parts at this position
11428: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11429: }
11430: }
11431: $metaentry{':partorder'}=~s/^\,//;
11432: }
11433:
1.737 albertel 11434: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 11435: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 11436: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 11437: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 11438: # this is the end of "was not already recently cached
1.71 www 11439: }
1.599 albertel 11440: return $metaentry{':'.$what};
1.261 albertel 11441: }
11442:
1.488 albertel 11443: sub metadata_create_package_def {
1.483 albertel 11444: my ($uri,$key,$package,$metathesekeys)=@_;
11445: my ($pack,$name,$subp)=split(/\&/,$key);
11446: if ($subp eq 'default') { next; }
11447:
1.599 albertel 11448: if (defined($metaentry{':packages'})) {
11449: $metaentry{':packages'}.=','.$package;
1.483 albertel 11450: } else {
1.599 albertel 11451: $metaentry{':packages'}=$package;
1.483 albertel 11452: }
11453: my $value=$packagetab{$key};
11454: my $unikey;
11455: $unikey='parameter_0_'.$name;
1.599 albertel 11456: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 11457: $$metathesekeys{$unikey}=1;
1.599 albertel 11458: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11459: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 11460: }
1.599 albertel 11461: if (defined($metaentry{':'.$unikey.'.default'})) {
11462: $metaentry{':'.$unikey}=
11463: $metaentry{':'.$unikey.'.default'};
1.483 albertel 11464: }
11465: }
11466:
1.261 albertel 11467: sub metadata_generate_part0 {
11468: my ($metadata,$metacache,$uri) = @_;
11469: my %allnames;
1.737 albertel 11470: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 11471: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 11472: my $part=$$metacache{':'.$metakey.'.part'};
11473: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 11474: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 11475: $allnames{$name}=$part;
11476: }
11477: }
11478: }
11479: foreach my $name (keys(%allnames)) {
11480: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 11481: my $key=":parameter_0_$name";
1.261 albertel 11482: $$metacache{"$key.part"}='0';
11483: $$metacache{"$key.name"}=$name;
1.428 albertel 11484: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 11485: $allnames{$name}.'_'.$name.
11486: '.type'};
1.428 albertel 11487: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 11488: '.display'};
1.644 www 11489: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 11490: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 11491: $$metacache{"$key.display"}=$olddis;
11492: }
1.71 www 11493: }
11494:
1.764 albertel 11495: # ------------------------------------------------------ Devalidate title cache
11496:
11497: sub devalidate_title_cache {
11498: my ($url)=@_;
11499: if (!$env{'request.course.id'}) { return; }
11500: my $symb=&symbread($url);
11501: if (!$symb) { return; }
11502: my $key=$env{'request.course.id'}."\0".$symb;
11503: &devalidate_cache_new('title',$key);
11504: }
11505:
1.1014 droeschl 11506: # ------------------------------------------------- Get the title of a course
11507:
11508: sub current_course_title {
11509: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11510: }
1.301 www 11511: # ------------------------------------------------- Get the title of a resource
11512:
11513: sub gettitle {
11514: my $urlsymb=shift;
11515: my $symb=&symbread($urlsymb);
1.534 albertel 11516: if ($symb) {
1.620 albertel 11517: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 11518: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 11519: if (defined($cached)) {
11520: return $result;
11521: }
1.534 albertel 11522: my ($map,$resid,$url)=&decode_symb($symb);
11523: my $title='';
1.907 albertel 11524: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11525: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11526: } else {
11527: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11528: &GDBM_READER(),0640)) {
11529: my $mapid=$bighash{'map_pc_'.&clutter($map)};
11530: $title=$bighash{'title_'.$mapid.'.'.$resid};
11531: untie(%bighash);
11532: }
1.534 albertel 11533: }
11534: $title=~s/\&colon\;/\:/gs;
11535: if ($title) {
1.1159 www 11536: # Remember both $symb and $title for dynamic metadata
11537: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 11538: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 11539: # Cache this title and then return it
1.599 albertel 11540: return &do_cache_new('title',$key,$title,600);
1.534 albertel 11541: }
11542: $urlsymb=$url;
11543: }
11544: my $title=&metadata($urlsymb,'title');
11545: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
11546: return $title;
1.301 www 11547: }
1.613 albertel 11548:
1.614 albertel 11549: sub get_slot {
11550: my ($which,$cnum,$cdom)=@_;
11551: if (!$cnum || !$cdom) {
1.790 albertel 11552: (undef,my $courseid)=&whichuser();
1.620 albertel 11553: $cdom=$env{'course.'.$courseid.'.domain'};
11554: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11555: }
1.703 albertel 11556: my $key=join("\0",'slots',$cdom,$cnum,$which);
11557: my %slotinfo;
11558: if (exists($remembered{$key})) {
11559: $slotinfo{$which} = $remembered{$key};
11560: } else {
11561: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11562: &Apache::lonhomework::showhash(%slotinfo);
11563: my ($tmp)=keys(%slotinfo);
11564: if ($tmp=~/^error:/) { return (); }
11565: $remembered{$key} = $slotinfo{$which};
11566: }
1.616 albertel 11567: if (ref($slotinfo{$which}) eq 'HASH') {
11568: return %{$slotinfo{$which}};
11569: }
11570: return $slotinfo{$which};
1.614 albertel 11571: }
1.1150 raeburn 11572:
11573: sub get_reservable_slots {
11574: my ($cnum,$cdom,$uname,$udom) = @_;
11575: my $now = time;
11576: my $reservable_info;
11577: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11578: if (exists($remembered{$key})) {
11579: $reservable_info = $remembered{$key};
11580: } else {
11581: my %resv;
11582: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11583: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11584: $reservable_info = \%resv;
11585: $remembered{$key} = $reservable_info;
11586: }
11587: return $reservable_info;
11588: }
11589:
11590: sub get_course_slots {
11591: my ($cnum,$cdom) = @_;
11592: my $hashid=$cnum.':'.$cdom;
11593: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11594: if (defined($cached)) {
11595: if (ref($result) eq 'HASH') {
11596: return %{$result};
11597: }
11598: } else {
11599: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11600: my ($tmp) = keys(%slots);
11601: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 11602: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11603: return %slots;
11604: }
11605: }
11606: return;
11607: }
11608:
11609: sub devalidate_slots_cache {
11610: my ($cnum,$cdom)=@_;
11611: my $hashid=$cnum.':'.$cdom;
11612: &devalidate_cache_new('allslots',$hashid);
11613: }
11614:
1.1181 raeburn 11615: sub get_coursechange {
11616: my ($cdom,$cnum) = @_;
11617: if ($cdom eq '' || $cnum eq '') {
11618: return unless ($env{'request.course.id'});
11619: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11620: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11621: }
11622: my $hashid=$cdom.'_'.$cnum;
11623: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11624: if ((defined($cached)) && ($change ne '')) {
11625: return $change;
11626: } else {
11627: my %crshash;
11628: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11629: if ($crshash{'internal.contentchange'} eq '') {
11630: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11631: if ($change eq '') {
11632: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11633: $change = $crshash{'internal.created'};
11634: }
11635: } else {
11636: $change = $crshash{'internal.contentchange'};
11637: }
11638: my $cachetime = 600;
11639: &do_cache_new('crschange',$hashid,$change,$cachetime);
11640: }
11641: return $change;
11642: }
11643:
11644: sub devalidate_coursechange_cache {
11645: my ($cnum,$cdom)=@_;
11646: my $hashid=$cnum.':'.$cdom;
11647: &devalidate_cache_new('crschange',$hashid);
11648: }
11649:
1.31 www 11650: # ------------------------------------------------- Update symbolic store links
11651:
11652: sub symblist {
11653: my ($mapname,%newhash)=@_;
1.438 www 11654: $mapname=&deversion(&declutter($mapname));
1.31 www 11655: my %hash;
1.620 albertel 11656: if (($env{'request.course.fn'}) && (%newhash)) {
11657: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11658: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11659: foreach my $url (keys(%newhash)) {
1.711 albertel 11660: next if ($url eq 'last_known'
11661: && $env{'form.no_update_last_known'});
11662: $hash{declutter($url)}=&encode_symb($mapname,
11663: $newhash{$url}->[1],
11664: $newhash{$url}->[0]);
1.191 harris41 11665: }
1.31 www 11666: if (untie(%hash)) {
11667: return 'ok';
11668: }
11669: }
11670: }
11671: return 'error';
1.212 www 11672: }
11673:
11674: # --------------------------------------------------------------- Verify a symb
11675:
11676: sub symbverify {
1.1190 raeburn 11677: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11678: my $thisfn=$thisurl;
1.439 www 11679: $thisfn=&declutter($thisfn);
1.215 www 11680: # direct jump to resource in page or to a sequence - will construct own symbs
11681: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11682: # check URL part
1.409 www 11683: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11684:
1.431 www 11685: unless ($url eq $thisfn) { return 0; }
1.213 www 11686:
1.216 www 11687: $symb=&symbclean($symb);
1.510 www 11688: $thisurl=&deversion($thisurl);
1.439 www 11689: $thisfn=&deversion($thisfn);
1.213 www 11690:
11691: my %bighash;
11692: my $okay=0;
1.431 www 11693:
1.620 albertel 11694: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11695: &GDBM_READER(),0640)) {
1.1204 raeburn 11696: my $noclutter;
1.1032 raeburn 11697: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11698: $thisurl =~ s/\?.+$//;
1.1204 raeburn 11699: if ($map =~ m{^uploaded/.+\.page$}) {
11700: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11701: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11702: $noclutter = 1;
11703: }
11704: }
11705: my $ids;
11706: if ($noclutter) {
11707: $ids=$bighash{'ids_'.$thisurl};
11708: } else {
11709: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 11710: }
1.1102 raeburn 11711: unless ($ids) {
11712: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
11713: $ids=$bighash{$idkey};
1.216 www 11714: }
11715: if ($ids) {
11716: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 11717: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 11718: $symb =~ s/\?.+$//;
1.1202 raeburn 11719: }
1.800 albertel 11720: foreach my $id (split(/\,/,$ids)) {
11721: my ($mapid,$resid)=split(/\./,$id);
1.216 www 11722: if (
11723: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 11724: eq $symb) {
11725: if (ref($encstate)) {
11726: $$encstate = $bighash{'encrypted_'.$id};
11727: }
1.620 albertel 11728: if (($env{'request.role.adv'}) ||
1.1101 raeburn 11729: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
11730: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 11731: $okay=1;
1.1202 raeburn 11732: last;
1.582 albertel 11733: }
11734: }
1.216 www 11735: }
11736: }
1.213 www 11737: untie(%bighash);
11738: }
11739: return $okay;
1.31 www 11740: }
11741:
1.210 www 11742: # --------------------------------------------------------------- Clean-up symb
11743:
11744: sub symbclean {
11745: my $symb=shift;
1.568 albertel 11746: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 11747: # remove version from map
11748: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 11749:
1.210 www 11750: # remove version from URL
11751: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 11752:
1.507 www 11753: # remove wrapper
11754:
1.510 www 11755: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 11756: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 11757: return $symb;
1.409 www 11758: }
11759:
11760: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 11761:
11762: sub encode_symb {
11763: my ($map,$resid,$url)=@_;
11764: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11765: }
1.409 www 11766:
11767: sub decode_symb {
1.568 albertel 11768: my $symb=shift;
11769: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11770: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 11771: return (&fixversion($map),$resid,&fixversion($url));
11772: }
11773:
11774: sub fixversion {
11775: my $fn=shift;
1.609 banghart 11776: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 11777: my %bighash;
11778: my $uri=&clutter($fn);
1.620 albertel 11779: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 11780: # is this cached?
1.599 albertel 11781: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 11782: if (defined($cached)) { return $result; }
11783: # unfortunately not cached, or expired
1.620 albertel 11784: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 11785: &GDBM_READER(),0640)) {
11786: if ($bighash{'version_'.$uri}) {
11787: my $version=$bighash{'version_'.$uri};
1.444 www 11788: unless (($version eq 'mostrecent') ||
11789: ($version==&getversion($uri))) {
1.440 www 11790: $uri=~s/\.(\w+)$/\.$version\.$1/;
11791: }
11792: }
11793: untie %bighash;
1.413 www 11794: }
1.599 albertel 11795: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 11796: }
11797:
11798: sub deversion {
11799: my $url=shift;
11800: $url=~s/\.\d+\.(\w+)$/\.$1/;
11801: return $url;
1.210 www 11802: }
11803:
1.31 www 11804: # ------------------------------------------------------ Return symb list entry
11805:
11806: sub symbread {
1.1282 raeburn 11807: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265 raeburn 11808: my $cache_str='request.symbread.cached.'.$thisfn;
1.1282 raeburn 11809: if (defined($env{$cache_str})) {
11810: if ($ignorecachednull) {
11811: return $env{$cache_str} unless ($env{$cache_str} eq '');
11812: } else {
11813: return $env{$cache_str};
11814: }
11815: }
1.242 www 11816: # no filename provided? try from environment
1.1265 raeburn 11817: unless ($thisfn) {
1.620 albertel 11818: if ($env{'request.symb'}) {
11819: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 11820: }
1.620 albertel 11821: $thisfn=$env{'request.filename'};
1.44 www 11822: }
1.569 albertel 11823: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 11824: # is that filename actually a symb? Verify, clean, and return
11825: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 11826: if (&symbverify($thisfn,$1)) {
1.620 albertel 11827: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 11828: }
1.242 www 11829: }
1.44 www 11830: $thisfn=declutter($thisfn);
1.31 www 11831: my %hash;
1.37 www 11832: my %bighash;
11833: my $syval='';
1.620 albertel 11834: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 11835: my $targetfn = $thisfn;
1.609 banghart 11836: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 11837: $targetfn = 'adm/wrapper/'.$thisfn;
11838: }
1.687 albertel 11839: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11840: $targetfn=$1;
11841: }
1.620 albertel 11842: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11843: &GDBM_READER(),0640)) {
1.481 raeburn 11844: $syval=$hash{$targetfn};
1.37 www 11845: untie(%hash);
11846: }
11847: # ---------------------------------------------------------- There was an entry
11848: if ($syval) {
1.601 albertel 11849: #unless ($syval=~/\_\d+$/) {
1.620 albertel 11850: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 11851: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11852: #return $env{$cache_str}='';
1.601 albertel 11853: #}
11854: #$syval.=$1;
11855: #}
1.37 www 11856: } else {
11857: # ------------------------------------------------------- Was not in symb table
1.620 albertel 11858: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11859: &GDBM_READER(),0640)) {
1.37 www 11860: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 11861: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 11862: unless ($ids) {
11863: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 11864: }
11865: unless ($ids) {
11866: # alias?
11867: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 11868: }
1.37 www 11869: if ($ids) {
11870: # ------------------------------------------------------------------- Has ID(s)
11871: my @possibilities=split(/\,/,$ids);
1.39 www 11872: if ($#possibilities==0) {
11873: # ----------------------------------------------- There is only one possibility
1.37 www 11874: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 11875: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11876: $resid,$thisfn);
1.1282 raeburn 11877: if (ref($possibles) eq 'HASH') {
11878: $possibles->{$syval} = 1;
11879: }
11880: if ($checkforblock) {
11881: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11882: if (@blockers) {
11883: $syval = '';
11884: return;
11885: }
11886: }
11887: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 11888: # ------------------------------------------ There is more than one possibility
11889: my $realpossible=0;
1.800 albertel 11890: foreach my $id (@possibilities) {
11891: my $file=$bighash{'src_'.$id};
1.1282 raeburn 11892: my $canaccess;
11893: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11894: $canaccess = 1;
11895: } else {
11896: $canaccess = &allowed('bre',$file);
11897: }
11898: if ($canaccess) {
11899: my ($mapid,$resid)=split(/\./,$id);
11900: if ($bighash{'map_type_'.$mapid} ne 'page') {
11901: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11902: $resid,$thisfn);
11903: if (ref($possibles) eq 'HASH') {
11904: $possibles->{$syval} = 1;
11905: }
11906: if ($checkforblock) {
11907: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11908: unless (@blockers > 0) {
11909: $syval = $poss_syval;
11910: $realpossible++;
11911: }
11912: } else {
11913: $syval = $poss_syval;
11914: $realpossible++;
11915: }
11916: }
1.39 www 11917: }
1.191 harris41 11918: }
1.39 www 11919: if ($realpossible!=1) { $syval=''; }
1.249 www 11920: } else {
11921: $syval='';
1.37 www 11922: }
11923: }
1.1282 raeburn 11924: untie(%bighash);
1.481 raeburn 11925: }
1.31 www 11926: }
1.62 www 11927: if ($syval) {
1.620 albertel 11928: return $env{$cache_str}=$syval;
1.62 www 11929: }
1.31 www 11930: }
1.949 raeburn 11931: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 11932: return $env{$cache_str}='';
1.31 www 11933: }
11934:
11935: # ---------------------------------------------------------- Return random seed
11936:
1.32 www 11937: sub numval {
11938: my $txt=shift;
11939: $txt=~tr/A-J/0-9/;
11940: $txt=~tr/a-j/0-9/;
11941: $txt=~tr/K-T/0-9/;
11942: $txt=~tr/k-t/0-9/;
11943: $txt=~tr/U-Z/0-5/;
11944: $txt=~tr/u-z/0-5/;
11945: $txt=~s/\D//g;
1.564 albertel 11946: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 11947: return int($txt);
1.368 albertel 11948: }
11949:
1.484 albertel 11950: sub numval2 {
11951: my $txt=shift;
11952: $txt=~tr/A-J/0-9/;
11953: $txt=~tr/a-j/0-9/;
11954: $txt=~tr/K-T/0-9/;
11955: $txt=~tr/k-t/0-9/;
11956: $txt=~tr/U-Z/0-5/;
11957: $txt=~tr/u-z/0-5/;
11958: $txt=~s/\D//g;
11959: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11960: my $total;
11961: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 11962: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 11963: return int($total);
11964: }
11965:
1.575 albertel 11966: sub numval3 {
11967: use integer;
11968: my $txt=shift;
11969: $txt=~tr/A-J/0-9/;
11970: $txt=~tr/a-j/0-9/;
11971: $txt=~tr/K-T/0-9/;
11972: $txt=~tr/k-t/0-9/;
11973: $txt=~tr/U-Z/0-5/;
11974: $txt=~tr/u-z/0-5/;
11975: $txt=~s/\D//g;
11976: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11977: my $total;
11978: foreach my $val (@txts) { $total+=$val; }
11979: if ($_64bit) { $total=(($total<<32)>>32); }
11980: return $total;
11981: }
11982:
1.675 albertel 11983: sub digest {
11984: my ($data)=@_;
11985: my $digest=&Digest::MD5::md5($data);
11986: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11987: my ($e,$f);
11988: {
11989: use integer;
11990: $e=($a+$b);
11991: $f=($c+$d);
11992: if ($_64bit) {
11993: $e=(($e<<32)>>32);
11994: $f=(($f<<32)>>32);
11995: }
11996: }
11997: if (wantarray) {
11998: return ($e,$f);
11999: } else {
12000: my $g;
12001: {
12002: use integer;
12003: $g=($e+$f);
12004: if ($_64bit) {
12005: $g=(($g<<32)>>32);
12006: }
12007: }
12008: return $g;
12009: }
12010: }
12011:
1.368 albertel 12012: sub latest_rnd_algorithm_id {
1.675 albertel 12013: return '64bit5';
1.366 albertel 12014: }
1.32 www 12015:
1.503 albertel 12016: sub get_rand_alg {
12017: my ($courseid)=@_;
1.790 albertel 12018: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12019: if ($courseid) {
1.620 albertel 12020: return $env{"course.$courseid.rndseed"};
1.503 albertel 12021: }
12022: return &latest_rnd_algorithm_id();
12023: }
12024:
1.562 albertel 12025: sub validCODE {
12026: my ($CODE)=@_;
12027: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12028: return 0;
12029: }
12030:
1.491 albertel 12031: sub getCODE {
1.620 albertel 12032: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12033: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12034: defined($Apache::lonhomework::parsing_a_task) ) &&
12035: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12036: return $Apache::lonhomework::history{'resource.CODE'};
12037: }
12038: return undef;
12039: }
1.1133 foxr 12040: #
12041: # Determines the random seed for a specific context:
12042: #
12043: # parameters:
12044: # symb - in course context the symb for the seed.
12045: # course_id - The course id of the form domain_coursenum.
12046: # domain - Domain for the user.
12047: # course - Course for the user.
12048: # cenv - environment of the course.
12049: #
12050: # NOTE:
12051: # All parameters are picked out of the environment if missing
12052: # or not defined.
12053: # If a symb cannot be determined the current time is used instead.
12054: #
12055: # For a given well defined symb, courside, domain, username,
12056: # and course environment, the seed is reproducible.
12057: #
1.31 www 12058: sub rndseed {
1.1133 foxr 12059: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12060: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12061: if (!defined($symb)) {
1.366 albertel 12062: unless ($symb=$wsymb) { return time; }
12063: }
1.1146 foxr 12064: if (!defined $courseid) {
12065: $courseid=$wcourseid;
12066: }
12067: if (!defined $domain) { $domain=$wdomain; }
12068: if (!defined $username) { $username=$wusername }
1.1133 foxr 12069:
12070: my $which;
12071: if (defined($cenv->{'rndseed'})) {
12072: $which = $cenv->{'rndseed'};
12073: } else {
12074: $which =&get_rand_alg($courseid);
12075: }
1.491 albertel 12076: if (defined(&getCODE())) {
1.1133 foxr 12077:
1.675 albertel 12078: if ($which eq '64bit5') {
12079: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12080: } elsif ($which eq '64bit4') {
1.575 albertel 12081: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12082: } else {
12083: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12084: }
1.675 albertel 12085: } elsif ($which eq '64bit5') {
12086: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12087: } elsif ($which eq '64bit4') {
12088: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12089: } elsif ($which eq '64bit3') {
12090: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12091: } elsif ($which eq '64bit2') {
12092: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12093: } elsif ($which eq '64bit') {
12094: return &rndseed_64bit($symb,$courseid,$domain,$username);
12095: }
12096: return &rndseed_32bit($symb,$courseid,$domain,$username);
12097: }
12098:
12099: sub rndseed_32bit {
12100: my ($symb,$courseid,$domain,$username)=@_;
12101: {
12102: use integer;
12103: my $symbchck=unpack("%32C*",$symb) << 27;
12104: my $symbseed=numval($symb) << 22;
12105: my $namechck=unpack("%32C*",$username) << 17;
12106: my $nameseed=numval($username) << 12;
12107: my $domainseed=unpack("%32C*",$domain) << 7;
12108: my $courseseed=unpack("%32C*",$courseid);
12109: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12110: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12111: #&logthis("rndseed :$num:$symb");
1.564 albertel 12112: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 12113: return $num;
12114: }
12115: }
12116:
12117: sub rndseed_64bit {
12118: my ($symb,$courseid,$domain,$username)=@_;
12119: {
12120: use integer;
12121: my $symbchck=unpack("%32S*",$symb) << 21;
12122: my $symbseed=numval($symb) << 10;
12123: my $namechck=unpack("%32S*",$username);
12124:
12125: my $nameseed=numval($username) << 21;
12126: my $domainseed=unpack("%32S*",$domain) << 10;
12127: my $courseseed=unpack("%32S*",$courseid);
12128:
12129: my $num1=$symbchck+$symbseed+$namechck;
12130: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12131: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12132: #&logthis("rndseed :$num:$symb");
1.564 albertel 12133: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 12134: return "$num1,$num2";
1.155 albertel 12135: }
1.366 albertel 12136: }
12137:
1.443 albertel 12138: sub rndseed_64bit2 {
12139: my ($symb,$courseid,$domain,$username)=@_;
12140: {
12141: use integer;
12142: # strings need to be an even # of cahracters long, it it is odd the
12143: # last characters gets thrown away
12144: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12145: my $symbseed=numval($symb) << 10;
12146: my $namechck=unpack("%32S*",$username.' ');
12147:
12148: my $nameseed=numval($username) << 21;
1.501 albertel 12149: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12150: my $courseseed=unpack("%32S*",$courseid.' ');
12151:
12152: my $num1=$symbchck+$symbseed+$namechck;
12153: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12154: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12155: #&logthis("rndseed :$num:$symb");
1.803 albertel 12156: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 12157: return "$num1,$num2";
12158: }
12159: }
12160:
12161: sub rndseed_64bit3 {
12162: my ($symb,$courseid,$domain,$username)=@_;
12163: {
12164: use integer;
12165: # strings need to be an even # of cahracters long, it it is odd the
12166: # last characters gets thrown away
12167: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12168: my $symbseed=numval2($symb) << 10;
12169: my $namechck=unpack("%32S*",$username.' ');
12170:
12171: my $nameseed=numval2($username) << 21;
1.443 albertel 12172: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12173: my $courseseed=unpack("%32S*",$courseid.' ');
12174:
12175: my $num1=$symbchck+$symbseed+$namechck;
12176: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12177: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12178: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 12179: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12180:
1.503 albertel 12181: return "$num1:$num2";
1.443 albertel 12182: }
12183: }
12184:
1.575 albertel 12185: sub rndseed_64bit4 {
12186: my ($symb,$courseid,$domain,$username)=@_;
12187: {
12188: use integer;
12189: # strings need to be an even # of cahracters long, it it is odd the
12190: # last characters gets thrown away
12191: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12192: my $symbseed=numval3($symb) << 10;
12193: my $namechck=unpack("%32S*",$username.' ');
12194:
12195: my $nameseed=numval3($username) << 21;
12196: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12197: my $courseseed=unpack("%32S*",$courseid.' ');
12198:
12199: my $num1=$symbchck+$symbseed+$namechck;
12200: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12201: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12202: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 12203: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12204:
1.575 albertel 12205: return "$num1:$num2";
12206: }
12207: }
12208:
1.675 albertel 12209: sub rndseed_64bit5 {
12210: my ($symb,$courseid,$domain,$username)=@_;
12211: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12212: return "$num1:$num2";
12213: }
12214:
1.366 albertel 12215: sub rndseed_CODE_64bit {
12216: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 12217: {
1.366 albertel 12218: use integer;
1.443 albertel 12219: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 12220: my $symbseed=numval2($symb);
1.491 albertel 12221: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12222: my $CODEseed=numval(&getCODE());
1.443 albertel 12223: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 12224: my $num1=$symbseed+$CODEchck;
12225: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12226: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12227: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 12228: if ($_64bit) { $num1=(($num1<<32)>>32); }
12229: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 12230: return "$num1:$num2";
1.366 albertel 12231: }
12232: }
12233:
1.575 albertel 12234: sub rndseed_CODE_64bit4 {
12235: my ($symb,$courseid,$domain,$username)=@_;
12236: {
12237: use integer;
12238: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12239: my $symbseed=numval3($symb);
12240: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12241: my $CODEseed=numval3(&getCODE());
12242: my $courseseed=unpack("%32S*",$courseid.' ');
12243: my $num1=$symbseed+$CODEchck;
12244: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12245: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12246: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 12247: if ($_64bit) { $num1=(($num1<<32)>>32); }
12248: if ($_64bit) { $num2=(($num2<<32)>>32); }
12249: return "$num1:$num2";
12250: }
12251: }
12252:
1.675 albertel 12253: sub rndseed_CODE_64bit5 {
12254: my ($symb,$courseid,$domain,$username)=@_;
12255: my $code = &getCODE();
12256: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12257: return "$num1:$num2";
12258: }
12259:
1.366 albertel 12260: sub setup_random_from_rndseed {
12261: my ($rndseed)=@_;
1.503 albertel 12262: if ($rndseed =~/([,:])/) {
1.1262 raeburn 12263: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12264: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12265: &Math::Random::random_set_seed_from_phrase($rndseed);
12266: } else {
12267: &Math::Random::random_set_seed($num1,$num2);
12268: }
1.366 albertel 12269: } else {
12270: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12271: }
1.36 albertel 12272: }
12273:
1.474 albertel 12274: sub latest_receipt_algorithm_id {
1.835 albertel 12275: return 'receipt3';
1.474 albertel 12276: }
12277:
1.480 www 12278: sub recunique {
12279: my $fucourseid=shift;
12280: my $unique;
1.835 albertel 12281: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12282: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12283: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12284: } else {
12285: $unique=$perlvar{'lonReceipt'};
12286: }
12287: return unpack("%32C*",$unique);
12288: }
12289:
12290: sub recprefix {
12291: my $fucourseid=shift;
12292: my $prefix;
1.835 albertel 12293: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12294: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12295: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12296: } else {
12297: $prefix=$perlvar{'lonHostID'};
12298: }
12299: return unpack("%32C*",$prefix);
12300: }
12301:
1.76 www 12302: sub ireceipt {
1.474 albertel 12303: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12304:
12305: my $return =&recprefix($fucourseid).'-';
12306:
12307: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12308: $env{'request.state'} eq 'construct') {
12309: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12310: return $return;
12311: }
12312:
1.76 www 12313: my $cuname=unpack("%32C*",$funame);
12314: my $cudom=unpack("%32C*",$fudom);
12315: my $cucourseid=unpack("%32C*",$fucourseid);
12316: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12317: my $cunique=&recunique($fucourseid);
1.474 albertel 12318: my $cpart=unpack("%32S*",$part);
1.835 albertel 12319: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12320:
1.790 albertel 12321: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12322:
12323: $return.= ($cunique%$cuname+
12324: $cunique%$cudom+
12325: $cusymb%$cuname+
12326: $cusymb%$cudom+
12327: $cucourseid%$cuname+
12328: $cucourseid%$cudom+
12329: $cpart%$cuname+
12330: $cpart%$cudom);
12331: } else {
12332: $return.= ($cunique%$cuname+
12333: $cunique%$cudom+
12334: $cusymb%$cuname+
12335: $cusymb%$cudom+
12336: $cucourseid%$cuname+
12337: $cucourseid%$cudom);
12338: }
12339: return $return;
1.76 www 12340: }
12341:
12342: sub receipt {
1.474 albertel 12343: my ($part)=@_;
1.790 albertel 12344: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 12345: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 12346: }
1.260 ng 12347:
1.790 albertel 12348: sub whichuser {
12349: my ($passedsymb)=@_;
12350: my ($symb,$courseid,$domain,$name,$publicuser);
12351: if (defined($env{'form.grade_symb'})) {
12352: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12353: my $allowed=&allowed('vgr',$tmp_courseid);
12354: if (!$allowed &&
12355: exists($env{'request.course.sec'}) &&
12356: $env{'request.course.sec'} !~ /^\s*$/) {
12357: $allowed=&allowed('vgr',$tmp_courseid.
12358: '/'.$env{'request.course.sec'});
12359: }
12360: if ($allowed) {
12361: ($symb)=&get_env_multiple('form.grade_symb');
12362: $courseid=$tmp_courseid;
12363: ($domain)=&get_env_multiple('form.grade_domain');
12364: ($name)=&get_env_multiple('form.grade_username');
12365: return ($symb,$courseid,$domain,$name,$publicuser);
12366: }
12367: }
12368: if (!$passedsymb) {
12369: $symb=&symbread();
12370: } else {
12371: $symb=$passedsymb;
12372: }
12373: $courseid=$env{'request.course.id'};
12374: $domain=$env{'user.domain'};
12375: $name=$env{'user.name'};
12376: if ($name eq 'public' && $domain eq 'public') {
12377: if (!defined($env{'form.username'})) {
12378: $env{'form.username'}.=time.rand(10000000);
12379: }
12380: $name.=$env{'form.username'};
12381: }
12382: return ($symb,$courseid,$domain,$name,$publicuser);
12383:
12384: }
12385:
1.36 albertel 12386: # ------------------------------------------------------------ Serves up a file
1.472 albertel 12387: # returns either the contents of the file or
12388: # -1 if the file doesn't exist
1.481 raeburn 12389: #
12390: # if the target is a file that was uploaded via DOCS,
12391: # a check will be made to see if a current copy exists on the local server,
12392: # if it does this will be served, otherwise a copy will be retrieved from
12393: # the home server for the course and stored in /home/httpd/html/userfiles on
12394: # the local server.
1.472 albertel 12395:
1.36 albertel 12396: sub getfile {
1.538 albertel 12397: my ($file) = @_;
1.609 banghart 12398: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 12399: &repcopy($file);
12400: return &readfile($file);
12401: }
12402:
12403: sub repcopy_userfile {
12404: my ($file)=@_;
1.1142 raeburn 12405: my $londocroot = $perlvar{'lonDocRoot'};
12406: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 12407: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 12408: my ($cdom,$cnum,$filename) =
1.811 albertel 12409: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 12410: my $uri="/uploaded/$cdom/$cnum/$filename";
12411: if (-e "$file") {
1.828 www 12412: # we already have a local copy, check it out
1.538 albertel 12413: my @fileinfo = stat($file);
1.828 www 12414: my $rtncode;
12415: my $info;
1.538 albertel 12416: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 12417: if ($lwpresp ne 'ok') {
1.828 www 12418: # there is no such file anymore, even though we had a local copy
1.482 albertel 12419: if ($rtncode eq '404') {
1.538 albertel 12420: unlink($file);
1.482 albertel 12421: }
12422: return -1;
12423: }
12424: if ($info < $fileinfo[9]) {
1.828 www 12425: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 12426: return 'ok';
1.828 www 12427: } else {
12428: # the file is outdated, get rid of it
12429: unlink($file);
1.482 albertel 12430: }
1.828 www 12431: }
12432: # one way or the other, at this point, we don't have the file
12433: # construct the correct path for the file
12434: my @parts = ($cdom,$cnum);
12435: if ($filename =~ m|^(.+)/[^/]+$|) {
12436: push @parts, split(/\//,$1);
12437: }
12438: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12439: foreach my $part (@parts) {
12440: $path .= '/'.$part;
12441: if (!-e $path) {
12442: mkdir($path,0770);
1.482 albertel 12443: }
12444: }
1.828 www 12445: # now the path exists for sure
12446: # get a user agent
12447: my $ua=new LWP::UserAgent;
12448: my $transferfile=$file.'.in.transfer';
12449: # FIXME: this should flock
12450: if (-e $transferfile) { return 'ok'; }
12451: my $request;
12452: $uri=~s/^\///;
1.980 raeburn 12453: my $homeserver = &homeserver($cnum,$cdom);
12454: my $protocol = $protocol{$homeserver};
12455: $protocol = 'http' if ($protocol ne 'https');
12456: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 12457: my $response=$ua->request($request,$transferfile);
12458: # did it work?
12459: if ($response->is_error()) {
12460: unlink($transferfile);
12461: &logthis("Userfile repcopy failed for $uri");
12462: return -1;
12463: }
12464: # worked, rename the transfer file
12465: rename($transferfile,$file);
1.607 raeburn 12466: return 'ok';
1.481 raeburn 12467: }
12468:
1.517 albertel 12469: sub tokenwrapper {
12470: my $uri=shift;
1.980 raeburn 12471: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 12472: $uri=~s|^/||;
1.620 albertel 12473: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 12474: my $token=$1;
1.552 albertel 12475: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12476: if ($udom && $uname && $file) {
12477: $file=~s|(\?\.*)*$||;
1.949 raeburn 12478: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 12479: my $homeserver = &homeserver($uname,$udom);
12480: my $protocol = $protocol{$homeserver};
12481: $protocol = 'http' if ($protocol ne 'https');
12482: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 12483: (($uri=~/\?/)?'&':'?').'token='.$token.
12484: '&tokenissued='.$perlvar{'lonHostID'};
12485: } else {
12486: return '/adm/notfound.html';
12487: }
12488: }
12489:
1.828 www 12490: # call with reqtype HEAD: get last modification time
12491: # call with reqtype GET: get the file contents
12492: # Do not call this with reqtype GET for large files! It loads everything into memory
12493: #
1.481 raeburn 12494: sub getuploaded {
12495: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12496: $uri=~s/^\///;
1.980 raeburn 12497: my $homeserver = &homeserver($cnum,$cdom);
12498: my $protocol = $protocol{$homeserver};
12499: $protocol = 'http' if ($protocol ne 'https');
12500: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 12501: my $ua=new LWP::UserAgent;
12502: my $request=new HTTP::Request($reqtype,$uri);
12503: my $response=$ua->request($request);
12504: $$rtncode = $response->code;
1.482 albertel 12505: if (! $response->is_success()) {
12506: return 'failed';
12507: }
12508: if ($reqtype eq 'HEAD') {
1.486 www 12509: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 12510: } elsif ($reqtype eq 'GET') {
12511: $$info = $response->content;
1.472 albertel 12512: }
1.482 albertel 12513: return 'ok';
1.36 albertel 12514: }
12515:
1.481 raeburn 12516: sub readfile {
12517: my $file = shift;
12518: if ( (! -e $file ) || ($file eq '') ) { return -1; };
12519: my $fh;
12520: open($fh,"<$file");
12521: my $a='';
1.800 albertel 12522: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 12523: return $a;
12524: }
12525:
1.36 albertel 12526: sub filelocation {
1.590 banghart 12527: my ($dir,$file) = @_;
12528: my $location;
12529: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 12530:
12531: if ($file =~ m-^/adm/-) {
12532: $file=~s-^/adm/wrapper/-/-;
12533: $file=~s-^/adm/coursedocs/showdoc/-/-;
12534: }
1.882 albertel 12535:
1.1139 www 12536: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 12537: $location = $file;
1.609 banghart 12538: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 12539: my ($udom,$uname,$filename)=
1.811 albertel 12540: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 12541: my $home=&homeserver($uname,$udom);
12542: my $is_me=0;
12543: my @ids=¤t_machine_ids();
12544: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12545: if ($is_me) {
1.1117 foxr 12546: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 12547: } else {
12548: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12549: $udom.'/'.$uname.'/'.$filename;
12550: }
1.882 albertel 12551: } elsif ($file =~ m-^/adm/-) {
12552: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 12553: } else {
12554: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12555: $file=~s:^/(res|priv)/:/:;
12556: my $space=$1;
1.590 banghart 12557: if ( !( $file =~ m:^/:) ) {
12558: $location = $dir. '/'.$file;
12559: } else {
1.1142 raeburn 12560: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12561: }
1.59 albertel 12562: }
1.590 banghart 12563: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12564: while ($location=~m{/\.\./}) {
12565: if ($location =~ m{/[^/]+/\.\./}) {
12566: $location=~ s{/[^/]+/\.\./}{/}g;
12567: } else {
12568: $location=~ s{/\.\./}{/}g;
12569: }
12570: } #remove dir/..
1.590 banghart 12571: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12572: return $location;
1.46 www 12573: }
1.36 albertel 12574:
1.46 www 12575: sub hreflocation {
12576: my ($dir,$file)=@_;
1.980 raeburn 12577: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12578: $file=filelocation($dir,$file);
1.700 albertel 12579: } elsif ($file=~m-^/adm/-) {
12580: $file=~s-^/adm/wrapper/-/-;
12581: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12582: }
12583: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12584: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12585: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12586: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12587: {/uploaded/$1/$2/}x;
1.46 www 12588: }
1.913 albertel 12589: if ($file=~ m{^/userfiles/}) {
12590: $file =~ s{^/userfiles/}{/uploaded/};
12591: }
1.462 albertel 12592: return $file;
1.465 albertel 12593: }
12594:
1.1139 www 12595:
12596:
12597:
12598:
1.465 albertel 12599: sub current_machine_domains {
1.853 albertel 12600: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12601: }
12602:
12603: sub machine_domains {
12604: my ($hostname) = @_;
1.465 albertel 12605: my @domains;
1.838 albertel 12606: my %hostname = &all_hostnames();
1.465 albertel 12607: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12608: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12609: if ($hostname eq $name) {
1.844 albertel 12610: push(@domains,&host_domain($id));
1.465 albertel 12611: }
12612: }
12613: return @domains;
12614: }
12615:
12616: sub current_machine_ids {
1.853 albertel 12617: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12618: }
12619:
12620: sub machine_ids {
12621: my ($hostname) = @_;
12622: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12623: my @ids;
1.888 albertel 12624: my %name_to_host = &all_names();
1.889 albertel 12625: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12626: return @{ $name_to_host{$hostname} };
12627: }
12628: return;
1.31 www 12629: }
12630:
1.824 raeburn 12631: sub additional_machine_domains {
12632: my @domains;
12633: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12634: while( my $line = <$fh>) {
12635: $line =~ s/\s//g;
12636: push(@domains,$line);
12637: }
12638: return @domains;
12639: }
12640:
12641: sub default_login_domain {
12642: my $domain = $perlvar{'lonDefDomain'};
12643: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12644: foreach my $posdom (¤t_machine_domains(),
12645: &additional_machine_domains()) {
12646: if (lc($posdom) eq lc($testdomain)) {
12647: $domain=$posdom;
12648: last;
12649: }
12650: }
12651: return $domain;
12652: }
12653:
1.31 www 12654: # ------------------------------------------------------------- Declutters URLs
12655:
12656: sub declutter {
12657: my $thisfn=shift;
1.569 albertel 12658: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 12659: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12660: $thisfn=~s{^/home/httpd/html}{};
12661: }
1.31 www 12662: $thisfn=~s/^\///;
1.697 albertel 12663: $thisfn=~s|^adm/wrapper/||;
12664: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12665: $thisfn=~s/^res\///;
1.1172 bisitz 12666: $thisfn=~s/^priv\///;
1.1032 raeburn 12667: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12668: $thisfn=~s/\?.+$//;
12669: }
1.268 www 12670: return $thisfn;
12671: }
12672:
12673: # ------------------------------------------------------------- Clutter up URLs
12674:
12675: sub clutter {
12676: my $thisfn='/'.&declutter(shift);
1.887 albertel 12677: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12678: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12679: $thisfn='/res'.$thisfn;
12680: }
1.1031 raeburn 12681: if ($thisfn !~m|^/adm|) {
12682: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12683: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12684: } else {
12685: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12686: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12687: if ($embstyle eq 'ssi'
12688: || ($embstyle eq 'hdn')
12689: || ($embstyle eq 'rat')
12690: || ($embstyle eq 'prv')
12691: || ($embstyle eq 'ign')) {
12692: #do nothing with these
12693: } elsif (($embstyle eq 'img')
1.695 albertel 12694: || ($embstyle eq 'emb')
12695: || ($embstyle eq 'wrp')) {
12696: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12697: } elsif ($embstyle eq 'unk'
12698: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12699: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12700: } else {
1.718 www 12701: # &logthis("Got a blank emb style");
1.695 albertel 12702: }
1.694 albertel 12703: }
1.1298 raeburn 12704: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
12705: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 12706: }
1.31 www 12707: return $thisfn;
1.12 www 12708: }
12709:
1.787 albertel 12710: sub clutter_with_no_wrapper {
12711: my $uri = &clutter(shift);
12712: if ($uri =~ m-^/adm/-) {
12713: $uri =~ s-^/adm/wrapper/-/-;
12714: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
12715: }
12716: return $uri;
12717: }
12718:
1.557 albertel 12719: sub freeze_escape {
12720: my ($value)=@_;
12721: if (ref($value)) {
12722: $value=&nfreeze($value);
12723: return '__FROZEN__'.&escape($value);
12724: }
12725: return &escape($value);
12726: }
12727:
1.11 www 12728:
1.557 albertel 12729: sub thaw_unescape {
12730: my ($value)=@_;
12731: if ($value =~ /^__FROZEN__/) {
12732: substr($value,0,10,undef);
12733: $value=&unescape($value);
12734: return &thaw($value);
12735: }
12736: return &unescape($value);
12737: }
12738:
1.436 albertel 12739: sub correct_line_ends {
12740: my ($result)=@_;
12741: $$result =~s/\r\n/\n/mg;
12742: $$result =~s/\r/\n/mg;
1.415 albertel 12743: }
1.1 albertel 12744: # ================================================================ Main Program
12745:
1.184 www 12746: sub goodbye {
1.204 albertel 12747: &logthis("Starting Shut down");
1.443 albertel 12748: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 12749: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 12750: #converted
1.599 albertel 12751: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 12752: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12753: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12754: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 12755: #1.1 only
1.870 albertel 12756: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12757: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12758: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12759: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12760: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 12761: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12762: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 12763: &flushcourselogs();
12764: &logthis("Shutting down");
12765: }
12766:
1.852 albertel 12767: sub get_dns {
1.1210 raeburn 12768: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 12769: if (!$ignore_cache) {
12770: my ($content,$cached)=
12771: &Apache::lonnet::is_cached_new('dns',$url);
12772: if ($cached) {
1.1210 raeburn 12773: &$func($content,$hashref);
1.869 albertel 12774: return;
12775: }
12776: }
12777:
12778: my %alldns;
1.852 albertel 12779: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12780: foreach my $dns (<$config>) {
12781: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 12782: my $line = $1;
12783: my ($host,$protocol) = split(/:/,$line);
12784: if ($protocol ne 'https') {
12785: $protocol = 'http';
12786: }
12787: $alldns{$host} = $protocol;
1.869 albertel 12788: }
12789: while (%alldns) {
1.1263 raeburn 12790: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 12791: my $ua=new LWP::UserAgent;
1.1134 raeburn 12792: $ua->timeout(30);
1.979 raeburn 12793: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 12794: my $response=$ua->request($request);
1.979 raeburn 12795: delete($alldns{$dns});
1.852 albertel 12796: next if ($response->is_error());
12797: my @content = split("\n",$response->content);
1.1210 raeburn 12798: unless ($nocache) {
1.1219 raeburn 12799: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 12800: }
12801: &$func(\@content,$hashref);
1.869 albertel 12802: return;
1.852 albertel 12803: }
12804: close($config);
1.871 albertel 12805: my $which = (split('/',$url))[3];
12806: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12807: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 12808: my @content = <$config>;
1.1210 raeburn 12809: &$func(\@content,$hashref);
12810: return;
12811: }
12812:
12813: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 12814: sub parse_dns_checksums_tab {
1.1210 raeburn 12815: my ($lines,$hashref) = @_;
1.1264 raeburn 12816: my $lonhost = $perlvar{'lonHostID'};
12817: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 12818: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 12819: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12820: my $webconfdir = '/etc/httpd/conf';
12821: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12822: $webconfdir = '/etc/apache2';
12823: } elsif ($distro =~ /^sles(\d+)$/) {
12824: if ($1 >= 10) {
12825: $webconfdir = '/etc/apache2';
12826: }
12827: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12828: if ($1 >= 10.0) {
12829: $webconfdir = '/etc/apache2';
12830: }
12831: }
1.1210 raeburn 12832: my ($release,$timestamp) = split(/\-/,$loncaparev);
12833: my (%chksum,%revnum);
12834: if (ref($lines) eq 'ARRAY') {
12835: chomp(@{$lines});
1.1238 raeburn 12836: my $version = shift(@{$lines});
12837: if ($version eq $release) {
1.1210 raeburn 12838: foreach my $line (@{$lines}) {
1.1238 raeburn 12839: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 12840: if ($file =~ m{^/etc/httpd/conf}) {
12841: if ($webconfdir eq '/etc/apache2') {
12842: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12843: }
12844: }
1.1238 raeburn 12845: $chksum{$file} = $shasum;
12846: $revnum{$file} = $version;
1.1210 raeburn 12847: }
12848: if (ref($hashref) eq 'HASH') {
12849: %{$hashref} = (
12850: sums => \%chksum,
12851: versions => \%revnum,
12852: );
12853: }
12854: }
12855: }
1.869 albertel 12856: return;
1.852 albertel 12857: }
1.1210 raeburn 12858:
12859: sub fetch_dns_checksums {
1.1238 raeburn 12860: my %checksums;
12861: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 12862: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 12863: my ($release,$timestamp) = split(/\-/,$loncaparev);
12864: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 12865: \%checksums);
1.1210 raeburn 12866: return \%checksums;
12867: }
12868:
1.327 albertel 12869: # ------------------------------------------------------------ Read domain file
12870: {
1.852 albertel 12871: my $loaded;
1.846 albertel 12872: my %domain;
12873:
1.852 albertel 12874: sub parse_domain_tab {
12875: my ($lines) = @_;
12876: foreach my $line (@$lines) {
12877: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 12878:
1.846 albertel 12879: chomp($line);
1.852 albertel 12880: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 12881: my %this_domain;
12882: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12883: 'lang_def', 'city', 'longi', 'lati',
12884: 'primary') {
12885: $this_domain{$field} = shift(@elements);
12886: }
12887: $domain{$name} = \%this_domain;
1.852 albertel 12888: }
12889: }
1.864 albertel 12890:
12891: sub reset_domain_info {
12892: undef($loaded);
12893: undef(%domain);
12894: }
12895:
1.852 albertel 12896: sub load_domain_tab {
1.1293 raeburn 12897: my ($ignore_cache,$nocache) = @_;
12898: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 12899: my $fh;
12900: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12901: my @lines = <$fh>;
12902: &parse_domain_tab(\@lines);
1.448 albertel 12903: }
1.852 albertel 12904: close($fh);
12905: $loaded = 1;
1.327 albertel 12906: }
1.846 albertel 12907:
12908: sub domain {
1.852 albertel 12909: &load_domain_tab() if (!$loaded);
12910:
1.846 albertel 12911: my ($name,$what) = @_;
12912: return if ( !exists($domain{$name}) );
12913:
12914: if (!$what) {
12915: return $domain{$name}{'description'};
12916: }
12917: return $domain{$name}{$what};
12918: }
1.974 raeburn 12919:
12920: sub domain_info {
12921: &load_domain_tab() if (!$loaded);
12922: return %domain;
12923: }
12924:
1.327 albertel 12925: }
12926:
12927:
1.1 albertel 12928: # ------------------------------------------------------------- Read hosts file
12929: {
1.838 albertel 12930: my %hostname;
1.844 albertel 12931: my %hostdom;
1.845 albertel 12932: my %libserv;
1.852 albertel 12933: my $loaded;
1.888 albertel 12934: my %name_to_host;
1.1074 raeburn 12935: my %internetdom;
1.1107 raeburn 12936: my %LC_dns_serv;
1.852 albertel 12937:
12938: sub parse_hosts_tab {
12939: my ($file) = @_;
12940: foreach my $configline (@$file) {
12941: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 12942: chomp($configline);
12943: if ($configline =~ /^\^/) {
12944: if ($configline =~ /^\^([\w.\-]+)/) {
12945: $LC_dns_serv{$1} = 1;
12946: }
12947: next;
12948: }
1.1074 raeburn 12949: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 12950: $name=~s/\s//g;
12951: if ($id && $domain && $role && $name) {
12952: $hostname{$id}=$name;
1.888 albertel 12953: push(@{$name_to_host{$name}}, $id);
1.852 albertel 12954: $hostdom{$id}=$domain;
12955: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 12956: if (defined($protocol)) {
12957: if ($protocol eq 'https') {
12958: $protocol{$id} = $protocol;
12959: } else {
12960: $protocol{$id} = 'http';
12961: }
1.968 raeburn 12962: } else {
1.969 raeburn 12963: $protocol{$id} = 'http';
1.968 raeburn 12964: }
1.1074 raeburn 12965: if (defined($intdom)) {
12966: $internetdom{$id} = $intdom;
12967: }
1.852 albertel 12968: }
12969: }
12970: }
1.864 albertel 12971:
12972: sub reset_hosts_info {
1.897 albertel 12973: &purge_remembered();
1.864 albertel 12974: &reset_domain_info();
12975: &reset_hosts_ip_info();
1.892 albertel 12976: undef(%name_to_host);
1.864 albertel 12977: undef(%hostname);
12978: undef(%hostdom);
12979: undef(%libserv);
12980: undef($loaded);
12981: }
1.1 albertel 12982:
1.852 albertel 12983: sub load_hosts_tab {
1.1293 raeburn 12984: my ($ignore_cache,$nocache) = @_;
12985: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852 albertel 12986: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12987: my @config = <$config>;
12988: &parse_hosts_tab(\@config);
12989: close($config);
12990: $loaded=1;
1.1 albertel 12991: }
1.852 albertel 12992:
1.838 albertel 12993: sub hostname {
1.852 albertel 12994: &load_hosts_tab() if (!$loaded);
12995:
1.838 albertel 12996: my ($lonid) = @_;
12997: return $hostname{$lonid};
12998: }
1.845 albertel 12999:
1.838 albertel 13000: sub all_hostnames {
1.852 albertel 13001: &load_hosts_tab() if (!$loaded);
13002:
1.838 albertel 13003: return %hostname;
13004: }
1.845 albertel 13005:
1.888 albertel 13006: sub all_names {
1.1293 raeburn 13007: my ($ignore_cache,$nocache) = @_;
13008: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 13009:
13010: return %name_to_host;
13011: }
13012:
1.974 raeburn 13013: sub all_host_domain {
13014: &load_hosts_tab() if (!$loaded);
13015: return %hostdom;
13016: }
13017:
1.845 albertel 13018: sub is_library {
1.852 albertel 13019: &load_hosts_tab() if (!$loaded);
13020:
1.845 albertel 13021: return exists($libserv{$_[0]});
13022: }
13023:
13024: sub all_library {
1.852 albertel 13025: &load_hosts_tab() if (!$loaded);
13026:
1.845 albertel 13027: return %libserv;
13028: }
13029:
1.1062 droeschl 13030: sub unique_library {
13031: #2x reverse removes all hostnames that appear more than once
13032: my %unique = reverse &all_library();
13033: return reverse %unique;
13034: }
13035:
1.841 albertel 13036: sub get_servers {
1.852 albertel 13037: &load_hosts_tab() if (!$loaded);
13038:
1.841 albertel 13039: my ($domain,$type) = @_;
13040: my %possible_hosts = ($type eq 'library') ? %libserv
13041: : %hostname;
13042: my %result;
1.842 albertel 13043: if (ref($domain) eq 'ARRAY') {
13044: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 13045: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 13046: $result{$host} = $hostname;
13047: }
13048: }
13049: } else {
13050: while ( my ($host,$hostname) = each(%possible_hosts)) {
13051: if ($hostdom{$host} eq $domain) {
13052: $result{$host} = $hostname;
13053: }
1.841 albertel 13054: }
13055: }
13056: return %result;
13057: }
1.845 albertel 13058:
1.1062 droeschl 13059: sub get_unique_servers {
13060: my %unique = reverse &get_servers(@_);
13061: return reverse %unique;
13062: }
13063:
1.844 albertel 13064: sub host_domain {
1.852 albertel 13065: &load_hosts_tab() if (!$loaded);
13066:
1.844 albertel 13067: my ($lonid) = @_;
13068: return $hostdom{$lonid};
13069: }
13070:
1.841 albertel 13071: sub all_domains {
1.852 albertel 13072: &load_hosts_tab() if (!$loaded);
13073:
1.841 albertel 13074: my %seen;
13075: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13076: return @uniq;
13077: }
1.1074 raeburn 13078:
13079: sub internet_dom {
13080: &load_hosts_tab() if (!$loaded);
13081:
13082: my ($lonid) = @_;
13083: return $internetdom{$lonid};
13084: }
1.1107 raeburn 13085:
13086: sub is_LC_dns {
13087: &load_hosts_tab() if (!$loaded);
13088:
13089: my ($hostname) = @_;
13090: return exists($LC_dns_serv{$hostname});
13091: }
13092:
1.1 albertel 13093: }
13094:
1.847 albertel 13095: {
13096: my %iphost;
1.856 albertel 13097: my %name_to_ip;
13098: my %lonid_to_ip;
1.869 albertel 13099:
1.847 albertel 13100: sub get_hosts_from_ip {
13101: my ($ip) = @_;
13102: my %iphosts = &get_iphost();
13103: if (ref($iphosts{$ip})) {
13104: return @{$iphosts{$ip}};
13105: }
13106: return;
1.839 albertel 13107: }
1.864 albertel 13108:
13109: sub reset_hosts_ip_info {
13110: undef(%iphost);
13111: undef(%name_to_ip);
13112: undef(%lonid_to_ip);
13113: }
1.856 albertel 13114:
13115: sub get_host_ip {
13116: my ($lonid) = @_;
13117: if (exists($lonid_to_ip{$lonid})) {
13118: return $lonid_to_ip{$lonid};
13119: }
13120: my $name=&hostname($lonid);
13121: my $ip = gethostbyname($name);
13122: return if (!$ip || length($ip) ne 4);
13123: $ip=inet_ntoa($ip);
13124: $name_to_ip{$name} = $ip;
13125: $lonid_to_ip{$lonid} = $ip;
13126: return $ip;
13127: }
1.847 albertel 13128:
13129: sub get_iphost {
1.1293 raeburn 13130: my ($ignore_cache,$nocache) = @_;
1.894 albertel 13131:
1.869 albertel 13132: if (!$ignore_cache) {
13133: if (%iphost) {
13134: return %iphost;
13135: }
13136: my ($ip_info,$cached)=
13137: &Apache::lonnet::is_cached_new('iphost','iphost');
13138: if ($cached) {
13139: %iphost = %{$ip_info->[0]};
13140: %name_to_ip = %{$ip_info->[1]};
13141: %lonid_to_ip = %{$ip_info->[2]};
13142: return %iphost;
13143: }
13144: }
1.894 albertel 13145:
13146: # get yesterday's info for fallback
13147: my %old_name_to_ip;
13148: my ($ip_info,$cached)=
13149: &Apache::lonnet::is_cached_new('iphost','iphost');
13150: if ($cached) {
13151: %old_name_to_ip = %{$ip_info->[1]};
13152: }
13153:
1.1293 raeburn 13154: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 13155: foreach my $name (keys(%name_to_host)) {
1.847 albertel 13156: my $ip;
13157: if (!exists($name_to_ip{$name})) {
13158: $ip = gethostbyname($name);
13159: if (!$ip || length($ip) ne 4) {
1.894 albertel 13160: if (defined($old_name_to_ip{$name})) {
13161: $ip = $old_name_to_ip{$name};
13162: &logthis("Can't find $name defaulting to old $ip");
13163: } else {
13164: &logthis("Name $name no IP found");
13165: next;
13166: }
13167: } else {
13168: $ip=inet_ntoa($ip);
1.847 albertel 13169: }
13170: $name_to_ip{$name} = $ip;
13171: } else {
13172: $ip = $name_to_ip{$name};
1.653 albertel 13173: }
1.888 albertel 13174: foreach my $id (@{ $name_to_host{$name} }) {
13175: $lonid_to_ip{$id} = $ip;
13176: }
13177: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 13178: }
1.1293 raeburn 13179: unless ($nocache) {
13180: &do_cache_new('iphost','iphost',
13181: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13182: 48*60*60);
13183: }
1.869 albertel 13184:
1.847 albertel 13185: return %iphost;
1.598 albertel 13186: }
13187:
1.992 raeburn 13188: #
13189: # Given a DNS returns the loncapa host name for that DNS
13190: #
13191: sub host_from_dns {
13192: my ($dns) = @_;
13193: my @hosts;
13194: my $ip;
13195:
1.993 raeburn 13196: if (exists($name_to_ip{$dns})) {
1.992 raeburn 13197: $ip = $name_to_ip{$dns};
13198: }
13199: if (!$ip) {
13200: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13201: if (length($ip) == 4) {
13202: $ip = &IO::Socket::inet_ntoa($ip);
13203: }
13204: }
13205: if ($ip) {
13206: @hosts = get_hosts_from_ip($ip);
13207: return $hosts[0];
13208: }
13209: return undef;
1.986 foxr 13210: }
1.992 raeburn 13211:
1.1074 raeburn 13212: sub get_internet_names {
13213: my ($lonid) = @_;
13214: return if ($lonid eq '');
13215: my ($idnref,$cached)=
13216: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13217: if ($cached) {
13218: return $idnref;
13219: }
13220: my $ip = &get_host_ip($lonid);
13221: my @hosts = &get_hosts_from_ip($ip);
13222: my %iphost = &get_iphost();
13223: my (@idns,%seen);
13224: foreach my $id (@hosts) {
13225: my $dom = &host_domain($id);
13226: my $prim_id = &domain($dom,'primary');
13227: my $prim_ip = &get_host_ip($prim_id);
13228: next if ($seen{$prim_ip});
13229: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13230: foreach my $id (@{$iphost{$prim_ip}}) {
13231: my $intdom = &internet_dom($id);
13232: unless (grep(/^\Q$intdom\E$/,@idns)) {
13233: push(@idns,$intdom);
13234: }
13235: }
13236: }
13237: $seen{$prim_ip} = 1;
13238: }
1.1219 raeburn 13239: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 13240: }
13241:
1.986 foxr 13242: }
13243:
1.1079 raeburn 13244: sub all_loncaparevs {
1.1249 raeburn 13245: 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 13246: }
13247:
1.1227 raeburn 13248: # ---------------------------------------------------------- Read loncaparev table
13249: {
13250: sub load_loncaparevs {
13251: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13252: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13253: while (my $configline=<$config>) {
13254: chomp($configline);
13255: my ($hostid,$loncaparev)=split(/:/,$configline);
13256: $loncaparevs{$hostid}=$loncaparev;
13257: }
13258: close($config);
13259: }
13260: }
13261: }
13262: }
13263:
13264: # ---------------------------------------------------------- Read serverhostID table
13265: {
13266: sub load_serverhomeIDs {
13267: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13268: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13269: while (my $configline=<$config>) {
13270: chomp($configline);
13271: my ($name,$id)=split(/:/,$configline);
13272: $serverhomeIDs{$name}=$id;
13273: }
13274: close($config);
13275: }
13276: }
13277: }
13278: }
13279:
13280:
1.862 albertel 13281: BEGIN {
13282:
13283: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13284: unless ($readit) {
13285: {
13286: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13287: %perlvar = (%perlvar,%{$configvars});
13288: }
13289:
13290:
1.1 albertel 13291: # ------------------------------------------------------ Read spare server file
13292: {
1.448 albertel 13293: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 13294:
13295: while (my $configline=<$config>) {
13296: chomp($configline);
1.284 matthew 13297: if ($configline) {
1.784 albertel 13298: my ($host,$type) = split(':',$configline,2);
1.785 albertel 13299: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 13300: push(@{ $spareid{$type} }, $host);
1.1 albertel 13301: }
13302: }
1.448 albertel 13303: close($config);
1.1 albertel 13304: }
1.11 www 13305: # ------------------------------------------------------------ Read permissions
13306: {
1.448 albertel 13307: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 13308:
13309: while (my $configline=<$config>) {
1.448 albertel 13310: chomp($configline);
13311: if ($configline) {
13312: my ($role,$perm)=split(/ /,$configline);
13313: if ($perm ne '') { $pr{$role}=$perm; }
13314: }
1.11 www 13315: }
1.448 albertel 13316: close($config);
1.11 www 13317: }
13318:
13319: # -------------------------------------------- Read plain texts for permissions
13320: {
1.448 albertel 13321: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 13322:
13323: while (my $configline=<$config>) {
1.448 albertel 13324: chomp($configline);
13325: if ($configline) {
1.742 raeburn 13326: my ($short,@plain)=split(/:/,$configline);
13327: %{$prp{$short}} = ();
13328: if (@plain > 0) {
13329: $prp{$short}{'std'} = $plain[0];
13330: for (my $i=1; $i<@plain; $i++) {
13331: $prp{$short}{'alt'.$i} = $plain[$i];
13332: }
13333: }
1.448 albertel 13334: }
1.135 www 13335: }
1.448 albertel 13336: close($config);
1.135 www 13337: }
13338:
13339: # ---------------------------------------------------------- Read package table
13340: {
1.448 albertel 13341: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 13342:
13343: while (my $configline=<$config>) {
1.483 albertel 13344: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 13345: chomp($configline);
13346: my ($short,$plain)=split(/:/,$configline);
13347: my ($pack,$name)=split(/\&/,$short);
13348: if ($plain ne '') {
13349: $packagetab{$pack.'&'.$name.'&name'}=$name;
13350: $packagetab{$short}=$plain;
13351: }
1.11 www 13352: }
1.448 albertel 13353: close($config);
1.329 matthew 13354: }
13355:
1.1073 raeburn 13356: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 13357:
13358: &load_loncaparevs();
1.1073 raeburn 13359:
1.1074 raeburn 13360: # ---------------------------------------------------------- Read serverhostID table
13361:
1.1227 raeburn 13362: &load_serverhomeIDs();
13363:
13364: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 13365: {
13366: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13367: if (-e $file) {
13368: my $parser = HTML::LCParser->new($file);
13369: while (my $token = $parser->get_token()) {
13370: if ($token->[0] eq 'S') {
13371: my $item = $token->[1];
13372: my $name = $token->[2]{'name'};
13373: my $value = $token->[2]{'value'};
1.1285 raeburn 13374: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 13375: my $namematch = $token->[2]{'namematch'};
13376: if ($item eq 'parameter') {
13377: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
13378: my $release = $parser->get_text();
13379: $release =~ s/(^\s*|\s*$ )//gx;
13380: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
13381: }
13382: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 13383: my $release = $parser->get_text();
13384: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 13385: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 13386: }
13387: }
13388: }
13389: }
1.1073 raeburn 13390: }
13391:
1.1138 raeburn 13392: # ---------------------------------------------------------- Read managers table
13393: {
13394: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13395: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
13396: while (my $configline=<$config>) {
13397: chomp($configline);
13398: next if ($configline =~ /^\#/);
13399: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13400: $managerstab{$configline} = 1;
13401: }
13402: }
13403: close($config);
13404: }
13405: }
13406: }
13407:
1.329 matthew 13408: # ------------- set up temporary directory
13409: {
1.1117 foxr 13410: $tmpdir = LONCAPA::tempdir();
1.329 matthew 13411:
1.11 www 13412: }
13413:
1.794 albertel 13414: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13415: 'compress_threshold'=> 20_000,
13416: });
1.185 www 13417:
1.281 www 13418: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 13419: $dumpcount=0;
1.958 www 13420: $locknum=0;
1.22 www 13421:
1.163 harris41 13422: &logtouch();
1.672 albertel 13423: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 13424: $readit=1;
1.564 albertel 13425: {
13426: use integer;
13427: my $test=(2**32)+1;
1.568 albertel 13428: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 13429: &logthis(" Detected 64bit platform ($_64bit)");
13430: }
1.195 www 13431: }
1.1 albertel 13432: }
1.179 www 13433:
1.1 albertel 13434: 1;
1.191 harris41 13435: __END__
13436:
1.243 albertel 13437: =pod
13438:
1.191 harris41 13439: =head1 NAME
13440:
1.243 albertel 13441: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 13442:
13443: =head1 SYNOPSIS
13444:
1.243 albertel 13445: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 13446:
13447: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13448:
1.243 albertel 13449: Common parameters:
13450:
13451: =over 4
13452:
13453: =item *
13454:
13455: $uname : an internal username (if $cname expecting a course Id specifically)
13456:
13457: =item *
13458:
13459: $udom : a domain (if $cdom expecting a course's domain specifically)
13460:
13461: =item *
13462:
13463: $symb : a resource instance identifier
13464:
13465: =item *
13466:
13467: $namespace : the name of a .db file that contains the data needed or
13468: being set.
13469:
13470: =back
13471:
1.394 bowersj2 13472: =head1 OVERVIEW
1.191 harris41 13473:
1.394 bowersj2 13474: lonnet provides subroutines which interact with the
13475: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13476: about classes, users, and resources.
1.243 albertel 13477:
13478: For many of these objects you can also use this to store data about
13479: them or modify them in various ways.
1.191 harris41 13480:
1.394 bowersj2 13481: =head2 Symbs
1.191 harris41 13482:
1.394 bowersj2 13483: To identify a specific instance of a resource, LON-CAPA uses symbols
13484: or "symbs"X<symb>. These identifiers are built from the URL of the
13485: map, the resource number of the resource in the map, and the URL of
13486: the resource itself. The latter is somewhat redundant, but might help
13487: if maps change.
13488:
13489: An example is
13490:
13491: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13492:
13493: The respective map entry is
13494:
13495: <resource id="19" src="/res/msu/korte/tests/part12.problem"
13496: title="Problem 2">
13497: </resource>
13498:
13499: Symbs are used by the random number generator, as well as to store and
13500: restore data specific to a certain instance of for example a problem.
13501:
13502: =head2 Storing And Retrieving Data
13503:
13504: X<store()>X<cstore()>X<restore()>Three of the most important functions
13505: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13506: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13507: is is the non-critical message twin of cstore. These functions are for
13508: handlers to store a perl hash to a user's permanent data space in an
13509: easy manner, and to retrieve it again on another call. It is expected
13510: that a handler would use this once at the beginning to retrieve data,
13511: and then again once at the end to send only the new data back.
13512:
13513: The data is stored in the user's data directory on the user's
13514: homeserver under the ID of the course.
13515:
13516: The hash that is returned by restore will have all of the previous
13517: value for all of the elements of the hash.
13518:
13519: Example:
13520:
13521: #creating a hash
13522: my %hash;
13523: $hash{'foo'}='bar';
13524:
13525: #storing it
13526: &Apache::lonnet::cstore(\%hash);
13527:
13528: #changing a value
13529: $hash{'foo'}='notbar';
13530:
13531: #adding a new value
13532: $hash{'bar'}='foo';
13533: &Apache::lonnet::cstore(\%hash);
13534:
13535: #retrieving the hash
13536: my %history=&Apache::lonnet::restore();
13537:
13538: #print the hash
13539: foreach my $key (sort(keys(%history))) {
13540: print("\%history{$key} = $history{$key}");
13541: }
13542:
13543: Will print out:
1.191 harris41 13544:
1.394 bowersj2 13545: %history{1:foo} = bar
13546: %history{1:keys} = foo:timestamp
13547: %history{1:timestamp} = 990455579
13548: %history{2:bar} = foo
13549: %history{2:foo} = notbar
13550: %history{2:keys} = foo:bar:timestamp
13551: %history{2:timestamp} = 990455580
13552: %history{bar} = foo
13553: %history{foo} = notbar
13554: %history{timestamp} = 990455580
13555: %history{version} = 2
13556:
13557: Note that the special hash entries C<keys>, C<version> and
13558: C<timestamp> were added to the hash. C<version> will be equal to the
13559: total number of versions of the data that have been stored. The
13560: C<timestamp> attribute will be the UNIX time the hash was
13561: stored. C<keys> is available in every historical section to list which
13562: keys were added or changed at a specific historical revision of a
13563: hash.
13564:
13565: B<Warning>: do not store the hash that restore returns directly. This
13566: will cause a mess since it will restore the historical keys as if the
13567: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13568:
1.394 bowersj2 13569: Calling convention:
1.191 harris41 13570:
1.1225 raeburn 13571: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 13572: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13573:
1.394 bowersj2 13574: For more detailed information, see lonnet specific documentation.
1.191 harris41 13575:
1.394 bowersj2 13576: =head1 RETURN MESSAGES
1.191 harris41 13577:
1.394 bowersj2 13578: =over 4
1.191 harris41 13579:
1.394 bowersj2 13580: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13581:
1.394 bowersj2 13582: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13583: when the connection is brought back up
1.191 harris41 13584:
1.394 bowersj2 13585: =item * B<con_failed>: unable to contact remote host and unable to save message
13586: for later delivery
1.191 harris41 13587:
1.967 bisitz 13588: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13589:
1.394 bowersj2 13590: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13591: that was requested
1.191 harris41 13592:
1.243 albertel 13593: =back
1.191 harris41 13594:
1.243 albertel 13595: =head1 PUBLIC SUBROUTINES
1.191 harris41 13596:
1.243 albertel 13597: =head2 Session Environment Functions
1.191 harris41 13598:
1.243 albertel 13599: =over 4
1.191 harris41 13600:
1.394 bowersj2 13601: =item *
13602: X<appenv()>
1.949 raeburn 13603: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13604: the user envirnoment file, and will be restored for each access this
1.620 albertel 13605: user makes during this session, also modifies the %env for the current
1.949 raeburn 13606: process. Optional rolesarrayref - if defined contains a reference to an array
13607: of roles which are exempt from the restriction on modifying user.role entries
13608: in the user's environment.db and in %env.
1.191 harris41 13609:
13610: =item *
1.394 bowersj2 13611: X<delenv()>
1.987 raeburn 13612: B<delenv($delthis,$regexp)>: removes all items from the session
13613: environment file that begin with $delthis. If the
13614: optional second arg - $regexp - is true, $delthis is treated as a
13615: regular expression, otherwise \Q$delthis\E is used.
13616: The values are also deleted from the current processes %env.
1.191 harris41 13617:
1.795 albertel 13618: =item * get_env_multiple($name)
13619:
13620: gets $name from the %env hash, it seemlessly handles the cases where multiple
13621: values may be defined and end up as an array ref.
13622:
13623: returns an array of values
13624:
1.243 albertel 13625: =back
13626:
13627: =head2 User Information
1.191 harris41 13628:
1.243 albertel 13629: =over 4
1.191 harris41 13630:
13631: =item *
1.394 bowersj2 13632: X<queryauthenticate()>
13633: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13634: authentication scheme
13635:
13636: =item *
1.394 bowersj2 13637: X<authenticate()>
1.1073 raeburn 13638: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13639: authenticate user from domain's lib servers (first use the current
13640: one). C<$upass> should be the users password.
1.1073 raeburn 13641: $checkdefauth is optional (value is 1 if a check should be made to
13642: authenticate user using default authentication method, and allow
13643: account creation if username does not have account in the domain).
13644: $clientcancheckhost is optional (value is 1 if checking whether the
13645: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13646:
13647: =item *
1.394 bowersj2 13648: X<homeserver()>
13649: B<homeserver($uname,$udom)>: find the server which has
13650: the user's directory and files (there must be only one), this caches
13651: the answer, and also caches if there is a borken connection.
1.191 harris41 13652:
13653: =item *
1.394 bowersj2 13654: X<idget()>
1.1300 raeburn 13655: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
13656: a list of student/employee IDs or clicker IDs
13657: (student/employee IDs are a unique resource in a domain, there must be
13658: only 1 ID per username, and only 1 username per ID in a specific domain).
13659: clickerIDs are not necessarily unique, as students might share clickers.
13660: (returns hash: id=>name,id=>name)
1.191 harris41 13661:
13662: =item *
1.394 bowersj2 13663: X<idrget()>
13664: B<idrget($udom,@unames)>: find the IDs behind a list of
13665: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13666:
13667: =item *
1.394 bowersj2 13668: X<idput()>
1.1300 raeburn 13669: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
13670: names and associated student/employee IDs or clicker IDs.
13671:
13672: =item *
13673: X<iddel()>
13674: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
13675: student/employee ID or clicker ID username look-ups from domain.
13676: The homeserver ($uhome) and namespace ($namespace) are optional.
13677: If no $uhome is provided, it will be determined usig &homeserver()
13678: for each user. If no $namespace is provided, the default is ids.
13679:
13680: =item *
13681: X<updateclickers()>
13682: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
13683: clicker ID-to-username look-ups in clickers.db on library server.
13684: Permitted actions are add or del (i.e., add or delete). The
13685: clickers.db contains clickerID as keys (escaped), and each corresponding
13686: value is an escaped comma-separated list of usernames (for whom the
13687: library server is the homeserver), who registered that particular ID.
13688: If $critical is true, the update will be sent via &critical, otherwise
13689: &reply() will be used.
1.191 harris41 13690:
13691: =item *
1.394 bowersj2 13692: X<rolesinit()>
1.1169 droeschl 13693: B<rolesinit($udom,$username)>: get user privileges.
13694: returns user role, first access and timer interval hashes
1.243 albertel 13695:
13696: =item *
1.1171 droeschl 13697: X<privileged()>
13698: B<privileged($username,$domain)>: returns a true if user has a
13699: privileged and active role (i.e. su or dc), false otherwise.
13700:
13701: =item *
1.551 albertel 13702: X<getsection()>
13703: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 13704: course $cname, return section name/number or '' for "not in course"
13705: and '-1' for "no section"
13706:
13707: =item *
1.394 bowersj2 13708: X<userenvironment()>
13709: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 13710: passed in @what from the requested user's environment, returns a hash
13711:
1.858 raeburn 13712: =item *
13713: X<userlog_query()>
1.859 albertel 13714: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13715: activity.log file. %filters defines filters applied when parsing the
13716: log file. These can be start or end timestamps, or the type of action
13717: - log to look for Login or Logout events, check for Checkin or
13718: Checkout, role for role selection. The response is in the form
13719: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
13720: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 13721:
1.243 albertel 13722: =back
13723:
13724: =head2 User Roles
13725:
13726: =over 4
13727:
13728: =item *
13729:
1.1284 raeburn 13730: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
13731: returns codes for allowed actions.
13732:
13733: The first argument is required, all others are optional.
13734:
13735: $priv is the privilege being checked.
13736: $uri contains additional information about what is being checked for access (e.g.,
13737: URL, course ID etc.).
13738: $symb is the unique resource instance identifier in a course; if needed,
13739: but not provided, it will be retrieved via a call to &symbread().
13740: $role is the role for which a priv is being checked (only used if priv is evb).
13741: $clientip is the user's IP address (only used when checking for access to portfolio
13742: files).
13743: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
13744: prevents recursive calls to &allowed.
13745:
1.243 albertel 13746: F: full access
13747: U,I,K: authentication modes (cxx only)
13748: '': forbidden
13749: 1: user needs to choose course
13750: 2: browse allowed
1.766 albertel 13751: A: passphrase authentication needed
1.1284 raeburn 13752: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 13753:
13754: =item *
13755:
1.1192 raeburn 13756: constructaccess($url,$setpriv) : check for access to construction space URL
13757:
13758: See if the owner domain and name in the URL match those in the
13759: expected environment. If so, return three element list
13760: ($ownername,$ownerdomain,$ownerhome).
13761:
13762: Otherwise return the null string.
13763:
13764: If second argument 'setpriv' is true, it assigns the privileges,
13765: and returns the same three element list, unless the owner has
13766: blocked "ad hoc" Domain Coordinator access to the Author Space,
13767: in which case the null string is returned.
13768:
13769: =item *
13770:
1.1326 raeburn 13771: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
13772: define a custom role rolename set privileges in format of lonTabs/roles.tab
13773: for system, domain, and course level. $uname and $udom are optional (current
13774: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 13775:
13776: =item *
13777:
1.988 raeburn 13778: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
13779: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 13780: $type is Course (default) or Community.
1.988 raeburn 13781: If $forcedefault evaluates to true, text returned will be default
13782: text for $type. Otherwise, if this is a course, the text returned
13783: will be a custom name for the role (if defined in the course's
13784: environment). If no custom name is defined the default is returned.
13785:
1.832 raeburn 13786: =item *
13787:
1.1219 raeburn 13788: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 13789: All arguments are optional. Returns a hash of a roles, either for
13790: co-author/assistant author roles for a user's Construction Space
1.906 albertel 13791: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 13792: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13793: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13794: For each key, value is set to colon-separated start and end times for
13795: the role. If no username and domain are specified, will default to
1.934 raeburn 13796: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 13797: of role statuses (active, future or previous), roles
13798: (e.g., cc,in, st etc.) and domains of the roles which can be used
13799: to restrict the list of roles reported. If no array ref is
13800: provided for types, will default to return only active roles.
1.834 albertel 13801:
1.1195 raeburn 13802: =item *
13803:
13804: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 13805: user: $uname:$udom has a role in the course: $cdom_$cnum.
13806:
13807: Additional optional arguments are: $type (if role checking is to be restricted
13808: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 13809: available roles) or future (roles available in the future), and
13810: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 13811: have active Domain Coordinator role in course's domain or in additional
13812: domains (specified in 'Domains to check for privileged users' in course
13813: environment -- set via: Course Settings -> Classlists and staff listing).
13814:
13815: =item *
13816:
13817: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13818: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13819: $possdomains and $possroles are optional array refs -- to domains to check and
13820: roles to check. If $possdomains is not specified, a dump will be done of the
13821: users' roles.db to check for a dc or su role in any domain. This can be
13822: time consuming if &privileged is called repeatedly (e.g., when displaying a
13823: classlist), so in such cases, supplying a $possdomains array is preferred, as
13824: this then allows &privileged_by_domain() to be used, which caches the identity
13825: of privileged users, eliminating the need for repeated calls to &dump().
13826:
13827: =item *
13828:
13829: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13830: where the outer hash keys are domains specified in the $possdomains array ref,
13831: next inner hash keys are privileged roles specified in the $roles array ref,
13832: and the innermost hash contains key = value pairs for username:domain = end:start
13833: for active or future "privileged" users with that role in that domain. To avoid
13834: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13835: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 13836:
1.243 albertel 13837: =back
13838:
13839: =head2 User Modification
13840:
13841: =over 4
13842:
13843: =item *
13844:
1.957 raeburn 13845: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 13846: user for the level given by URL. Optional start and end dates (leave empty
13847: string or zero for "no date")
1.191 harris41 13848:
13849: =item *
13850:
1.243 albertel 13851: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13852: change a users, password, possible return values are: ok,
13853: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13854: refused
1.191 harris41 13855:
13856: =item *
13857:
1.243 albertel 13858: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 13859:
13860: =item *
13861:
1.1058 raeburn 13862: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13863: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13864:
13865: will update user information (firstname,middlename,lastname,generation,
13866: permanentemail), and if forceid is true, student/employee ID also.
13867: A user's institutional affiliation(s) can also be updated.
13868: User information fields will not be overwritten with empty entries
13869: unless the field is included in the $candelete array reference.
13870: This array is included when a single user is modified via "Manage Users",
13871: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 13872:
13873: =item *
13874:
1.286 matthew 13875: modifystudent
13876:
1.957 raeburn 13877: modify a student's enrollment and identification information.
1.1235 raeburn 13878: The course id is resolved based on the current user's environment.
13879: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 13880: associated with a course.
13881:
1.297 matthew 13882: This call is essentially a wrapper for lonnet::modifyuser and
13883: lonnet::modify_student_enrollment
1.286 matthew 13884:
13885: Inputs:
13886:
13887: =over 4
13888:
1.957 raeburn 13889: =item B<$udom> Student's loncapa domain
1.286 matthew 13890:
1.957 raeburn 13891: =item B<$uname> Student's loncapa login name
1.286 matthew 13892:
1.964 bisitz 13893: =item B<$uid> Student/Employee ID
1.286 matthew 13894:
1.957 raeburn 13895: =item B<$umode> Student's authentication mode
1.286 matthew 13896:
1.957 raeburn 13897: =item B<$upass> Student's password
1.286 matthew 13898:
1.957 raeburn 13899: =item B<$first> Student's first name
1.286 matthew 13900:
1.957 raeburn 13901: =item B<$middle> Student's middle name
1.286 matthew 13902:
1.957 raeburn 13903: =item B<$last> Student's last name
1.286 matthew 13904:
1.957 raeburn 13905: =item B<$gene> Student's generation
1.286 matthew 13906:
1.957 raeburn 13907: =item B<$usec> Student's section in course
1.286 matthew 13908:
13909: =item B<$end> Unix time of the roles expiration
13910:
13911: =item B<$start> Unix time of the roles start date
13912:
13913: =item B<$forceid> If defined, allow $uid to be changed
13914:
13915: =item B<$desiredhome> server to use as home server for student
13916:
1.957 raeburn 13917: =item B<$email> Student's permanent e-mail address
13918:
13919: =item B<$type> Type of enrollment (auto or manual)
13920:
1.963 raeburn 13921: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13922:
13923: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 13924:
1.963 raeburn 13925: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 13926:
1.963 raeburn 13927: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 13928:
1.1216 raeburn 13929: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13930:
13931: =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 13932:
1.286 matthew 13933: =back
1.297 matthew 13934:
13935: =item *
13936:
13937: modify_student_enrollment
13938:
1.1235 raeburn 13939: Change a student's enrollment status in a class. The environment variable
1.297 matthew 13940: 'role.request.course' must be defined for this function to proceed.
13941:
13942: Inputs:
13943:
13944: =over 4
13945:
1.1235 raeburn 13946: =item $udom, student's domain
1.297 matthew 13947:
1.1235 raeburn 13948: =item $uname, student's name
1.297 matthew 13949:
1.1235 raeburn 13950: =item $uid, student's user id
1.297 matthew 13951:
1.1235 raeburn 13952: =item $first, student's first name
1.297 matthew 13953:
13954: =item $middle
13955:
13956: =item $last
13957:
13958: =item $gene
13959:
13960: =item $usec
13961:
13962: =item $end
13963:
13964: =item $start
13965:
1.957 raeburn 13966: =item $type
13967:
13968: =item $locktype
13969:
13970: =item $cid
13971:
13972: =item $selfenroll
13973:
13974: =item $context
13975:
1.1216 raeburn 13976: =item $credits, number of credits student will earn from this class
13977:
1.1314 raeburn 13978: =item $instsec, institutional course section code for student
13979:
1.297 matthew 13980: =back
13981:
1.191 harris41 13982:
13983: =item *
13984:
1.243 albertel 13985: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13986: custom role; give a custom role to a user for the level given by URL. Specify
13987: name and domain of role author, and role name
1.191 harris41 13988:
13989: =item *
13990:
1.243 albertel 13991: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 13992:
13993: =item *
13994:
1.243 albertel 13995: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13996:
13997: =back
13998:
13999: =head2 Course Infomation
14000:
14001: =over 4
1.191 harris41 14002:
14003: =item *
14004:
1.1118 foxr 14005: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 14006: specified course id, including all environment settings for the
14007: course, the description of the course will be in the hash under the
14008: key 'description'
1.191 harris41 14009:
1.1118 foxr 14010: $options is an optional parameter that if supplied is a hash reference that controls
14011: what how this function works. It has the following key/values:
14012:
14013: =over 4
14014:
14015: =item freshen_cache
14016:
14017: If defined, and the environment cache for the course is valid, it is
14018: returned in the returned hash.
14019:
14020: =item one_time
14021:
14022: If defined, the last cache time is set to _now_
14023:
14024: =item user
14025:
14026: If defined, the supplied username is used instead of the current user.
14027:
14028:
14029: =back
14030:
1.191 harris41 14031: =item *
14032:
1.624 albertel 14033: resdata($name,$domain,$type,@which) : request for current parameter
14034: setting for a specific $type, where $type is either 'course' or 'user',
14035: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 14036: answers for 10 minutes.
1.243 albertel 14037:
1.877 foxr 14038: =item *
14039:
14040: get_courseresdata($courseid, $domain) : dump the entire course resource
14041: data base, returning a hash that is keyed by the resource name and has
14042: values that are the resource value. I believe that the timestamps and
14043: versions are also returned.
14044:
1.1236 raeburn 14045: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14046: supplemental content area. This routine caches the number of files for
14047: 10 minutes.
14048:
1.243 albertel 14049: =back
14050:
14051: =head2 Course Modification
14052:
14053: =over 4
1.191 harris41 14054:
14055: =item *
14056:
1.243 albertel 14057: writecoursepref($courseid,%prefs) : write preferences (environment
14058: database) for a course
1.191 harris41 14059:
14060: =item *
14061:
1.1011 raeburn 14062: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14063:
14064: =item *
14065:
1.1038 raeburn 14066: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 14067:
1.1167 droeschl 14068: =item *
14069:
14070: is_course($courseid), is_course($cdom, $cnum)
14071:
14072: Accepts either a combined $courseid (in the form of domain_courseid) or the
14073: two component version $cdom, $cnum. It checks if the specified course exists.
14074:
14075: Returns:
14076: undef if the course doesn't exist, otherwise
14077: in scalar context the combined courseid.
14078: in list context the two components of the course identifier, domain and
14079: courseid.
14080:
1.243 albertel 14081: =back
14082:
14083: =head2 Resource Subroutines
14084:
14085: =over 4
1.191 harris41 14086:
14087: =item *
14088:
1.243 albertel 14089: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 14090:
14091: =item *
14092:
1.243 albertel 14093: repcopy($filename) : subscribes to the requested file, and attempts to
14094: replicate from the owning library server, Might return
1.607 raeburn 14095: 'unavailable', 'not_found', 'forbidden', 'ok', or
14096: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 14097: resource. Expects the local filesystem pathname
14098: (/home/httpd/html/res/....)
14099:
14100: =back
14101:
14102: =head2 Resource Information
14103:
14104: =over 4
1.191 harris41 14105:
14106: =item *
14107:
1.1228 raeburn 14108: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
14109: and returns the value of a variety of different possible values,
14110: $varname should be a request string, and the other parameters can be
14111: used to specify who and what one is asking about. Ordinarily, $cid
14112: does not need to be specified, as it is retrived from
14113: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14114: within lonuserstate::loadmap() when initializing a course, before
14115: $env{'request.course.id'} has been set, so it needs to be provided
14116: in that one case.
1.243 albertel 14117:
14118: Possible values for $varname are environment.lastname (or other item
14119: from the envirnment hash), user.name (or someother aspect about the
14120: user), resource.0.maxtries (or some other part and parameter of a
14121: resource)
1.204 albertel 14122:
14123: =item *
14124:
1.243 albertel 14125: directcondval($number) : get current value of a condition; reads from a state
14126: string
1.204 albertel 14127:
14128: =item *
14129:
1.243 albertel 14130: condval($condidx) : value of condition index based on state
1.204 albertel 14131:
14132: =item *
14133:
1.243 albertel 14134: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14135: resource's metadata, $what should be either a specific key, or either
14136: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14137: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14138:
14139: this function automatically caches all requests
1.191 harris41 14140:
14141: =item *
14142:
1.243 albertel 14143: metadata_query($query,$custom,$customshow) : make a metadata query against the
14144: network of library servers; returns file handle of where SQL and regex results
14145: will be stored for query
1.191 harris41 14146:
14147: =item *
14148:
1.1282 raeburn 14149: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14150: return symbolic list entry (all arguments optional).
14151:
14152: Args: filename is the filename (including path) for the file for which a symb
14153: is required; donotrecurse, if true will prevent calls to allowed() being made
14154: to check access status if more than one resource was found in the bighash
14155: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14156: a randompick); ignorecachednull, if true will prevent a symb of '' being
14157: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14158: cause possible symbs to be checked to determine if they are subject to content
14159: blocking, if so they will not be included as possible symbs; possibles is a
14160: ref to a hash, which, as a side effect, will be populated with all possible
14161: symbs (content blocking not tested).
14162:
1.243 albertel 14163: returns the data handle
1.191 harris41 14164:
14165: =item *
14166:
1.1190 raeburn 14167: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
14168: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 14169: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 14170: on failure, user must be in a course, as it assumes the existence of
14171: the course initial hash, and uses $env('request.course.id'}. The third
14172: arg is an optional reference to a scalar. If this arg is passed in the
14173: call to symbverify, it will be set to 1 if the symb has been set to be
14174: encrypted; otherwise it will be null.
1.191 harris41 14175:
14176: =item *
14177:
1.243 albertel 14178: symbclean($symb) : removes versions numbers from a symb, returns the
14179: cleaned symb
1.191 harris41 14180:
14181: =item *
14182:
1.243 albertel 14183: is_on_map($uri) : checks if the $uri is somewhere on the current
14184: course map, user must be in a course for it to work.
1.191 harris41 14185:
14186: =item *
14187:
1.243 albertel 14188: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 14189:
14190: =item *
14191:
1.243 albertel 14192: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14193: a random seed, all arguments are optional, if they aren't sent it uses the
14194: environment to derive them. Note: if symb isn't sent and it can't get one
14195: from &symbread it will use the current time as its return value
1.191 harris41 14196:
14197: =item *
14198:
1.243 albertel 14199: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14200: unfakeable, receipt
1.191 harris41 14201:
14202: =item *
14203:
1.620 albertel 14204: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 14205:
14206: =item *
14207:
1.243 albertel 14208: countacc($url) : count the number of accesses to a given URL
1.191 harris41 14209:
14210: =item *
14211:
1.243 albertel 14212: 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 14213:
14214: =item *
14215:
1.243 albertel 14216: 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 14217:
14218: =item *
14219:
1.243 albertel 14220: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 14221:
14222: =item *
14223:
1.243 albertel 14224: devalidate($symb) : devalidate temporary spreadsheet calculations,
14225: forcing spreadsheet to reevaluate the resource scores next time.
14226:
1.1195 raeburn 14227: =item *
14228:
1.1196 raeburn 14229: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14230: when viewing in course context.
1.1195 raeburn 14231:
1.1196 raeburn 14232: input: six args -- filename (decluttered), course number, course domain,
14233: url, symb (if registered) and group (if this is a
14234: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 14235:
1.1196 raeburn 14236: output: array of five scalars --
1.1195 raeburn 14237: $cfile -- url for file editing if editable on current server
14238: $home -- homeserver of resource (i.e., for author if published,
14239: or course if uploaded.).
14240: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 14241: $forceedit -- 1 if icon/link should be to go to edit mode
14242: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 14243:
14244: =item *
14245:
14246: is_course_upload($file,$cnum,$cdom)
14247:
14248: Used in course context to determine if current file was uploaded to
14249: the course (i.e., would be found in /userfiles/docs on the course's
14250: homeserver.
14251:
14252: input: 3 args -- filename (decluttered), course number and course domain.
14253: output: boolean -- 1 if file was uploaded.
14254:
1.243 albertel 14255: =back
14256:
14257: =head2 Storing/Retreiving Data
14258:
14259: =over 4
1.191 harris41 14260:
14261: =item *
14262:
1.1269 raeburn 14263: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14264: permanently for this url; hashref needs to be given and should be a \%hashname;
14265: the remaining args aren't required and if they aren't passed or are '' they will
14266: be derived from the env (with the exception of $laststore, which is an
14267: optional arg used when a user's submission is stored in grading).
14268: $laststore is $version=$timestamp, where $version is the most recent version
14269: number retrieved for the corresponding $symb in the $namespace db file, and
14270: $timestamp is the timestamp for that transaction (UNIX time).
14271: $laststore is currently only passed when cstore() is called by
14272: structuretags::finalize_storage().
1.191 harris41 14273:
14274: =item *
14275:
1.1269 raeburn 14276: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14277: but uses critical subroutine
1.191 harris41 14278:
14279: =item *
14280:
1.243 albertel 14281: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14282: all args are optional
1.191 harris41 14283:
14284: =item *
14285:
1.717 albertel 14286: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14287: dumps the complete (or key matching regexp) namespace into a hash
14288: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14289: normally &store()ed into
14290:
14291: $range should be either an integer '100' (give me the first 100
14292: matching records)
14293: or be two integers sperated by a - with no spaces
14294: '30-50' (give me the 30th through the 50th matching
14295: records)
14296:
14297:
14298: =item *
14299:
1.1269 raeburn 14300: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 14301: replaces a &store() version of data with a replacement set of data
14302: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 14303: reference. If $tolog is true, the transaction is logged in the courselog
14304: with an action=PUTSTORE.
1.717 albertel 14305:
14306: =item *
14307:
1.243 albertel 14308: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14309: works very similar to store/cstore, but all data is stored in a
14310: temporary location and can be reset using tmpreset, $storehash should
14311: be a hash reference, returns nothing on success
1.191 harris41 14312:
14313: =item *
14314:
1.243 albertel 14315: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14316: similar to restore, but all data is stored in a temporary location and
14317: can be reset using tmpreset. Returns a hash of values on success,
14318: error string otherwise.
1.191 harris41 14319:
14320: =item *
14321:
1.243 albertel 14322: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14323: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 14324:
14325: =item *
14326:
1.243 albertel 14327: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14328: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 14329:
14330: =item *
14331:
1.243 albertel 14332: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14333: namesp ($udom and $uname are optional)
1.191 harris41 14334:
14335: =item *
14336:
1.702 albertel 14337: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 14338: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 14339: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 14340:
1.702 albertel 14341: $range should be either an integer '100' (give me the first 100
14342: matching records)
14343: or be two integers sperated by a - with no spaces
14344: '30-50' (give me the 30th through the 50th matching
14345: records)
1.449 matthew 14346: =item *
14347:
14348: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14349: $store can be a scalar, an array reference, or if the amount to be
14350: incremented is > 1, a hash reference.
14351:
14352: ($udom and $uname are optional)
1.191 harris41 14353:
14354: =item *
14355:
1.243 albertel 14356: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14357: ($udom and $uname are optional)
1.191 harris41 14358:
14359: =item *
14360:
1.243 albertel 14361: cput($namespace,$storehash,$udom,$uname) : critical put
14362: ($udom and $uname are optional)
1.191 harris41 14363:
14364: =item *
14365:
1.748 albertel 14366: newput($namespace,$storehash,$udom,$uname) :
14367:
14368: Attempts to store the items in the $storehash, but only if they don't
14369: currently exist, if this succeeds you can be certain that you have
14370: successfully created a new key value pair in the $namespace db.
14371:
14372:
14373: Args:
14374: $namespace: name of database to store values to
14375: $storehash: hashref to store to the db
14376: $udom: (optional) domain of user containing the db
14377: $uname: (optional) name of user caontaining the db
14378:
14379: Returns:
14380: 'ok' -> succeeded in storing all keys of $storehash
14381: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14382: least <key> already existed in the db (other
14383: requested keys may also already exist)
1.967 bisitz 14384: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 14385: 'con_lost' -> unable to contact request server
14386: 'refused' -> action was not allowed by remote machine
14387:
14388:
14389: =item *
14390:
1.243 albertel 14391: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14392: reference filled in from namesp (encrypts the return communication)
14393: ($udom and $uname are optional)
1.191 harris41 14394:
14395: =item *
14396:
1.243 albertel 14397: log($udom,$name,$home,$message) : write to permanent log for user; use
14398: critical subroutine
14399:
1.806 raeburn 14400: =item *
14401:
1.860 raeburn 14402: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14403: array reference filled in from namespace found in domain level on either
14404: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 14405:
14406: =item *
14407:
1.860 raeburn 14408: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14409: domain level either on specified domain server ($uhome) or primary domain
14410: server ($udom and $uhome are optional)
1.806 raeburn 14411:
1.943 raeburn 14412: =item *
14413:
1.1240 raeburn 14414: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14415: for: authentication, language, quotas, timezone, date locale, and portal URL in
14416: the target domain.
14417:
14418: May also include additional key => value pairs for the following groups:
14419:
14420: =over
14421:
14422: =item
14423: disk quotas (MB allocated by default to portfolios and authoring spaces).
14424:
14425: =over
14426:
14427: =item defaultquota, authorquota
14428:
14429: =back
14430:
14431: =item
14432: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14433: portfolio for users).
14434:
14435: =over
14436:
14437: =item
14438: aboutme, blog, webdav, portfolio
14439:
14440: =back
14441:
14442: =item
14443: requestcourses: ability to request courses, and how requests are processed.
14444:
14445: =over
14446:
14447: =item
1.1305 raeburn 14448: official, unofficial, community, textbook, placement
1.1240 raeburn 14449:
14450: =back
14451:
14452: =item
14453: inststatus: types of institutional affiliation, and order in which they are displayed.
14454:
14455: =over
14456:
14457: =item
1.1256 raeburn 14458: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 14459:
14460: =back
14461:
14462: =item
14463: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14464: for course's uploaded content.
14465:
14466: =over
14467:
14468: =item
1.1246 raeburn 14469: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 14470: communityquota, textbookquota, placementquota
1.1240 raeburn 14471:
14472: =back
14473:
14474: =item
14475: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14476: on your servers.
14477:
14478: =over
14479:
14480: =item
14481: remotesessions, hostedsessions
14482:
14483: =back
14484:
14485: =back
14486:
14487: In cases where a domain coordinator has never used the "Set Domain Configuration"
14488: utility to create a configuration.db file on a domain's primary library server
14489: only the following domain defaults: auth_def, auth_arg_def, lang_def
14490: -- corresponding values are authentication type (internal, krb4, krb5,
14491: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
14492: will be available. Values are retrieved from cache (if current), unless the
14493: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14494: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14495:
14496: Typical usage:
1.943 raeburn 14497:
1.1240 raeburn 14498: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 14499:
1.243 albertel 14500: =back
14501:
14502: =head2 Network Status Functions
14503:
14504: =over 4
1.191 harris41 14505:
14506: =item *
14507:
1.1137 raeburn 14508: dirlist() : return directory list based on URI (first arg).
14509:
14510: Inputs: 1 required, 5 optional.
14511:
14512: =over
14513:
14514: =item
14515: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14516:
14517: =item
14518: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
14519:
14520: =item
14521: $username - username of user/course to be listed. Extracted from $uri if absent.
14522:
14523: =item
14524: $getpropath - boolean: 1 if prepend path using &propath().
14525:
14526: =item
14527: $getuserdir - boolean: 1 if prepend path for "userfiles".
14528:
14529: =item
14530: $alternateRoot - path to prepend in place of path from $uri.
14531:
14532: =back
14533:
14534: Returns: Array of up to two items.
14535:
14536: =over
14537:
14538: a reference to an array of files/subdirectories
14539:
14540: =over
14541:
14542: Each element in the array of files/subdirectories is a & separated list of
14543: item name and the result of running stat on the item. If dirlist was requested
14544: for a file instead of a directory, the item name will be ''. For a directory
14545: listing, if the item is a metadata file, the element will end &N&M
14546: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14547: default copyright set (1).
14548:
14549: =back
14550:
14551: a scalar containing error condition (if encountered).
14552:
14553: =over
14554:
14555: =item
14556: no_host (no homeserver identified for $username:$domain).
14557:
14558: =item
14559: no_such_host (server contacted for listing not identified as valid host).
14560:
14561: =item
14562: con_lost (connection to remote server failed).
14563:
14564: =item
14565: refused (invalid $username:$domain received on lond side).
14566:
14567: =item
14568: no_such_dir (directory at specified path on lond side does not exist).
14569:
14570: =item
14571: empty (directory at specified path on lond side is empty).
14572:
14573: =over
14574:
14575: This is currently not encountered because the &ls3, &ls2,
14576: &ls (_handler) routines on the lond side do not filter out
14577: . and .. from a directory listing.
14578:
14579: =back
14580:
14581: =back
14582:
14583: =back
1.191 harris41 14584:
14585: =item *
14586:
1.243 albertel 14587: spareserver() : find server with least workload from spare.tab
14588:
1.986 foxr 14589:
14590: =item *
14591:
14592: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14593: if there is no corresponding loncapa host.
14594:
1.243 albertel 14595: =back
14596:
1.986 foxr 14597:
1.243 albertel 14598: =head2 Apache Request
14599:
14600: =over 4
1.191 harris41 14601:
14602: =item *
14603:
1.243 albertel 14604: ssi($url,%hash) : server side include, does a complete request cycle on url to
14605: localhost, posts hash
14606:
14607: =back
14608:
14609: =head2 Data to String to Data
14610:
14611: =over 4
1.191 harris41 14612:
14613: =item *
14614:
1.243 albertel 14615: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14616: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14617:
14618: =item *
14619:
1.243 albertel 14620: hashref2str($hashref) : convert a hashref into a string complete with
14621: escaping and '=' and '&' separators, supports elements that are
14622: arrayrefs and hashrefs
1.191 harris41 14623:
14624: =item *
14625:
1.243 albertel 14626: arrayref2str($arrayref) : convert an arrayref into a string complete
14627: with escaping and '&' separators, supports elements that are arrayrefs
14628: and hashrefs
1.191 harris41 14629:
14630: =item *
14631:
1.243 albertel 14632: str2hash($string) : convert string to hash using unescaping and
14633: splitting on '=' and '&', supports elements that are arrayrefs and
14634: hashrefs
1.191 harris41 14635:
14636: =item *
14637:
1.243 albertel 14638: str2array($string) : convert string to hash using unescaping and
14639: splitting on '&', supports elements that are arrayrefs and hashrefs
14640:
14641: =back
14642:
14643: =head2 Logging Routines
14644:
14645:
14646: These routines allow one to make log messages in the lonnet.log and
14647: lonnet.perm logfiles.
1.191 harris41 14648:
1.1119 foxr 14649: =over 4
14650:
1.191 harris41 14651: =item *
14652:
1.243 albertel 14653: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14654:
14655: =item *
14656:
1.243 albertel 14657: logthis() : append message to the normal lonnet.log file, it gets
14658: preiodically rolled over and deleted.
1.191 harris41 14659:
14660: =item *
14661:
1.243 albertel 14662: logperm() : append a permanent message to lonnet.perm.log, this log
14663: file never gets deleted by any automated portion of the system, only
14664: messages of critical importance should go in here.
14665:
1.1119 foxr 14666:
1.243 albertel 14667: =back
14668:
14669: =head2 General File Helper Routines
14670:
14671: =over 4
1.191 harris41 14672:
14673: =item *
14674:
1.481 raeburn 14675: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14676: (a) files in /uploaded
14677: (i) If a local copy of the file exists -
14678: compares modification date of local copy with last-modified date for
14679: definitive version stored on home server for course. If local copy is
14680: stale, requests a new version from the home server and stores it.
14681: If the original has been removed from the home server, then local copy
14682: is unlinked.
14683: (ii) If local copy does not exist -
14684: requests the file from the home server and stores it.
14685:
14686: If $caller is 'uploadrep':
14687: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14688: for request for files originally uploaded via DOCS.
14689: - returns 'ok' if fresh local copy now available, -1 otherwise.
14690:
14691: Otherwise:
14692: This indicates a call from the content generation phase of the request.
14693: - returns the entire contents of the file or -1.
14694:
14695: (b) files in /res
14696: - returns the entire contents of a file or -1;
14697: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14698:
1.712 albertel 14699:
14700: =item *
14701:
14702: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14703: reference
14704:
14705: returns either a stat() list of data about the file or an empty list
14706: if the file doesn't exist or couldn't find out about it (connection
14707: problems or user unknown)
14708:
1.191 harris41 14709: =item *
14710:
1.243 albertel 14711: filelocation($dir,$file) : returns file system location of a file
14712: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14713: directory that relative $file lookups are to looked in ($dir of /a/dir
14714: and a file of ../bob will become /a/bob)
1.191 harris41 14715:
14716: =item *
14717:
14718: hreflocation($dir,$file) : returns file system location or a URL; same as
14719: filelocation except for hrefs
14720:
14721: =item *
14722:
1.1261 raeburn 14723: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14724: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 14725:
1.243 albertel 14726: =back
14727:
1.608 albertel 14728: =head2 Usererfile file routines (/uploaded*)
14729:
14730: =over 4
14731:
14732: =item *
14733:
14734: userfileupload(): main rotine for putting a file in a user or course's
14735: filespace, arguments are,
14736:
1.620 albertel 14737: formname - required - this is the name of the element in $env where the
1.608 albertel 14738: filename, and the contents of the file to create/modifed exist
1.620 albertel 14739: the filename is in $env{'form.'.$formname.'.filename'} and the
14740: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 14741: context - if coursedoc, store the file in the course of the active role
14742: of the current user;
14743: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14744: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 14745: subdir - required - subdirectory to put the file in under ../userfiles/
14746: if undefined, it will be placed in "unknown"
14747:
14748: (This routine calls clean_filename() to remove any dangerous
14749: characters from the filename, and then calls finuserfileupload() to
14750: complete the transaction)
14751:
14752: returns either the url of the uploaded file (/uploaded/....) if successful
14753: and /adm/notfound.html if unsuccessful
14754:
14755: =item *
14756:
14757: clean_filename(): routine for cleaing a filename up for storage in
14758: userfile space, argument is:
14759:
14760: filename - proposed filename
14761:
14762: returns: the new clean filename
14763:
14764: =item *
14765:
1.1090 raeburn 14766: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 14767: userspace, probably shouldn't be called directly
14768:
14769: docuname: username or courseid of destination for the file
14770: docudom: domain of user/course of destination for the file
14771: formname: same as for userfileupload()
1.1090 raeburn 14772: fname: filename (including subdirectories) for the file
14773: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14774: allfiles: reference to hash used to store objects found by parser
14775: codebase: reference to hash used for codebases of java objects found by parser
14776: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14777: thumbheight: height (pixels) of thumbnail to be created for uploaded image
14778: resizewidth: width to be used to resize image using resizeImage from ImageMagick
14779: resizeheight: height to be used to resize image using resizeImage from ImageMagick
14780: context: if 'overwrite', will move the uploaded file from its temporary location to
14781: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 14782: mimetype: reference to scalar to accommodate mime type determined
14783: from File::MMagic if $parser = parse.
1.608 albertel 14784:
14785: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 14786: and /adm/notfound.html if unsuccessful (or an error message if context
14787: was 'overwrite').
14788:
1.608 albertel 14789:
14790: =item *
14791:
14792: renameuserfile(): renames an existing userfile to a new name
14793:
14794: Args:
14795: docuname: username or courseid of destination for the file
14796: docudom: domain of user/course of destination for the file
14797: old: current file name (including any subdirs under userfiles)
14798: new: desired file name (including any subdirs under userfiles)
14799:
14800: =item *
14801:
14802: mkdiruserfile(): creates a directory is a userfiles dir
14803:
14804: Args:
14805: docuname: username or courseid of destination for the file
14806: docudom: domain of user/course of destination for the file
14807: dir: dir to create (including any subdirs under userfiles)
14808:
14809: =item *
14810:
14811: removeuserfile(): removes a file that exists in userfiles
14812:
14813: Args:
14814: docuname: username or courseid of destination for the file
14815: docudom: domain of user/course of destination for the file
14816: fname: filname to delete (including any subdirs under userfiles)
14817:
14818: =item *
14819:
14820: removeuploadedurl(): convience function for removeuserfile()
14821:
14822: Args:
14823: url: a full /uploaded/... url to delete
14824:
1.747 albertel 14825: =item *
14826:
14827: get_portfile_permissions():
14828: Args:
14829: domain: domain of user or course contain the portfolio files
14830: user: name of user or num of course contain the portfolio files
14831: Returns:
14832: hashref of a dump of the proper file_permissions.db
14833:
14834:
14835: =item *
14836:
14837: get_access_controls():
14838:
14839: Args:
14840: current_permissions: the hash ref returned from get_portfile_permissions()
14841: group: (optional) the group you want the files associated with
14842: file: (optional) the file you want access info on
14843:
14844: Returns:
1.749 raeburn 14845: a hash (keys are file names) of hashes containing
14846: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14847: values are XML containing access control settings (see below)
1.747 albertel 14848:
14849: Internal notes:
14850:
1.749 raeburn 14851: access controls are stored in file_permissions.db as key=value pairs.
14852: key -> path to file/file_name\0uniqueID:scope_end_start
14853: where scope -> public,guest,course,group,domains or users.
14854: end -> UNIX time for end of access (0 -> no end date)
14855: start -> UNIX time for start of access
14856:
14857: value -> XML description of access control
14858: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14859: <start></start>
14860: <end></end>
14861:
14862: <password></password> for scope type = guest
14863:
14864: <domain></domain> for scope type = course or group
14865: <number></number>
14866: <roles id="">
14867: <role></role>
14868: <access></access>
14869: <section></section>
14870: <group></group>
14871: </roles>
14872:
14873: <dom></dom> for scope type = domains
14874:
14875: <users> for scope type = users
14876: <user>
14877: <uname></uname>
14878: <udom></udom>
14879: </user>
14880: </users>
14881: </scope>
14882:
14883: Access data is also aggregated for each file in an additional key=value pair:
14884: key -> path to file/file_name\0accesscontrol
14885: value -> reference to hash
14886: hash contains key = value pairs
14887: where key = uniqueID:scope_end_start
14888: value = UNIX time record was last updated
14889:
14890: Used to improve speed of look-ups of access controls for each file.
14891:
14892: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14893:
1.1198 raeburn 14894: =item *
14895:
1.749 raeburn 14896: modify_access_controls():
14897:
14898: Modifies access controls for a portfolio file
14899: Args
14900: 1. file name
14901: 2. reference to hash of required changes,
14902: 3. domain
14903: 4. username
14904: where domain,username are the domain of the portfolio owner
14905: (either a user or a course)
14906:
14907: Returns:
14908: 1. result of additions or updates ('ok' or 'error', with error message).
14909: 2. result of deletions ('ok' or 'error', with error message).
14910: 3. reference to hash of any new or updated access controls.
14911: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14912: key = integer (inbound ID)
1.1198 raeburn 14913: value = uniqueID
14914:
14915: =item *
14916:
14917: get_timebased_id():
14918:
14919: Attempts to get a unique timestamp-based suffix for use with items added to a
14920: course via the Course Editor (e.g., folders, composite pages,
14921: group bulletin boards).
14922:
14923: Args: (first three required; six others optional)
14924:
14925: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14926: docssequence, or name of group
14927:
14928: 2. keyid (alphanumeric): name of temporary locking key in hash,
14929: e.g., num, boardids
14930:
14931: 3. namespace: name of gdbm file used to store suffixes already assigned;
14932: file will be named nohist_namespace.db
14933:
14934: 4. cdom: domain of course; default is current course domain from %env
14935:
14936: 5. cnum: course number; default is current course number from %env
14937:
14938: 6. idtype: set to concat if an additional digit is to be appended to the
14939: unix timestamp to form the suffix, if the plain timestamp is already
14940: in use. Default is to not do this, but simply increment the unix
14941: timestamp by 1 until a unique key is obtained.
14942:
14943: 7. who: holder of locking key; defaults to user:domain for user.
14944:
14945: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14946: retrying); default is 3.
14947:
14948: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14949:
14950: Returns:
14951:
14952: 1. suffix obtained (numeric)
14953:
14954: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14955:
14956: 3. error: contains (localized) error message if an error occurred.
14957:
1.747 albertel 14958:
1.608 albertel 14959: =back
14960:
1.243 albertel 14961: =head2 HTTP Helper Routines
14962:
14963: =over 4
14964:
1.191 harris41 14965: =item *
14966:
14967: escape() : unpack non-word characters into CGI-compatible hex codes
14968:
14969: =item *
14970:
14971: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14972:
1.243 albertel 14973: =back
14974:
14975: =head1 PRIVATE SUBROUTINES
14976:
14977: =head2 Underlying communication routines (Shouldn't call)
14978:
14979: =over 4
14980:
14981: =item *
14982:
14983: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14984:
14985: =item *
14986:
14987: reply() : uses subreply to send a message to remote machine, logs all failures
14988:
14989: =item *
14990:
14991: critical() : passes a critical message to another server; if cannot
14992: get through then place message in connection buffer directory and
14993: returns con_delayed, if incapable of saving message, returns
14994: con_failed
14995:
14996: =item *
14997:
14998: reconlonc() : tries to reconnect lonc client processes.
14999:
15000: =back
15001:
15002: =head2 Resource Access Logging
15003:
15004: =over 4
15005:
15006: =item *
15007:
15008: flushcourselogs() : flush (save) buffer logs and access logs
15009:
15010: =item *
15011:
15012: courselog($what) : save message for course in hash
15013:
15014: =item *
15015:
15016: courseacclog($what) : save message for course using &courselog(). Perform
15017: special processing for specific resource types (problems, exams, quizzes, etc).
15018:
1.191 harris41 15019: =item *
15020:
15021: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15022: as a PerlChildExitHandler
1.243 albertel 15023:
15024: =back
15025:
15026: =head2 Other
15027:
15028: =over 4
15029:
15030: =item *
15031:
15032: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 15033:
15034: =back
15035:
15036: =cut
1.877 foxr 15037:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>