Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1339
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1339 ! raeburn 4: # $Id: lonnet.pm,v 1.1338 2017/02/25 20:30:57 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.1337 raeburn 653: my ($linkname,$pubname);
1.1155 raeburn 654: if ($name eq '') {
655: $name = 'lonID';
1.1337 raeburn 656: $linkname = 'lonLinkID';
657: $pubname = 'lonPubID';
1.1155 raeburn 658: }
659: my $lonid=$cookies{$name};
1.1337 raeburn 660: if (!$lonid) {
661: if (($name eq 'lonID') && ($ENV{'SERVER_PORT'} != 443) && ($linkname)) {
662: $lonid=$cookies{$linkname};
663: }
664: if (!$lonid) {
665: if (($name eq 'lonID') && ($pubname)) {
666: $lonid=$cookies{$pubname};
667: }
668: }
669: }
1.916 albertel 670: return undef if (!$lonid);
671:
672: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 673: my $lonidsdir;
674: if ($name eq 'lonDAV') {
675: $lonidsdir=$r->dir_config('lonDAVsessDir');
676: } else {
677: $lonidsdir=$r->dir_config('lonIDsDir');
678: }
1.916 albertel 679: return undef if (!-e "$lonidsdir/$handle.id");
680:
1.917 albertel 681: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
682: return undef if (!$opened);
1.916 albertel 683:
684: flock($idf,LOCK_SH);
685: my %disk_env;
686: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
687: &GDBM_READER(),0640)) {
688: return undef;
689: }
690:
691: if (!defined($disk_env{'user.name'})
692: || !defined($disk_env{'user.domain'})) {
693: return undef;
694: }
1.1245 raeburn 695:
696: if (ref($userhashref) eq 'HASH') {
697: $userhashref->{'name'} = $disk_env{'user.name'};
698: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212 raeburn 699: }
1.1245 raeburn 700:
1.916 albertel 701: return $handle;
702: }
703:
1.830 albertel 704: sub timed_flock {
705: my ($file,$lock_type) = @_;
706: my $failed=0;
707: eval {
708: local $SIG{__DIE__}='DEFAULT';
709: local $SIG{ALRM}=sub {
710: $failed=1;
711: die("failed lock");
712: };
713: alarm(13);
714: flock($file,$lock_type);
715: alarm(0);
716: };
717: if ($failed) {
718: return undef;
719: } else {
720: return 1;
721: }
722: }
723:
1.5 www 724: # ---------------------------------------------------------- Append Environment
725:
726: sub appenv {
1.949 raeburn 727: my ($newenv,$roles) = @_;
728: if (ref($newenv) eq 'HASH') {
729: foreach my $key (keys(%{$newenv})) {
730: my $refused = 0;
731: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
732: $refused = 1;
733: if (ref($roles) eq 'ARRAY') {
1.1250 raeburn 734: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 735: if (grep(/^\Q$role\E$/,@{$roles})) {
736: $refused = 0;
737: }
738: }
739: }
740: if ($refused) {
741: &logthis("<font color=\"blue\">WARNING: ".
742: "Attempt to modify environment ".$key." to ".$newenv->{$key}
743: .'</font>');
744: delete($newenv->{$key});
745: } else {
746: $env{$key}=$newenv->{$key};
747: }
748: }
749: my $opened = open(my $env_file,'+<',$env{'user.environment'});
750: if ($opened
751: && &timed_flock($env_file,LOCK_EX)
752: &&
753: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
754: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
755: while (my ($key,$value) = each(%{$newenv})) {
756: $disk_env{$key} = $value;
757: }
758: untie(%disk_env);
1.35 www 759: }
1.191 harris41 760: }
1.56 www 761: return 'ok';
762: }
763: # ----------------------------------------------------- Delete from Environment
764:
765: sub delenv {
1.1104 raeburn 766: my ($delthis,$regexp,$roles) = @_;
767: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
768: my $refused = 1;
769: if (ref($roles) eq 'ARRAY') {
770: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
771: if (grep(/^\Q$role\E$/,@{$roles})) {
772: $refused = 0;
773: }
774: }
775: if ($refused) {
776: &logthis("<font color=\"blue\">WARNING: ".
777: "Attempt to delete from environment ".$delthis);
778: return 'error';
779: }
1.56 www 780: }
1.917 albertel 781: my $opened = open(my $env_file,'+<',$env{'user.environment'});
782: if ($opened
1.915 albertel 783: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 784: &&
785: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
786: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 787: foreach my $key (keys(%disk_env)) {
1.987 raeburn 788: if ($regexp) {
789: if ($key=~/^$delthis/) {
790: delete($env{$key});
791: delete($disk_env{$key});
792: }
793: } else {
794: if ($key=~/^\Q$delthis\E/) {
795: delete($env{$key});
796: delete($disk_env{$key});
797: }
798: }
1.448 albertel 799: }
1.783 albertel 800: untie(%disk_env);
1.5 www 801: }
802: return 'ok';
1.369 albertel 803: }
804:
1.790 albertel 805: sub get_env_multiple {
806: my ($name) = @_;
807: my @values;
808: if (defined($env{$name})) {
809: # exists is it an array
810: if (ref($env{$name})) {
811: @values=@{ $env{$name} };
812: } else {
813: $values[0]=$env{$name};
814: }
815: }
816: return(@values);
817: }
818:
1.958 www 819: # ------------------------------------------------------------------- Locking
820:
821: sub set_lock {
822: my ($text)=@_;
823: $locknum++;
824: my $id=$$.'-'.$locknum;
825: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
826: 'session.lock.'.$id => $text});
827: return $id;
828: }
829:
830: sub get_locks {
831: my $num=0;
832: my %texts=();
833: foreach my $lock (split(/\,/,$env{'session.locks'})) {
834: if ($lock=~/\w/) {
835: $num++;
836: $texts{$lock}=$env{'session.lock.'.$lock};
837: }
838: }
839: return ($num,%texts);
840: }
841:
842: sub remove_lock {
843: my ($id)=@_;
844: my $newlocks='';
845: foreach my $lock (split(/\,/,$env{'session.locks'})) {
846: if (($lock=~/\w/) && ($lock ne $id)) {
847: $newlocks.=','.$lock;
848: }
849: }
850: &appenv({'session.locks' => $newlocks});
851: &delenv('session.lock.'.$id);
852: }
853:
854: sub remove_all_locks {
855: my $activelocks=$env{'session.locks'};
856: foreach my $lock (split(/\,/,$env{'session.locks'})) {
857: if ($lock=~/\w/) {
858: &remove_lock($lock);
859: }
860: }
861: }
862:
863:
1.369 albertel 864: # ------------------------------------------ Find out current server userload
865: sub userload {
866: my $numusers=0;
867: {
868: opendir(LONIDS,$perlvar{'lonIDsDir'});
869: my $filename;
870: my $curtime=time;
871: while ($filename=readdir(LONIDS)) {
1.925 albertel 872: next if ($filename eq '.' || $filename eq '..');
873: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 874: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 875: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 876: }
877: closedir(LONIDS);
878: }
879: my $userloadpercent=0;
880: my $maxuserload=$perlvar{'lonUserLoadLim'};
881: if ($maxuserload) {
1.371 albertel 882: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 883: }
1.372 albertel 884: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 885: return $userloadpercent;
1.283 www 886: }
887:
1.1 albertel 888: # ------------------------------ Find server with least workload from spare.tab
1.11 www 889:
1.1 albertel 890: sub spareserver {
1.1083 raeburn 891: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 892: my $spare_server;
1.370 albertel 893: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 894: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
895: : $userloadpercent;
1.1083 raeburn 896: my ($uint_dom,$remotesessions);
897: if (($udom ne '') && (&domain($udom) ne '')) {
898: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
899: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
900: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
901: $remotesessions = $udomdefaults{'remotesessions'};
902: }
1.1123 raeburn 903: my $spareshash = &this_host_spares($udom);
904: if (ref($spareshash) eq 'HASH') {
905: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
906: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279 raeburn 907: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
908: $try_server));
1.1123 raeburn 909: ($spare_server, $lowest_load) =
910: &compare_server_load($try_server, $spare_server, $lowest_load);
911: }
1.1083 raeburn 912: }
1.784 albertel 913:
1.1123 raeburn 914: my $found_server = ($spare_server ne '' && $lowest_load < 100);
915:
916: if (!$found_server) {
917: if (ref($spareshash->{'default'}) eq 'ARRAY') {
918: foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279 raeburn 919: next unless (&spare_can_host($udom,$uint_dom,
920: $remotesessions,$try_server));
1.1123 raeburn 921: ($spare_server, $lowest_load) =
922: &compare_server_load($try_server, $spare_server, $lowest_load);
923: }
924: }
925: }
1.784 albertel 926: }
927:
928: if (!$want_server_name) {
1.968 raeburn 929: my $protocol = 'http';
930: if ($protocol{$spare_server} eq 'https') {
931: $protocol = $protocol{$spare_server};
932: }
1.1001 raeburn 933: if (defined($spare_server)) {
934: my $hostname = &hostname($spare_server);
1.1083 raeburn 935: if (defined($hostname)) {
1.1001 raeburn 936: $spare_server = $protocol.'://'.$hostname;
937: }
938: }
1.784 albertel 939: }
940: return $spare_server;
941: }
942:
943: sub compare_server_load {
1.1253 raeburn 944: my ($try_server, $spare_server, $lowest_load, $required) = @_;
945:
946: if ($required) {
947: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
948: my $remoterev = &get_server_loncaparev(undef,$try_server);
949: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
950: if (($major eq '' && $minor eq '') ||
951: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
952: return ($spare_server,$lowest_load);
953: }
954: }
1.784 albertel 955:
956: my $loadans = &reply('load', $try_server);
957: my $userloadans = &reply('userload',$try_server);
958:
959: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 960: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 961: }
962:
963: my $load;
964: if ($loadans =~ /\d/) {
965: if ($userloadans =~ /\d/) {
966: #both are numbers, pick the bigger one
967: $load = ($loadans > $userloadans) ? $loadans
968: : $userloadans;
1.411 albertel 969: } else {
1.784 albertel 970: $load = $loadans;
1.411 albertel 971: }
1.784 albertel 972: } else {
973: $load = $userloadans;
974: }
975:
976: if (($load =~ /\d/) && ($load < $lowest_load)) {
977: $spare_server = $try_server;
978: $lowest_load = $load;
1.370 albertel 979: }
1.784 albertel 980: return ($spare_server,$lowest_load);
1.202 matthew 981: }
1.914 albertel 982:
983: # --------------------------- ask offload servers if user already has a session
984: sub find_existing_session {
985: my ($udom,$uname) = @_;
1.1123 raeburn 986: my $spareshash = &this_host_spares($udom);
987: if (ref($spareshash) eq 'HASH') {
988: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
989: foreach my $try_server (@{ $spareshash->{'primary'} }) {
990: return $try_server if (&has_user_session($try_server, $udom, $uname));
991: }
992: }
993: if (ref($spareshash->{'default'}) eq 'ARRAY') {
994: foreach my $try_server (@{ $spareshash->{'default'} }) {
995: return $try_server if (&has_user_session($try_server, $udom, $uname));
996: }
997: }
1.914 albertel 998: }
999: return;
1000: }
1001:
1002: # -------------------------------- ask if server already has a session for user
1003: sub has_user_session {
1004: my ($lonid,$udom,$uname) = @_;
1005: my $result = &reply(join(':','userhassession',
1006: map {&escape($_)} ($udom,$uname)),$lonid);
1007: return 1 if ($result eq 'ok');
1008:
1009: return 0;
1010: }
1011:
1.1076 raeburn 1012: # --------- determine least loaded server in a user's domain which allows login
1013:
1014: sub choose_server {
1.1259 raeburn 1015: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076 raeburn 1016: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 1017: my %servers = &get_servers($udom);
1.1076 raeburn 1018: my $lowest_load = 30000;
1.1259 raeburn 1019: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1020: if ($skiploadbal) {
1021: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1022: unless (defined($cached)) {
1023: my $cachetime = 60*60*24;
1024: my %domconfig =
1025: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1026: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1027: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1028: $cachetime);
1029: }
1030: }
1031: }
1.1076 raeburn 1032: foreach my $lonhost (keys(%servers)) {
1.1259 raeburn 1033: if ($skiploadbal) {
1034: if (ref($balancers) eq 'HASH') {
1035: next if (exists($balancers->{$lonhost}));
1036: }
1037: }
1.1115 raeburn 1038: my $loginvia;
1039: if ($checkloginvia) {
1040: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 1041: if ($loginvia) {
1042: my ($server,$path) = split(/:/,$loginvia);
1043: ($login_host, $lowest_load) =
1.1253 raeburn 1044: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 1045: if ($login_host eq $server) {
1046: $portal_path = $path;
1.1151 raeburn 1047: $isredirect = 1;
1.1116 raeburn 1048: }
1049: } else {
1050: ($login_host, $lowest_load) =
1.1253 raeburn 1051: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 1052: if ($login_host eq $lonhost) {
1053: $portal_path = '';
1.1151 raeburn 1054: $isredirect = '';
1.1116 raeburn 1055: }
1056: }
1057: } else {
1.1076 raeburn 1058: ($login_host, $lowest_load) =
1.1253 raeburn 1059: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 1060: }
1061: }
1062: if ($login_host ne '') {
1.1116 raeburn 1063: $hostname = &hostname($login_host);
1.1076 raeburn 1064: }
1.1331 raeburn 1065: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076 raeburn 1066: }
1067:
1.202 matthew 1068: # --------------------------------------------- Try to change a user's password
1069:
1070: sub changepass {
1.799 raeburn 1071: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1072: $currentpass = &escape($currentpass);
1073: $newpass = &escape($newpass);
1.1030 raeburn 1074: my $lonhost = $perlvar{'lonHostID'};
1075: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1076: $server);
1077: if (! $answer) {
1078: &logthis("No reply on password change request to $server ".
1079: "by $uname in domain $udom.");
1080: } elsif ($answer =~ "^ok") {
1081: &logthis("$uname in $udom successfully changed their password ".
1082: "on $server.");
1083: } elsif ($answer =~ "^pwchange_failure") {
1084: &logthis("$uname in $udom was unable to change their password ".
1085: "on $server. The action was blocked by either lcpasswd ".
1086: "or pwchange");
1087: } elsif ($answer =~ "^non_authorized") {
1088: &logthis("$uname in $udom did not get their password correct when ".
1089: "attempting to change it on $server.");
1090: } elsif ($answer =~ "^auth_mode_error") {
1091: &logthis("$uname in $udom attempted to change their password despite ".
1092: "not being locally or internally authenticated on $server.");
1093: } elsif ($answer =~ "^unknown_user") {
1094: &logthis("$uname in $udom attempted to change their password ".
1095: "on $server but were unable to because $server is not ".
1096: "their home server.");
1097: } elsif ($answer =~ "^refused") {
1098: &logthis("$server refused to change $uname in $udom password because ".
1099: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1100: } elsif ($answer =~ "invalid_client") {
1101: &logthis("$server refused to change $uname in $udom password because ".
1102: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1103: }
1104: return $answer;
1.1 albertel 1105: }
1106:
1.169 harris41 1107: # ----------------------- Try to determine user's current authentication scheme
1108:
1109: sub queryauthenticate {
1110: my ($uname,$udom)=@_;
1.456 albertel 1111: my $uhome=&homeserver($uname,$udom);
1112: if (!$uhome) {
1113: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1114: return 'no_host';
1115: }
1116: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1117: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1118: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1119: }
1.456 albertel 1120: return $answer;
1.169 harris41 1121: }
1122:
1.1 albertel 1123: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1124:
1.1 albertel 1125: sub authenticate {
1.1073 raeburn 1126: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1127: $upass=&escape($upass);
1128: $uname= &LONCAPA::clean_username($uname);
1.836 www 1129: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1130: my $newhome;
1.836 www 1131: if ((!$uhome) || ($uhome eq 'no_host')) {
1132: # Maybe the machine was offline and only re-appeared again recently?
1133: &reconlonc();
1134: # One more
1.952 raeburn 1135: $uhome=&homeserver($uname,$udom,1);
1136: if (($uhome eq 'no_host') && $checkdefauth) {
1137: if (defined(&domain($udom,'primary'))) {
1138: $newhome=&domain($udom,'primary');
1139: }
1140: if ($newhome ne '') {
1141: $uhome = $newhome;
1142: }
1143: }
1.836 www 1144: if ((!$uhome) || ($uhome eq 'no_host')) {
1145: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1146: return 'no_host';
1147: }
1.1 albertel 1148: }
1.1073 raeburn 1149: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1150: if ($answer eq 'authorized') {
1.952 raeburn 1151: if ($newhome) {
1152: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1153: return 'no_account_on_host';
1154: } else {
1155: &logthis("User $uname at $udom authorized by $uhome");
1156: return $uhome;
1157: }
1.471 albertel 1158: }
1159: if ($answer eq 'non_authorized') {
1160: &logthis("User $uname at $udom rejected by $uhome");
1161: return 'no_host';
1.9 www 1162: }
1.471 albertel 1163: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1164: return 'no_host';
1165: }
1166:
1.1073 raeburn 1167: sub can_host_session {
1.1074 raeburn 1168: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1169: my $canhost = 1;
1.1074 raeburn 1170: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1171: if (ref($remotesessions) eq 'HASH') {
1172: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1173: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1174: $canhost = 0;
1175: } else {
1176: $canhost = 1;
1177: }
1178: }
1179: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1180: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1181: $canhost = 1;
1182: } else {
1183: $canhost = 0;
1184: }
1185: }
1186: if ($canhost) {
1187: if ($remotesessions->{'version'} ne '') {
1188: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1189: if ($reqmajor ne '' && $reqminor ne '') {
1190: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1191: my $major = $1;
1192: my $minor = $2;
1193: if (($major < $reqmajor ) ||
1194: (($major == $reqmajor) && ($minor < $reqminor))) {
1195: $canhost = 0;
1196: }
1197: } else {
1198: $canhost = 0;
1199: }
1200: }
1201: }
1202: }
1203: }
1204: if ($canhost) {
1205: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1206: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1207: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1208: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1209: if (($uint_dom ne '') &&
1210: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1211: $canhost = 0;
1212: } else {
1213: $canhost = 1;
1214: }
1215: }
1216: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1217: if (($uint_dom ne '') &&
1218: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1219: $canhost = 1;
1220: } else {
1221: $canhost = 0;
1222: }
1223: }
1224: }
1225: }
1226: return $canhost;
1227: }
1228:
1.1083 raeburn 1229: sub spare_can_host {
1230: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1231: my $canhost=1;
1.1279 raeburn 1232: my $try_server_hostname = &hostname($try_server);
1233: my $serverhomeID = &get_server_homeID($try_server_hostname);
1234: my $serverhomedom = &host_domain($serverhomeID);
1235: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1236: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1237: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1238: $canhost = 0;
1239: }
1240: }
1241: if (($canhost) && ($uint_dom)) {
1242: my @intdoms;
1243: my $internet_names = &get_internet_names($try_server);
1244: if (ref($internet_names) eq 'ARRAY') {
1245: @intdoms = @{$internet_names};
1246: }
1247: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1248: my $remoterev = &get_server_loncaparev(undef,$try_server);
1249: $canhost = &can_host_session($udom,$try_server,$remoterev,
1250: $remotesessions,
1251: $defdomdefaults{'hostedsessions'});
1252: }
1.1083 raeburn 1253: }
1254: return $canhost;
1255: }
1256:
1.1123 raeburn 1257: sub this_host_spares {
1258: my ($dom) = @_;
1.1126 raeburn 1259: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1260: my @hosts = ¤t_machine_ids();
1261: foreach my $lonhost (@hosts) {
1262: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1263: $dom_in_use = $dom;
1264: $lonhost_in_use = $lonhost;
1.1123 raeburn 1265: last;
1266: }
1267: }
1.1126 raeburn 1268: if ($dom_in_use ne '') {
1269: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1270: }
1271: if (ref($result) ne 'HASH') {
1272: $lonhost_in_use = $perlvar{'lonHostID'};
1273: $dom_in_use = &host_domain($lonhost_in_use);
1274: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1275: if (ref($result) ne 'HASH') {
1276: $result = \%spareid;
1277: }
1278: }
1279: return $result;
1280: }
1281:
1282: sub spares_for_offload {
1283: my ($dom_in_use,$lonhost_in_use) = @_;
1284: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1285: if (defined($cached)) {
1286: return $result;
1287: } else {
1.1126 raeburn 1288: my $cachetime = 60*60*24;
1289: my %domconfig =
1290: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1291: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1292: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1293: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1294: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1295: }
1296: }
1297: }
1298: }
1.1126 raeburn 1299: return;
1.1123 raeburn 1300: }
1301:
1.1129 raeburn 1302: sub get_lonbalancer_config {
1303: my ($servers) = @_;
1304: my ($currbalancer,$currtargets);
1305: if (ref($servers) eq 'HASH') {
1306: foreach my $server (keys(%{$servers})) {
1307: my %what = (
1308: spareid => 1,
1309: perlvar => 1,
1310: );
1311: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1312: if ($result eq 'ok') {
1313: if (ref($returnhash) eq 'HASH') {
1314: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1315: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1316: $currbalancer = $server;
1317: $currtargets = {};
1318: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1319: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1320: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1321: }
1322: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1323: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1324: }
1325: }
1326: last;
1327: }
1328: }
1329: }
1330: }
1331: }
1332: }
1333: return ($currbalancer,$currtargets);
1334: }
1335:
1336: sub check_loadbalancing {
1.1331 raeburn 1337: my ($uname,$udom,$caller) = @_;
1.1191 raeburn 1338: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1339: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1340: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1341: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1342: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1343: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1344: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1345: my $serverhomedom = &host_domain($lonhost);
1.1307 raeburn 1346: my $domneedscache;
1.1129 raeburn 1347: my $cachetime = 60*60*24;
1348:
1349: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1350: $dom_in_use = $udom;
1351: $homeintdom = 1;
1352: } else {
1353: $dom_in_use = $serverhomedom;
1354: }
1355: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1356: unless (defined($cached)) {
1357: my %domconfig =
1358: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1359: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1360: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307 raeburn 1361: } else {
1362: $domneedscache = $dom_in_use;
1.1129 raeburn 1363: }
1364: }
1365: if (ref($result) eq 'HASH') {
1.1191 raeburn 1366: ($is_balancer,$currtargets,$currrules) =
1367: &check_balancer_result($result,@hosts);
1.1129 raeburn 1368: if ($is_balancer) {
1369: if (ref($currrules) eq 'HASH') {
1370: if ($homeintdom) {
1371: if ($uname ne '') {
1372: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1373: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1374: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1375: $rule_in_effect = $currrules->{'_LC_author'};
1376: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1377: $rule_in_effect = $currrules->{'_LC_adv'}
1378: }
1379: }
1380: if ($rule_in_effect eq '') {
1381: my %userenv = &userenvironment($udom,$uname,'inststatus');
1382: if ($userenv{'inststatus'} ne '') {
1383: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1384: my ($othertitle,$usertypes,$types) =
1385: &Apache::loncommon::sorted_inst_types($udom);
1386: if (ref($types) eq 'ARRAY') {
1387: foreach my $type (@{$types}) {
1388: if (grep(/^\Q$type\E$/,@statuses)) {
1389: if (exists($currrules->{$type})) {
1390: $rule_in_effect = $currrules->{$type};
1391: }
1392: }
1393: }
1394: }
1395: } else {
1396: if (exists($currrules->{'default'})) {
1397: $rule_in_effect = $currrules->{'default'};
1398: }
1399: }
1400: }
1401: } else {
1402: if (exists($currrules->{'default'})) {
1403: $rule_in_effect = $currrules->{'default'};
1404: }
1405: }
1406: } else {
1407: if ($currrules->{'_LC_external'} ne '') {
1408: $rule_in_effect = $currrules->{'_LC_external'};
1409: }
1410: }
1411: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1412: $uname,$udom);
1413: }
1414: }
1415: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1416: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1417: unless (defined($cached)) {
1418: my %domconfig =
1419: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1420: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307 raeburn 1421: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1422: } else {
1423: $domneedscache = $serverhomedom;
1.1129 raeburn 1424: }
1425: }
1426: if (ref($result) eq 'HASH') {
1.1191 raeburn 1427: ($is_balancer,$currtargets,$currrules) =
1428: &check_balancer_result($result,@hosts);
1429: if ($is_balancer) {
1.1129 raeburn 1430: if (ref($currrules) eq 'HASH') {
1431: if ($currrules->{'_LC_internetdom'} ne '') {
1432: $rule_in_effect = $currrules->{'_LC_internetdom'};
1433: }
1434: }
1435: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1436: $uname,$udom);
1437: }
1438: } else {
1439: if ($perlvar{'lonBalancer'} eq 'yes') {
1440: $is_balancer = 1;
1441: $offloadto = &this_host_spares($dom_in_use);
1442: }
1.1307 raeburn 1443: unless (defined($cached)) {
1444: $domneedscache = $serverhomedom;
1445: }
1.1129 raeburn 1446: }
1447: } else {
1448: if ($perlvar{'lonBalancer'} eq 'yes') {
1449: $is_balancer = 1;
1450: $offloadto = &this_host_spares($dom_in_use);
1451: }
1.1307 raeburn 1452: unless (defined($cached)) {
1453: $domneedscache = $serverhomedom;
1454: }
1455: }
1456: if ($domneedscache) {
1457: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129 raeburn 1458: }
1.1176 raeburn 1459: if ($is_balancer) {
1460: my $lowest_load = 30000;
1461: if (ref($offloadto) eq 'HASH') {
1462: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1463: foreach my $try_server (@{$offloadto->{'primary'}}) {
1464: ($otherserver,$lowest_load) =
1465: &compare_server_load($try_server,$otherserver,$lowest_load);
1466: }
1.1129 raeburn 1467: }
1.1176 raeburn 1468: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1469:
1.1176 raeburn 1470: if (!$found_server) {
1471: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1472: foreach my $try_server (@{$offloadto->{'default'}}) {
1473: ($otherserver,$lowest_load) =
1474: &compare_server_load($try_server,$otherserver,$lowest_load);
1475: }
1476: }
1477: }
1478: } elsif (ref($offloadto) eq 'ARRAY') {
1479: if (@{$offloadto} == 1) {
1480: $otherserver = $offloadto->[0];
1481: } elsif (@{$offloadto} > 1) {
1482: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1483: ($otherserver,$lowest_load) =
1484: &compare_server_load($try_server,$otherserver,$lowest_load);
1485: }
1486: }
1487: }
1.1331 raeburn 1488: unless ($caller eq 'login') {
1489: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1490: $is_balancer = 0;
1491: if ($uname ne '' && $udom ne '') {
1492: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1176 raeburn 1493:
1.1331 raeburn 1494: &appenv({'user.loadbalexempt' => $lonhost,
1495: 'user.loadbalcheck.time' => time});
1496: }
1.1176 raeburn 1497: }
1.1129 raeburn 1498: }
1499: }
1500: }
1501: return ($is_balancer,$otherserver);
1502: }
1503:
1.1191 raeburn 1504: sub check_balancer_result {
1505: my ($result,@hosts) = @_;
1506: my ($is_balancer,$currtargets,$currrules);
1507: if (ref($result) eq 'HASH') {
1508: if ($result->{'lonhost'} ne '') {
1509: my $currbalancer = $result->{'lonhost'};
1510: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1511: $is_balancer = 1;
1512: $currtargets = $result->{'targets'};
1513: $currrules = $result->{'rules'};
1514: }
1515: } else {
1516: foreach my $key (keys(%{$result})) {
1517: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1518: (ref($result->{$key}) eq 'HASH')) {
1519: $is_balancer = 1;
1520: $currrules = $result->{$key}{'rules'};
1521: $currtargets = $result->{$key}{'targets'};
1522: last;
1523: }
1524: }
1525: }
1526: }
1527: return ($is_balancer,$currtargets,$currrules);
1528: }
1529:
1.1129 raeburn 1530: sub get_loadbalancer_targets {
1531: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1532: my $offloadto;
1.1175 raeburn 1533: if ($rule_in_effect eq 'none') {
1534: return [$perlvar{'lonHostID'}];
1535: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1536: $offloadto = $currtargets;
1537: } else {
1538: if ($rule_in_effect eq 'homeserver') {
1539: my $homeserver = &homeserver($uname,$udom);
1540: if ($homeserver ne 'no_host') {
1541: $offloadto = [$homeserver];
1542: }
1543: } elsif ($rule_in_effect eq 'externalbalancer') {
1544: my %domconfig =
1545: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1546: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1547: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1548: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1549: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1550: }
1551: }
1552: } else {
1.1178 raeburn 1553: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1554: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1555: if (&hostname($remotebalancer) ne '') {
1556: $offloadto = [$remotebalancer];
1557: }
1558: }
1559: } elsif (&hostname($rule_in_effect) ne '') {
1560: $offloadto = [$rule_in_effect];
1561: }
1562: }
1563: return $offloadto;
1564: }
1565:
1.1127 raeburn 1566: sub internet_dom_servers {
1567: my ($dom) = @_;
1568: my (%uniqservers,%servers);
1569: my $primaryserver = &hostname(&domain($dom,'primary'));
1570: my @machinedoms = &machine_domains($primaryserver);
1571: foreach my $mdom (@machinedoms) {
1572: my %currservers = %servers;
1573: my %server = &get_servers($mdom);
1574: %servers = (%currservers,%server);
1575: }
1576: my %by_hostname;
1577: foreach my $id (keys(%servers)) {
1578: push(@{$by_hostname{$servers{$id}}},$id);
1579: }
1580: foreach my $hostname (sort(keys(%by_hostname))) {
1581: if (@{$by_hostname{$hostname}} > 1) {
1582: my $match = 0;
1583: foreach my $id (@{$by_hostname{$hostname}}) {
1584: if (&host_domain($id) eq $dom) {
1585: $uniqservers{$id} = $hostname;
1586: $match = 1;
1587: }
1588: }
1589: unless ($match) {
1590: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1591: }
1592: } else {
1593: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1594: }
1595: }
1596: return %uniqservers;
1597: }
1598:
1.1 albertel 1599: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1600:
1.599 albertel 1601: my %homecache;
1.1 albertel 1602: sub homeserver {
1.230 stredwic 1603: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1604: my $index="$uname:$udom";
1.426 albertel 1605:
1.599 albertel 1606: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1607:
1608: my %servers = &get_servers($udom,'library');
1609: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1610: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1611: exists($badServerCache{$tryserver}));
1.841 albertel 1612:
1613: my $answer=reply("home:$udom:$uname",$tryserver);
1614: if ($answer eq 'found') {
1615: delete($badServerCache{$tryserver});
1616: return $homecache{$index}=$tryserver;
1617: } elsif ($answer eq 'no_host') {
1618: $badServerCache{$tryserver}=1;
1619: }
1.1 albertel 1620: }
1621: return 'no_host';
1.70 www 1622: }
1623:
1.1300 raeburn 1624: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70 www 1625:
1626: sub idget {
1.1300 raeburn 1627: my ($udom,$idsref,$namespace)=@_;
1.70 www 1628: my %returnhash=();
1.1300 raeburn 1629: my @ids=();
1630: if (ref($idsref) eq 'ARRAY') {
1631: @ids = @{$idsref};
1632: } else {
1633: return %returnhash;
1634: }
1635: if ($namespace eq '') {
1636: $namespace = 'ids';
1637: }
1.70 www 1638:
1.841 albertel 1639: my %servers = &get_servers($udom,'library');
1640: foreach my $tryserver (keys(%servers)) {
1.1299 raeburn 1641: my $idlist=join('&', map { &escape($_); } @ids);
1.1300 raeburn 1642: if ($namespace eq 'ids') {
1643: $idlist=~tr/A-Z/a-z/;
1644: }
1645: my $reply;
1646: if ($namespace eq 'ids') {
1647: $reply=&reply("idget:$udom:".$idlist,$tryserver);
1648: } else {
1649: $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
1650: }
1.841 albertel 1651: my @answer=();
1652: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1653: @answer=split(/\&/,$reply);
1654: } ;
1655: my $i;
1656: for ($i=0;$i<=$#ids;$i++) {
1657: if ($answer[$i]) {
1.1299 raeburn 1658: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300 raeburn 1659: }
1.841 albertel 1660: }
1.1300 raeburn 1661: }
1.70 www 1662: return %returnhash;
1663: }
1664:
1665: # ------------------------------------- Find the IDs behind a list of usernames
1666:
1667: sub idrget {
1668: my ($udom,@unames)=@_;
1669: my %returnhash=();
1.800 albertel 1670: foreach my $uname (@unames) {
1671: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1672: }
1.70 www 1673: return %returnhash;
1674: }
1675:
1.1300 raeburn 1676: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70 www 1677:
1678: sub idput {
1.1300 raeburn 1679: my ($udom,$idsref,$uhom,$namespace)=@_;
1.70 www 1680: my %servers=();
1.1300 raeburn 1681: my %ids=();
1682: my %byid = ();
1683: if (ref($idsref) eq 'HASH') {
1684: %ids=%{$idsref};
1685: }
1686: if ($namespace eq '') {
1687: $namespace = 'ids';
1688: }
1.800 albertel 1689: foreach my $uname (keys(%ids)) {
1690: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300 raeburn 1691: if ($uhom eq '') {
1692: $uhom=&homeserver($uname,$udom);
1693: }
1.70 www 1694: if ($uhom ne 'no_host') {
1.800 albertel 1695: my $esc_unam=&escape($uname);
1.1300 raeburn 1696: if ($namespace eq 'ids') {
1697: my $id=&escape($ids{$uname});
1698: $id=~tr/A-Z/a-z/;
1699: my $esc_unam=&escape($uname);
1700: $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70 www 1701: } else {
1.1300 raeburn 1702: my @currids = split(/,/,$ids{$uname});
1703: foreach my $id (@currids) {
1704: $byid{$uhom}{$id} .= $uname.',';
1705: }
1706: }
1707: }
1708: }
1709: if ($namespace eq 'clickers') {
1710: foreach my $server (keys(%byid)) {
1711: if (ref($byid{$server}) eq 'HASH') {
1712: foreach my $id (keys(%{$byid{$server}})) {
1713: $byid{$server} =~ s/,$//;
1714: $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&';
1715: }
1.70 www 1716: }
1717: }
1.191 harris41 1718: }
1.800 albertel 1719: foreach my $server (keys(%servers)) {
1.1300 raeburn 1720: $servers{$server} =~ s/\&$//;
1721: if ($namespace eq 'ids') {
1722: &critical('idput:'.$udom.':'.$servers{$server},$server);
1723: } else {
1724: &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
1725: }
1.191 harris41 1726: }
1.344 www 1727: }
1728:
1.1300 raeburn 1729: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231 raeburn 1730:
1731: sub iddel {
1.1300 raeburn 1732: my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231 raeburn 1733: my %result=();
1.1300 raeburn 1734: my %ids=();
1735: my %byid = ();
1736: if (ref($idshashref) eq 'HASH') {
1737: %ids=%{$idshashref};
1738: } else {
1.1231 raeburn 1739: return %result;
1740: }
1.1300 raeburn 1741: if ($namespace eq '') {
1742: $namespace = 'ids';
1743: }
1.1231 raeburn 1744: my %servers=();
1.1300 raeburn 1745: while (my ($id,$unamestr) = each(%ids)) {
1746: if ($namespace eq 'ids') {
1747: my $uhom = $uhome;
1748: if ($uhom eq '') {
1749: $uhom=&homeserver($unamestr,$udom);
1750: }
1751: if ($uhom ne 'no_host') {
1752: $servers{$uhom}.='&'.&escape($id);
1753: }
1754: } else {
1755: my @curritems = split(/,/,$ids{$id});
1756: foreach my $uname (@curritems) {
1757: my $uhom = $uhome;
1758: if ($uhom eq '') {
1759: $uhom=&homeserver($uname,$udom);
1760: }
1761: if ($uhom ne 'no_host') {
1762: $byid{$uhom}{$id} .= $uname.',';
1763: }
1764: }
1.1231 raeburn 1765: }
1.1300 raeburn 1766: }
1767: if ($namespace eq 'clickers') {
1768: foreach my $server (keys(%byid)) {
1769: if (ref($byid{$server}) eq 'HASH') {
1770: foreach my $id (keys(%{$byid{$server}})) {
1771: $byid{$server}{$id} =~ s/,$//;
1772: $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
1773: }
1.1231 raeburn 1774: }
1775: }
1776: }
1777: foreach my $server (keys(%servers)) {
1.1300 raeburn 1778: $servers{$server} =~ s/\&$//;
1779: if ($namespace eq 'ids') {
1780: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1781: } elsif ($namespace eq 'clickers') {
1782: $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
1783: }
1.1231 raeburn 1784: }
1785: return %result;
1786: }
1787:
1.1300 raeburn 1788: # ----- Update clicker ID-to-username look-ups in clickers.db on library server
1789:
1790: sub updateclickers {
1791: my ($udom,$action,$idshashref,$uhome,$critical) = @_;
1792: my %clickers;
1793: if (ref($idshashref) eq 'HASH') {
1794: %clickers=%{$idshashref};
1795: } else {
1796: return;
1797: }
1798: my $items='';
1799: foreach my $item (keys(%clickers)) {
1800: $items.=&escape($item).'='.&escape($clickers{$item}).'&';
1801: }
1802: $items=~s/\&$//;
1803: my $request = "updateclickers:$udom:$action:$items";
1804: if ($critical) {
1805: return &critical($request,$uhome);
1806: } else {
1807: return &reply($request,$uhome);
1808: }
1809: }
1810:
1.1023 raeburn 1811: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1812: sub dump_dom {
1.1165 droeschl 1813: my ($namespace, $udom, $regexp) = @_;
1814:
1815: $udom ||= $env{'user.domain'};
1816:
1817: return () unless $udom;
1818:
1819: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1820: }
1821:
1.1023 raeburn 1822: # ------------------------------------------ get items from domain db files
1.806 raeburn 1823:
1824: sub get_dom {
1.860 raeburn 1825: my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267 raeburn 1826: return if ($udom eq 'public');
1.806 raeburn 1827: my $items='';
1828: foreach my $item (@$storearr) {
1829: $items.=&escape($item).'&';
1830: }
1831: $items=~s/\&$//;
1.860 raeburn 1832: if (!$udom) {
1833: $udom=$env{'user.domain'};
1.1267 raeburn 1834: return if ($udom eq 'public');
1.860 raeburn 1835: if (defined(&domain($udom,'primary'))) {
1836: $uhome=&domain($udom,'primary');
1837: } else {
1.874 albertel 1838: undef($uhome);
1.860 raeburn 1839: }
1840: } else {
1841: if (!$uhome) {
1842: if (defined(&domain($udom,'primary'))) {
1843: $uhome=&domain($udom,'primary');
1844: }
1845: }
1846: }
1847: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1848: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1849: my %returnhash;
1.875 albertel 1850: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1851: return %returnhash;
1852: }
1.806 raeburn 1853: my @pairs=split(/\&/,$rep);
1854: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1855: return @pairs;
1856: }
1857: my $i=0;
1858: foreach my $item (@$storearr) {
1859: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1860: $i++;
1861: }
1862: return %returnhash;
1863: } else {
1.880 banghart 1864: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1865: }
1866: }
1867:
1868: # -------------------------------------------- put items in domain db files
1869:
1870: sub put_dom {
1.860 raeburn 1871: my ($namespace,$storehash,$udom,$uhome)=@_;
1872: if (!$udom) {
1873: $udom=$env{'user.domain'};
1874: if (defined(&domain($udom,'primary'))) {
1875: $uhome=&domain($udom,'primary');
1876: } else {
1.874 albertel 1877: undef($uhome);
1.860 raeburn 1878: }
1879: } else {
1880: if (!$uhome) {
1881: if (defined(&domain($udom,'primary'))) {
1882: $uhome=&domain($udom,'primary');
1883: }
1884: }
1885: }
1886: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1887: my $items='';
1888: foreach my $item (keys(%$storehash)) {
1889: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1890: }
1891: $items=~s/\&$//;
1892: return &reply("putdom:$udom:$namespace:$items",$uhome);
1893: } else {
1.860 raeburn 1894: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1895: }
1896: }
1897:
1.1023 raeburn 1898: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1899: sub newput_dom {
1.1023 raeburn 1900: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1901: my $result;
1902: if (!$udom) {
1903: $udom=$env{'user.domain'};
1904: }
1.1023 raeburn 1905: if ($udom) {
1906: my $uname = &get_domainconfiguser($udom);
1907: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1908: }
1909: return $result;
1910: }
1911:
1.1023 raeburn 1912: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1913: sub del_dom {
1.1023 raeburn 1914: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1915: if (ref($storearr) eq 'ARRAY') {
1916: if (!$udom) {
1917: $udom=$env{'user.domain'};
1918: }
1.1023 raeburn 1919: if ($udom) {
1920: my $uname = &get_domainconfiguser($udom);
1921: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1922: }
1923: }
1924: }
1925:
1.1023 raeburn 1926: # ----------------------------------construct domainconfig user for a domain
1927: sub get_domainconfiguser {
1928: my ($udom) = @_;
1929: return $udom.'-domainconfig';
1930: }
1931:
1.837 raeburn 1932: sub retrieve_inst_usertypes {
1933: my ($udom) = @_;
1934: my (%returnhash,@order);
1.989 raeburn 1935: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1936: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1937: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 1938: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1939: } else {
1940: if (defined(&domain($udom,'primary'))) {
1941: my $uhome=&domain($udom,'primary');
1942: my $rep=&reply("inst_usertypes:$udom",$uhome);
1943: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 1944: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1945: return (\%returnhash,\@order);
1946: }
1947: my ($hashitems,$orderitems) = split(/:/,$rep);
1948: my @pairs=split(/\&/,$hashitems);
1949: foreach my $item (@pairs) {
1950: my ($key,$value)=split(/=/,$item,2);
1951: $key = &unescape($key);
1952: next if ($key =~ /^error: 2 /);
1953: $returnhash{$key}=&thaw_unescape($value);
1954: }
1955: my @esc_order = split(/\&/,$orderitems);
1956: foreach my $item (@esc_order) {
1957: push(@order,&unescape($item));
1958: }
1959: } else {
1.1256 raeburn 1960: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1961: }
1.1256 raeburn 1962: return (\%returnhash,\@order);
1.837 raeburn 1963: }
1964: }
1965:
1.868 raeburn 1966: sub is_domainimage {
1967: my ($url) = @_;
1.1306 raeburn 1968: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 1969: if (&domain($1) ne '') {
1970: return '1';
1971: }
1972: }
1973: return;
1974: }
1975:
1.899 raeburn 1976: sub inst_directory_query {
1977: my ($srch) = @_;
1978: my $udom = $srch->{'srchdomain'};
1979: my %results;
1980: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1981: my $outcome;
1.899 raeburn 1982: if ($homeserver ne '') {
1.904 albertel 1983: my $queryid=&reply("querysend:instdirsearch:".
1984: &escape($srch->{'srchby'}).':'.
1985: &escape($srch->{'srchterm'}).':'.
1986: &escape($srch->{'srchtype'}),$homeserver);
1987: my $host=&hostname($homeserver);
1988: if ($queryid !~/^\Q$host\E\_/) {
1989: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1990: return;
1991: }
1992: my $response = &get_query_reply($queryid);
1993: my $maxtries = 5;
1994: my $tries = 1;
1995: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1996: $response = &get_query_reply($queryid);
1997: $tries ++;
1998: }
1999:
2000: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2001: if ($response eq 'unavailable') {
2002: $outcome = $response;
2003: } else {
2004: $outcome = 'ok';
2005: my @matches = split(/\n/,$response);
2006: foreach my $match (@matches) {
2007: my ($key,$value) = split(/=/,$match);
2008: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2009: }
1.899 raeburn 2010: }
2011: }
2012: }
1.909 raeburn 2013: return ($outcome,%results);
1.899 raeburn 2014: }
2015:
2016: sub usersearch {
2017: my ($srch) = @_;
2018: my $dom = $srch->{'srchdomain'};
2019: my %results;
2020: my %libserv = &all_library();
2021: my $query = 'usersearch';
2022: foreach my $tryserver (keys(%libserv)) {
2023: if (&host_domain($tryserver) eq $dom) {
2024: my $host=&hostname($tryserver);
2025: my $queryid=
1.911 raeburn 2026: &reply("querysend:".&escape($query).':'.
2027: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2028: &escape($srch->{'srchtype'}).':'.
2029: &escape($srch->{'srchterm'}),$tryserver);
2030: if ($queryid !~/^\Q$host\E\_/) {
2031: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2032: next;
1.899 raeburn 2033: }
2034: my $reply = &get_query_reply($queryid);
2035: my $maxtries = 1;
2036: my $tries = 1;
2037: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2038: $reply = &get_query_reply($queryid);
2039: $tries ++;
2040: }
2041: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2042: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2043: } else {
1.911 raeburn 2044: my @matches;
2045: if ($reply =~ /\n/) {
2046: @matches = split(/\n/,$reply);
2047: } else {
2048: @matches = split(/\&/,$reply);
2049: }
1.899 raeburn 2050: foreach my $match (@matches) {
2051: my ($uname,$udom,%userhash);
1.911 raeburn 2052: foreach my $entry (split(/:/,$match)) {
2053: my ($key,$value) =
2054: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2055: $userhash{$key} = $value;
2056: if ($key eq 'username') {
2057: $uname = $value;
2058: } elsif ($key eq 'domain') {
2059: $udom = $value;
1.911 raeburn 2060: }
1.899 raeburn 2061: }
2062: $results{$uname.':'.$udom} = \%userhash;
2063: }
2064: }
2065: }
2066: }
2067: return %results;
2068: }
2069:
1.912 raeburn 2070: sub get_instuser {
2071: my ($udom,$uname,$id) = @_;
2072: my $homeserver = &domain($udom,'primary');
2073: my ($outcome,%results);
2074: if ($homeserver ne '') {
2075: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2076: &escape($id).':'.&escape($udom),$homeserver);
2077: my $host=&hostname($homeserver);
2078: if ($queryid !~/^\Q$host\E\_/) {
2079: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2080: return;
2081: }
2082: my $response = &get_query_reply($queryid);
2083: my $maxtries = 5;
2084: my $tries = 1;
2085: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2086: $response = &get_query_reply($queryid);
2087: $tries ++;
2088: }
2089: if (!&error($response) && $response ne 'refused') {
2090: if ($response eq 'unavailable') {
2091: $outcome = $response;
2092: } else {
2093: $outcome = 'ok';
2094: my @matches = split(/\n/,$response);
2095: foreach my $match (@matches) {
2096: my ($key,$value) = split(/=/,$match);
2097: $results{&unescape($key)} = &thaw_unescape($value);
2098: }
2099: }
2100: }
2101: }
2102: my %userinfo;
2103: if (ref($results{$uname}) eq 'HASH') {
2104: %userinfo = %{$results{$uname}};
2105: }
2106: return ($outcome,%userinfo);
2107: }
2108:
1.1290 raeburn 2109: sub get_multiple_instusers {
2110: my ($udom,$users,$caller) = @_;
2111: my ($outcome,$results);
2112: if (ref($users) eq 'HASH') {
2113: my $count = keys(%{$users});
2114: my $requested = &freeze_escape($users);
2115: my $homeserver = &domain($udom,'primary');
2116: if ($homeserver ne '') {
2117: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2118: my $host=&hostname($homeserver);
2119: if ($queryid !~/^\Q$host\E\_/) {
2120: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2121: ' for host: '.$homeserver.'in domain '.$udom);
2122: return ($outcome,$results);
2123: }
2124: my $response = &get_query_reply($queryid);
2125: my $maxtries = 5;
2126: if ($count > 100) {
2127: $maxtries = 1+int($count/20);
2128: }
2129: my $tries = 1;
2130: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2131: $response = &get_query_reply($queryid);
2132: $tries ++;
2133: }
2134: if ($response eq '') {
2135: $results = {};
2136: foreach my $key (keys(%{$users})) {
2137: my ($uname,$id);
2138: if ($caller eq 'id') {
2139: $id = $key;
2140: } else {
2141: $uname = $key;
2142: }
2143: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291 raeburn 2144: $outcome = $resp;
1.1290 raeburn 2145: if ($resp eq 'ok') {
2146: %{$results} = (%{$results}, %info);
2147: } else {
2148: last;
2149: }
2150: }
2151: } elsif(!&error($response) && ($response ne 'refused')) {
2152: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2153: $outcome = $response;
2154: } else {
1.1291 raeburn 2155: ($outcome,my $userdata) = split(/=/,$response,2);
1.1290 raeburn 2156: if ($outcome eq 'ok') {
2157: $results = &thaw_unescape($userdata);
2158: }
2159: }
2160: }
2161: }
2162: }
2163: return ($outcome,$results);
2164: }
2165:
1.912 raeburn 2166: sub inst_rulecheck {
1.923 raeburn 2167: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2168: my %returnhash;
2169: if ($udom ne '') {
2170: if (ref($rules) eq 'ARRAY') {
2171: @{$rules} = map {&escape($_);} (@{$rules});
2172: my $rulestr = join(':',@{$rules});
2173: my $homeserver=&domain($udom,'primary');
2174: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2175: my $response;
2176: if ($item eq 'username') {
2177: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2178: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2179: $homeserver));
1.923 raeburn 2180: } elsif ($item eq 'id') {
2181: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2182: ':'.&escape($id).':'.$rulestr,
2183: $homeserver));
1.945 raeburn 2184: } elsif ($item eq 'selfcreate') {
2185: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2186: &escape($udom).':'.&escape($uname).
2187: ':'.$rulestr,$homeserver));
1.923 raeburn 2188: }
1.912 raeburn 2189: if ($response ne 'refused') {
2190: my @pairs=split(/\&/,$response);
2191: foreach my $item (@pairs) {
2192: my ($key,$value)=split(/=/,$item,2);
2193: $key = &unescape($key);
2194: next if ($key =~ /^error: 2 /);
2195: $returnhash{$key}=&thaw_unescape($value);
2196: }
2197: }
2198: }
2199: }
2200: }
2201: return %returnhash;
2202: }
2203:
2204: sub inst_userrules {
1.923 raeburn 2205: my ($udom,$check) = @_;
1.912 raeburn 2206: my (%ruleshash,@ruleorder);
2207: if ($udom ne '') {
2208: my $homeserver=&domain($udom,'primary');
2209: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2210: my $response;
2211: if ($check eq 'id') {
2212: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2213: $homeserver);
1.943 raeburn 2214: } elsif ($check eq 'email') {
2215: $response=&reply('instemailrules:'.&escape($udom),
2216: $homeserver);
1.923 raeburn 2217: } else {
2218: $response=&reply('instuserrules:'.&escape($udom),
2219: $homeserver);
2220: }
1.912 raeburn 2221: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2222: ($response ne 'unknown_cmd') &&
1.912 raeburn 2223: ($response ne 'no_such_host')) {
2224: my ($hashitems,$orderitems) = split(/:/,$response);
2225: my @pairs=split(/\&/,$hashitems);
2226: foreach my $item (@pairs) {
2227: my ($key,$value)=split(/=/,$item,2);
2228: $key = &unescape($key);
2229: next if ($key =~ /^error: 2 /);
2230: $ruleshash{$key}=&thaw_unescape($value);
2231: }
2232: my @esc_order = split(/\&/,$orderitems);
2233: foreach my $item (@esc_order) {
2234: push(@ruleorder,&unescape($item));
2235: }
2236: }
2237: }
2238: }
2239: return (\%ruleshash,\@ruleorder);
2240: }
2241:
1.976 raeburn 2242: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2243:
2244: sub get_domain_defaults {
1.1240 raeburn 2245: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2246: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2247: my $cachetime = 60*60*24;
1.1240 raeburn 2248: unless ($ignore_cache) {
2249: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2250: if (defined($cached)) {
2251: if (ref($result) eq 'HASH') {
2252: return %{$result};
2253: }
1.943 raeburn 2254: }
2255: }
2256: my %domdefaults;
2257: my %domconfig =
1.989 raeburn 2258: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2259: 'requestcourses','inststatus',
1.1183 raeburn 2260: 'coursedefaults','usersessions',
1.1258 raeburn 2261: 'requestauthor','selfenrollment',
1.1320 raeburn 2262: 'coursecategories','ssl','autoenroll',
1.1332 raeburn 2263: 'trust','helpsettings'],$domain);
1.1305 raeburn 2264: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2265: if (ref($domconfig{'defaults'}) eq 'HASH') {
2266: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2267: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2268: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2269: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2270: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2271: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2272: } else {
2273: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2274: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2275: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2276: }
1.976 raeburn 2277: if (ref($domconfig{'quotas'}) eq 'HASH') {
2278: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2279: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2280: } else {
2281: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2282: }
1.1177 raeburn 2283: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2284: foreach my $item (@usertools) {
2285: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2286: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2287: }
2288: }
1.1229 raeburn 2289: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2290: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2291: }
1.976 raeburn 2292: }
1.985 raeburn 2293: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 raeburn 2294: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2295: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2296: }
2297: }
1.1183 raeburn 2298: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2299: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2300: }
1.989 raeburn 2301: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2302: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2303: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2304: }
2305: }
1.1047 raeburn 2306: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2307: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2308: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2309: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2310: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2311: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2312: }
1.1254 raeburn 2313: foreach my $type (@coursetypes) {
2314: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2315: unless ($type eq 'community') {
2316: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2317: }
2318: }
2319: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2320: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2321: }
1.1277 raeburn 2322: if ($domdefaults{'postsubmit'} eq 'on') {
2323: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2324: $domdefaults{$type.'postsubtimeout'} =
2325: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2326: }
2327: }
1.1230 raeburn 2328: }
1.1286 raeburn 2329: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2330: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2331: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2332: if (@clonecodes) {
2333: $domdefaults{'canclone'} = join('+',@clonecodes);
2334: }
2335: }
2336: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2337: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2338: }
1.1047 raeburn 2339: }
1.1073 raeburn 2340: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2341: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2342: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2343: }
2344: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2345: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2346: }
1.1279 raeburn 2347: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2348: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2349: }
1.1073 raeburn 2350: }
1.1254 raeburn 2351: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2352: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2353: my @settings = ('types','registered','enroll_dates','access_dates','section',
2354: 'approval','limit');
2355: foreach my $type (@coursetypes) {
2356: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2357: my @mgrdc = ();
2358: foreach my $item (@settings) {
2359: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2360: push(@mgrdc,$item);
2361: }
2362: }
2363: if (@mgrdc) {
2364: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2365: }
2366: }
2367: }
2368: }
2369: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2370: foreach my $type (@coursetypes) {
2371: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2372: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2373: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2374: }
2375: }
2376: }
2377: }
2378: }
1.1258 raeburn 2379: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2380: $domdefaults{'catauth'} = 'std';
2381: $domdefaults{'catunauth'} = 'std';
2382: if ($domconfig{'coursecategories'}{'auth'}) {
2383: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2384: }
2385: if ($domconfig{'coursecategories'}{'unauth'}) {
2386: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2387: }
2388: }
1.1315 raeburn 2389: if (ref($domconfig{'ssl'}) eq 'HASH') {
2390: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2391: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2392: }
1.1338 raeburn 2393: if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
2394: $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
2395: }
2396: if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
2397: $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315 raeburn 2398: }
2399: }
1.1320 raeburn 2400: if (ref($domconfig{'trust'}) eq 'HASH') {
2401: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2402: foreach my $prefix (@prefixes) {
2403: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2404: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2405: }
2406: }
2407: }
1.1314 raeburn 2408: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2409: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2410: }
1.1332 raeburn 2411: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2412: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2413: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2414: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2415: }
2416: }
1.1219 raeburn 2417: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2418: return %domdefaults;
2419: }
2420:
1.1311 raeburn 2421: sub course_portal_url {
2422: my ($cnum,$cdom) = @_;
2423: my $chome = &homeserver($cnum,$cdom);
2424: my $hostname = &hostname($chome);
2425: my $protocol = $protocol{$chome};
2426: $protocol = 'http' if ($protocol ne 'https');
2427: my %domdefaults = &get_domain_defaults($cdom);
2428: my $firsturl;
2429: if ($domdefaults{'portal_def'}) {
2430: $firsturl = $domdefaults{'portal_def'};
2431: } else {
2432: $firsturl = $protocol.'://'.$hostname;
2433: }
2434: return $firsturl;
2435: }
2436:
1.344 www 2437: # --------------------------------------------------- Assign a key to a student
2438:
2439: sub assign_access_key {
1.364 www 2440: #
2441: # a valid key looks like uname:udom#comments
2442: # comments are being appended
2443: #
1.498 www 2444: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2445: $kdom=
1.620 albertel 2446: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2447: $knum=
1.620 albertel 2448: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2449: $cdom=
1.620 albertel 2450: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2451: $cnum=
1.620 albertel 2452: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2453: $udom=$env{'user.name'} unless (defined($udom));
2454: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2455: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2456: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2457: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2458: # assigned to this person
2459: # - this should not happen,
1.345 www 2460: # unless something went wrong
2461: # the first time around
2462: # ready to assign
1.364 www 2463: $logentry=$1.'; '.$logentry;
1.496 www 2464: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2465: $kdom,$knum) eq 'ok') {
1.345 www 2466: # key now belongs to user
1.346 www 2467: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2468: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2469: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2470: return 'ok';
2471: } else {
2472: return
2473: 'error: Count not permanently assign key, will need to be re-entered later.';
2474: }
2475: } else {
2476: return 'error: Could not assign key, try again later.';
2477: }
1.364 www 2478: } elsif (!$existing{$ckey}) {
1.345 www 2479: # the key does not exist
2480: return 'error: The key does not exist';
2481: } else {
2482: # the key is somebody else's
2483: return 'error: The key is already in use';
2484: }
1.344 www 2485: }
2486:
1.364 www 2487: # ------------------------------------------ put an additional comment on a key
2488:
2489: sub comment_access_key {
2490: #
2491: # a valid key looks like uname:udom#comments
2492: # comments are being appended
2493: #
2494: my ($ckey,$cdom,$cnum,$logentry)=@_;
2495: $cdom=
1.620 albertel 2496: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2497: $cnum=
1.620 albertel 2498: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2499: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2500: if ($existing{$ckey}) {
2501: $existing{$ckey}.='; '.$logentry;
2502: # ready to assign
1.367 www 2503: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2504: $cdom,$cnum) eq 'ok') {
2505: return 'ok';
2506: } else {
2507: return 'error: Count not store comment.';
2508: }
2509: } else {
2510: # the key does not exist
2511: return 'error: The key does not exist';
2512: }
2513: }
2514:
1.344 www 2515: # ------------------------------------------------------ Generate a set of keys
2516:
2517: sub generate_access_keys {
1.364 www 2518: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2519: $cdom=
1.620 albertel 2520: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2521: $cnum=
1.620 albertel 2522: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2523: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2524: unless (($cdom) && ($cnum)) { return 0; }
2525: if ($number>10000) { return 0; }
2526: sleep(2); # make sure don't get same seed twice
2527: srand(time()^($$+($$<<15))); # from "Programming Perl"
2528: my $total=0;
2529: for (my $i=1;$i<=$number;$i++) {
2530: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2531: sprintf("%lx",int(100000*rand)).'-'.
2532: sprintf("%lx",int(100000*rand));
2533: $newkey=~s/1/g/g; # folks mix up 1 and l
2534: $newkey=~s/0/h/g; # and also 0 and O
2535: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2536: if ($existing{$newkey}) {
2537: $i--;
2538: } else {
1.364 www 2539: if (&put('accesskeys',
2540: { $newkey => '# generated '.localtime().
1.620 albertel 2541: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2542: '; '.$logentry },
2543: $cdom,$cnum) eq 'ok') {
1.344 www 2544: $total++;
2545: }
2546: }
2547: }
1.620 albertel 2548: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2549: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2550: return $total;
2551: }
2552:
2553: # ------------------------------------------------------- Validate an accesskey
2554:
2555: sub validate_access_key {
2556: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2557: $cdom=
1.620 albertel 2558: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2559: $cnum=
1.620 albertel 2560: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2561: $udom=$env{'user.domain'} unless (defined($udom));
2562: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2563: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2564: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2565: }
2566:
2567: # ------------------------------------- Find the section of student in a course
1.652 albertel 2568: sub devalidate_getsection_cache {
2569: my ($udom,$unam,$courseid)=@_;
2570: my $hashid="$udom:$unam:$courseid";
2571: &devalidate_cache_new('getsection',$hashid);
2572: }
1.298 matthew 2573:
1.815 albertel 2574: sub courseid_to_courseurl {
2575: my ($courseid) = @_;
2576: #already url style courseid
2577: return $courseid if ($courseid =~ m{^/});
2578:
2579: if (exists($env{'course.'.$courseid.'.num'})) {
2580: my $cnum = $env{'course.'.$courseid.'.num'};
2581: my $cdom = $env{'course.'.$courseid.'.domain'};
2582: return "/$cdom/$cnum";
2583: }
2584:
2585: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2586: if (exists($courseinfo{'num'})) {
2587: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2588: }
2589:
2590: return undef;
2591: }
2592:
1.298 matthew 2593: sub getsection {
2594: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2595: my $cachetime=1800;
1.551 albertel 2596:
2597: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2598: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2599: if (defined($cached)) { return $result; }
2600:
1.298 matthew 2601: my %Pending;
2602: my %Expired;
2603: #
2604: # Each role can either have not started yet (pending), be active,
2605: # or have expired.
2606: #
2607: # If there is an active role, we are done.
2608: #
2609: # If there is more than one role which has not started yet,
2610: # choose the one which will start sooner
2611: # If there is one role which has not started yet, return it.
2612: #
2613: # If there is more than one expired role, choose the one which ended last.
2614: # If there is a role which has expired, return it.
2615: #
1.815 albertel 2616: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2617: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2618: foreach my $key (keys(%roleshash)) {
1.479 albertel 2619: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2620: my $section=$1;
2621: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2622: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2623: my $now=time;
1.548 albertel 2624: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2625: $Expired{$end}=$section;
2626: next;
2627: }
1.548 albertel 2628: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2629: $Pending{$start}=$section;
2630: next;
2631: }
1.599 albertel 2632: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2633: }
2634: #
2635: # Presumedly there will be few matching roles from the above
2636: # loop and the sorting time will be negligible.
2637: if (scalar(keys(%Pending))) {
2638: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2639: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2640: }
2641: if (scalar(keys(%Expired))) {
2642: my @sorted = sort {$a <=> $b} keys(%Expired);
2643: my $time = pop(@sorted);
1.599 albertel 2644: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2645: }
1.599 albertel 2646: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2647: }
1.70 www 2648:
1.599 albertel 2649: sub save_cache {
2650: &purge_remembered();
1.722 albertel 2651: #&Apache::loncommon::validate_page();
1.620 albertel 2652: undef(%env);
1.780 albertel 2653: undef($env_loaded);
1.599 albertel 2654: }
1.452 albertel 2655:
1.599 albertel 2656: my $to_remember=-1;
2657: my %remembered;
2658: my %accessed;
2659: my $kicks=0;
2660: my $hits=0;
1.849 albertel 2661: sub make_key {
2662: my ($name,$id) = @_;
1.872 albertel 2663: if (length($id) > 65
2664: && length(&escape($id)) > 200) {
2665: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2666: }
1.849 albertel 2667: return &escape($name.':'.$id);
2668: }
2669:
1.599 albertel 2670: sub devalidate_cache_new {
2671: my ($name,$id,$debug) = @_;
2672: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319 damieng 2673: my $remembered_id=$name.':'.$id;
1.849 albertel 2674: $id=&make_key($name,$id);
1.599 albertel 2675: $memcache->delete($id);
1.1319 damieng 2676: delete($remembered{$remembered_id});
2677: delete($accessed{$remembered_id});
1.599 albertel 2678: }
2679:
2680: sub is_cached_new {
2681: my ($name,$id,$debug) = @_;
1.1319 damieng 2682: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
2683: if (exists($remembered{$remembered_id})) {
2684: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2685: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2686: $hits++;
1.1319 damieng 2687: return ($remembered{$remembered_id},1);
1.599 albertel 2688: }
1.1319 damieng 2689: $id=&make_key($name,$id);
1.599 albertel 2690: my $value = $memcache->get($id);
2691: if (!(defined($value))) {
2692: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2693: return (undef,undef);
1.416 albertel 2694: }
1.599 albertel 2695: if ($value eq '__undef__') {
2696: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2697: $value=undef;
2698: }
1.1319 damieng 2699: &make_room($remembered_id,$value,$debug);
1.599 albertel 2700: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2701: return ($value,1);
2702: }
2703:
2704: sub do_cache_new {
2705: my ($name,$id,$value,$time,$debug) = @_;
1.1319 damieng 2706: my $remembered_id=$name.':'.$id;
1.849 albertel 2707: $id=&make_key($name,$id);
1.599 albertel 2708: my $setvalue=$value;
2709: if (!defined($setvalue)) {
2710: $setvalue='__undef__';
2711: }
1.623 albertel 2712: if (!defined($time) ) {
2713: $time=600;
2714: }
1.599 albertel 2715: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2716: my $result = $memcache->set($id,$setvalue,$time);
2717: if (! $result) {
1.872 albertel 2718: &logthis("caching of id -> $id failed");
1.910 albertel 2719: $memcache->disconnect_all();
1.872 albertel 2720: }
1.600 albertel 2721: # need to make a copy of $value
1.1319 damieng 2722: &make_room($remembered_id,$value,$debug);
1.599 albertel 2723: return $value;
2724: }
2725:
2726: sub make_room {
1.1319 damieng 2727: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2728:
1.1319 damieng 2729: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2730: : $value;
1.599 albertel 2731: if ($to_remember<0) { return; }
1.1319 damieng 2732: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2733: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2734: my $to_kick;
2735: my $max_time=0;
2736: foreach my $other (keys(%accessed)) {
2737: if (&tv_interval($accessed{$other}) > $max_time) {
2738: $to_kick=$other;
2739: $max_time=&tv_interval($accessed{$other});
2740: }
2741: }
2742: delete($remembered{$to_kick});
2743: delete($accessed{$to_kick});
2744: $kicks++;
2745: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2746: return;
2747: }
2748:
1.599 albertel 2749: sub purge_remembered {
1.604 albertel 2750: #&logthis("Tossing ".scalar(keys(%remembered)));
2751: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2752: undef(%remembered);
2753: undef(%accessed);
1.428 albertel 2754: }
1.70 www 2755: # ------------------------------------- Read an entry from a user's environment
2756:
2757: sub userenvironment {
2758: my ($udom,$unam,@what)=@_;
1.976 raeburn 2759: my $items;
2760: foreach my $item (@what) {
2761: $items.=&escape($item).'&';
2762: }
2763: $items=~s/\&$//;
1.70 www 2764: my %returnhash=();
1.1009 raeburn 2765: my $uhome = &homeserver($unam,$udom);
2766: unless ($uhome eq 'no_host') {
2767: my @answer=split(/\&/,
2768: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2769: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2770: return %returnhash;
2771: }
1.1009 raeburn 2772: my $i;
2773: for ($i=0;$i<=$#what;$i++) {
2774: $returnhash{$what[$i]}=&unescape($answer[$i]);
2775: }
1.70 www 2776: }
2777: return %returnhash;
1.1 albertel 2778: }
2779:
1.617 albertel 2780: # ---------------------------------------------------------- Get a studentphoto
2781: sub studentphoto {
2782: my ($udom,$unam,$ext) = @_;
2783: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2784: if (defined($env{'request.course.id'})) {
1.708 raeburn 2785: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2786: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2787: return(&retrievestudentphoto($udom,$unam,$ext));
2788: } else {
2789: my ($result,$perm_reqd)=
1.707 albertel 2790: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2791: if ($result eq 'ok') {
2792: if (!($perm_reqd eq 'yes')) {
2793: return(&retrievestudentphoto($udom,$unam,$ext));
2794: }
2795: }
2796: }
2797: }
2798: } else {
2799: my ($result,$perm_reqd) =
1.707 albertel 2800: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2801: if ($result eq 'ok') {
2802: if (!($perm_reqd eq 'yes')) {
2803: return(&retrievestudentphoto($udom,$unam,$ext));
2804: }
2805: }
2806: }
2807: return '/adm/lonKaputt/lonlogo_broken.gif';
2808: }
2809:
2810: sub retrievestudentphoto {
2811: my ($udom,$unam,$ext,$type) = @_;
2812: my $home=&Apache::lonnet::homeserver($unam,$udom);
2813: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2814: if ($ret eq 'ok') {
2815: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2816: if ($type eq 'thumbnail') {
2817: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2818: }
2819: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2820: return $tokenurl;
2821: } else {
2822: if ($type eq 'thumbnail') {
2823: return '/adm/lonKaputt/genericstudent_tn.gif';
2824: } else {
2825: return '/adm/lonKaputt/lonlogo_broken.gif';
2826: }
1.617 albertel 2827: }
2828: }
2829:
1.263 www 2830: # -------------------------------------------------------------------- New chat
2831:
2832: sub chatsend {
1.724 raeburn 2833: my ($newentry,$anon,$group)=@_;
1.620 albertel 2834: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2835: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2836: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2837: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2838: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2839: &escape($newentry)).':'.$group,$chome);
1.292 www 2840: }
2841:
2842: # ------------------------------------------ Find current version of a resource
2843:
2844: sub getversion {
2845: my $fname=&clutter(shift);
1.1189 raeburn 2846: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2847: return ¤tversion(&filelocation('',$fname));
2848: }
2849:
2850: sub currentversion {
2851: my $fname=shift;
2852: my $author=$fname;
2853: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2854: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2855: my $home=&homeserver($uname,$udom);
1.292 www 2856: if ($home eq 'no_host') {
2857: return -1;
2858: }
1.1112 www 2859: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2860: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2861: return -1;
2862: }
1.1112 www 2863: return $answer;
1.263 www 2864: }
2865:
1.1111 www 2866: #
2867: # Return special version number of resource if set by override, empty otherwise
2868: #
2869: sub usedversion {
2870: my $fname=shift;
2871: unless ($fname) { $fname=$env{'request.uri'}; }
2872: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2873: if ($urlversion) { return $urlversion; }
2874: return '';
2875: }
2876:
1.1 albertel 2877: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2878:
1.1 albertel 2879: sub subscribe {
2880: my $fname=shift;
1.761 raeburn 2881: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2882: $fname=~s/[\n\r]//g;
1.1 albertel 2883: my $author=$fname;
2884: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2885: my ($udom,$uname)=split(/\//,$author);
2886: my $home=homeserver($uname,$udom);
1.335 albertel 2887: if ($home eq 'no_host') {
2888: return 'not_found';
1.1 albertel 2889: }
2890: my $answer=reply("sub:$fname",$home);
1.64 www 2891: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2892: $answer.=' by '.$home;
2893: }
1.1 albertel 2894: return $answer;
2895: }
2896:
1.8 www 2897: # -------------------------------------------------------------- Replicate file
2898:
2899: sub repcopy {
2900: my $filename=shift;
1.23 www 2901: $filename=~s/\/+/\//g;
1.1142 raeburn 2902: my $londocroot = $perlvar{'lonDocRoot'};
2903: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2904: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2905: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2906: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2907: return &repcopy_userfile($filename);
2908: }
1.532 albertel 2909: $filename=~s/[\n\r]//g;
1.8 www 2910: my $transname="$filename.in.transfer";
1.828 www 2911: # FIXME: this should flock
1.607 raeburn 2912: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2913: my $remoteurl=subscribe($filename);
1.64 www 2914: if ($remoteurl =~ /^con_lost by/) {
2915: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2916: return 'unavailable';
1.8 www 2917: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2918: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2919: return 'not_found';
1.64 www 2920: } elsif ($remoteurl =~ /^rejected by/) {
2921: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2922: return 'forbidden';
1.20 www 2923: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2924: return 'ok';
1.8 www 2925: } else {
1.290 www 2926: my $author=$filename;
2927: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2928: my ($udom,$uname)=split(/\//,$author);
2929: my $home=homeserver($uname,$udom);
2930: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2931: my @parts=split(/\//,$filename);
2932: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2933: if ($path ne "$londocroot/res") {
1.8 www 2934: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2935: return 'bad_request';
1.8 www 2936: }
2937: my $count;
2938: for ($count=5;$count<$#parts;$count++) {
2939: $path.="/$parts[$count]";
2940: if ((-e $path)!=1) {
2941: mkdir($path,0777);
2942: }
2943: }
2944: my $ua=new LWP::UserAgent;
2945: my $request=new HTTP::Request('GET',"$remoteurl");
2946: my $response=$ua->request($request,$transname);
2947: if ($response->is_error()) {
2948: unlink($transname);
2949: my $message=$response->status_line;
1.672 albertel 2950: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2951: ." LWP get: $message: $filename</font>");
1.607 raeburn 2952: return 'unavailable';
1.8 www 2953: } else {
1.16 www 2954: if ($remoteurl!~/\.meta$/) {
2955: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2956: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2957: if ($mresponse->is_error()) {
2958: unlink($filename.'.meta');
2959: &logthis(
1.672 albertel 2960: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2961: }
2962: }
1.8 www 2963: rename($transname,$filename);
1.607 raeburn 2964: return 'ok';
1.8 www 2965: }
1.290 www 2966: }
1.8 www 2967: }
1.330 www 2968: }
2969:
2970: # ------------------------------------------------ Get server side include body
2971: sub ssi_body {
1.381 albertel 2972: my ($filelink,%form)=@_;
1.606 matthew 2973: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2974: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2975: }
1.953 www 2976: my $output='';
2977: my $response;
1.980 raeburn 2978: if ($filelink=~/^https?\:/) {
1.954 raeburn 2979: ($output,$response)=&externalssi($filelink);
1.953 www 2980: } else {
1.1004 droeschl 2981: $filelink .= $filelink=~/\?/ ? '&' : '?';
2982: $filelink .= 'inhibitmenu=yes';
1.953 www 2983: ($output,$response)=&ssi($filelink,%form);
2984: }
1.778 albertel 2985: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2986: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2987: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2988: if (wantarray) {
2989: return ($output, $response);
2990: } else {
2991: return $output;
2992: }
1.8 www 2993: }
2994:
1.15 www 2995: # --------------------------------------------------------- Server Side Include
2996:
1.782 albertel 2997: sub absolute_url {
2998: my ($host_name) = @_;
2999: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3000: if ($host_name eq '') {
3001: $host_name = $ENV{'SERVER_NAME'};
3002: }
3003: return $protocol.$host_name;
3004: }
3005:
1.942 foxr 3006: #
3007: # Server side include.
3008: # Parameters:
3009: # fn Possibly encrypted resource name/id.
3010: # form Hash that describes how the rendering should be done
3011: # and other things.
1.944 foxr 3012: # Returns:
1.950 raeburn 3013: # Scalar context: The content of the response.
3014: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3015: #
1.15 www 3016: sub ssi {
3017:
1.944 foxr 3018: my ($fn,%form)=@_;
1.15 www 3019: my $ua=new LWP::UserAgent;
1.23 www 3020: my $request;
1.711 albertel 3021:
3022: $form{'no_update_last_known'}=1;
1.895 albertel 3023: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3024: if (%form) {
1.782 albertel 3025: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272 droeschl 3026: $request->content(join('&',map {
3027: my $name = escape($_);
3028: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3029: ? join("&$name=", map {escape($_) } @{$form{$_}})
3030: : &escape($form{$_}) );
3031: } keys(%form)));
1.23 www 3032: } else {
1.782 albertel 3033: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 3034: }
3035:
1.15 www 3036: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 3037: my $response= $ua->request($request);
1.1182 foxr 3038: my $content = $response->content;
3039:
3040:
1.944 foxr 3041: if (wantarray) {
1.1173 foxr 3042: return ($content, $response);
1.944 foxr 3043: } else {
1.1173 foxr 3044: return $content;
1.942 foxr 3045: }
1.324 www 3046: }
3047:
3048: sub externalssi {
3049: my ($url)=@_;
3050: my $ua=new LWP::UserAgent;
3051: my $request=new HTTP::Request('GET',$url);
3052: my $response=$ua->request($request);
1.954 raeburn 3053: if (wantarray) {
3054: return ($response->content, $response);
3055: } else {
3056: return $response->content;
3057: }
1.15 www 3058: }
1.254 www 3059:
1.492 albertel 3060: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3061:
3062: sub allowuploaded {
3063: my ($srcurl,$url)=@_;
3064: $url=&clutter(&declutter($url));
3065: my $dir=$url;
3066: $dir=~s/\/[^\/]+$//;
3067: my %httpref=();
3068: my $httpurl=&hreflocation('',$url);
3069: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3070: &Apache::lonnet::appenv(\%httpref);
1.254 www 3071: }
1.477 raeburn 3072:
1.1193 raeburn 3073: #
3074: # Determine if the current user should be able to edit a particular resource,
3075: # when viewing in course context.
3076: # (a) When viewing resource used to determine if "Edit" item is included in
3077: # Functions.
3078: # (b) When displaying folder contents in course editor, used to determine if
3079: # "Edit" link will be displayed alongside resource.
3080: #
1.1196 raeburn 3081: # input: six args -- filename (decluttered), course number, course domain,
3082: # url, symb (if registered) and group (if this is a group
3083: # item -- e.g., bulletin board, group page etc.).
3084: # output: array of five scalars --
1.1193 raeburn 3085: # $cfile -- url for file editing if editable on current server
3086: # $home -- homeserver of resource (i.e., for author if published,
3087: # or course if uploaded.).
3088: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 3089: # $forceedit -- 1 if icon/link should be to go to edit mode
3090: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 3091: #
3092:
3093: sub can_edit_resource {
1.1194 raeburn 3094: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3095: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3096: #
3097: # For aboutme pages user can only edit his/her own.
3098: #
1.1199 raeburn 3099: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 3100: my ($sdom,$sname) = ($1,$2);
3101: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3102: $home = $env{'user.home'};
3103: $cfile = $resurl;
3104: if ($env{'form.forceedit'}) {
3105: $forceview = 1;
3106: } else {
3107: $forceedit = 1;
3108: }
3109: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3110: } else {
3111: return;
3112: }
3113: }
3114:
3115: if ($env{'request.course.id'}) {
3116: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3117: if ($group ne '') {
3118: # if this is a group homepage or group bulletin board, check group privs
3119: my $allowed = 0;
1.1197 raeburn 3120: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3121: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3122: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3123: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3124: $allowed = 1;
3125: }
1.1197 raeburn 3126: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3127: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3128: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3129: $allowed = 1;
3130: }
3131: }
3132: if ($allowed) {
3133: $home=&homeserver($cnum,$cdom);
3134: if ($env{'form.forceedit'}) {
3135: $forceview = 1;
3136: } else {
3137: $forceedit = 1;
3138: }
3139: $cfile = $resurl;
3140: } else {
3141: return;
3142: }
3143: } else {
1.1208 raeburn 3144: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3145: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3146: return;
3147: }
3148: } elsif (!$crsedit) {
1.1194 raeburn 3149: #
3150: # No edit allowed where CC has switched to student role.
3151: #
3152: return;
3153: }
3154: }
3155: }
3156:
1.1193 raeburn 3157: if ($file ne '') {
3158: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3159: if (&is_course_upload($file,$cnum,$cdom)) {
3160: $uploaded = 1;
3161: $incourse = 1;
1.1193 raeburn 3162: if ($file =~/\.(htm|html|css|js|txt)$/) {
3163: $cfile = &hreflocation('',$file);
1.1201 raeburn 3164: if ($env{'form.forceedit'}) {
3165: $forceview = 1;
3166: } else {
3167: $forceedit = 1;
3168: }
1.1194 raeburn 3169: }
3170: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3171: $incourse = 1;
3172: if ($env{'form.forceedit'}) {
3173: $forceview = 1;
3174: } else {
3175: $forceedit = 1;
3176: }
3177: $cfile = $resurl;
3178: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3179: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3180: $incourse = 1;
3181: if ($env{'form.forceedit'}) {
3182: $forceview = 1;
3183: } else {
3184: $forceedit = 1;
3185: }
3186: $cfile = $resurl;
1.1199 raeburn 3187: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3188: $incourse = 1;
3189: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3190: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3191: $incourse = 1;
1.1199 raeburn 3192: if ($env{'form.forceedit'}) {
3193: $forceview = 1;
3194: } else {
3195: $forceedit = 1;
3196: }
3197: $cfile = $resurl;
1.1298 raeburn 3198: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
3199: $incourse = 1;
3200: if ($env{'form.forceedit'}) {
3201: $forceview = 1;
3202: } else {
3203: $forceedit = 1;
3204: }
3205: $cfile = $resurl;
1.1208 raeburn 3206: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3207: $incourse = 1;
3208: if ($env{'form.forceedit'}) {
3209: $forceview = 1;
3210: } else {
3211: $forceedit = 1;
3212: }
3213: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3214: }
3215: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3216: my $template = '/res/lib/templates/simpleproblem.problem';
3217: if (&is_on_map($template)) {
3218: $incourse = 1;
3219: $forceview = 1;
3220: $cfile = $template;
1.1193 raeburn 3221: }
1.1199 raeburn 3222: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3223: $incourse = 1;
3224: if ($env{'form.forceedit'}) {
3225: $forceview = 1;
3226: } else {
3227: $forceedit = 1;
3228: }
3229: $cfile = $resurl;
1.1298 raeburn 3230: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3231: $incourse = 1;
3232: if ($env{'form.forceedit'}) {
3233: $forceview = 1;
3234: } else {
3235: $forceedit = 1;
3236: }
3237: $cfile = $resurl;
1.1199 raeburn 3238: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3239: $incourse = 1;
3240: $forceview = 1;
3241: if ($symb) {
3242: my ($map,$id,$res)=&decode_symb($symb);
3243: $env{'request.symb'} = $symb;
3244: $cfile = &clutter($res);
3245: } else {
3246: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3247: my $escfile = &unescape($cfile);
3248: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
3249: $cfile = '/adm/wrapper'.$escfile;
3250: } else {
3251: $escfile =~ s{^http://}{};
3252: $cfile = &escape("/adm/wrapper/ext/$escfile");
3253: }
1.1199 raeburn 3254: }
1.1234 raeburn 3255: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3256: if ($env{'form.forceedit'}) {
3257: $forceview = 1;
3258: } else {
3259: $forceedit = 1;
3260: }
3261: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 3262: }
3263: }
1.1194 raeburn 3264: if ($uploaded || $incourse) {
3265: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 3266: } elsif ($file !~ m{/$}) {
1.1193 raeburn 3267: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3268: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3269: # Check that the user has permission to edit this resource
3270: my $setpriv = 1;
3271: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3272: if (defined($cfudom)) {
3273: $home=&homeserver($cfuname,$cfudom);
3274: $cfile=$file;
3275: }
3276: }
1.1194 raeburn 3277: if (($cfile ne '') && (!$incourse || $uploaded) &&
3278: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 3279: my @ids=¤t_machine_ids();
3280: unless (grep(/^\Q$home\E$/,@ids)) {
3281: $switchserver=1;
3282: }
3283: }
3284: }
1.1194 raeburn 3285: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 3286: }
3287:
3288: sub is_course_upload {
3289: my ($file,$cnum,$cdom) = @_;
3290: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3291: $uploadpath =~ s{^\/}{};
1.1201 raeburn 3292: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3293: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 3294: return 1;
3295: }
3296: return;
3297: }
3298:
1.1194 raeburn 3299: sub in_course {
1.1195 raeburn 3300: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3301: if ($hideprivileged) {
3302: my $skipuser;
1.1219 raeburn 3303: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3304: my @possdoms = ($cdom);
3305: if ($coursehash{'checkforpriv'}) {
3306: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3307: }
3308: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3309: $skipuser = 1;
3310: if ($coursehash{'nothideprivileged'}) {
3311: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3312: my $user;
3313: if ($item =~ /:/) {
3314: $user = $item;
3315: } else {
3316: $user = join(':',split(/[\@]/,$item));
3317: }
3318: if ($user eq $uname.':'.$udom) {
3319: undef($skipuser);
3320: last;
3321: }
3322: }
3323: }
3324: if ($skipuser) {
3325: return 0;
3326: }
3327: }
3328: }
1.1194 raeburn 3329: $type ||= 'any';
3330: if (!defined($cdom) || !defined($cnum)) {
3331: my $cid = $env{'request.course.id'};
3332: $cdom = $env{'course.'.$cid.'.domain'};
3333: $cnum = $env{'course.'.$cid.'.num'};
3334: }
3335: my $typesref;
1.1195 raeburn 3336: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3337: $typesref = ['active','previous','future'];
3338: } elsif ($type eq 'previous' || $type eq 'future') {
3339: $typesref = [$type];
3340: }
3341: my %roles = &get_my_roles($uname,$udom,'userroles',
3342: $typesref,undef,[$cdom]);
3343: my ($tmp) = keys(%roles);
3344: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3345: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3346: if (@course_roles > 0) {
3347: return 1;
3348: }
3349: return 0;
3350: }
3351:
1.478 albertel 3352: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3353: # input: action, courseID, current domain, intended
1.637 raeburn 3354: # path to file, source of file, instruction to parse file for objects,
3355: # ref to hash for embedded objects,
3356: # ref to hash for codebase of java objects.
1.1095 raeburn 3357: # reference to scalar to accommodate mime type determined
3358: # from File::MMagic if $parser = parse.
1.637 raeburn 3359: #
1.485 raeburn 3360: # output: url to file (if action was uploaddoc),
3361: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3362: #
1.478 albertel 3363: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3364: # course.
1.477 raeburn 3365: #
1.478 albertel 3366: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3367: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3368: # course's home server.
1.477 raeburn 3369: #
1.478 albertel 3370: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3371: # be copied from $source (current location) to
3372: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3373: # and will then be copied to
3374: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3375: # course's home server.
1.485 raeburn 3376: #
1.481 raeburn 3377: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3378: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3379: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3380: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3381: # in course's home server.
1.637 raeburn 3382: #
1.477 raeburn 3383:
3384: sub process_coursefile {
1.1095 raeburn 3385: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3386: $mimetype)=@_;
1.477 raeburn 3387: my $fetchresult;
1.638 albertel 3388: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3389: if ($action eq 'propagate') {
1.638 albertel 3390: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3391: $home);
1.481 raeburn 3392: } else {
1.477 raeburn 3393: my $fpath = '';
3394: my $fname = $file;
1.478 albertel 3395: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3396: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3397: my $filepath = &build_filepath($fpath);
1.481 raeburn 3398: if ($action eq 'copy') {
3399: if ($source eq '') {
3400: $fetchresult = 'no source file';
3401: return $fetchresult;
3402: } else {
3403: my $destination = $filepath.'/'.$fname;
3404: rename($source,$destination);
3405: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3406: $home);
1.481 raeburn 3407: }
3408: } elsif ($action eq 'uploaddoc') {
3409: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3410: print $fh $env{'form.'.$source};
1.481 raeburn 3411: close($fh);
1.637 raeburn 3412: if ($parser eq 'parse') {
1.1024 raeburn 3413: my $mm = new File::MMagic;
1.1095 raeburn 3414: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3415: if ($type eq 'text/html') {
1.1024 raeburn 3416: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3417: unless ($parse_result eq 'ok') {
3418: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3419: }
1.637 raeburn 3420: }
1.1095 raeburn 3421: if (ref($mimetype)) {
3422: $$mimetype = $type;
3423: }
1.637 raeburn 3424: }
1.477 raeburn 3425: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3426: $home);
1.481 raeburn 3427: if ($fetchresult eq 'ok') {
3428: return '/uploaded/'.$fpath.'/'.$fname;
3429: } else {
3430: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3431: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3432: return '/adm/notfound.html';
3433: }
1.477 raeburn 3434: }
3435: }
1.485 raeburn 3436: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3437: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3438: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3439: }
3440: return $fetchresult;
3441: }
3442:
1.637 raeburn 3443: sub build_filepath {
3444: my ($fpath) = @_;
3445: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3446: unless ($fpath eq '') {
3447: my @parts=split('/',$fpath);
3448: foreach my $part (@parts) {
3449: $filepath.= '/'.$part;
3450: if ((-e $filepath)!=1) {
3451: mkdir($filepath,0777);
3452: }
3453: }
3454: }
3455: return $filepath;
3456: }
3457:
3458: sub store_edited_file {
1.638 albertel 3459: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3460: my $file = $primary_url;
3461: $file =~ s#^/uploaded/$docudom/$docuname/##;
3462: my $fpath = '';
3463: my $fname = $file;
3464: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3465: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3466: my $filepath = &build_filepath($fpath);
3467: open(my $fh,'>'.$filepath.'/'.$fname);
3468: print $fh $content;
3469: close($fh);
1.638 albertel 3470: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3471: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3472: $home);
1.637 raeburn 3473: if ($$fetchresult eq 'ok') {
3474: return '/uploaded/'.$fpath.'/'.$fname;
3475: } else {
1.638 albertel 3476: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3477: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3478: return '/adm/notfound.html';
3479: }
3480: }
3481:
1.531 albertel 3482: sub clean_filename {
1.831 albertel 3483: my ($fname,$args)=@_;
1.315 www 3484: # Replace Windows backslashes by forward slashes
1.257 www 3485: $fname=~s/\\/\//g;
1.831 albertel 3486: if (!$args->{'keep_path'}) {
3487: # Get rid of everything but the actual filename
3488: $fname=~s/^.*\/([^\/]+)$/$1/;
3489: }
1.315 www 3490: # Replace spaces by underscores
3491: $fname=~s/\s+/\_/g;
3492: # Replace all other weird characters by nothing
1.831 albertel 3493: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3494: # Replace all .\d. sequences with _\d. so they no longer look like version
3495: # numbers
3496: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3497: return $fname;
3498: }
1.1051 raeburn 3499: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3500: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3501: # image with the same aspect ratio as the original, but with dimensions which do
3502: # not exceed $resizewidth and $resizeheight.
3503:
1.984 neumanie 3504: sub resizeImage {
1.1051 raeburn 3505: my ($img_path,$resizewidth,$resizeheight) = @_;
3506: my $ima = Image::Magick->new;
3507: my $resized;
3508: if (-e $img_path) {
3509: $ima->Read($img_path);
3510: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3511: my $width = $ima->Get('width');
3512: my $height = $ima->Get('height');
3513: if ($width > $resizewidth) {
3514: my $factor = $width/$resizewidth;
3515: my $newheight = $height/$factor;
3516: $ima->Scale(width=>$resizewidth,height=>$newheight);
3517: $resized = 1;
3518: }
3519: }
3520: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3521: my $width = $ima->Get('width');
3522: my $height = $ima->Get('height');
3523: if ($height > $resizeheight) {
3524: my $factor = $height/$resizeheight;
3525: my $newwidth = $width/$factor;
3526: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3527: $resized = 1;
3528: }
3529: }
3530: if ($resized) {
3531: $ima->Write($img_path);
3532: }
3533: }
3534: return;
1.977 amueller 3535: }
3536:
1.608 albertel 3537: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3538: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3539: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3540: # $context - possible values: coursedoc, existingfile, overwrite,
3541: # canceloverwrite, or ''.
3542: # if 'coursedoc': upload to the current course
3543: # if 'existingfile': write file to tmp/overwrites directory
3544: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3545: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3546: # $subdir - directory in userfile to store the file into
1.858 raeburn 3547: # $parser - instruction to parse file for objects ($parser = parse)
3548: # $allfiles - reference to hash for embedded objects
3549: # $codebase - reference to hash for codebase of java objects
3550: # $desuname - username for permanent storage of uploaded file
3551: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3552: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3553: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3554: # $resizewidth - width (pixels) to which to resize uploaded image
3555: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3556: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3557: # from File::MMagic.
1.858 raeburn 3558: #
1.686 albertel 3559: # output: url of file in userspace, or error: <message>
3560: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3561:
1.531 albertel 3562: sub userfileupload {
1.1090 raeburn 3563: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3564: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3565: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3566: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3567: $fname=&clean_filename($fname);
1.1090 raeburn 3568: # See if there is anything left
1.257 www 3569: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3570: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3571: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3572: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3573: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3574: my $now = time;
1.1090 raeburn 3575: my $filepath;
1.1095 raeburn 3576: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3577: $filepath = 'tmp/helprequests/'.$now;
3578: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3579: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3580: '_'.$env{'user.domain'}.'/pending';
3581: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3582: my ($docuname,$docudom);
3583: if ($destudom) {
3584: $docudom = $destudom;
3585: } else {
3586: $docudom = $env{'user.domain'};
3587: }
3588: if ($destuname) {
3589: $docuname = $destuname;
3590: } else {
3591: $docuname = $env{'user.name'};
3592: }
3593: if (exists($env{'form.group'})) {
3594: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3595: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3596: }
3597: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3598: if ($context eq 'canceloverwrite') {
3599: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3600: if (-e $tempfile) {
3601: my @info = stat($tempfile);
3602: if ($info[9] eq $env{'form.timestamp'}) {
3603: unlink($tempfile);
3604: }
3605: }
3606: return;
1.523 raeburn 3607: }
3608: }
1.1090 raeburn 3609: # Create the directory if not present
1.741 raeburn 3610: my @parts=split(/\//,$filepath);
3611: my $fullpath = $perlvar{'lonDaemons'};
3612: for (my $i=0;$i<@parts;$i++) {
3613: $fullpath .= '/'.$parts[$i];
3614: if ((-e $fullpath)!=1) {
3615: mkdir($fullpath,0777);
3616: }
3617: }
3618: open(my $fh,'>'.$fullpath.'/'.$fname);
3619: print $fh $env{'form.'.$formname};
3620: close($fh);
1.1090 raeburn 3621: if ($context eq 'existingfile') {
3622: my @info = stat($fullpath.'/'.$fname);
3623: return ($fullpath.'/'.$fname,$info[9]);
3624: } else {
3625: return $fullpath.'/'.$fname;
3626: }
1.523 raeburn 3627: }
1.995 raeburn 3628: if ($subdir eq 'scantron') {
3629: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3630: } else {
1.995 raeburn 3631: $fname="$subdir/$fname";
3632: }
1.1090 raeburn 3633: if ($context eq 'coursedoc') {
1.638 albertel 3634: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3635: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3636: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3637: return &finishuserfileupload($docuname,$docudom,
3638: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3639: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3640: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3641: } else {
1.1218 raeburn 3642: if ($env{'form.folder'}) {
3643: $fname=$env{'form.folder'}.'/'.$fname;
3644: }
1.638 albertel 3645: return &process_coursefile('uploaddoc',$docuname,$docudom,
3646: $fname,$formname,$parser,
1.1095 raeburn 3647: $allfiles,$codebase,$mimetype);
1.481 raeburn 3648: }
1.719 banghart 3649: } elsif (defined($destuname)) {
3650: my $docuname=$destuname;
3651: my $docudom=$destudom;
1.860 raeburn 3652: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3653: $parser,$allfiles,$codebase,
1.1051 raeburn 3654: $thumbwidth,$thumbheight,
1.1095 raeburn 3655: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3656: } else {
1.638 albertel 3657: my $docuname=$env{'user.name'};
3658: my $docudom=$env{'user.domain'};
1.1220 raeburn 3659: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3660: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3661: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3662: }
1.860 raeburn 3663: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3664: $parser,$allfiles,$codebase,
1.1051 raeburn 3665: $thumbwidth,$thumbheight,
1.1095 raeburn 3666: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3667: }
1.271 www 3668: }
3669:
3670: sub finishuserfileupload {
1.860 raeburn 3671: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3672: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3673: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3674: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3675:
1.860 raeburn 3676: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3677: $file=$fname;
3678: if ($fname=~m|/|) {
3679: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3680: $path.=$fnamepath.'/';
3681: }
1.259 www 3682: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3683: my $count;
3684: for ($count=4;$count<=$#parts;$count++) {
3685: $filepath.="/$parts[$count]";
3686: if ((-e $filepath)!=1) {
3687: mkdir($filepath,0777);
3688: }
3689: }
1.984 neumanie 3690:
1.258 www 3691: # Save the file
3692: {
1.701 albertel 3693: if (!open(FH,'>'.$filepath.'/'.$file)) {
3694: &logthis('Failed to create '.$filepath.'/'.$file);
3695: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3696: return '/adm/notfound.html';
3697: }
1.1090 raeburn 3698: if ($context eq 'overwrite') {
1.1117 foxr 3699: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3700: my $target = $filepath.'/'.$file;
3701: if (-e $source) {
3702: my @info = stat($source);
3703: if ($info[9] eq $env{'form.timestamp'}) {
3704: unless (&File::Copy::move($source,$target)) {
3705: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3706: return "Moving from $source failed";
3707: }
3708: } else {
3709: return "Temporary file: $source had unexpected date/time for last modification";
3710: }
3711: } else {
3712: return "Temporary file: $source missing";
3713: }
3714: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3715: &logthis('Failed to write to '.$filepath.'/'.$file);
3716: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3717: return '/adm/notfound.html';
3718: }
1.570 albertel 3719: close(FH);
1.1051 raeburn 3720: if ($resizewidth && $resizeheight) {
3721: my $mm = new File::MMagic;
3722: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3723: if ($mime_type =~ m{^image/}) {
3724: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3725: }
1.977 amueller 3726: }
1.258 www 3727: }
1.1152 raeburn 3728: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3729: if (ref($mimetype)) {
3730: if ($$mimetype eq '') {
3731: my $mm = new File::MMagic;
3732: my $type = $mm->checktype_filename($filepath.'/'.$file);
3733: $$mimetype = $type;
3734: }
3735: }
3736: }
1.637 raeburn 3737: if ($parser eq 'parse') {
1.1152 raeburn 3738: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3739: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3740: $allfiles,$codebase);
3741: unless ($parse_result eq 'ok') {
3742: &logthis('Failed to parse '.$filepath.$file.
3743: ' for embedded media: '.$parse_result);
3744: }
1.637 raeburn 3745: }
3746: }
1.860 raeburn 3747: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3748: my $input = $filepath.'/'.$file;
3749: my $output = $filepath.'/'.'tn-'.$file;
3750: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3751: system("convert -sample $thumbsize $input $output");
3752: if (-e $filepath.'/'.'tn-'.$file) {
3753: $fetchthumb = 1;
3754: }
3755: }
1.858 raeburn 3756:
1.259 www 3757: # Notify homeserver to grep it
3758: #
1.984 neumanie 3759: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3760: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3761: if ($fetchresult eq 'ok') {
1.860 raeburn 3762: if ($fetchthumb) {
3763: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3764: if ($thumbresult ne 'ok') {
3765: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3766: $docuhome.': '.$thumbresult);
3767: }
3768: }
1.259 www 3769: #
1.258 www 3770: # Return the URL to it
1.494 albertel 3771: return '/uploaded/'.$path.$file;
1.263 www 3772: } else {
1.494 albertel 3773: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3774: ': '.$fetchresult);
1.263 www 3775: return '/adm/notfound.html';
1.858 raeburn 3776: }
1.493 albertel 3777: }
3778:
1.637 raeburn 3779: sub extract_embedded_items {
1.961 raeburn 3780: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3781: my @state = ();
1.1164 raeburn 3782: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3783: my %javafiles = (
3784: codebase => '',
3785: code => '',
3786: archive => ''
3787: );
3788: my %mediafiles = (
3789: src => '',
3790: movie => '',
3791: );
1.648 raeburn 3792: my $p;
3793: if ($content) {
3794: $p = HTML::LCParser->new($content);
3795: } else {
1.961 raeburn 3796: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3797: }
1.641 albertel 3798: while (my $t=$p->get_token()) {
1.640 albertel 3799: if ($t->[0] eq 'S') {
3800: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3801: push(@state, $tagname);
1.648 raeburn 3802: if (lc($tagname) eq 'allow') {
3803: &add_filetype($allfiles,$attr->{'src'},'src');
3804: }
1.640 albertel 3805: if (lc($tagname) eq 'img') {
3806: &add_filetype($allfiles,$attr->{'src'},'src');
3807: }
1.886 albertel 3808: if (lc($tagname) eq 'a') {
1.1222 raeburn 3809: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3810: &add_filetype($allfiles,$attr->{'href'},'href');
3811: }
1.886 albertel 3812: }
1.645 raeburn 3813: if (lc($tagname) eq 'script') {
1.1164 raeburn 3814: my $src;
1.645 raeburn 3815: if ($attr->{'archive'} =~ /\.jar$/i) {
3816: &add_filetype($allfiles,$attr->{'archive'},'archive');
3817: } else {
1.1164 raeburn 3818: if ($attr->{'src'} ne '') {
3819: $src = $attr->{'src'};
3820: &add_filetype($allfiles,$src,'src');
3821: }
3822: }
3823: my $text = $p->get_trimmed_text();
3824: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3825: my @swfargs = split(/,/,$1);
3826: foreach my $item (@swfargs) {
3827: $item =~ s/["']//g;
3828: $item =~ s/^\s+//;
3829: $item =~ s/\s+$//;
3830: }
3831: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3832: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3833: push(@{$related{$swfargs[0]}},$swfargs[2]);
3834: } else {
3835: $related{$swfargs[0]} = [$swfargs[2]];
3836: }
3837: }
1.645 raeburn 3838: }
3839: }
3840: if (lc($tagname) eq 'link') {
3841: if (lc($attr->{'rel'}) eq 'stylesheet') {
3842: &add_filetype($allfiles,$attr->{'href'},'href');
3843: }
3844: }
1.640 albertel 3845: if (lc($tagname) eq 'object' ||
3846: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3847: foreach my $item (keys(%javafiles)) {
3848: $javafiles{$item} = '';
3849: }
1.1164 raeburn 3850: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3851: $lastids{lc($tagname)} = $attr->{'id'};
3852: }
1.640 albertel 3853: }
3854: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3855: my $name = lc($attr->{'name'});
3856: foreach my $item (keys(%javafiles)) {
3857: if ($name eq $item) {
3858: $javafiles{$item} = $attr->{'value'};
3859: last;
3860: }
3861: }
1.1164 raeburn 3862: my $pathfrom;
1.640 albertel 3863: foreach my $item (keys(%mediafiles)) {
3864: if ($name eq $item) {
1.1164 raeburn 3865: $pathfrom = $attr->{'value'};
3866: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3867: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3868: last;
3869: }
3870: }
1.1164 raeburn 3871: if ($name eq 'flashvars') {
3872: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3873: }
3874: if ($pathfrom ne '') {
3875: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3876: $pathfrom);
3877: }
1.640 albertel 3878: }
3879: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3880: foreach my $item (keys(%javafiles)) {
3881: if ($attr->{$item}) {
3882: $javafiles{$item} = $attr->{$item};
3883: last;
3884: }
3885: }
3886: foreach my $item (keys(%mediafiles)) {
3887: if ($attr->{$item}) {
3888: &add_filetype($allfiles,$attr->{$item},$item);
3889: last;
3890: }
3891: }
1.1164 raeburn 3892: if (lc($tagname) eq 'embed') {
3893: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3894: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3895: $attr->{'src'});
3896: }
3897: }
1.640 albertel 3898: }
1.1243 raeburn 3899: if (lc($tagname) eq 'iframe') {
3900: my $src = $attr->{'src'} ;
3901: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3902: &add_filetype($allfiles,$src,'src');
3903: } elsif ($src =~ m{^/}) {
3904: if ($env{'request.course.id'}) {
3905: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3906: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3907: my $url = &hreflocation('',$fullpath);
3908: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3909: my $relpath = $1;
3910: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3911: &add_filetype($allfiles,$1,'src');
3912: }
3913: }
3914: }
3915: }
3916: }
1.1164 raeburn 3917: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3918: pop(@state);
1.1164 raeburn 3919: }
1.640 albertel 3920: } elsif ($t->[0] eq 'E') {
3921: my ($tagname) = ($t->[1]);
3922: if ($javafiles{'codebase'} ne '') {
3923: $javafiles{'codebase'} .= '/';
3924: }
3925: if (lc($tagname) eq 'applet' ||
3926: lc($tagname) eq 'object' ||
3927: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3928: ) {
3929: foreach my $item (keys(%javafiles)) {
3930: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3931: my $file=$javafiles{'codebase'}.$javafiles{$item};
3932: &add_filetype($allfiles,$file,$item);
3933: }
3934: }
3935: }
3936: pop @state;
3937: }
3938: }
1.1164 raeburn 3939: foreach my $id (sort(keys(%flashvars))) {
3940: if ($shockwave{$id} ne '') {
3941: my @pairs = split(/\&/,$flashvars{$id});
3942: foreach my $pair (@pairs) {
3943: my ($key,$value) = split(/\=/,$pair);
3944: if ($key eq 'thumb') {
3945: &add_filetype($allfiles,$value,$key);
3946: } elsif ($key eq 'content') {
3947: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3948: my ($ext) = ($value =~ /\.([^.]+)$/);
3949: if ($ext ne '') {
3950: &add_filetype($allfiles,$path.$value,$ext);
3951: }
3952: }
3953: }
3954: }
3955: }
1.637 raeburn 3956: return 'ok';
3957: }
3958:
1.639 albertel 3959: sub add_filetype {
3960: my ($allfiles,$file,$type)=@_;
3961: if (exists($allfiles->{$file})) {
3962: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3963: push(@{$allfiles->{$file}}, &escape($type));
3964: }
3965: } else {
3966: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3967: }
3968: }
3969:
1.1164 raeburn 3970: sub embedded_dependency {
3971: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3972: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3973: if (($identifier ne '') &&
3974: (ref($related->{$identifier}) eq 'ARRAY') &&
3975: ($pathfrom ne '')) {
3976: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3977: foreach my $dep (@{$related->{$identifier}}) {
3978: &add_filetype($allfiles,$path.$dep,'object');
3979: }
3980: }
3981: }
3982: return;
3983: }
3984:
1.493 albertel 3985: sub removeuploadedurl {
1.984 neumanie 3986: my ($url)=@_;
3987: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3988: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3989: }
3990:
3991: sub removeuserfile {
3992: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3993: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3994: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3995: if ($result eq 'ok') {
1.798 raeburn 3996: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3997: my $metafile = $fname.'.meta';
3998: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3999: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4000: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4001: my $sqlresult =
1.823 albertel 4002: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4003: 'portfolio_metadata',$group,
4004: 'delete');
1.798 raeburn 4005: }
4006: }
4007: return $result;
1.257 www 4008: }
1.15 www 4009:
1.530 albertel 4010: sub mkdiruserfile {
4011: my ($docuname,$docudom,$dir)=@_;
4012: my $home=&homeserver($docuname,$docudom);
4013: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4014: }
4015:
1.531 albertel 4016: sub renameuserfile {
4017: my ($docuname,$docudom,$old,$new)=@_;
4018: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4019: my $result = &reply("renameuserfile:$docudom:$docuname:".
4020: &escape("$old").':'.&escape("$new"),$home);
4021: if ($result eq 'ok') {
4022: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4023: my $oldmeta = $old.'.meta';
4024: my $newmeta = $new.'.meta';
4025: my $metaresult =
4026: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4027: my $url = "/uploaded/$docudom/$docuname/$old";
4028: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4029: my $sqlresult =
1.823 albertel 4030: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4031: 'portfolio_metadata',$group,
4032: 'delete');
1.798 raeburn 4033: }
4034: }
4035: return $result;
1.531 albertel 4036: }
4037:
1.14 www 4038: # ------------------------------------------------------------------------- Log
4039:
4040: sub log {
4041: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4042: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4043: }
4044:
4045: # ------------------------------------------------------------------ Course Log
1.352 www 4046: #
4047: # This routine flushes several buffers of non-mission-critical nature
4048: #
1.157 www 4049:
4050: sub flushcourselogs {
1.352 www 4051: &logthis('Flushing log buffers');
4052: #
4053: # course logs
4054: # This is a log of all transactions in a course, which can be used
4055: # for data mining purposes
4056: #
4057: # It also collects the courseid database, which lists last transaction
4058: # times and course titles for all courseids
4059: #
4060: my %courseidbuffer=();
1.921 raeburn 4061: foreach my $crsid (keys(%courselogs)) {
1.352 www 4062: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4063: &escape($courselogs{$crsid}),
4064: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4065: delete $courselogs{$crsid};
4066: } else {
4067: &logthis('Failed to flush log buffer for '.$crsid);
4068: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4069: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4070: " exceeded maximum size, deleting.</font>");
4071: delete $courselogs{$crsid};
4072: }
1.352 www 4073: }
1.920 raeburn 4074: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4075: 'description' => $coursedescrbuf{$crsid},
4076: 'inst_code' => $courseinstcodebuf{$crsid},
4077: 'type' => $coursetypebuf{$crsid},
4078: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4079: };
1.191 harris41 4080: }
1.352 www 4081: #
4082: # Write course id database (reverse lookup) to homeserver of courses
4083: # Is used in pickcourse
4084: #
1.840 albertel 4085: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4086: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4087: $courseidbuffer{$crs_home},
4088: $crs_home,'timeonly');
1.352 www 4089: }
4090: #
4091: # File accesses
4092: # Writes to the dynamic metadata of resources to get hit counts, etc.
4093: #
1.449 matthew 4094: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4095: if ($entry =~ /___count$/) {
4096: my ($dom,$name);
1.807 albertel 4097: ($dom,$name,undef)=
1.811 albertel 4098: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4099: if (! defined($dom) || $dom eq '' ||
4100: ! defined($name) || $name eq '') {
1.620 albertel 4101: my $cid = $env{'request.course.id'};
4102: $dom = $env{'request.'.$cid.'.domain'};
4103: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4104: }
1.450 matthew 4105: my $value = $accesshash{$entry};
4106: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4107: my %temphash=($url => $value);
1.449 matthew 4108: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4109: if ($result eq 'ok') {
4110: delete $accesshash{$entry};
4111: }
4112: } else {
1.811 albertel 4113: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4114: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4115: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4116: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4117: delete $accesshash{$entry};
4118: }
1.185 www 4119: }
1.191 harris41 4120: }
1.352 www 4121: #
4122: # Roles
4123: # Reverse lookup of user roles for course faculty/staff and co-authorship
4124: #
1.800 albertel 4125: foreach my $entry (keys(%userrolehash)) {
1.351 www 4126: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4127: split(/\:/,$entry);
4128: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4129: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4130: $rudom,$runame) eq 'ok') {
4131: delete $userrolehash{$entry};
4132: }
4133: }
1.662 raeburn 4134: #
1.1334 raeburn 4135: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4136: #
4137: my %domrolebuffer = ();
1.1000 raeburn 4138: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4139: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4140: if ($domrolebuffer{$rudom}) {
4141: $domrolebuffer{$rudom}.='&'.&escape($entry).
4142: '='.&escape($domainrolehash{$entry});
4143: } else {
4144: $domrolebuffer{$rudom}.=&escape($entry).
4145: '='.&escape($domainrolehash{$entry});
4146: }
4147: delete $domainrolehash{$entry};
4148: }
4149: foreach my $dom (keys(%domrolebuffer)) {
1.1324 raeburn 4150: my %servers;
4151: if (defined(&domain($dom,'primary'))) {
4152: my $primary=&domain($dom,'primary');
4153: my $hostname=&hostname($primary);
4154: $servers{$primary} = $hostname;
4155: } else {
4156: %servers = &get_servers($dom,'library');
4157: }
1.841 albertel 4158: foreach my $tryserver (keys(%servers)) {
1.1324 raeburn 4159: if (&reply('domroleput:'.$dom.':'.
4160: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4161: last;
4162: } else {
1.841 albertel 4163: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4164: }
1.662 raeburn 4165: }
4166: }
1.186 www 4167: $dumpcount++;
1.157 www 4168: }
4169:
4170: sub courselog {
4171: my $what=shift;
1.158 www 4172: $what=time.':'.$what;
1.620 albertel 4173: unless ($env{'request.course.id'}) { return ''; }
4174: $coursedombuf{$env{'request.course.id'}}=
4175: $env{'course.'.$env{'request.course.id'}.'.domain'};
4176: $coursenumbuf{$env{'request.course.id'}}=
4177: $env{'course.'.$env{'request.course.id'}.'.num'};
4178: $coursehombuf{$env{'request.course.id'}}=
4179: $env{'course.'.$env{'request.course.id'}.'.home'};
4180: $coursedescrbuf{$env{'request.course.id'}}=
4181: $env{'course.'.$env{'request.course.id'}.'.description'};
4182: $courseinstcodebuf{$env{'request.course.id'}}=
4183: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4184: $courseownerbuf{$env{'request.course.id'}}=
4185: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4186: $coursetypebuf{$env{'request.course.id'}}=
4187: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4188: if (defined $courselogs{$env{'request.course.id'}}) {
4189: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4190: } else {
1.620 albertel 4191: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4192: }
1.620 albertel 4193: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4194: &flushcourselogs();
4195: }
1.158 www 4196: }
4197:
4198: sub courseacclog {
4199: my $fnsymb=shift;
1.620 albertel 4200: unless ($env{'request.course.id'}) { return ''; }
4201: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4202: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4203: $what.=':POST';
1.583 matthew 4204: # FIXME: Probably ought to escape things....
1.800 albertel 4205: foreach my $key (keys(%env)) {
4206: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4207: my $formitem = $1;
4208: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4209: $what.=':'.$formitem.'='.$env{$key};
4210: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4211: $what.=':'.$formitem.'='.$env{$key};
4212: }
1.158 www 4213: }
1.191 harris41 4214: }
1.583 matthew 4215: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4216: # FIXME: We should not be depending on a form parameter that someone
4217: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4218: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4219: $what.= ':POST';
4220: # FIXME: Probably ought to escape things....
4221: foreach my $element ('courseexp','crsfulltext','crsrelated',
4222: 'crsdiscuss') {
1.620 albertel 4223: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4224: }
4225: }
1.158 www 4226: }
4227: &courselog($what);
1.149 www 4228: }
4229:
1.185 www 4230: sub countacc {
4231: my $url=&declutter(shift);
1.458 matthew 4232: return if (! defined($url) || $url eq '');
1.620 albertel 4233: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4234: #
4235: # Mark that this url was used in this course
4236: #
1.620 albertel 4237: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4238: #
4239: # Increase the access count for this resource in this child process
4240: #
1.281 www 4241: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4242: $accesshash{$key}++;
1.185 www 4243: }
1.349 www 4244:
1.361 www 4245: sub linklog {
4246: my ($from,$to)=@_;
4247: $from=&declutter($from);
4248: $to=&declutter($to);
4249: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4250: $accesshash{$to.'___'.$from.'___goto'}=1;
4251: }
1.1160 www 4252:
4253: sub statslog {
4254: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4255: if ($users<2) { return; }
4256: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4257: 'course' => $env{'request.course.id'},
4258: 'sections' => '"all"',
4259: 'num_students' => $users,
4260: 'part' => $part,
4261: 'symb' => $symb,
4262: 'mean_tries' => $av_attempts,
4263: 'deg_of_diff' => $degdiff});
4264: foreach my $key (keys(%dynstore)) {
4265: $accesshash{$key}=$dynstore{$key};
4266: }
4267: }
1.361 www 4268:
1.349 www 4269: sub userrolelog {
4270: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4271: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4272: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4273: $userrolehash
4274: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4275: =$tend.':'.$tstart;
1.662 raeburn 4276: }
1.1169 droeschl 4277: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4278: $userrolehash
4279: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4280: =$tend.':'.$tstart;
4281: }
1.1334 raeburn 4282: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4283: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4284: $domainrolehash
4285: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4286: = $tend.':'.$tstart;
4287: }
1.351 www 4288: }
4289:
1.957 raeburn 4290: sub courserolelog {
4291: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 4292: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4293: my $cdom = $1;
4294: my $cnum = $2;
4295: my $sec = $3;
4296: my $namespace = 'rolelog';
4297: my %storehash = (
4298: role => $trole,
4299: start => $tstart,
4300: end => $tend,
4301: selfenroll => $selfenroll,
4302: context => $context,
4303: );
4304: if ($trole eq 'gr') {
4305: $namespace = 'groupslog';
4306: $storehash{'group'} = $sec;
4307: } else {
4308: $storehash{'section'} = $sec;
4309: }
1.1188 raeburn 4310: &write_log('course',$namespace,\%storehash,$delflag,$username,
4311: $domain,$cnum,$cdom);
1.1184 raeburn 4312: if (($trole ne 'st') || ($sec ne '')) {
4313: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4314: }
4315: }
4316: return;
4317: }
4318:
1.1184 raeburn 4319: sub domainrolelog {
4320: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4321: if ($area =~ m{^/($match_domain)/$}) {
4322: my $cdom = $1;
4323: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4324: my $namespace = 'rolelog';
4325: my %storehash = (
4326: role => $trole,
4327: start => $tstart,
4328: end => $tend,
4329: context => $context,
4330: );
1.1188 raeburn 4331: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4332: $domain,$domconfiguser,$cdom);
1.1184 raeburn 4333: }
4334: return;
4335:
4336: }
4337:
4338: sub coauthorrolelog {
4339: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4340: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4341: my $audom = $1;
4342: my $auname = $2;
4343: my $namespace = 'rolelog';
4344: my %storehash = (
4345: role => $trole,
4346: start => $tstart,
4347: end => $tend,
4348: context => $context,
4349: );
1.1188 raeburn 4350: &write_log('author',$namespace,\%storehash,$delflag,$username,
4351: $domain,$auname,$audom);
1.1184 raeburn 4352: }
4353: return;
4354: }
4355:
1.351 www 4356: sub get_course_adv_roles {
1.948 raeburn 4357: my ($cid,$codes) = @_;
1.620 albertel 4358: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4359: my %coursehash=&coursedescription($cid);
1.988 raeburn 4360: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4361: my %nothide=();
1.800 albertel 4362: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4363: if ($user !~ /:/) {
4364: $nothide{join(':',split(/[\@]/,$user))}=1;
4365: } else {
4366: $nothide{$user}=1;
4367: }
1.470 www 4368: }
1.1219 raeburn 4369: my @possdoms = ($coursehash{'domain'});
4370: if ($coursehash{'checkforpriv'}) {
4371: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4372: }
1.351 www 4373: my %returnhash=();
4374: my %dumphash=
4375: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4376: my $now=time;
1.997 raeburn 4377: my %privileged;
1.1000 raeburn 4378: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4379: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4380: if (($tstart) && ($tstart<0)) { next; }
4381: if (($tend) && ($tend<$now)) { next; }
4382: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4383: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4384: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 4385: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4386: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4387: if ($role eq 'cr') { next; }
1.948 raeburn 4388: if ($codes) {
4389: if ($section) { $role .= ':'.$section; }
4390: if ($returnhash{$role}) {
4391: $returnhash{$role}.=','.$username.':'.$domain;
4392: } else {
4393: $returnhash{$role}=$username.':'.$domain;
4394: }
1.351 www 4395: } else {
1.988 raeburn 4396: my $key=&plaintext($role,$crstype);
1.973 bisitz 4397: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4398: if ($returnhash{$key}) {
4399: $returnhash{$key}.=','.$username.':'.$domain;
4400: } else {
4401: $returnhash{$key}=$username.':'.$domain;
4402: }
1.351 www 4403: }
1.948 raeburn 4404: }
1.400 www 4405: return %returnhash;
4406: }
4407:
4408: sub get_my_roles {
1.937 raeburn 4409: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4410: unless (defined($uname)) { $uname=$env{'user.name'}; }
4411: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4412: my (%dumphash,%nothide);
1.1086 raeburn 4413: if ($context eq 'userroles') {
1.1166 raeburn 4414: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4415: } else {
1.1219 raeburn 4416: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4417: if ($hidepriv) {
4418: my %coursehash=&coursedescription($udom.'_'.$uname);
4419: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4420: if ($user !~ /:/) {
4421: $nothide{join(':',split(/[\@]/,$user))} = 1;
4422: } else {
4423: $nothide{$user} = 1;
4424: }
4425: }
4426: }
1.858 raeburn 4427: }
1.400 www 4428: my %returnhash=();
4429: my $now=time;
1.999 raeburn 4430: my %privileged;
1.800 albertel 4431: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4432: my ($role,$tend,$tstart);
4433: if ($context eq 'userroles') {
1.1149 raeburn 4434: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4435: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4436: } else {
4437: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4438: }
1.400 www 4439: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4440: my $status = 'active';
1.939 raeburn 4441: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4442: $status = 'previous';
4443: }
4444: if (($tstart) && ($now<$tstart)) {
4445: $status = 'future';
4446: }
4447: if (ref($types) eq 'ARRAY') {
4448: if (!grep(/^\Q$status\E$/,@{$types})) {
4449: next;
4450: }
4451: } else {
4452: if ($status ne 'active') {
4453: next;
4454: }
4455: }
1.867 raeburn 4456: my ($rolecode,$username,$domain,$section,$area);
4457: if ($context eq 'userroles') {
1.1186 raeburn 4458: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4459: (undef,$domain,$username,$section) = split(/\//,$area);
4460: } else {
4461: ($role,$username,$domain,$section) = split(/\:/,$entry);
4462: }
1.832 raeburn 4463: if (ref($roledoms) eq 'ARRAY') {
4464: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4465: next;
4466: }
4467: }
4468: if (ref($roles) eq 'ARRAY') {
4469: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4470: if ($role =~ /^cr\//) {
4471: if (!grep(/^cr$/,@{$roles})) {
4472: next;
4473: }
1.1104 raeburn 4474: } elsif ($role =~ /^gr\//) {
4475: if (!grep(/^gr$/,@{$roles})) {
4476: next;
4477: }
1.922 raeburn 4478: } else {
4479: next;
4480: }
1.832 raeburn 4481: }
1.867 raeburn 4482: }
1.937 raeburn 4483: if ($hidepriv) {
1.1219 raeburn 4484: my @privroles = ('dc','su');
1.999 raeburn 4485: if ($context eq 'userroles') {
1.1219 raeburn 4486: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4487: } else {
1.1219 raeburn 4488: my $possdoms = [$domain];
4489: if (ref($roledoms) eq 'ARRAY') {
4490: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4491: }
1.1219 raeburn 4492: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4493: if (!$nothide{$username.':'.$domain}) {
4494: next;
4495: }
4496: }
1.937 raeburn 4497: }
4498: }
1.933 raeburn 4499: if ($withsec) {
4500: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4501: $tstart.':'.$tend;
4502: } else {
4503: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4504: }
1.832 raeburn 4505: }
1.373 www 4506: return %returnhash;
1.399 www 4507: }
4508:
1.1333 raeburn 4509: sub get_all_adhocroles {
4510: my ($dom) = @_;
4511: my @roles_by_num = ();
4512: my %domdefaults = &get_domain_defaults($dom);
4513: my (%description,%access_in_dom,%access_info);
4514: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
4515: my $count = 0;
4516: my %domcurrent = %{$domdefaults{'adhocroles'}};
4517: my %ordered;
4518: foreach my $role (sort(keys(%domcurrent))) {
4519: my ($order,$desc,$access_in_dom);
4520: if (ref($domcurrent{$role}) eq 'HASH') {
4521: $order = $domcurrent{$role}{'order'};
4522: $desc = $domcurrent{$role}{'desc'};
4523: $access_in_dom{$role} = $domcurrent{$role}{'access'};
4524: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
4525: }
4526: if ($order eq '') {
4527: $order = $count;
4528: }
4529: $ordered{$order} = $role;
4530: if ($desc ne '') {
4531: $description{$role} = $desc;
4532: } else {
4533: $description{$role}= $role;
4534: }
4535: $count++;
4536: }
4537: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
4538: push(@roles_by_num,$ordered{$item});
4539: }
4540: }
4541: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
4542: }
4543:
1.1332 raeburn 4544: sub get_my_adhocroles {
1.1333 raeburn 4545: my ($cid,$checkreg) = @_;
4546: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
4547: if ($env{'request.course.id'} eq $cid) {
4548: $cdom = $env{'course.'.$cid.'.domain'};
4549: $cnum = $env{'course.'.$cid.'.num'};
4550: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
4551: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
4552: $cdom = $1;
4553: $cnum = $2;
4554: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
4555: $cdom,$cnum);
4556: }
4557: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
4558: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4559: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
4560: if ($rosterhash{$user} ne '') {
4561: my $type = (split(/:/,$rosterhash{$user}))[5];
4562: return ([],{}) if ($type eq 'auto');
4563: }
4564: }
4565: if (($cdom ne '') && ($cnum ne '')) {
1.1334 raeburn 4566: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332 raeburn 4567: my $then=$env{'user.login.time'};
4568: my $update=$env{'user.update.time'};
1.1335 raeburn 4569: if (!$update) {
4570: $update = $then;
4571: }
4572: my @liveroles;
1.1334 raeburn 4573: foreach my $role ('dh','da') {
4574: if ($env{"user.role.$role./$cdom/"}) {
1.1335 raeburn 4575: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334 raeburn 4576: my $limit = $update;
4577: if ($env{'request.role'} eq "$role./$cdom/") {
4578: $limit = $then;
4579: }
1.1335 raeburn 4580: my $activerole = 1;
4581: if ($tstart && $tstart>$limit) { $activerole = 0; }
4582: if ($tend && $tend <$limit) { $activerole = 0; }
4583: if ($activerole) {
4584: push(@liveroles,$role);
4585: }
1.1334 raeburn 4586: }
1.1332 raeburn 4587: }
1.1335 raeburn 4588: if (@liveroles) {
1.1332 raeburn 4589: if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333 raeburn 4590: my ($accessref,$accessinfo,%access_in_dom);
4591: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
4592: if (ref($roles_by_num) eq 'ARRAY') {
4593: if (@{$roles_by_num}) {
1.1332 raeburn 4594: my %settings;
4595: if ($env{'request.course.id'} eq $cid) {
4596: foreach my $envkey (keys(%env)) {
4597: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
4598: $settings{$1} = $env{$envkey};
4599: }
4600: }
4601: } else {
4602: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
4603: }
4604: my %setincrs;
4605: if ($settings{'internal.adhocaccess'}) {
4606: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
4607: }
4608: my @statuses;
4609: if ($env{'environment.inststatus'}) {
4610: @statuses = split(/,/,$env{'environment.inststatus'});
4611: }
4612: my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333 raeburn 4613: if (ref($accessref) eq 'HASH') {
4614: %access_in_dom = %{$accessref};
4615: }
4616: foreach my $role (@{$roles_by_num}) {
1.1332 raeburn 4617: my ($curraccess,@okstatus,@personnel);
4618: if ($setincrs{$role}) {
4619: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
4620: if ($curraccess eq 'status') {
4621: @okstatus = split(/\&/,$rest);
4622: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4623: @personnel = split(/\&/,$rest);
4624: }
4625: } else {
4626: $curraccess = $access_in_dom{$role};
1.1333 raeburn 4627: if (ref($accessinfo) eq 'HASH') {
4628: if ($curraccess eq 'status') {
4629: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4630: @okstatus = @{$accessinfo->{$role}};
4631: }
4632: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4633: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4634: @personnel = @{$accessinfo->{$role}};
4635: }
1.1332 raeburn 4636: }
4637: }
4638: }
4639: if ($curraccess eq 'none') {
4640: next;
4641: } elsif ($curraccess eq 'all') {
4642: push(@possroles,$role);
1.1336 raeburn 4643: } elsif ($curraccess eq 'dh') {
1.1335 raeburn 4644: if (grep(/^dh$/,@liveroles)) {
4645: push(@possroles,$role);
4646: } else {
4647: next;
4648: }
1.1336 raeburn 4649: } elsif ($curraccess eq 'da') {
1.1335 raeburn 4650: if (grep(/^da$/,@liveroles)) {
4651: push(@possroles,$role);
4652: } else {
4653: next;
4654: }
1.1332 raeburn 4655: } elsif ($curraccess eq 'status') {
4656: if (@okstatus) {
4657: if (!@statuses) {
4658: if (grep(/^default$/,@okstatus)) {
4659: push(@possroles,$role);
4660: }
4661: } else {
4662: foreach my $status (@okstatus) {
4663: if (grep(/^\Q$status\E$/,@statuses)) {
4664: push(@possroles,$role);
4665: last;
4666: }
4667: }
4668: }
4669: }
4670: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4671: if (grep(/^\Q$user\E$/,@personnel)) {
4672: if ($curraccess eq 'exc') {
4673: push(@possroles,$role);
4674: }
4675: } elsif ($curraccess eq 'inc') {
4676: push(@possroles,$role);
4677: }
4678: }
4679: }
4680: }
4681: }
4682: }
4683: }
4684: }
4685: }
1.1333 raeburn 4686: unless (ref($description) eq 'HASH') {
4687: if (ref($roles_by_num) eq 'ARRAY') {
4688: my %desc;
4689: map { $desc{$_} = $_; } (@{$roles_by_num});
4690: $description = \%desc;
4691: } else {
4692: $description = {};
4693: }
4694: }
4695: return (\@possroles,$description);
1.1332 raeburn 4696: }
4697:
1.399 www 4698: # ----------------------------------------------------- Frontpage Announcements
4699: #
4700: #
4701:
4702: sub postannounce {
4703: my ($server,$text)=@_;
1.844 albertel 4704: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4705: unless ($text=~/\w/) { $text=''; }
4706: return &reply('setannounce:'.&escape($text),$server);
4707: }
4708:
4709: sub getannounce {
1.448 albertel 4710:
4711: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4712: my $announcement='';
1.800 albertel 4713: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4714: close($fh);
1.399 www 4715: if ($announcement=~/\w/) {
4716: return
4717: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4718: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4719: } else {
4720: return '';
4721: }
4722: } else {
4723: return '';
4724: }
1.351 www 4725: }
1.353 www 4726:
4727: # ---------------------------------------------------------- Course ID routines
4728: # Deal with domain's nohist_courseid.db files
4729: #
4730:
4731: sub courseidput {
1.921 raeburn 4732: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4733: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4734: my $outcome;
4735: if ($caller eq 'timeonly') {
4736: my $cids = '';
4737: foreach my $item (keys(%$storehash)) {
4738: $cids.=&escape($item).'&';
4739: }
4740: $cids=~s/\&$//;
4741: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4742: $coursehome);
4743: } else {
4744: my $items = '';
4745: foreach my $item (keys(%$storehash)) {
4746: $items.= &escape($item).'='.
4747: &freeze_escape($$storehash{$item}).'&';
4748: }
4749: $items=~s/\&$//;
4750: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4751: $coursehome);
1.918 raeburn 4752: }
4753: if ($outcome eq 'unknown_cmd') {
4754: my $what;
4755: foreach my $cid (keys(%$storehash)) {
4756: $what .= &escape($cid).'=';
1.921 raeburn 4757: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4758: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4759: }
4760: $what =~ s/\:$/&/;
4761: }
4762: $what =~ s/\&$//;
4763: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4764: } else {
4765: return $outcome;
4766: }
1.353 www 4767: }
4768:
4769: sub courseiddump {
1.921 raeburn 4770: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4771: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4772: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4773: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 4774: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4775: my $as_hash = 1;
4776: my %returnhash;
4777: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4778: my %libserv = &all_library();
4779: foreach my $tryserver (keys(%libserv)) {
4780: if ( ( $hostidflag == 1
4781: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4782: || (!defined($hostidflag)) ) {
4783:
1.918 raeburn 4784: if (($domfilter eq '') ||
4785: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4786: my $rep;
4787: if (grep { $_ eq $tryserver } current_machine_ids()) {
4788: $rep = LONCAPA::Lond::dump_course_id_handler(
4789: join(":", (&host_domain($tryserver), $sincefilter,
4790: &escape($descfilter), &escape($instcodefilter),
4791: &escape($ownerfilter), &escape($coursefilter),
4792: &escape($typefilter), &escape($regexp_ok),
4793: $as_hash, &escape($selfenrollonly),
4794: &escape($catfilter), $showhidden, $caller,
4795: &escape($cloner), &escape($cc_clone), $cloneonly,
4796: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 4797: &escape($creationcontext),$domcloner,$hasuniquecode,
4798: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 4799: } else {
4800: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4801: $sincefilter.':'.&escape($descfilter).':'.
4802: &escape($instcodefilter).':'.&escape($ownerfilter).
4803: ':'.&escape($coursefilter).':'.&escape($typefilter).
4804: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4805: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4806: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4807: &escape($cc_clone).':'.$cloneonly.':'.
4808: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 4809: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4810: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 4811: }
4812:
1.918 raeburn 4813: my @pairs=split(/\&/,$rep);
4814: foreach my $item (@pairs) {
4815: my ($key,$value)=split(/\=/,$item,2);
4816: $key = &unescape($key);
4817: next if ($key =~ /^error: 2 /);
4818: my $result = &thaw_unescape($value);
4819: if (ref($result) eq 'HASH') {
4820: $returnhash{$key}=$result;
4821: } else {
1.921 raeburn 4822: my @responses = split(/:/,$value);
4823: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4824: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4825: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4826: }
1.1008 raeburn 4827: }
1.353 www 4828: }
4829: }
4830: }
4831: }
4832: return %returnhash;
4833: }
4834:
1.1055 raeburn 4835: sub courselastaccess {
4836: my ($cdom,$cnum,$hostidref) = @_;
4837: my %returnhash;
4838: if ($cdom && $cnum) {
4839: my $chome = &homeserver($cnum,$cdom);
4840: if ($chome ne 'no_host') {
4841: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4842: &extract_lastaccess(\%returnhash,$rep);
4843: }
4844: } else {
4845: if (!$cdom) { $cdom=''; }
4846: my %libserv = &all_library();
4847: foreach my $tryserver (keys(%libserv)) {
4848: if (ref($hostidref) eq 'ARRAY') {
4849: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4850: }
4851: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4852: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4853: &extract_lastaccess(\%returnhash,$rep);
4854: }
4855: }
4856: }
4857: return %returnhash;
4858: }
4859:
4860: sub extract_lastaccess {
4861: my ($returnhash,$rep) = @_;
4862: if (ref($returnhash) eq 'HASH') {
4863: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4864: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4865: $rep eq '') {
4866: my @pairs=split(/\&/,$rep);
4867: foreach my $item (@pairs) {
4868: my ($key,$value)=split(/\=/,$item,2);
4869: $key = &unescape($key);
4870: next if ($key =~ /^error: 2 /);
4871: $returnhash->{$key} = &thaw_unescape($value);
4872: }
4873: }
4874: }
4875: return;
4876: }
4877:
1.658 raeburn 4878: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4879:
4880: sub dcmailput {
1.685 raeburn 4881: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4882: my $status = &Apache::lonnet::critical(
1.740 www 4883: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4884: &escape($message),$server);
1.662 raeburn 4885: return $status;
4886: }
4887:
1.658 raeburn 4888: sub dcmaildump {
4889: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4890: my %returnhash=();
1.846 albertel 4891:
4892: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4893: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4894: &escape($enddate).':';
4895: my @esc_senders=map { &escape($_)} @$senders;
4896: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4897: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4898: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4899: if (($key) && ($value)) {
4900: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4901: }
4902: }
4903: }
4904: return %returnhash;
4905: }
1.662 raeburn 4906: # ---------------------------------------------------------- Domain roles
4907:
4908: sub get_domain_roles {
4909: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4910: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4911: $startdate = '.';
4912: }
1.1018 raeburn 4913: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4914: $enddate = '.';
4915: }
1.922 raeburn 4916: my $rolelist;
4917: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4918: $rolelist = join('&',@{$roles});
1.922 raeburn 4919: }
1.662 raeburn 4920: my %personnel = ();
1.841 albertel 4921:
4922: my %servers = &get_servers($dom,'library');
4923: foreach my $tryserver (keys(%servers)) {
4924: %{$personnel{$tryserver}}=();
4925: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4926: &escape($startdate).':'.
4927: &escape($enddate).':'.
4928: &escape($rolelist), $tryserver))) {
4929: my ($key,$value) = split(/\=/,$line,2);
4930: if (($key) && ($value)) {
4931: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4932: }
4933: }
1.662 raeburn 4934: }
4935: return %personnel;
4936: }
1.658 raeburn 4937:
1.1332 raeburn 4938: sub get_active_domroles {
4939: my ($dom,$roles) = @_;
4940: return () unless (ref($roles) eq 'ARRAY');
4941: my $now = time;
4942: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
4943: my %domroles;
4944: foreach my $server (keys(%dompersonnel)) {
4945: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
4946: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
4947: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
4948: }
4949: }
4950: return %domroles;
4951: }
4952:
1.1057 www 4953: # ----------------------------------------------------------- Interval timing
1.149 www 4954:
1.1153 www 4955: {
4956: # Caches needed for speedup of navmaps
4957: # We don't want to cache this for very long at all (5 seconds at most)
4958: #
4959: # The user for whom we cache
4960: my $cachedkey='';
4961: # The cached times for this user
4962: my %cachedtimes=();
4963: # When this was last done
1.1282 raeburn 4964: my $cachedtime='';
1.1153 www 4965:
4966: sub load_all_first_access {
1.1308 raeburn 4967: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 4968: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 raeburn 4969: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
4970: (!$ignorecache)) {
1.1154 raeburn 4971: return;
4972: }
4973: $cachedtime=time;
4974: $cachedkey=$uname.':'.$udom;
4975: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4976: }
4977:
1.504 albertel 4978: sub get_first_access {
1.1308 raeburn 4979: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 4980: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4981: if ($argsymb) { $symb=$argsymb; }
4982: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4983: if ($argmap) { $map = $argmap; }
1.926 albertel 4984: if ($type eq 'course') {
4985: $res='course';
4986: } elsif ($type eq 'map') {
1.588 albertel 4987: $res=&symbread($map);
4988: } else {
4989: $res=$symb;
4990: }
1.1308 raeburn 4991: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 4992: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4993: }
4994:
4995: sub set_first_access {
1.1162 raeburn 4996: my ($type,$interval)=@_;
1.790 albertel 4997: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4998: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4999: if ($type eq 'course') {
5000: $res='course';
5001: } elsif ($type eq 'map') {
1.588 albertel 5002: $res=&symbread($map);
5003: } else {
5004: $res=$symb;
5005: }
1.1153 www 5006: $cachedkey='';
1.1162 raeburn 5007: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 5008: if (!$firstaccess) {
1.1162 raeburn 5009: my $start = time;
5010: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5011: $udom,$uname);
5012: if ($putres eq 'ok') {
5013: &put('timerinterval',{"$courseid\0$res"=>$interval},
5014: $udom,$uname);
5015: &appenv(
5016: {
5017: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5018: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5019: }
5020: );
5021: }
5022: return $putres;
1.505 albertel 5023: }
5024: return 'already_set';
1.504 albertel 5025: }
1.1153 www 5026: }
1.1282 raeburn 5027:
1.110 www 5028: # --------------------------------------------- Set Expire Date for Spreadsheet
5029:
5030: sub expirespread {
5031: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5032: my $cid=$env{'request.course.id'};
1.110 www 5033: if ($cid) {
5034: my $now=time;
5035: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5036: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5037: $env{'course.'.$cid.'.num'}.
1.110 www 5038: ':nohist_expirationdates:'.
5039: &escape($key).'='.$now,
1.620 albertel 5040: $env{'course.'.$cid.'.home'})
1.110 www 5041: }
5042: return 'ok';
1.14 www 5043: }
5044:
1.109 www 5045: # ----------------------------------------------------- Devalidate Spreadsheets
5046:
5047: sub devalidate {
1.325 www 5048: my ($symb,$uname,$udom)=@_;
1.620 albertel 5049: my $cid=$env{'request.course.id'};
1.109 www 5050: if ($cid) {
1.391 matthew 5051: # delete the stored spreadsheets for
5052: # - the student level sheet of this user in course's homespace
5053: # - the assessment level sheet for this resource
5054: # for this user in user's homespace
1.553 albertel 5055: # - current conditional state info
1.325 www 5056: my $key=$uname.':'.$udom.':';
1.109 www 5057: my $status=
1.299 matthew 5058: &del('nohist_calculatedsheets',
1.391 matthew 5059: [$key.'studentcalc:'],
1.620 albertel 5060: $env{'course.'.$cid.'.domain'},
5061: $env{'course.'.$cid.'.num'})
1.133 albertel 5062: .' '.
5063: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5064: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5065: unless ($status eq 'ok ok') {
5066: &logthis('Could not devalidate spreadsheet '.
1.325 www 5067: $uname.' at '.$udom.' for '.
1.109 www 5068: $symb.': '.$status);
1.133 albertel 5069: }
1.553 albertel 5070: &delenv('user.state.'.$cid);
1.109 www 5071: }
5072: }
5073:
1.265 albertel 5074: sub get_scalar {
5075: my ($string,$end) = @_;
5076: my $value;
5077: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5078: $value = $1;
5079: } elsif ($$string =~ s/^([^&]*?)&//) {
5080: $value = $1;
5081: }
5082: return &unescape($value);
5083: }
5084:
5085: sub array2str {
5086: my (@array) = @_;
5087: my $result=&arrayref2str(\@array);
5088: $result=~s/^__ARRAY_REF__//;
5089: $result=~s/__END_ARRAY_REF__$//;
5090: return $result;
5091: }
5092:
1.204 albertel 5093: sub arrayref2str {
5094: my ($arrayref) = @_;
1.265 albertel 5095: my $result='__ARRAY_REF__';
1.204 albertel 5096: foreach my $elem (@$arrayref) {
1.265 albertel 5097: if(ref($elem) eq 'ARRAY') {
5098: $result.=&arrayref2str($elem).'&';
5099: } elsif(ref($elem) eq 'HASH') {
5100: $result.=&hashref2str($elem).'&';
5101: } elsif(ref($elem)) {
5102: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5103: } else {
5104: $result.=&escape($elem).'&';
5105: }
5106: }
5107: $result=~s/\&$//;
1.265 albertel 5108: $result .= '__END_ARRAY_REF__';
1.204 albertel 5109: return $result;
5110: }
5111:
1.168 albertel 5112: sub hash2str {
1.204 albertel 5113: my (%hash) = @_;
5114: my $result=&hashref2str(\%hash);
1.265 albertel 5115: $result=~s/^__HASH_REF__//;
5116: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5117: return $result;
5118: }
5119:
5120: sub hashref2str {
5121: my ($hashref)=@_;
1.265 albertel 5122: my $result='__HASH_REF__';
1.800 albertel 5123: foreach my $key (sort(keys(%$hashref))) {
5124: if (ref($key) eq 'ARRAY') {
5125: $result.=&arrayref2str($key).'=';
5126: } elsif (ref($key) eq 'HASH') {
5127: $result.=&hashref2str($key).'=';
5128: } elsif (ref($key)) {
1.265 albertel 5129: $result.='=';
1.800 albertel 5130: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5131: } else {
1.1132 raeburn 5132: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5133: }
5134:
1.800 albertel 5135: if(ref($hashref->{$key}) eq 'ARRAY') {
5136: $result.=&arrayref2str($hashref->{$key}).'&';
5137: } elsif(ref($hashref->{$key}) eq 'HASH') {
5138: $result.=&hashref2str($hashref->{$key}).'&';
5139: } elsif(ref($hashref->{$key})) {
1.265 albertel 5140: $result.='&';
1.800 albertel 5141: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5142: } else {
1.800 albertel 5143: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5144: }
5145: }
1.168 albertel 5146: $result=~s/\&$//;
1.265 albertel 5147: $result .= '__END_HASH_REF__';
1.168 albertel 5148: return $result;
5149: }
5150:
5151: sub str2hash {
1.265 albertel 5152: my ($string)=@_;
5153: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5154: return %$hash;
5155: }
5156:
5157: sub str2hashref {
1.168 albertel 5158: my ($string) = @_;
1.265 albertel 5159:
5160: my %hash;
5161:
5162: if($string !~ /^__HASH_REF__/) {
5163: if (! ($string eq '' || !defined($string))) {
5164: $hash{'error'}='Not hash reference';
5165: }
5166: return (\%hash, $string);
5167: }
5168:
5169: $string =~ s/^__HASH_REF__//;
5170:
5171: while($string !~ /^__END_HASH_REF__/) {
5172: #key
5173: my $key='';
5174: if($string =~ /^__HASH_REF__/) {
5175: ($key, $string)=&str2hashref($string);
5176: if(defined($key->{'error'})) {
5177: $hash{'error'}='Bad data';
5178: return (\%hash, $string);
5179: }
5180: } elsif($string =~ /^__ARRAY_REF__/) {
5181: ($key, $string)=&str2arrayref($string);
5182: if($key->[0] eq 'Array reference error') {
5183: $hash{'error'}='Bad data';
5184: return (\%hash, $string);
5185: }
5186: } else {
5187: $string =~ s/^(.*?)=//;
1.267 albertel 5188: $key=&unescape($1);
1.265 albertel 5189: }
5190: $string =~ s/^=//;
5191:
5192: #value
5193: my $value='';
5194: if($string =~ /^__HASH_REF__/) {
5195: ($value, $string)=&str2hashref($string);
5196: if(defined($value->{'error'})) {
5197: $hash{'error'}='Bad data';
5198: return (\%hash, $string);
5199: }
5200: } elsif($string =~ /^__ARRAY_REF__/) {
5201: ($value, $string)=&str2arrayref($string);
5202: if($value->[0] eq 'Array reference error') {
5203: $hash{'error'}='Bad data';
5204: return (\%hash, $string);
5205: }
5206: } else {
5207: $value=&get_scalar(\$string,'__END_HASH_REF__');
5208: }
5209: $string =~ s/^&//;
5210:
5211: $hash{$key}=$value;
1.204 albertel 5212: }
1.265 albertel 5213:
5214: $string =~ s/^__END_HASH_REF__//;
5215:
5216: return (\%hash, $string);
1.204 albertel 5217: }
5218:
5219: sub str2array {
1.265 albertel 5220: my ($string)=@_;
5221: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5222: return @$array;
5223: }
5224:
5225: sub str2arrayref {
1.204 albertel 5226: my ($string) = @_;
1.265 albertel 5227: my @array;
5228:
5229: if($string !~ /^__ARRAY_REF__/) {
5230: if (! ($string eq '' || !defined($string))) {
5231: $array[0]='Array reference error';
5232: }
5233: return (\@array, $string);
5234: }
5235:
5236: $string =~ s/^__ARRAY_REF__//;
5237:
5238: while($string !~ /^__END_ARRAY_REF__/) {
5239: my $value='';
5240: if($string =~ /^__HASH_REF__/) {
5241: ($value, $string)=&str2hashref($string);
5242: if(defined($value->{'error'})) {
5243: $array[0] ='Array reference error';
5244: return (\@array, $string);
5245: }
5246: } elsif($string =~ /^__ARRAY_REF__/) {
5247: ($value, $string)=&str2arrayref($string);
5248: if($value->[0] eq 'Array reference error') {
5249: $array[0] ='Array reference error';
5250: return (\@array, $string);
5251: }
5252: } else {
5253: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5254: }
5255: $string =~ s/^&//;
5256:
5257: push(@array, $value);
1.191 harris41 5258: }
1.265 albertel 5259:
5260: $string =~ s/^__END_ARRAY_REF__//;
5261:
5262: return (\@array, $string);
1.168 albertel 5263: }
5264:
1.167 albertel 5265: # -------------------------------------------------------------------Temp Store
5266:
1.168 albertel 5267: sub tmpreset {
5268: my ($symb,$namespace,$domain,$stuname) = @_;
5269: if (!$symb) {
5270: $symb=&symbread();
1.620 albertel 5271: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5272: }
5273: $symb=escape($symb);
5274:
1.620 albertel 5275: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5276: $namespace=~s/\//\_/g;
5277: $namespace=~s/\W//g;
5278:
1.620 albertel 5279: if (!$domain) { $domain=$env{'user.domain'}; }
5280: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5281: if ($domain eq 'public' && $stuname eq 'public') {
5282: $stuname=$ENV{'REMOTE_ADDR'};
5283: }
1.1117 foxr 5284: my $path=LONCAPA::tempdir();
1.168 albertel 5285: my %hash;
5286: if (tie(%hash,'GDBM_File',
5287: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5288: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5289: foreach my $key (keys(%hash)) {
1.180 albertel 5290: if ($key=~ /:$symb/) {
1.168 albertel 5291: delete($hash{$key});
5292: }
5293: }
5294: }
5295: }
5296:
1.167 albertel 5297: sub tmpstore {
1.168 albertel 5298: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5299:
5300: if (!$symb) {
5301: $symb=&symbread();
1.620 albertel 5302: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5303: }
5304: $symb=escape($symb);
5305:
5306: if (!$namespace) {
5307: # I don't think we would ever want to store this for a course.
5308: # it seems this will only be used if we don't have a course.
1.620 albertel 5309: #$namespace=$env{'request.course.id'};
1.168 albertel 5310: #if (!$namespace) {
1.620 albertel 5311: $namespace=$env{'request.state'};
1.168 albertel 5312: #}
5313: }
5314: $namespace=~s/\//\_/g;
5315: $namespace=~s/\W//g;
1.620 albertel 5316: if (!$domain) { $domain=$env{'user.domain'}; }
5317: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5318: if ($domain eq 'public' && $stuname eq 'public') {
5319: $stuname=$ENV{'REMOTE_ADDR'};
5320: }
1.168 albertel 5321: my $now=time;
5322: my %hash;
1.1117 foxr 5323: my $path=LONCAPA::tempdir();
1.168 albertel 5324: if (tie(%hash,'GDBM_File',
5325: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5326: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5327: $hash{"version:$symb"}++;
5328: my $version=$hash{"version:$symb"};
5329: my $allkeys='';
5330: foreach my $key (keys(%$storehash)) {
5331: $allkeys.=$key.':';
1.591 albertel 5332: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5333: }
5334: $hash{"$version:$symb:timestamp"}=$now;
5335: $allkeys.='timestamp';
5336: $hash{"$version:keys:$symb"}=$allkeys;
5337: if (untie(%hash)) {
5338: return 'ok';
5339: } else {
5340: return "error:$!";
5341: }
5342: } else {
5343: return "error:$!";
5344: }
5345: }
1.167 albertel 5346:
1.168 albertel 5347: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5348:
1.168 albertel 5349: sub tmprestore {
5350: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5351:
1.168 albertel 5352: if (!$symb) {
5353: $symb=&symbread();
1.620 albertel 5354: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5355: }
5356: $symb=escape($symb);
5357:
1.620 albertel 5358: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5359:
1.620 albertel 5360: if (!$domain) { $domain=$env{'user.domain'}; }
5361: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5362: if ($domain eq 'public' && $stuname eq 'public') {
5363: $stuname=$ENV{'REMOTE_ADDR'};
5364: }
1.168 albertel 5365: my %returnhash;
5366: $namespace=~s/\//\_/g;
5367: $namespace=~s/\W//g;
5368: my %hash;
1.1117 foxr 5369: my $path=LONCAPA::tempdir();
1.168 albertel 5370: if (tie(%hash,'GDBM_File',
5371: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5372: &GDBM_READER(),0640)) {
1.168 albertel 5373: my $version=$hash{"version:$symb"};
5374: $returnhash{'version'}=$version;
5375: my $scope;
5376: for ($scope=1;$scope<=$version;$scope++) {
5377: my $vkeys=$hash{"$scope:keys:$symb"};
5378: my @keys=split(/:/,$vkeys);
5379: my $key;
5380: $returnhash{"$scope:keys"}=$vkeys;
5381: foreach $key (@keys) {
1.591 albertel 5382: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5383: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5384: }
5385: }
1.168 albertel 5386: if (!(untie(%hash))) {
5387: return "error:$!";
5388: }
5389: } else {
5390: return "error:$!";
5391: }
5392: return %returnhash;
1.167 albertel 5393: }
5394:
1.9 www 5395: # ----------------------------------------------------------------------- Store
5396:
5397: sub store {
1.1269 raeburn 5398: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5399: my $home='';
5400:
1.168 albertel 5401: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5402:
1.213 www 5403: $symb=&symbclean($symb);
1.122 albertel 5404: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5405:
1.620 albertel 5406: if (!$domain) { $domain=$env{'user.domain'}; }
5407: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5408:
5409: &devalidate($symb,$stuname,$domain);
1.109 www 5410:
5411: $symb=escape($symb);
1.187 www 5412: if (!$namespace) {
1.620 albertel 5413: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5414: return '';
5415: }
5416: }
1.620 albertel 5417: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5418:
5419: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5420: $$storehash{'host'}=$perlvar{'lonHostID'};
5421:
1.12 www 5422: my $namevalue='';
1.800 albertel 5423: foreach my $key (keys(%$storehash)) {
5424: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5425: }
1.12 www 5426: $namevalue=~s/\&$//;
1.187 www 5427: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 5428: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5429: }
5430:
1.47 www 5431: # -------------------------------------------------------------- Critical Store
5432:
5433: sub cstore {
1.1269 raeburn 5434: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5435: my $home='';
5436:
1.168 albertel 5437: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5438:
1.213 www 5439: $symb=&symbclean($symb);
1.122 albertel 5440: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5441:
1.620 albertel 5442: if (!$domain) { $domain=$env{'user.domain'}; }
5443: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5444:
5445: &devalidate($symb,$stuname,$domain);
1.109 www 5446:
5447: $symb=escape($symb);
1.187 www 5448: if (!$namespace) {
1.620 albertel 5449: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5450: return '';
5451: }
5452: }
1.620 albertel 5453: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5454:
5455: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5456: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5457:
1.47 www 5458: my $namevalue='';
1.800 albertel 5459: foreach my $key (keys(%$storehash)) {
5460: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5461: }
1.47 www 5462: $namevalue=~s/\&$//;
1.187 www 5463: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5464: return critical
1.1269 raeburn 5465: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5466: }
5467:
1.9 www 5468: # --------------------------------------------------------------------- Restore
5469:
5470: sub restore {
1.124 www 5471: my ($symb,$namespace,$domain,$stuname) = @_;
5472: my $home='';
5473:
1.168 albertel 5474: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5475:
1.122 albertel 5476: if (!$symb) {
1.1224 raeburn 5477: return if ($namespace eq 'courserequests');
5478: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5479: } else {
1.1224 raeburn 5480: unless ($namespace eq 'courserequests') {
5481: $symb=&escape(&symbclean($symb));
5482: }
1.122 albertel 5483: }
1.188 www 5484: if (!$namespace) {
1.620 albertel 5485: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5486: return '';
5487: }
5488: }
1.620 albertel 5489: if (!$domain) { $domain=$env{'user.domain'}; }
5490: if (!$stuname) { $stuname=$env{'user.name'}; }
5491: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5492: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5493:
1.12 www 5494: my %returnhash=();
1.800 albertel 5495: foreach my $line (split(/\&/,$answer)) {
5496: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5497: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5498: }
1.75 www 5499: my $version;
5500: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5501: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5502: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5503: }
1.75 www 5504: }
1.13 www 5505: return %returnhash;
1.34 www 5506: }
5507:
5508: # ---------------------------------------------------------- Course Description
1.1118 foxr 5509: #
5510: #
1.34 www 5511:
5512: sub coursedescription {
1.731 albertel 5513: my ($courseid,$args)=@_;
1.34 www 5514: $courseid=~s/^\///;
1.49 www 5515: $courseid=~s/\_/\//g;
1.34 www 5516: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5517: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5518: my $normalid=$cdomain.'_'.$cnum;
5519: # need to always cache even if we get errors otherwise we keep
5520: # trying and trying and trying to get the course description.
5521: my %envhash=();
5522: my %returnhash=();
1.731 albertel 5523:
5524: my $expiretime=600;
5525: if ($env{'request.course.id'} eq $normalid) {
5526: $expiretime=120;
5527: }
5528:
5529: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5530: if (!$args->{'freshen_cache'}
5531: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5532: foreach my $key (keys(%env)) {
5533: next if ($key !~ /^\Q$prefix\E(.*)/);
5534: my ($setting) = $1;
5535: $returnhash{$setting} = $env{$key};
5536: }
5537: return %returnhash;
5538: }
5539:
1.1118 foxr 5540: # get the data again
5541:
1.731 albertel 5542: if (!$args->{'one_time'}) {
5543: $envhash{'course.'.$normalid.'.last_cache'}=time;
5544: }
1.811 albertel 5545:
1.34 www 5546: if ($chome ne 'no_host') {
1.302 albertel 5547: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5548: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5549: my $username = $env{'user.name'}; # Defult username
5550: if(defined $args->{'user'}) {
5551: $username = $args->{'user'};
5552: }
1.129 albertel 5553: $returnhash{'home'}= $chome;
5554: $returnhash{'domain'} = $cdomain;
5555: $returnhash{'num'} = $cnum;
1.741 raeburn 5556: if (!defined($returnhash{'type'})) {
5557: $returnhash{'type'} = 'Course';
5558: }
1.130 albertel 5559: while (my ($name,$value) = each %returnhash) {
1.53 www 5560: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5561: }
1.270 www 5562: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5563: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5564: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5565: $envhash{'course.'.$normalid.'.home'}=$chome;
5566: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5567: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5568: }
5569: }
1.731 albertel 5570: if (!$args->{'one_time'}) {
1.949 raeburn 5571: &appenv(\%envhash);
1.731 albertel 5572: }
1.302 albertel 5573: return %returnhash;
1.461 www 5574: }
5575:
1.1080 raeburn 5576: sub update_released_required {
5577: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5578: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5579: $cid = $env{'request.course.id'};
5580: $cdom = $env{'course.'.$cid.'.domain'};
5581: $cnum = $env{'course.'.$cid.'.num'};
5582: $chome = $env{'course.'.$cid.'.home'};
5583: }
5584: if ($needsrelease) {
5585: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5586: my $needsupdate;
5587: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5588: $needsupdate = 1;
5589: } else {
5590: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5591: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5592: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5593: $needsupdate = 1;
5594: }
5595: }
5596: if ($needsupdate) {
5597: my %needshash = (
5598: 'internal.releaserequired' => $needsrelease,
5599: );
5600: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5601: if ($putresult eq 'ok') {
5602: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5603: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5604: if (ref($crsinfo{$cid}) eq 'HASH') {
5605: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5606: &courseidput($cdom,\%crsinfo,$chome,'notime');
5607: }
5608: }
5609: }
5610: }
5611: return;
5612: }
5613:
1.461 www 5614: # -------------------------------------------------See if a user is privileged
5615:
5616: sub privileged {
1.1219 raeburn 5617: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5618: my $now = time;
1.1219 raeburn 5619: my $roles;
5620: if (ref($possroles) eq 'ARRAY') {
5621: $roles = $possroles;
5622: } else {
5623: $roles = ['dc','su'];
5624: }
5625: if (ref($possdomains) eq 'ARRAY') {
5626: my %privileged = &privileged_by_domain($possdomains,$roles);
5627: foreach my $dom (@{$possdomains}) {
5628: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5629: (ref($privileged{$dom}) eq 'HASH')) {
5630: foreach my $role (@{$roles}) {
5631: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5632: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5633: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5634: return 1 unless (($end && $end < $now) ||
5635: ($start && $start > $now));
5636: }
5637: }
5638: }
5639: }
5640: }
5641: } else {
5642: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5643: my $now = time;
1.1170 droeschl 5644:
1.1275 musolffc 5645: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5646: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5647: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5648: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5649: or ($tstart && $tstart > $now);
1.1170 droeschl 5650: }
1.1219 raeburn 5651: }
5652: }
5653: return 0;
5654: }
1.1170 droeschl 5655:
1.1219 raeburn 5656: sub privileged_by_domain {
5657: my ($domains,$roles) = @_;
5658: my %privileged = ();
5659: my $cachetime = 60*60*24;
5660: my $now = time;
5661: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5662: return %privileged;
5663: }
5664: foreach my $dom (@{$domains}) {
5665: next if (ref($privileged{$dom}) eq 'HASH');
5666: my $needroles;
5667: foreach my $role (@{$roles}) {
5668: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5669: if (defined($cached)) {
5670: if (ref($result) eq 'HASH') {
5671: $privileged{$dom}{$role} = $result;
5672: }
5673: } else {
5674: $needroles = 1;
5675: }
5676: }
5677: if ($needroles) {
5678: my %dompersonnel = &get_domain_roles($dom,$roles);
5679: $privileged{$dom} = {};
5680: foreach my $server (keys(%dompersonnel)) {
5681: if (ref($dompersonnel{$server}) eq 'HASH') {
5682: foreach my $item (keys(%{$dompersonnel{$server}})) {
5683: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5684: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5685: next if ($end && $end < $now);
5686: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5687: $dompersonnel{$server}{$item};
5688: }
5689: }
5690: }
5691: if (ref($privileged{$dom}) eq 'HASH') {
5692: foreach my $role (@{$roles}) {
5693: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5694: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5695: } else {
5696: my %hash = ();
5697: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5698: }
5699: }
5700: }
5701: }
5702: }
5703: return %privileged;
1.9 www 5704: }
1.1 albertel 5705:
1.103 harris41 5706: # -------------------------------------------------------- Get user privileges
1.11 www 5707:
5708: sub rolesinit {
1.1169 droeschl 5709: my ($domain, $username) = @_;
5710: my %userroles = ('user.login.time' => time);
5711: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5712:
5713: # firstaccess and timerinterval are related to timed maps/resources.
5714: # also, blocking can be triggered by an activating timer
5715: # it's saved in the user's %env.
5716: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5717: my %timerinterval = &dump('timerinterval', $domain, $username);
5718: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5719: %timerintchk, %timerintenv);
5720:
1.1162 raeburn 5721: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5722: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5723: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5724: }
1.1169 droeschl 5725:
1.1162 raeburn 5726: foreach my $key (keys(%timerinterval)) {
5727: my ($cid,$rest) = split(/\0/,$key);
5728: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5729: }
1.1169 droeschl 5730:
1.11 www 5731: my %allroles=();
1.1162 raeburn 5732: my %allgroups=();
1.11 www 5733:
1.1274 raeburn 5734: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5735: my $role = $rolesdump{$area};
5736: $area =~ s/\_\w\w$//;
5737:
5738: my ($trole, $tend, $tstart, $group_privs);
5739:
5740: if ($role =~ /^cr/) {
5741: # Custom role, defined by a user
5742: # e.g., user.role.cr/msu/smith/mynewrole
5743: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5744: $trole = $1;
5745: ($tend, $tstart) = split('_', $2);
5746: } else {
5747: $trole = $role;
5748: }
5749: } elsif ($role =~ m|^gr/|) {
5750: # Role of member in a group, defined within a course/community
5751: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5752: ($trole, $tend, $tstart) = split(/_/, $role);
5753: next if $tstart eq '-1';
5754: ($trole, $group_privs) = split(/\//, $trole);
5755: $group_privs = &unescape($group_privs);
5756: } else {
5757: # Just a normal role, defined in roles.tab
5758: ($trole, $tend, $tstart) = split(/_/,$role);
5759: }
5760:
5761: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5762: $username);
5763: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5764:
5765: # role expired or not available yet?
5766: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5767: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5768:
5769: next if $area eq '' or $trole eq '';
5770:
5771: my $spec = "$trole.$area";
5772: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5773:
5774: if ($trole =~ /^cr\//) {
5775: # Custom role, defined by a user
5776: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5777: } elsif ($trole eq 'gr') {
5778: # Role of a member in a group, defined within a course/community
5779: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5780: next;
5781: } else {
5782: # Normal role, defined in roles.tab
5783: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5784: }
5785:
5786: my $cid = $tdomain.'_'.$trest;
5787: unless ($firstaccchk{$cid}) {
5788: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5789: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5790: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5791: $coursetimerstarts{$cid}{$item};
5792: }
5793: }
5794: $firstaccchk{$cid} = 1;
5795: }
5796: unless ($timerintchk{$cid}) {
5797: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5798: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5799: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5800: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5801: }
1.12 www 5802: }
1.1169 droeschl 5803: $timerintchk{$cid} = 1;
1.191 harris41 5804: }
1.11 www 5805: }
1.1169 droeschl 5806:
5807: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5808: \%allroles, \%allgroups);
5809: $env{'user.adv'} = $userroles{'user.adv'};
5810:
1.1162 raeburn 5811: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5812: }
5813:
1.567 raeburn 5814: sub set_arearole {
1.1215 raeburn 5815: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5816: unless ($nolog) {
1.567 raeburn 5817: # log the associated role with the area
1.1215 raeburn 5818: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5819: }
1.743 albertel 5820: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5821: }
5822:
5823: sub custom_roleprivs {
5824: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5825: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 5826: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5827: if (&hostname($homsvr) ne '') {
1.567 raeburn 5828: my ($rdummy,$roledef)=
5829: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5830: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5831: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5832: if (defined($syspriv)) {
1.1043 raeburn 5833: if ($trest =~ /^$match_community$/) {
5834: $syspriv =~ s/bre\&S//;
5835: }
1.567 raeburn 5836: $$allroles{'cm./'}.=':'.$syspriv;
5837: $$allroles{$spec.'./'}.=':'.$syspriv;
5838: }
5839: if ($tdomain ne '') {
5840: if (defined($dompriv)) {
5841: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5842: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5843: }
5844: if (($trest ne '') && (defined($coursepriv))) {
1.1332 raeburn 5845: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
5846: my $rolename = $1;
5847: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
5848: }
1.567 raeburn 5849: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5850: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5851: }
5852: }
5853: }
5854: }
5855: }
5856:
1.1332 raeburn 5857: sub course_adhocrole_privs {
5858: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
5859: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
5860: if ($overrides{"internal.adhocpriv.$rolename"}) {
5861: my (%currprivs,%storeprivs);
5862: foreach my $item (split(/:/,$coursepriv)) {
5863: my ($priv,$restrict) = split(/\&/,$item);
5864: $currprivs{$priv} = $restrict;
5865: }
5866: my (%possadd,%possremove,%full);
5867: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
5868: my ($priv,$restrict)=split(/\&/,$item);
5869: $full{$priv} = $restrict;
5870: }
5871: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
5872: next if ($item eq '');
5873: my ($rule,$rest) = split(/=/,$item);
5874: next unless (($rule eq 'off') || ($rule eq 'on'));
5875: foreach my $priv (split(/:/,$rest)) {
5876: if ($priv ne '') {
5877: if ($rule eq 'off') {
5878: $possremove{$priv} = 1;
5879: } else {
5880: $possadd{$priv} = 1;
5881: }
5882: }
5883: }
5884: }
5885: foreach my $priv (sort(keys(%full))) {
5886: if (exists($currprivs{$priv})) {
5887: unless (exists($possremove{$priv})) {
5888: $storeprivs{$priv} = $currprivs{$priv};
5889: }
5890: } elsif (exists($possadd{$priv})) {
5891: $storeprivs{$priv} = $full{$priv};
5892: }
5893: }
5894: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
5895: }
5896: return $coursepriv;
5897: }
5898:
1.678 raeburn 5899: sub group_roleprivs {
5900: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5901: my $access = 1;
5902: my $now = time;
5903: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5904: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5905: if ($access) {
1.811 albertel 5906: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5907: $$allgroups{$course}{$group} .=':'.$group_privs;
5908: }
5909: }
1.567 raeburn 5910:
5911: sub standard_roleprivs {
5912: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5913: if (defined($pr{$trole.':s'})) {
5914: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5915: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5916: }
5917: if ($tdomain ne '') {
5918: if (defined($pr{$trole.':d'})) {
5919: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5920: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5921: }
5922: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5923: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5924: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5925: }
5926: }
5927: }
5928:
5929: sub set_userprivs {
1.1064 raeburn 5930: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5931: my $author=0;
5932: my $adv=0;
1.678 raeburn 5933: my %grouproles = ();
5934: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5935: my @groupkeys;
1.1000 raeburn 5936: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5937: push(@groupkeys,$role);
5938: }
5939: if (ref($groups_roles) eq 'HASH') {
5940: foreach my $key (keys(%{$groups_roles})) {
5941: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5942: push(@groupkeys,$key);
5943: }
5944: }
5945: }
5946: if (@groupkeys > 0) {
5947: foreach my $role (@groupkeys) {
5948: my ($trole,$area,$sec,$extendedarea);
5949: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5950: $trole = $1;
5951: $area = $2;
5952: $sec = $3;
5953: $extendedarea = $area.$sec;
5954: if (exists($$allgroups{$area})) {
5955: foreach my $group (keys(%{$$allgroups{$area}})) {
5956: my $spec = $trole.'.'.$extendedarea;
5957: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5958: $$allgroups{$area}{$group};
1.1064 raeburn 5959: }
1.678 raeburn 5960: }
5961: }
5962: }
5963: }
5964: }
1.800 albertel 5965: foreach my $group (keys(%grouproles)) {
5966: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5967: }
1.800 albertel 5968: foreach my $role (keys(%{$allroles})) {
5969: my %thesepriv;
1.941 raeburn 5970: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5971: foreach my $item (split(/:/,$$allroles{$role})) {
5972: if ($item ne '') {
5973: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5974: if ($restrictions eq '') {
5975: $thesepriv{$privilege}='F';
5976: } elsif ($thesepriv{$privilege} ne 'F') {
5977: $thesepriv{$privilege}.=$restrictions;
5978: }
5979: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5980: }
5981: }
5982: my $thesestr='';
1.1104 raeburn 5983: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5984: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5985: }
5986: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5987: }
5988: return ($author,$adv);
5989: }
5990:
1.994 raeburn 5991: sub role_status {
1.1104 raeburn 5992: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5993: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 5994: my ($one,$two) = split(m{\./},$rolekey,2);
5995: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5996: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 5997: $$where = '/'.$two;
1.994 raeburn 5998: $$trolecode=$$role.'.'.$$where;
5999: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6000: $$tstatus='is';
1.1104 raeburn 6001: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6002: $$tstatus='future';
1.1034 raeburn 6003: if ($$tstart<$now) {
6004: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6005: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6006: my (%allroles,%allgroups,$group_privs,
6007: %groups_roles,@rolecodes);
1.1002 raeburn 6008: my %userroles = (
6009: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6010: );
1.1064 raeburn 6011: @rolecodes = ('cm');
1.1002 raeburn 6012: my $spec=$$role.'.'.$$where;
6013: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6014: if ($$role =~ /^cr\//) {
6015: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6016: push(@rolecodes,'cr');
1.1002 raeburn 6017: } elsif ($$role eq 'gr') {
1.1064 raeburn 6018: push(@rolecodes,$$role);
1.1002 raeburn 6019: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6020: $env{'user.name'});
1.1064 raeburn 6021: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6022: (undef,my $group_privs) = split(/\//,$trole);
6023: $group_privs = &unescape($group_privs);
6024: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6025: 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 6026: &get_groups_roles($tdomain,$trest,
6027: \%course_roles,\@rolecodes,
6028: \%groups_roles);
1.1002 raeburn 6029: } else {
1.1064 raeburn 6030: push(@rolecodes,$$role);
1.1002 raeburn 6031: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6032: }
1.1064 raeburn 6033: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
6034: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 6035: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
6036: }
6037: }
1.1034 raeburn 6038: $$tstatus = 'is';
1.1002 raeburn 6039: }
1.994 raeburn 6040: }
6041: if ($$tend) {
1.1104 raeburn 6042: if ($$tend<$update) {
1.994 raeburn 6043: $$tstatus='expired';
6044: } elsif ($$tend<$now) {
6045: $$tstatus='will_not';
6046: }
6047: }
6048: }
6049: }
6050: }
6051:
1.1104 raeburn 6052: sub get_groups_roles {
6053: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6054: return unless((ref($cdom_courseroles) eq 'HASH') &&
6055: (ref($rolecodes) eq 'ARRAY') &&
6056: (ref($groups_roles) eq 'HASH'));
6057: if (keys(%{$cdom_courseroles}) > 0) {
6058: my ($cnum) = ($rest =~ /^($match_courseid)/);
6059: if ($cdom ne '' && $cnum ne '') {
6060: foreach my $key (keys(%{$cdom_courseroles})) {
6061: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6062: my $crsrole = $1;
6063: my $crssec = $2;
6064: if ($crsrole =~ /^cr/) {
6065: unless (grep(/^cr$/,@{$rolecodes})) {
6066: push(@{$rolecodes},'cr');
6067: }
6068: } else {
6069: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6070: push(@{$rolecodes},$crsrole);
6071: }
6072: }
6073: my $rolekey = "$crsrole./$cdom/$cnum";
6074: if ($crssec ne '') {
6075: $rolekey .= "/$crssec";
6076: }
6077: $rolekey .= './';
6078: $groups_roles->{$rolekey} = $rolecodes;
6079: }
6080: }
6081: }
6082: }
6083: return;
6084: }
6085:
6086: sub delete_env_groupprivs {
6087: my ($where,$courseroles,$possroles) = @_;
6088: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6089: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6090: unless (ref($courseroles->{$udom}) eq 'HASH') {
6091: %{$courseroles->{$udom}} =
6092: &get_my_roles('','','userroles',['active'],
6093: $possroles,[$udom],1);
6094: }
6095: if (ref($courseroles->{$udom}) eq 'HASH') {
6096: foreach my $item (keys(%{$courseroles->{$udom}})) {
6097: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6098: my $area = '/'.$cdom.'/'.$cnum;
6099: my $privkey = "user.priv.$crsrole.$area";
6100: if ($crssec ne '') {
6101: $privkey .= '/'.$crssec;
6102: }
6103: $privkey .= ".$area/$group";
6104: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6105: }
6106: }
6107: return;
6108: }
6109:
1.994 raeburn 6110: sub check_adhoc_privs {
1.1329 raeburn 6111: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6112: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329 raeburn 6113: if ($sec) {
6114: $cckey .= '/'.$sec;
6115: }
1.1185 raeburn 6116: my $setprivs;
1.994 raeburn 6117: if ($env{$cckey}) {
6118: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6119: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6120: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329 raeburn 6121: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 6122: $setprivs = 1;
1.994 raeburn 6123: }
6124: } else {
1.1330 raeburn 6125: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 6126: $setprivs = 1;
1.994 raeburn 6127: }
1.1185 raeburn 6128: return $setprivs;
1.994 raeburn 6129: }
6130:
6131: sub set_adhoc_privileges {
1.1326 raeburn 6132: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329 raeburn 6133: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6134: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329 raeburn 6135: if ($sec ne '') {
6136: $area .= '/'.$sec;
6137: }
1.994 raeburn 6138: my $spec = $role.'.'.$area;
6139: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 6140: $env{'user.name'},1);
1.1326 raeburn 6141: my %rolehash = ();
1.1332 raeburn 6142: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6143: my $rolename = $1;
1.1326 raeburn 6144: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332 raeburn 6145: my %domdef = &get_domain_defaults($dcdom);
6146: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6147: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6148: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6149: }
6150: }
1.1326 raeburn 6151: } else {
6152: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6153: }
6154: my ($author,$adv)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6155: &appenv(\%userroles,[$role,'cm']);
6156: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 6157: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6158: &appenv( {'request.role' => $spec,
6159: 'request.role.domain' => $dcdom,
1.1332 raeburn 6160: 'request.course.sec' => $sec,
1.1088 raeburn 6161: }
6162: );
6163: my $tadv=0;
6164: if (&allowed('adv') eq 'F') { $tadv=1; }
6165: &appenv({'request.role.adv' => $tadv});
6166: }
1.994 raeburn 6167: }
6168:
1.12 www 6169: # --------------------------------------------------------------- get interface
6170:
6171: sub get {
1.131 albertel 6172: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6173: my $items='';
1.800 albertel 6174: foreach my $item (@$storearr) {
6175: $items.=&escape($item).'&';
1.191 harris41 6176: }
1.12 www 6177: $items=~s/\&$//;
1.620 albertel 6178: if (!$udomain) { $udomain=$env{'user.domain'}; }
6179: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6180: my $uhome=&homeserver($uname,$udomain);
6181:
1.133 albertel 6182: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6183: my @pairs=split(/\&/,$rep);
1.273 albertel 6184: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6185: return @pairs;
6186: }
1.15 www 6187: my %returnhash=();
1.42 www 6188: my $i=0;
1.800 albertel 6189: foreach my $item (@$storearr) {
6190: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6191: $i++;
1.191 harris41 6192: }
1.15 www 6193: return %returnhash;
1.27 www 6194: }
6195:
6196: # --------------------------------------------------------------- del interface
6197:
6198: sub del {
1.133 albertel 6199: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6200: my $items='';
1.800 albertel 6201: foreach my $item (@$storearr) {
6202: $items.=&escape($item).'&';
1.191 harris41 6203: }
1.984 neumanie 6204:
1.27 www 6205: $items=~s/\&$//;
1.620 albertel 6206: if (!$udomain) { $udomain=$env{'user.domain'}; }
6207: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6208: my $uhome=&homeserver($uname,$udomain);
6209: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6210: }
6211:
6212: # -------------------------------------------------------------- dump interface
6213:
1.1180 droeschl 6214: sub unserialize {
6215: my ($rep, $escapedkeys) = @_;
6216:
6217: return {} if $rep =~ /^error/;
6218:
6219: my %returnhash=();
1.1252 raeburn 6220: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 6221: my ($key, $value) = split(/=/, $item, 2);
6222: $key = unescape($key) unless $escapedkeys;
6223: next if $key =~ /^error: 2 /;
1.1252 raeburn 6224: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 6225: }
6226: #return %returnhash;
6227: return \%returnhash;
6228: }
6229:
6230: # see Lond::dump_with_regexp
6231: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6232: sub dump {
1.1180 droeschl 6233: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6234: if (!$udomain) { $udomain=$env{'user.domain'}; }
6235: if (!$uname) { $uname=$env{'user.name'}; }
6236: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6237:
1.1266 raeburn 6238: if ($regexp) {
6239: $regexp=&escape($regexp);
6240: } else {
6241: $regexp='.';
6242: }
1.1180 droeschl 6243: if (grep { $_ eq $uhome } current_machine_ids()) {
6244: # user is hosted on this machine
1.1266 raeburn 6245: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 6246: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 6247: return %{unserialize($reply, $escapedkeys)};
6248: }
1.1166 raeburn 6249: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6250: my @pairs=split(/\&/,$rep);
6251: my %returnhash=();
1.1098 foxr 6252: if (!($rep =~ /^error/ )) {
6253: foreach my $item (@pairs) {
6254: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 6255: $key = unescape($key) unless $escapedkeys;
6256: #$key = &unescape($key);
1.1098 foxr 6257: next if ($key =~ /^error: 2 /);
6258: $returnhash{$key}=&thaw_unescape($value);
6259: }
1.755 albertel 6260: }
6261: return %returnhash;
1.407 www 6262: }
6263:
1.1098 foxr 6264:
1.717 albertel 6265: # --------------------------------------------------------- dumpstore interface
6266:
6267: sub dumpstore {
6268: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 6269: # same as dump but keys must be escaped. They may contain colon separated
6270: # lists of values that may themself contain colons (e.g. symbs).
6271: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6272: }
6273:
1.407 www 6274: # -------------------------------------------------------------- keys interface
6275:
6276: sub getkeys {
6277: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6278: if (!$udomain) { $udomain=$env{'user.domain'}; }
6279: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6280: my $uhome=&homeserver($uname,$udomain);
6281: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6282: my @keyarray=();
1.800 albertel 6283: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6284: next if ($key =~ /^error: 2 /);
1.800 albertel 6285: push(@keyarray,&unescape($key));
1.407 www 6286: }
6287: return @keyarray;
1.318 matthew 6288: }
6289:
1.319 matthew 6290: # --------------------------------------------------------------- currentdump
6291: sub currentdump {
1.328 matthew 6292: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6293: $courseid = $env{'request.course.id'} if (! defined($courseid));
6294: $sdom = $env{'user.domain'} if (! defined($sdom));
6295: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6296: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 6297: my $rep;
6298:
6299: if (grep { $_ eq $uhome } current_machine_ids()) {
6300: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6301: $courseid)));
6302: } else {
6303: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6304: }
6305:
1.318 matthew 6306: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6307: #
1.318 matthew 6308: my %returnhash=();
1.319 matthew 6309: #
6310: if ($rep eq "unknown_cmd") {
6311: # an old lond will not know currentdump
6312: # Do a dump and make it look like a currentdump
1.822 albertel 6313: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6314: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6315: my %hash = @tmp;
6316: @tmp=();
1.424 matthew 6317: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6318: } else {
6319: my @pairs=split(/\&/,$rep);
1.800 albertel 6320: foreach my $pair (@pairs) {
6321: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6322: my ($symb,$param) = split(/:/,$key);
6323: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6324: &thaw_unescape($value);
1.319 matthew 6325: }
1.191 harris41 6326: }
1.12 www 6327: return %returnhash;
1.424 matthew 6328: }
6329:
6330: sub convert_dump_to_currentdump{
6331: my %hash = %{shift()};
6332: my %returnhash;
6333: # Code ripped from lond, essentially. The only difference
6334: # here is the unescaping done by lonnet::dump(). Conceivably
6335: # we might run in to problems with parameter names =~ /^v\./
6336: while (my ($key,$value) = each(%hash)) {
6337: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 6338: $symb = &unescape($symb);
6339: $param = &unescape($param);
1.424 matthew 6340: next if ($v eq 'version' || $symb eq 'keys');
6341: next if (exists($returnhash{$symb}) &&
6342: exists($returnhash{$symb}->{$param}) &&
6343: $returnhash{$symb}->{'v.'.$param} > $v);
6344: $returnhash{$symb}->{$param}=$value;
6345: $returnhash{$symb}->{'v.'.$param}=$v;
6346: }
6347: #
6348: # Remove all of the keys in the hashes which keep track of
6349: # the version of the parameter.
6350: while (my ($symb,$param_hash) = each(%returnhash)) {
6351: # use a foreach because we are going to delete from the hash.
6352: foreach my $key (keys(%$param_hash)) {
6353: delete($param_hash->{$key}) if ($key =~ /^v\./);
6354: }
6355: }
6356: return \%returnhash;
1.12 www 6357: }
6358:
1.627 albertel 6359: # ------------------------------------------------------ critical inc interface
6360:
6361: sub cinc {
6362: return &inc(@_,'critical');
6363: }
6364:
1.449 matthew 6365: # --------------------------------------------------------------- inc interface
6366:
6367: sub inc {
1.627 albertel 6368: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 6369: if (!$udomain) { $udomain=$env{'user.domain'}; }
6370: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 6371: my $uhome=&homeserver($uname,$udomain);
6372: my $items='';
6373: if (! ref($store)) {
6374: # got a single value, so use that instead
6375: $items = &escape($store).'=&';
6376: } elsif (ref($store) eq 'SCALAR') {
6377: $items = &escape($$store).'=&';
6378: } elsif (ref($store) eq 'ARRAY') {
6379: $items = join('=&',map {&escape($_);} @{$store});
6380: } elsif (ref($store) eq 'HASH') {
6381: while (my($key,$value) = each(%{$store})) {
6382: $items.= &escape($key).'='.&escape($value).'&';
6383: }
6384: }
6385: $items=~s/\&$//;
1.627 albertel 6386: if ($critical) {
6387: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6388: } else {
6389: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6390: }
1.449 matthew 6391: }
6392:
1.12 www 6393: # --------------------------------------------------------------- put interface
6394:
6395: sub put {
1.134 albertel 6396: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6397: if (!$udomain) { $udomain=$env{'user.domain'}; }
6398: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6399: my $uhome=&homeserver($uname,$udomain);
1.12 www 6400: my $items='';
1.800 albertel 6401: foreach my $item (keys(%$storehash)) {
6402: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6403: }
1.12 www 6404: $items=~s/\&$//;
1.134 albertel 6405: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6406: }
6407:
1.631 albertel 6408: # ------------------------------------------------------------ newput interface
6409:
6410: sub newput {
6411: my ($namespace,$storehash,$udomain,$uname)=@_;
6412: if (!$udomain) { $udomain=$env{'user.domain'}; }
6413: if (!$uname) { $uname=$env{'user.name'}; }
6414: my $uhome=&homeserver($uname,$udomain);
6415: my $items='';
6416: foreach my $key (keys(%$storehash)) {
6417: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6418: }
6419: $items=~s/\&$//;
6420: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6421: }
6422:
6423: # --------------------------------------------------------- putstore interface
6424:
1.524 raeburn 6425: sub putstore {
1.1269 raeburn 6426: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6427: if (!$udomain) { $udomain=$env{'user.domain'}; }
6428: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6429: my $uhome=&homeserver($uname,$udomain);
6430: my $items='';
1.715 albertel 6431: foreach my $key (keys(%$storehash)) {
6432: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6433: }
1.715 albertel 6434: $items=~s/\&$//;
1.716 albertel 6435: my $esc_symb=&escape($symb);
6436: my $esc_v=&escape($version);
1.715 albertel 6437: my $reply =
1.716 albertel 6438: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6439: $uhome);
1.1269 raeburn 6440: if (($tolog) && ($reply eq 'ok')) {
6441: my $namevalue='';
6442: foreach my $key (keys(%{$storehash})) {
6443: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6444: }
6445: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6446: '&host='.&escape($perlvar{'lonHostID'}).
6447: '&version='.$esc_v.
6448: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6449: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6450: }
1.715 albertel 6451: if ($reply eq 'unknown_cmd') {
1.716 albertel 6452: # gfall back to way things use to be done
1.715 albertel 6453: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6454: $uname);
1.524 raeburn 6455: }
1.715 albertel 6456: return $reply;
6457: }
6458:
6459: sub old_putstore {
1.716 albertel 6460: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6461: if (!$udomain) { $udomain=$env{'user.domain'}; }
6462: if (!$uname) { $uname=$env{'user.name'}; }
6463: my $uhome=&homeserver($uname,$udomain);
6464: my %newstorehash;
1.800 albertel 6465: foreach my $item (keys(%$storehash)) {
6466: my $key = $version.':'.&escape($symb).':'.$item;
6467: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6468: }
6469: my $items='';
6470: my %allitems = ();
1.800 albertel 6471: foreach my $item (keys(%newstorehash)) {
6472: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6473: my $key = $1.':keys:'.$2;
6474: $allitems{$key} .= $3.':';
6475: }
1.800 albertel 6476: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6477: }
1.800 albertel 6478: foreach my $item (keys(%allitems)) {
6479: $allitems{$item} =~ s/\:$//;
6480: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6481: }
6482: $items=~s/\&$//;
6483: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6484: }
6485:
1.47 www 6486: # ------------------------------------------------------ critical put interface
6487:
6488: sub cput {
1.134 albertel 6489: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6490: if (!$udomain) { $udomain=$env{'user.domain'}; }
6491: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6492: my $uhome=&homeserver($uname,$udomain);
1.47 www 6493: my $items='';
1.800 albertel 6494: foreach my $item (keys(%$storehash)) {
6495: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6496: }
1.47 www 6497: $items=~s/\&$//;
1.134 albertel 6498: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6499: }
6500:
6501: # -------------------------------------------------------------- eget interface
6502:
6503: sub eget {
1.133 albertel 6504: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6505: my $items='';
1.800 albertel 6506: foreach my $item (@$storearr) {
6507: $items.=&escape($item).'&';
1.191 harris41 6508: }
1.12 www 6509: $items=~s/\&$//;
1.620 albertel 6510: if (!$udomain) { $udomain=$env{'user.domain'}; }
6511: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6512: my $uhome=&homeserver($uname,$udomain);
6513: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6514: my @pairs=split(/\&/,$rep);
6515: my %returnhash=();
1.42 www 6516: my $i=0;
1.800 albertel 6517: foreach my $item (@$storearr) {
6518: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6519: $i++;
1.191 harris41 6520: }
1.12 www 6521: return %returnhash;
6522: }
6523:
1.667 albertel 6524: # ------------------------------------------------------------ tmpput interface
6525: sub tmpput {
1.802 raeburn 6526: my ($storehash,$server,$context)=@_;
1.667 albertel 6527: my $items='';
1.800 albertel 6528: foreach my $item (keys(%$storehash)) {
6529: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6530: }
6531: $items=~s/\&$//;
1.802 raeburn 6532: if (defined($context)) {
6533: $items .= ':'.&escape($context);
6534: }
1.667 albertel 6535: return &reply("tmpput:$items",$server);
6536: }
6537:
6538: # ------------------------------------------------------------ tmpget interface
6539: sub tmpget {
1.688 albertel 6540: my ($token,$server)=@_;
6541: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6542: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6543: my %returnhash;
1.1328 raeburn 6544: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
6545: return %returnhash;
6546: }
1.667 albertel 6547: foreach my $item (split(/\&/,$rep)) {
6548: my ($key,$value)=split(/=/,$item);
6549: $returnhash{&unescape($key)}=&thaw_unescape($value);
6550: }
6551: return %returnhash;
6552: }
6553:
1.1113 raeburn 6554: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6555: sub tmpdel {
6556: my ($token,$server)=@_;
6557: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6558: return &reply("tmpdel:$token",$server);
6559: }
6560:
1.1198 raeburn 6561: # ------------------------------------------------------------ get_timebased_id
6562:
6563: sub get_timebased_id {
6564: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6565: $maxtries) = @_;
6566: my ($newid,$error,$dellock);
6567: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6568: return ('','ok','invalid call to get suffix');
6569: }
6570:
6571: # set defaults for any optional args for which values were not supplied
6572: if ($who eq '') {
6573: $who = $env{'user.name'}.':'.$env{'user.domain'};
6574: }
6575: if (!$locktries) {
6576: $locktries = 3;
6577: }
6578: if (!$maxtries) {
6579: $maxtries = 10;
6580: }
6581:
6582: if (($cdom eq '') || ($cnum eq '')) {
6583: if ($env{'request.course.id'}) {
6584: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6585: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6586: }
6587: if (($cdom eq '') || ($cnum eq '')) {
6588: return ('','ok','call to get suffix not in course context');
6589: }
6590: }
6591:
6592: # construct locking item
6593: my $lockhash = {
6594: $prefix."\0".'locked_'.$keyid => $who,
6595: };
6596: my $tries = 0;
6597:
6598: # attempt to get lock on nohist_$namespace file
6599: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6600: while (($gotlock ne 'ok') && $tries <$locktries) {
6601: $tries ++;
6602: sleep 1;
6603: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6604: }
6605:
6606: # attempt to get unique identifier, based on current timestamp
6607: if ($gotlock eq 'ok') {
6608: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6609: my $id = time;
6610: $newid = $id;
1.1268 raeburn 6611: if ($idtype eq 'addcode') {
6612: $newid .= &sixnum_code();
6613: }
1.1198 raeburn 6614: my $idtries = 0;
6615: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6616: if ($idtype eq 'concat') {
6617: $newid = $id.$idtries;
1.1268 raeburn 6618: } elsif ($idtype eq 'addcode') {
6619: $newid = $newid.&sixnum_code();
1.1198 raeburn 6620: } else {
6621: $newid ++;
6622: }
6623: $idtries ++;
6624: }
6625: if (!exists($inuse{$prefix."\0".$newid})) {
6626: my %new_item = (
6627: $prefix."\0".$newid => $who,
6628: );
6629: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6630: $cdom,$cnum);
6631: if ($putresult ne 'ok') {
6632: undef($newid);
6633: $error = 'error saving new item: '.$putresult;
6634: }
6635: } else {
1.1268 raeburn 6636: undef($newid);
1.1198 raeburn 6637: $error = ('error: no unique suffix available for the new item ');
6638: }
6639: # remove lock
6640: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6641: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6642: } else {
6643: $error = "error: could not obtain lockfile\n";
6644: $dellock = 'ok';
1.1276 raeburn 6645: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6646: $dellock = 'nolock';
6647: }
1.1198 raeburn 6648: }
6649: return ($newid,$dellock,$error);
6650: }
6651:
1.1268 raeburn 6652: sub sixnum_code {
6653: my $code;
6654: for (0..6) {
6655: $code .= int( rand(9) );
6656: }
6657: return $code;
6658: }
6659:
1.765 albertel 6660: # -------------------------------------------------- portfolio access checking
6661:
6662: sub portfolio_access {
1.1270 raeburn 6663: my ($requrl,$clientip) = @_;
1.765 albertel 6664: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 6665: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6666: if ($result) {
6667: my %setters;
6668: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6669: my ($startblock,$endblock) =
6670: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6671: if ($startblock && $endblock) {
6672: return 'B';
6673: }
6674: } else {
6675: my ($startblock,$endblock) =
6676: &Apache::loncommon::blockcheck(\%setters,'port');
6677: if ($startblock && $endblock) {
6678: return 'B';
6679: }
6680: }
6681: }
1.765 albertel 6682: if ($result eq 'ok') {
1.766 albertel 6683: return 'F';
1.765 albertel 6684: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6685: return 'A';
1.765 albertel 6686: }
1.766 albertel 6687: return '';
1.765 albertel 6688: }
6689:
6690: sub get_portfolio_access {
1.1270 raeburn 6691: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6692:
6693: if (!ref($access_hash)) {
6694: my $current_perms = &get_portfile_permissions($udom,$unum);
6695: my %access_controls = &get_access_controls($current_perms,$group,
6696: $file_name);
6697: $access_hash = $access_controls{$file_name};
6698: }
6699:
1.1270 raeburn 6700: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6701: my $now = time;
6702: if (ref($access_hash) eq 'HASH') {
6703: foreach my $key (keys(%{$access_hash})) {
6704: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6705: if ($start > $now) {
6706: next;
6707: }
6708: if ($end && $end<$now) {
6709: next;
6710: }
6711: if ($scope eq 'public') {
6712: $public = $key;
6713: last;
6714: } elsif ($scope eq 'guest') {
6715: $guest = $key;
6716: } elsif ($scope eq 'domains') {
6717: push(@domains,$key);
6718: } elsif ($scope eq 'users') {
6719: push(@users,$key);
6720: } elsif ($scope eq 'course') {
6721: push(@courses,$key);
6722: } elsif ($scope eq 'group') {
6723: push(@groups,$key);
1.1270 raeburn 6724: } elsif ($scope eq 'ip') {
6725: push(@ips,$key);
1.765 albertel 6726: }
6727: }
6728: if ($public) {
6729: return 'ok';
1.1270 raeburn 6730: } elsif (@ips > 0) {
6731: my $allowed;
6732: foreach my $ipkey (@ips) {
6733: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6734: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6735: $allowed = 1;
6736: last;
6737: }
6738: }
6739: }
6740: if ($allowed) {
6741: return 'ok';
6742: }
1.765 albertel 6743: }
6744: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6745: if ($guest) {
6746: return $guest;
6747: }
6748: } else {
6749: if (@domains > 0) {
6750: foreach my $domkey (@domains) {
6751: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6752: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6753: return 'ok';
6754: }
6755: }
6756: }
6757: }
6758: if (@users > 0) {
6759: foreach my $userkey (@users) {
1.865 raeburn 6760: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6761: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6762: if (ref($item) eq 'HASH') {
6763: if (($item->{'uname'} eq $env{'user.name'}) &&
6764: ($item->{'udom'} eq $env{'user.domain'})) {
6765: return 'ok';
6766: }
6767: }
6768: }
6769: }
1.765 albertel 6770: }
6771: }
6772: my %roleshash;
6773: my @courses_and_groups = @courses;
6774: push(@courses_and_groups,@groups);
6775: if (@courses_and_groups > 0) {
6776: my (%allgroups,%allroles);
6777: my ($start,$end,$role,$sec,$group);
6778: foreach my $envkey (%env) {
1.1060 raeburn 6779: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6780: my $cid = $2.'_'.$3;
6781: if ($1 eq 'gr') {
6782: $group = $4;
6783: $allgroups{$cid}{$group} = $env{$envkey};
6784: } else {
6785: if ($4 eq '') {
6786: $sec = 'none';
6787: } else {
6788: $sec = $4;
6789: }
6790: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6791: }
1.811 albertel 6792: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6793: my $cid = $2.'_'.$3;
6794: if ($4 eq '') {
6795: $sec = 'none';
6796: } else {
6797: $sec = $4;
6798: }
6799: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6800: }
6801: }
6802: if (keys(%allroles) == 0) {
6803: return;
6804: }
6805: foreach my $key (@courses_and_groups) {
6806: my %content = %{$$access_hash{$key}};
6807: my $cnum = $content{'number'};
6808: my $cdom = $content{'domain'};
6809: my $cid = $cdom.'_'.$cnum;
6810: if (!exists($allroles{$cid})) {
6811: next;
6812: }
6813: foreach my $role_id (keys(%{$content{'roles'}})) {
6814: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6815: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6816: my @status = @{$content{'roles'}{$role_id}{'access'}};
6817: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6818: foreach my $role (keys(%{$allroles{$cid}})) {
6819: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6820: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6821: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6822: if (grep/^all$/,@sections) {
6823: return 'ok';
6824: } else {
6825: if (grep/^$sec$/,@sections) {
6826: return 'ok';
6827: }
6828: }
6829: }
6830: }
6831: if (keys(%{$allgroups{$cid}}) == 0) {
6832: if (grep/^none$/,@groups) {
6833: return 'ok';
6834: }
6835: } else {
6836: if (grep/^all$/,@groups) {
6837: return 'ok';
6838: }
6839: foreach my $group (keys(%{$allgroups{$cid}})) {
6840: if (grep/^$group$/,@groups) {
6841: return 'ok';
6842: }
6843: }
6844: }
6845: }
6846: }
6847: }
6848: }
6849: }
6850: if ($guest) {
6851: return $guest;
6852: }
6853: }
6854: }
6855: return;
6856: }
6857:
6858: sub course_group_datechecker {
6859: my ($dates,$now,$status) = @_;
6860: my ($start,$end) = split(/\./,$dates);
6861: if (!$start && !$end) {
6862: return 'ok';
6863: }
6864: if (grep/^active$/,@{$status}) {
6865: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6866: return 'ok';
6867: }
6868: }
6869: if (grep/^previous$/,@{$status}) {
6870: if ($end > $now ) {
6871: return 'ok';
6872: }
6873: }
6874: if (grep/^future$/,@{$status}) {
6875: if ($start > $now) {
6876: return 'ok';
6877: }
6878: }
6879: return;
6880: }
6881:
6882: sub parse_portfolio_url {
6883: my ($url) = @_;
6884:
6885: my ($type,$udom,$unum,$group,$file_name);
6886:
1.823 albertel 6887: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6888: $type = 1;
6889: $udom = $1;
6890: $unum = $2;
6891: $file_name = $3;
1.823 albertel 6892: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6893: $type = 2;
6894: $udom = $1;
6895: $unum = $2;
6896: $group = $3;
6897: $file_name = $3.'/'.$4;
6898: }
6899: if (wantarray) {
6900: return ($type,$udom,$unum,$file_name,$group);
6901: }
6902: return $type;
6903: }
6904:
6905: sub is_portfolio_url {
6906: my ($url) = @_;
6907: return scalar(&parse_portfolio_url($url));
6908: }
6909:
1.798 raeburn 6910: sub is_portfolio_file {
6911: my ($file) = @_;
1.820 raeburn 6912: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6913: return 1;
6914: }
6915: return;
6916: }
6917:
1.976 raeburn 6918: sub usertools_access {
1.1084 raeburn 6919: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6920: my ($access,%tools);
6921: if ($context eq '') {
6922: $context = 'tools';
6923: }
6924: if ($context eq 'requestcourses') {
6925: %tools = (
6926: official => 1,
6927: unofficial => 1,
1.1006 raeburn 6928: community => 1,
1.1246 raeburn 6929: textbook => 1,
1.1305 raeburn 6930: placement => 1,
1.985 raeburn 6931: );
1.1183 raeburn 6932: } elsif ($context eq 'requestauthor') {
6933: %tools = (
6934: requestauthor => 1,
6935: );
1.985 raeburn 6936: } else {
6937: %tools = (
6938: aboutme => 1,
6939: blog => 1,
1.1177 raeburn 6940: webdav => 1,
1.985 raeburn 6941: portfolio => 1,
6942: );
6943: }
1.976 raeburn 6944: return if (!defined($tools{$tool}));
6945:
1.1242 raeburn 6946: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6947: $udom = $env{'user.domain'};
6948: $uname = $env{'user.name'};
6949: }
6950:
1.978 raeburn 6951: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6952: if ($action ne 'reload') {
1.985 raeburn 6953: if ($context eq 'requestcourses') {
6954: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6955: } elsif ($context eq 'requestauthor') {
6956: return $env{'environment.canrequest.author'};
1.985 raeburn 6957: } else {
6958: return $env{'environment.availabletools.'.$tool};
6959: }
6960: }
1.976 raeburn 6961: }
6962:
1.1183 raeburn 6963: my ($toolstatus,$inststatus,$envkey);
6964: if ($context eq 'requestauthor') {
6965: $envkey = $context;
6966: } else {
6967: $envkey = $context.'.'.$tool;
6968: }
1.976 raeburn 6969:
1.985 raeburn 6970: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6971: ($action ne 'reload')) {
1.1183 raeburn 6972: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6973: $inststatus = $env{'environment.inststatus'};
6974: } else {
1.1084 raeburn 6975: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6976: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6977: $inststatus = $userenvref->{'inststatus'};
6978: } else {
1.1183 raeburn 6979: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6980: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6981: $inststatus = $userenv{'inststatus'};
6982: }
1.976 raeburn 6983: }
6984:
6985: if ($toolstatus ne '') {
6986: if ($toolstatus) {
6987: $access = 1;
6988: } else {
6989: $access = 0;
6990: }
6991: return $access;
6992: }
6993:
1.1084 raeburn 6994: my ($is_adv,%domdef);
6995: if (ref($is_advref) eq 'HASH') {
6996: $is_adv = $is_advref->{'is_adv'};
6997: } else {
6998: $is_adv = &is_advanced_user($udom,$uname);
6999: }
7000: if (ref($domdefref) eq 'HASH') {
7001: %domdef = %{$domdefref};
7002: } else {
7003: %domdef = &get_domain_defaults($udom);
7004: }
1.976 raeburn 7005: if (ref($domdef{$tool}) eq 'HASH') {
7006: if ($is_adv) {
7007: if ($domdef{$tool}{'_LC_adv'} ne '') {
7008: if ($domdef{$tool}{'_LC_adv'}) {
7009: $access = 1;
7010: } else {
7011: $access = 0;
7012: }
7013: return $access;
7014: }
7015: }
7016: if ($inststatus ne '') {
7017: my ($hasaccess,$hasnoaccess);
7018: foreach my $affiliation (split(/:/,$inststatus)) {
7019: if ($domdef{$tool}{$affiliation} ne '') {
7020: if ($domdef{$tool}{$affiliation}) {
7021: $hasaccess = 1;
7022: } else {
7023: $hasnoaccess = 1;
7024: }
7025: }
7026: }
7027: if ($hasaccess || $hasnoaccess) {
7028: if ($hasaccess) {
7029: $access = 1;
7030: } elsif ($hasnoaccess) {
7031: $access = 0;
7032: }
7033: return $access;
7034: }
7035: } else {
7036: if ($domdef{$tool}{'default'} ne '') {
7037: if ($domdef{$tool}{'default'}) {
7038: $access = 1;
7039: } elsif ($domdef{$tool}{'default'} == 0) {
7040: $access = 0;
7041: }
7042: return $access;
7043: }
7044: }
7045: } else {
1.1177 raeburn 7046: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7047: $access = 1;
7048: } else {
7049: $access = 0;
7050: }
1.976 raeburn 7051: return $access;
7052: }
7053: }
7054:
1.1050 raeburn 7055: sub is_course_owner {
7056: my ($cdom,$cnum,$udom,$uname) = @_;
7057: if (($udom eq '') || ($uname eq '')) {
7058: $udom = $env{'user.domain'};
7059: $uname = $env{'user.name'};
7060: }
7061: unless (($udom eq '') || ($uname eq '')) {
7062: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7063: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7064: return 1;
7065: } else {
7066: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7067: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7068: return 1;
7069: }
7070: }
7071: }
7072: }
7073: return;
7074: }
7075:
1.976 raeburn 7076: sub is_advanced_user {
7077: my ($udom,$uname) = @_;
1.1085 raeburn 7078: if ($udom ne '' && $uname ne '') {
7079: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7080: if (wantarray) {
7081: return ($env{'user.adv'},$env{'user.author'});
7082: } else {
7083: return $env{'user.adv'};
7084: }
1.1085 raeburn 7085: }
7086: }
1.976 raeburn 7087: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7088: my %allroles;
1.1128 raeburn 7089: my ($is_adv,$is_author);
1.976 raeburn 7090: foreach my $role (keys(%roleshash)) {
7091: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7092: my $area = '/'.$tdomain.'/'.$trest;
7093: if ($sec ne '') {
7094: $area .= '/'.$sec;
7095: }
7096: if (($area ne '') && ($trole ne '')) {
7097: my $spec=$trole.'.'.$area;
7098: if ($trole =~ /^cr\//) {
7099: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7100: } elsif ($trole ne 'gr') {
7101: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7102: }
1.1128 raeburn 7103: if ($trole eq 'au') {
7104: $is_author = 1;
7105: }
1.976 raeburn 7106: }
7107: }
7108: foreach my $role (keys(%allroles)) {
7109: last if ($is_adv);
7110: foreach my $item (split(/:/,$allroles{$role})) {
7111: if ($item ne '') {
7112: my ($privilege,$restrictions)=split(/&/,$item);
7113: if ($privilege eq 'adv') {
7114: $is_adv = 1;
7115: last;
7116: }
7117: }
7118: }
7119: }
1.1128 raeburn 7120: if (wantarray) {
7121: return ($is_adv,$is_author);
7122: }
1.976 raeburn 7123: return $is_adv;
7124: }
1.798 raeburn 7125:
1.1035 raeburn 7126: sub check_can_request {
1.1036 raeburn 7127: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7128: my $canreq = 0;
7129: my ($types,$typename) = &Apache::loncommon::course_types();
7130: my @options = ('approval','validate','autolimit');
7131: my $optregex = join('|',@options);
7132: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7133: foreach my $type (@{$types}) {
7134: if (&usertools_access($env{'user.name'},
7135: $env{'user.domain'},
7136: $type,undef,'requestcourses')) {
7137: $canreq ++;
1.1036 raeburn 7138: if (ref($request_domains) eq 'HASH') {
7139: push(@{$request_domains->{$type}},$env{'user.domain'});
7140: }
1.1035 raeburn 7141: if ($dom eq $env{'user.domain'}) {
7142: $can_request->{$type} = 1;
7143: }
7144: }
7145: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7146: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7147: if (@curr > 0) {
1.1036 raeburn 7148: foreach my $item (@curr) {
7149: if (ref($request_domains) eq 'HASH') {
7150: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7151: if ($otherdom ne '') {
7152: if (ref($request_domains->{$type}) eq 'ARRAY') {
7153: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7154: push(@{$request_domains->{$type}},$otherdom);
7155: }
7156: } else {
7157: push(@{$request_domains->{$type}},$otherdom);
7158: }
7159: }
7160: }
7161: }
7162: unless($dom eq $env{'user.domain'}) {
7163: $canreq ++;
1.1035 raeburn 7164: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7165: $can_request->{$type} = 1;
7166: }
7167: }
7168: }
7169: }
7170: }
7171: }
7172: return $canreq;
7173: }
7174:
1.341 www 7175: # ---------------------------------------------- Custom access rule evaluation
7176:
7177: sub customaccess {
7178: my ($priv,$uri)=@_;
1.807 albertel 7179: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7180: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7181: $udom = &LONCAPA::clean_domain($udom);
7182: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7183: my $access=0;
1.800 albertel 7184: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7185: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7186: if ($type eq 'user') {
7187: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7188: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7189: if ($tdom) {
7190: if ($tdom ne $env{'user.domain'}) { next; }
7191: }
1.896 albertel 7192: if ($tuname) {
7193: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7194: }
7195: $access=($effect eq 'allow');
7196: last;
7197: }
7198: } else {
7199: if ($role) {
7200: if ($role ne $urole) { next; }
7201: }
7202: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7203: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7204: if ($tdom) {
7205: if ($tdom ne $udom) { next; }
7206: }
7207: if ($tcrs) {
7208: if ($tcrs ne $ucrs) { next; }
7209: }
7210: if ($tsec) {
7211: if ($tsec ne $usec) { next; }
7212: }
7213: $access=($effect eq 'allow');
7214: last;
7215: }
7216: if ($realm eq '' && $role eq '') {
7217: $access=($effect eq 'allow');
7218: }
1.402 bowersj2 7219: }
1.341 www 7220: }
7221: return $access;
7222: }
7223:
1.103 harris41 7224: # ------------------------------------------------- Check for a user privilege
1.12 www 7225:
7226: sub allowed {
1.1281 raeburn 7227: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 7228: my $ver_orguri=$uri;
1.439 www 7229: $uri=&deversion($uri);
1.152 www 7230: my $orguri=$uri;
1.52 www 7231: $uri=&declutter($uri);
1.809 raeburn 7232:
1.810 raeburn 7233: if ($priv eq 'evb') {
7234: # Evade communication block restrictions for specified role in a course
7235: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7236: return $1;
7237: } else {
7238: return;
7239: }
7240: }
7241:
1.620 albertel 7242: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7243: # Free bre access to adm and meta resources
1.775 albertel 7244: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 7245: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7246: && ($priv eq 'bre')) {
1.14 www 7247: return 'F';
1.159 www 7248: }
7249:
1.545 banghart 7250: # Free bre access to user's own portfolio contents
1.714 raeburn 7251: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7252: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7253: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7254: my %setters;
7255: my ($startblock,$endblock) =
7256: &Apache::loncommon::blockcheck(\%setters,'port');
7257: if ($startblock && $endblock) {
7258: return 'B';
7259: } else {
7260: return 'F';
7261: }
1.545 banghart 7262: }
7263:
1.762 raeburn 7264: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7265: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7266: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7267: if (exists($env{'request.course.id'})) {
7268: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7269: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7270: if (($domain eq $cdom) && ($name eq $cnum)) {
7271: my $courseprivid=$env{'request.course.id'};
7272: $courseprivid=~s/\_/\//;
7273: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7274: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7275: return $1;
1.762 raeburn 7276: } else {
7277: if ($env{'request.course.sec'}) {
7278: $courseprivid.='/'.$env{'request.course.sec'};
7279: }
7280: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7281: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7282: return $2;
7283: }
1.714 raeburn 7284: }
7285: }
7286: }
7287: }
7288:
1.159 www 7289: # Free bre to public access
7290:
7291: if ($priv eq 'bre') {
1.238 www 7292: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7293: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7294: return 'F';
7295: }
1.238 www 7296: if ($copyright eq 'priv') {
7297: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7298: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7299: return '';
7300: }
7301: }
7302: if ($copyright eq 'domain') {
7303: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7304: unless (($env{'user.domain'} eq $1) ||
7305: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7306: return '';
7307: }
1.262 matthew 7308: }
1.620 albertel 7309: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7310: # Library role, so allow browsing of resources in this domain.
7311: return 'F';
1.238 www 7312: }
1.341 www 7313: if ($copyright eq 'custom') {
7314: unless (&customaccess($priv,$uri)) { return ''; }
7315: }
1.14 www 7316: }
1.264 matthew 7317: # Domain coordinator is trying to create a course
1.620 albertel 7318: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7319: # uri is the requested domain in this case.
7320: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7321: # a role of dc for the domain in question.
1.620 albertel 7322: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7323: }
1.29 www 7324:
1.52 www 7325: my $thisallowed='';
7326: my $statecond=0;
7327: my $courseprivid='';
7328:
1.1039 raeburn 7329: my $ownaccess;
1.1043 raeburn 7330: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7331: if (($priv eq 'bro') && ($env{'user.author'})) {
7332: if ($uri eq '') {
7333: $ownaccess = 1;
7334: } else {
7335: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7336: my $udom = $env{'user.domain'};
7337: my $uname = $env{'user.name'};
7338: if ($uri =~ m{^\Q$udom\E/?$}) {
7339: $ownaccess = 1;
1.1040 raeburn 7340: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 7341: unless ($uri =~ m{\.\./}) {
7342: $ownaccess = 1;
7343: }
7344: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7345: my $now = time;
7346: if ($uri =~ m{^([^/]+)/?$}) {
7347: my $adom = $1;
7348: foreach my $key (keys(%env)) {
1.1042 raeburn 7349: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 7350: my ($start,$end) = split('.',$env{$key});
7351: if (($now >= $start) && (!$end || $end < $now)) {
7352: $ownaccess = 1;
7353: last;
7354: }
7355: }
7356: }
7357: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7358: my $adom = $1;
7359: my $aname = $2;
1.1042 raeburn 7360: foreach my $role ('ca','aa') {
7361: if ($env{"user.role.$role./$adom/$aname"}) {
7362: my ($start,$end) =
7363: split('.',$env{"user.role.$role./$adom/$aname"});
7364: if (($now >= $start) && (!$end || $end < $now)) {
7365: $ownaccess = 1;
7366: last;
7367: }
1.1039 raeburn 7368: }
7369: }
7370: }
7371: }
7372: }
7373: }
7374: }
7375:
1.52 www 7376: # Course
7377:
1.620 albertel 7378: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7379: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7380: $thisallowed.=$1;
7381: }
1.52 www 7382: }
1.29 www 7383:
1.52 www 7384: # Domain
7385:
1.620 albertel 7386: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7387: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7388: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7389: $thisallowed.=$1;
7390: }
1.12 www 7391: }
1.52 www 7392:
1.1141 raeburn 7393: # User who is not author or co-author might still be able to edit
7394: # resource of an author in the domain (e.g., if Domain Coordinator).
7395: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7396: (&allowed('mdc',$env{'request.course.id'}))) {
7397: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7398: $thisallowed.=$1;
7399: }
7400: }
7401:
1.52 www 7402: # Course: uri itself is a course
1.66 www 7403: my $courseuri=$uri;
7404: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 7405: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7406:
1.620 albertel 7407: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7408: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7409: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7410: $thisallowed.=$1;
7411: }
1.12 www 7412: }
1.29 www 7413:
1.665 albertel 7414: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7415: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7416: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7417: $thisallowed='';
1.671 raeburn 7418: my ($match)=&is_on_map($uri);
7419: if ($match) {
7420: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7421: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 7422: my $value = $1;
7423: if ($noblockcheck) {
7424: $thisallowed.=$value;
1.1162 raeburn 7425: } else {
1.1281 raeburn 7426: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7427: if (@blockers > 0) {
7428: $thisallowed = 'B';
7429: } else {
7430: $thisallowed.=$value;
7431: }
1.1162 raeburn 7432: }
1.671 raeburn 7433: }
7434: } else {
1.705 albertel 7435: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7436: if ($refuri) {
7437: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7438: $thisallowed='F';
1.671 raeburn 7439: } else {
7440: $refuri=&declutter($refuri);
7441: my ($match) = &is_on_map($refuri);
7442: if ($match) {
1.1281 raeburn 7443: if ($noblockcheck) {
7444: $thisallowed='F';
1.1162 raeburn 7445: } else {
1.1281 raeburn 7446: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7447: if (@blockers > 0) {
7448: $thisallowed = 'B';
7449: } else {
7450: $thisallowed='F';
7451: }
1.1162 raeburn 7452: }
1.671 raeburn 7453: }
1.669 raeburn 7454: }
1.671 raeburn 7455: }
7456: }
1.314 www 7457: }
1.492 albertel 7458:
1.766 albertel 7459: if ($priv eq 'bre'
7460: && $thisallowed ne 'F'
7461: && $thisallowed ne '2'
7462: && &is_portfolio_url($uri)) {
1.1270 raeburn 7463: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7464: }
1.1250 raeburn 7465:
1.52 www 7466: # Full access at system, domain or course-wide level? Exit.
1.29 www 7467: if ($thisallowed=~/F/) {
7468: return 'F';
7469: }
7470:
1.52 www 7471: # If this is generating or modifying users, exit with special codes
1.29 www 7472:
1.643 www 7473: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7474: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7475: my ($audom,$auname)=split('/',$uri);
1.643 www 7476: # no author name given, so this just checks on the general right to make a co-author in this domain
7477: unless ($auname) { return $thisallowed; }
7478: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7479: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7480: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7481: ($audom ne $env{'request.role.domain'}))) { return ''; }
7482: }
1.52 www 7483: return $thisallowed;
7484: }
7485: #
1.103 harris41 7486: # Gathered so far: system, domain and course wide privileges
1.52 www 7487: #
7488: # Course: See if uri or referer is an individual resource that is part of
7489: # the course
7490:
1.620 albertel 7491: if ($env{'request.course.id'}) {
1.232 www 7492:
1.620 albertel 7493: $courseprivid=$env{'request.course.id'};
7494: if ($env{'request.course.sec'}) {
7495: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7496: }
7497: $courseprivid=~s/\_/\//;
7498: my $checkreferer=1;
1.232 www 7499: my ($match,$cond)=&is_on_map($uri);
7500: if ($match) {
7501: $statecond=$cond;
1.620 albertel 7502: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7503: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7504: my $value = $1;
7505: if ($priv eq 'bre') {
1.1281 raeburn 7506: if ($noblockcheck) {
7507: $thisallowed.=$value;
1.1162 raeburn 7508: } else {
1.1281 raeburn 7509: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7510: if (@blockers > 0) {
7511: $thisallowed = 'B';
7512: } else {
7513: $thisallowed.=$value;
7514: }
1.1162 raeburn 7515: }
7516: } else {
7517: $thisallowed.=$value;
7518: }
1.52 www 7519: $checkreferer=0;
7520: }
1.29 www 7521: }
1.83 www 7522:
1.148 www 7523: if ($checkreferer) {
1.620 albertel 7524: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7525: unless ($refuri) {
1.800 albertel 7526: foreach my $key (keys(%env)) {
7527: if ($key=~/^httpref\..*\*/) {
7528: my $pattern=$key;
1.156 www 7529: $pattern=~s/^httpref\.\/res\///;
1.148 www 7530: $pattern=~s/\*/\[\^\/\]\+/g;
7531: $pattern=~s/\//\\\//g;
1.152 www 7532: if ($orguri=~/$pattern/) {
1.800 albertel 7533: $refuri=$env{$key};
1.148 www 7534: }
7535: }
1.191 harris41 7536: }
1.148 www 7537: }
1.232 www 7538:
1.148 www 7539: if ($refuri) {
1.152 www 7540: $refuri=&declutter($refuri);
1.232 www 7541: my ($match,$cond)=&is_on_map($refuri);
7542: if ($match) {
7543: my $refstatecond=$cond;
1.620 albertel 7544: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7545: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7546: my $value = $1;
7547: if ($priv eq 'bre') {
1.1281 raeburn 7548: if ($noblockcheck) {
7549: $thisallowed.=$value;
1.1162 raeburn 7550: } else {
1.1281 raeburn 7551: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7552: if (@blockers > 0) {
7553: $thisallowed = 'B';
7554: } else {
7555: $thisallowed.=$value;
7556: }
1.1162 raeburn 7557: }
7558: } else {
7559: $thisallowed.=$value;
7560: }
1.53 www 7561: $uri=$refuri;
7562: $statecond=$refstatecond;
1.52 www 7563: }
7564: }
1.148 www 7565: }
1.29 www 7566: }
1.52 www 7567: }
1.29 www 7568:
1.52 www 7569: #
1.103 harris41 7570: # Gathered now: all privileges that could apply, and condition number
1.52 www 7571: #
7572: #
7573: # Full or no access?
7574: #
1.29 www 7575:
1.52 www 7576: if ($thisallowed=~/F/) {
7577: return 'F';
7578: }
1.29 www 7579:
1.52 www 7580: unless ($thisallowed) {
7581: return '';
7582: }
1.29 www 7583:
1.52 www 7584: # Restrictions exist, deal with them
7585: #
7586: # C:according to course preferences
7587: # R:according to resource settings
7588: # L:unless locked
7589: # X:according to user session state
7590: #
7591:
7592: # Possibly locked functionality, check all courses
1.54 www 7593: # Locks might take effect only after 10 minutes cache expiration for other
7594: # courses, and 2 minutes for current course
1.52 www 7595:
7596: my $envkey;
7597: if ($thisallowed=~/L/) {
1.1000 raeburn 7598: foreach $envkey (keys(%env)) {
1.54 www 7599: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7600: my $courseid=$2;
7601: my $roleid=$1.'.'.$2;
1.92 www 7602: $courseid=~s/^\///;
1.54 www 7603: my $expiretime=600;
1.620 albertel 7604: if ($env{'request.role'} eq $roleid) {
1.54 www 7605: $expiretime=120;
7606: }
7607: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7608: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7609: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7610: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7611: }
1.620 albertel 7612: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7613: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7614: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7615: &log($env{'user.domain'},$env{'user.name'},
7616: $env{'user.home'},
1.57 www 7617: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7618: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7619: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7620: return '';
7621: }
7622: }
1.620 albertel 7623: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7624: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7625: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7626: &log($env{'user.domain'},$env{'user.name'},
7627: $env{'user.home'},
1.57 www 7628: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7629: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7630: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7631: return '';
7632: }
7633: }
7634: }
1.29 www 7635: }
1.52 www 7636: }
7637:
7638: #
7639: # Rest of the restrictions depend on selected course
7640: #
7641:
1.620 albertel 7642: unless ($env{'request.course.id'}) {
1.766 albertel 7643: if ($thisallowed eq 'A') {
7644: return 'A';
1.814 raeburn 7645: } elsif ($thisallowed eq 'B') {
7646: return 'B';
1.766 albertel 7647: } else {
7648: return '1';
7649: }
1.52 www 7650: }
1.29 www 7651:
1.52 www 7652: #
7653: # Now user is definitely in a course
7654: #
1.53 www 7655:
7656:
7657: # Course preferences
7658:
7659: if ($thisallowed=~/C/) {
1.620 albertel 7660: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7661: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7662: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7663: =~/\Q$rolecode\E/) {
1.1304 raeburn 7664: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7665: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7666: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7667: $env{'request.course.id'});
7668: }
1.237 www 7669: return '';
7670: }
7671:
1.620 albertel 7672: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7673: =~/\Q$unamedom\E/) {
1.1304 raeburn 7674: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7675: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7676: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7677: $env{'request.course.id'});
7678: }
1.54 www 7679: return '';
7680: }
1.53 www 7681: }
7682:
7683: # Resource preferences
7684:
7685: if ($thisallowed=~/R/) {
1.620 albertel 7686: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7687: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7688: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7689: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7690: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7691: }
7692: return '';
1.54 www 7693: }
1.53 www 7694: }
1.30 www 7695:
1.246 www 7696: # Restricted by state or randomout?
1.30 www 7697:
1.52 www 7698: if ($thisallowed=~/X/) {
1.620 albertel 7699: if ($env{'acc.randomout'}) {
1.579 albertel 7700: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7701: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7702: return '';
7703: }
1.247 www 7704: }
7705: if (&condval($statecond)) {
1.52 www 7706: return '2';
7707: } else {
7708: return '';
7709: }
7710: }
1.30 www 7711:
1.766 albertel 7712: if ($thisallowed eq 'A') {
7713: return 'A';
1.814 raeburn 7714: } elsif ($thisallowed eq 'B') {
7715: return 'B';
1.766 albertel 7716: }
1.52 www 7717: return 'F';
1.232 www 7718: }
1.1162 raeburn 7719:
1.1192 raeburn 7720: # ------------------------------------------- Check construction space access
7721:
7722: sub constructaccess {
7723: my ($url,$setpriv)=@_;
7724:
7725: # We do not allow editing of previous versions of files
7726: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7727:
7728: # Get username and domain from URL
7729: my ($ownername,$ownerdomain,$ownerhome);
7730:
7731: ($ownerdomain,$ownername) =
1.1325 raeburn 7732: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192 raeburn 7733:
7734: # The URL does not really point to any authorspace, forget it
7735: unless (($ownername) && ($ownerdomain)) { return ''; }
7736:
7737: # Now we need to see if the user has access to the authorspace of
7738: # $ownername at $ownerdomain
7739:
7740: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7741: # Real author for this?
7742: $ownerhome = $env{'user.home'};
7743: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7744: return ($ownername,$ownerdomain,$ownerhome);
7745: }
7746: } else {
7747: # Co-author for this?
7748: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7749: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7750: $ownerhome = &homeserver($ownername,$ownerdomain);
7751: return ($ownername,$ownerdomain,$ownerhome);
7752: }
1.1312 raeburn 7753: if ($env{'request.course.id'}) {
7754: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
7755: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
7756: if (&allowed('mdc',$env{'request.course.id'})) {
7757: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
7758: return ($ownername,$ownerdomain,$ownerhome);
7759: }
7760: }
7761: }
1.1192 raeburn 7762: }
7763:
7764: # We don't have any access right now. If we are not possibly going to do anything about this,
7765: # we might as well leave
7766: unless ($setpriv) { return ''; }
7767:
7768: # Backdoor access?
7769: my $allowed=&allowed('eco',$ownerdomain);
7770: # Nope
7771: unless ($allowed) { return ''; }
7772: # Looks like we may have access, but could be locked by the owner of the construction space
7773: if ($allowed eq 'U') {
7774: my %blocked=&get('environment',['domcoord.author'],
7775: $ownerdomain,$ownername);
7776: # Is blocked by owner
7777: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7778: }
7779: if (($allowed eq 'F') || ($allowed eq 'U')) {
7780: # Grant temporary access
7781: my $then=$env{'user.login.time'};
1.1209 raeburn 7782: my $update=$env{'user.update.time'};
1.1192 raeburn 7783: if (!$update) { $update = $then; }
7784: my $refresh=$env{'user.refresh.time'};
7785: if (!$refresh) { $refresh = $update; }
7786: my $now = time;
7787: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7788: $now,'ca','constructaccess');
7789: $ownerhome = &homeserver($ownername,$ownerdomain);
7790: return($ownername,$ownerdomain,$ownerhome);
7791: }
7792: # No business here
7793: return '';
7794: }
7795:
1.1282 raeburn 7796: # ----------------------------------------------------------- Content Blocking
7797:
7798: {
7799: # Caches for faster Course Contents display where content blocking
7800: # is in operation (i.e., interval param set) for timed quiz.
7801: #
7802: # User for whom data are being temporarily cached.
7803: my $cacheduser='';
7804: # Cached blockers for this user (a hash of blocking items).
7805: my %cachedblockers=();
7806: # When the data were last cached.
7807: my $cachedlast='';
7808:
7809: sub load_all_blockers {
7810: my ($uname,$udom,$blocks)=@_;
7811: if (($uname ne '') && ($udom ne '')) {
7812: if (($cacheduser eq $uname.':'.$udom) &&
7813: (abs($cachedlast-time)<5)) {
7814: return;
7815: }
7816: }
7817: $cachedlast=time;
7818: $cacheduser=$uname.':'.$udom;
7819: %cachedblockers = &get_commblock_resources($blocks);
7820: }
7821:
1.1162 raeburn 7822: sub get_comm_blocks {
7823: my ($cdom,$cnum) = @_;
7824: if ($cdom eq '' || $cnum eq '') {
7825: return unless ($env{'request.course.id'});
7826: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7827: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7828: }
7829: my %commblocks;
7830: my $hashid=$cdom.'_'.$cnum;
7831: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7832: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7833: %commblocks = %{$blocksref};
7834: } else {
7835: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7836: my $cachetime = 600;
7837: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7838: }
7839: return %commblocks;
7840: }
7841:
1.1282 raeburn 7842: sub get_commblock_resources {
7843: my ($blocks) = @_;
7844: my %blockers = ();
7845: return %blockers unless ($env{'request.course.id'});
7846: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7847: my %commblocks;
7848: if (ref($blocks) eq 'HASH') {
7849: %commblocks = %{$blocks};
7850: } else {
7851: %commblocks = &get_comm_blocks();
7852: }
1.1282 raeburn 7853: return %blockers unless (keys(%commblocks) > 0);
7854: my $navmap = Apache::lonnavmaps::navmap->new();
7855: return %blockers unless (ref($navmap));
1.1162 raeburn 7856: my $now = time;
7857: foreach my $block (keys(%commblocks)) {
7858: if ($block =~ /^(\d+)____(\d+)$/) {
7859: my ($start,$end) = ($1,$2);
7860: if ($start <= $now && $end >= $now) {
7861: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7862: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7863: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 7864: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7865: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7866: }
7867: }
7868: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 7869: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7870: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7871: }
7872: }
7873: }
7874: }
7875: }
7876: } elsif ($block =~ /^firstaccess____(.+)$/) {
7877: my $item = $1;
1.1163 raeburn 7878: my @to_test;
1.1162 raeburn 7879: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7880: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282 raeburn 7881: my @interval;
7882: my $type = 'map';
7883: if ($item eq 'course') {
7884: $type = 'course';
7885: @interval=&EXT("resource.0.interval");
7886: } else {
7887: if ($item =~ /___\d+___/) {
7888: $type = 'resource';
7889: @interval=&EXT("resource.0.interval",$item);
7890: if (ref($navmap)) {
7891: my $res = $navmap->getBySymb($item);
7892: push(@to_test,$res);
7893: }
1.1162 raeburn 7894: } else {
1.1282 raeburn 7895: my $mapsymb = &symbread($item,1);
7896: if ($mapsymb) {
7897: if (ref($navmap)) {
7898: my $mapres = $navmap->getBySymb($mapsymb);
7899: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7900: foreach my $res (@to_test) {
7901: my $symb = $res->symb();
7902: next if ($symb eq $mapsymb);
7903: if ($symb ne '') {
7904: @interval=&EXT("resource.0.interval",$symb);
7905: if ($interval[1] eq 'map') {
7906: last;
1.1162 raeburn 7907: }
7908: }
7909: }
7910: }
7911: }
7912: }
1.1282 raeburn 7913: }
1.1310 raeburn 7914: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 7915: my $timelimit = $1;
1.1282 raeburn 7916: my $first_access;
7917: if ($type eq 'resource') {
7918: $first_access=&get_first_access($interval[1],$item);
7919: } elsif ($type eq 'map') {
7920: $first_access=&get_first_access($interval[1],undef,$item);
7921: } else {
7922: $first_access=&get_first_access($interval[1]);
7923: }
7924: if ($first_access) {
1.1292 raeburn 7925: my $timesup = $first_access+$timelimit;
1.1282 raeburn 7926: if ($timesup > $now) {
7927: my $activeblock;
7928: foreach my $res (@to_test) {
1.1283 raeburn 7929: if ($res->answerable()) {
1.1282 raeburn 7930: $activeblock = 1;
7931: last;
7932: }
7933: }
7934: if ($activeblock) {
7935: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7936: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7937: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7938: }
7939: }
7940: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7941: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7942: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7943: }
1.1162 raeburn 7944: }
7945: }
7946: }
7947: }
7948: }
7949: }
7950: }
7951: }
7952: }
1.1282 raeburn 7953: return %blockers;
1.1162 raeburn 7954: }
7955:
1.1282 raeburn 7956: sub has_comm_blocking {
7957: my ($priv,$symb,$uri,$blocks) = @_;
7958: my @blockers;
7959: return unless ($env{'request.course.id'});
7960: return unless ($priv eq 'bre');
7961: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7962: return if ($env{'request.state'} eq 'construct');
7963: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7964: return unless (keys(%cachedblockers) > 0);
7965: my (%possibles,@symbs);
7966: if (!$symb) {
7967: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7968: }
1.1282 raeburn 7969: if ($symb) {
7970: @symbs = ($symb);
7971: } elsif (keys(%possibles)) {
7972: @symbs = keys(%possibles);
7973: }
7974: my $noblock;
7975: foreach my $symb (@symbs) {
7976: last if ($noblock);
7977: my ($map,$resid,$resurl)=&decode_symb($symb);
7978: foreach my $block (keys(%cachedblockers)) {
7979: if ($block =~ /^firstaccess____(.+)$/) {
7980: my $item = $1;
7981: if (($item eq $map) || ($item eq $symb)) {
7982: $noblock = 1;
7983: last;
7984: }
7985: }
7986: if (ref($cachedblockers{$block}) eq 'HASH') {
7987: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
7988: if ($cachedblockers{$block}{'resources'}{$symb}) {
7989: unless (grep(/^\Q$block\E$/,@blockers)) {
7990: push(@blockers,$block);
7991: }
7992: }
7993: }
1.1162 raeburn 7994: }
1.1282 raeburn 7995: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
7996: if ($cachedblockers{$block}{'maps'}{$map}) {
7997: unless (grep(/^\Q$block\E$/,@blockers)) {
7998: push(@blockers,$block);
7999: }
8000: }
1.1162 raeburn 8001: }
8002: }
8003: }
1.1282 raeburn 8004: return if ($noblock);
8005: return @blockers;
8006: }
1.1162 raeburn 8007: }
8008:
1.1282 raeburn 8009: # -------------------------------- Deversion and split uri into path an filename
8010:
1.1133 foxr 8011: #
1.1282 raeburn 8012: # Removes the version from a URI and
1.1133 foxr 8013: # splits it in to its filename and path to the filename.
8014: # Seems like File::Basename could have done this more clearly.
8015: # Parameters:
8016: # $uri - input URI
8017: # Returns:
8018: # Two element list consisting of
8019: # $pathname - the URI up to and excluding the trailing /
8020: # $filename - The part of the URI following the last /
8021: # NOTE:
8022: # Another realization of this is simply:
8023: # use File::Basename;
8024: # ...
8025: # $uri = shift;
8026: # $filename = basename($uri);
8027: # $path = dirname($uri);
8028: # return ($filename, $path);
8029: #
8030: # The implementation below is probably faster however.
8031: #
1.710 albertel 8032: sub split_uri_for_cond {
8033: my $uri=&deversion(&declutter(shift));
8034: my @uriparts=split(/\//,$uri);
8035: my $filename=pop(@uriparts);
8036: my $pathname=join('/',@uriparts);
8037: return ($pathname,$filename);
8038: }
1.232 www 8039: # --------------------------------------------------- Is a resource on the map?
8040:
8041: sub is_on_map {
1.710 albertel 8042: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8043: #Trying to find the conditional for the file
1.620 albertel 8044: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8045: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8046: if ($match) {
1.289 bowersj2 8047: return (1,$1);
8048: } else {
1.434 www 8049: return (0,0);
1.289 bowersj2 8050: }
1.12 www 8051: }
8052:
1.427 www 8053: # --------------------------------------------------------- Get symb from alias
8054:
8055: sub get_symb_from_alias {
8056: my $symb=shift;
8057: my ($map,$resid,$url)=&decode_symb($symb);
8058: # Already is a symb
8059: if ($url) { return $symb; }
8060: # Must be an alias
8061: my $aliassymb='';
8062: my %bighash;
1.620 albertel 8063: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8064: &GDBM_READER(),0640)) {
8065: my $rid=$bighash{'mapalias_'.$symb};
8066: if ($rid) {
8067: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8068: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8069: $resid,$bighash{'src_'.$rid});
1.427 www 8070: }
8071: untie %bighash;
8072: }
8073: return $aliassymb;
8074: }
8075:
1.12 www 8076: # ----------------------------------------------------------------- Define Role
8077:
8078: sub definerole {
8079: if (allowed('mcr','/')) {
1.1326 raeburn 8080: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8081: foreach my $role (split(':',$sysrole)) {
8082: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8083: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8084: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8085: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8086: return "refused:s:$crole&$cqual";
8087: }
8088: }
1.191 harris41 8089: }
1.800 albertel 8090: foreach my $role (split(':',$domrole)) {
8091: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8092: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8093: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8094: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8095: return "refused:d:$crole&$cqual";
8096: }
8097: }
1.191 harris41 8098: }
1.800 albertel 8099: foreach my $role (split(':',$courole)) {
8100: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8101: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8102: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8103: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8104: return "refused:c:$crole&$cqual";
8105: }
8106: }
1.191 harris41 8107: }
1.1326 raeburn 8108: my $uhome;
8109: if (($uname ne '') && ($udom ne '')) {
8110: $uhome = &homeserver($uname,$udom);
8111: return $uhome if ($uhome eq 'no_host');
8112: } else {
8113: $uname = $env{'user.name'};
8114: $udom = $env{'user.domain'};
8115: $uhome = $env{'user.home'};
8116: }
1.620 albertel 8117: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326 raeburn 8118: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8119: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326 raeburn 8120: return reply($command,$uhome);
1.12 www 8121: } else {
8122: return 'refused';
8123: }
1.105 harris41 8124: }
8125:
8126: # ---------------- Make a metadata query against the network of library servers
8127:
8128: sub metadata_query {
1.1237 raeburn 8129: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8130: my %rhash;
1.845 albertel 8131: my %libserv = &all_library();
1.244 matthew 8132: my @server_list = (defined($server_array) ? @$server_array
8133: : keys(%libserv) );
8134: for my $server (@server_list) {
1.1237 raeburn 8135: my $domains = '';
8136: if (ref($domains_hash) eq 'HASH') {
8137: $domains = $domains_hash->{$server};
8138: }
1.118 harris41 8139: unless ($custom or $customshow) {
1.1237 raeburn 8140: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8141: $rhash{$server}=$reply;
8142: }
8143: else {
8144: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 8145: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8146: $server);
8147: $rhash{$server}=$reply;
8148: }
1.112 harris41 8149: }
1.118 harris41 8150: return \%rhash;
1.240 www 8151: }
8152:
8153: # ----------------------------------------- Send log queries and wait for reply
8154:
8155: sub log_query {
8156: my ($uname,$udom,$query,%filters)=@_;
8157: my $uhome=&homeserver($uname,$udom);
8158: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8159: my $uhost=&hostname($uhome);
1.800 albertel 8160: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8161: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8162: $uhome);
1.479 albertel 8163: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8164: return get_query_reply($queryid);
8165: }
8166:
1.818 raeburn 8167: # -------------------------- Update MySQL table for portfolio file
8168:
8169: sub update_portfolio_table {
1.821 raeburn 8170: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8171: if ($group ne '') {
8172: $file_name =~s /^\Q$group\E//;
8173: }
1.818 raeburn 8174: my $homeserver = &homeserver($uname,$udom);
8175: my $queryid=
1.821 raeburn 8176: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8177: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8178: my $reply = &get_query_reply($queryid);
8179: return $reply;
8180: }
8181:
1.899 raeburn 8182: # -------------------------- Update MySQL allusers table
8183:
8184: sub update_allusers_table {
8185: my ($uname,$udom,$names) = @_;
8186: my $homeserver = &homeserver($uname,$udom);
8187: my $queryid=
8188: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8189: 'lastname='.&escape($names->{'lastname'}).'%%'.
8190: 'firstname='.&escape($names->{'firstname'}).'%%'.
8191: 'middlename='.&escape($names->{'middlename'}).'%%'.
8192: 'generation='.&escape($names->{'generation'}).'%%'.
8193: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8194: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8195: return;
1.899 raeburn 8196: }
8197:
1.508 raeburn 8198: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8199:
8200: sub fetch_enrollment_query {
1.511 raeburn 8201: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 raeburn 8202: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8203: my $maxtries = 1;
1.508 raeburn 8204: if ($context eq 'automated') {
8205: $homeserver = $perlvar{'lonHostID'};
1.1317 raeburn 8206: $sleep = 2;
8207: $loopmax = 100;
1.547 raeburn 8208: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8209: } else {
8210: $homeserver = &homeserver($cnum,$dom);
8211: }
1.838 albertel 8212: my $host=&hostname($homeserver);
1.506 raeburn 8213: my $cmd = '';
1.1000 raeburn 8214: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8215: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8216: }
8217: $cmd =~ s/%%$//;
8218: $cmd = &escape($cmd);
8219: my $query = 'fetchenrollment';
1.620 albertel 8220: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8221: unless ($queryid=~/^\Q$host\E\_/) {
8222: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8223: return 'error: '.$queryid;
8224: }
1.1317 raeburn 8225: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8226: my $tries = 1;
8227: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 raeburn 8228: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8229: $tries ++;
8230: }
1.526 raeburn 8231: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 8232: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 8233: } else {
1.901 albertel 8234: my @responses = split(/:/,$reply);
1.1322 raeburn 8235: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 8236: foreach my $line (@responses) {
8237: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 8238: $$replyref{$key} = $value;
8239: }
8240: } else {
1.1117 foxr 8241: my $pathname = LONCAPA::tempdir();
1.800 albertel 8242: foreach my $line (@responses) {
8243: my ($key,$value) = split(/=/,$line);
1.506 raeburn 8244: $$replyref{$key} = $value;
8245: if ($value > 0) {
1.800 albertel 8246: foreach my $item (@{$$affiliatesref{$key}}) {
8247: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 8248: my $destname = $pathname.'/'.$filename;
8249: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 8250: if ($xml_classlist =~ /^error/) {
8251: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8252: } else {
1.506 raeburn 8253: if ( open(FILE,">$destname") ) {
8254: print FILE &unescape($xml_classlist);
8255: close(FILE);
1.526 raeburn 8256: } else {
8257: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 8258: }
8259: }
8260: }
8261: }
8262: }
8263: }
8264: return 'ok';
8265: }
8266: return 'error';
8267: }
8268:
1.242 www 8269: sub get_query_reply {
1.1317 raeburn 8270: my ($queryid,$sleep,$loopmax) = @_;;
8271: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8272: $sleep = 0.2;
8273: }
8274: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8275: $loopmax = 100;
8276: }
1.1117 foxr 8277: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 8278: my $reply='';
1.1317 raeburn 8279: for (1..$loopmax) {
8280: sleep($sleep);
1.240 www 8281: if (-e $replyfile.'.end') {
1.448 albertel 8282: if (open(my $fh,$replyfile)) {
1.904 albertel 8283: $reply = join('',<$fh>);
8284: close($fh);
1.240 www 8285: } else { return 'error: reply_file_error'; }
1.242 www 8286: return &unescape($reply);
8287: }
1.240 www 8288: }
1.242 www 8289: return 'timeout:'.$queryid;
1.240 www 8290: }
8291:
8292: sub courselog_query {
1.241 www 8293: #
8294: # possible filters:
8295: # url: url or symb
8296: # username
8297: # domain
8298: # action: view, submit, grade
8299: # start: timestamp
8300: # end: timestamp
8301: #
1.240 www 8302: my (%filters)=@_;
1.620 albertel 8303: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 8304: if ($filters{'url'}) {
8305: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8306: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8307: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8308: }
1.620 albertel 8309: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8310: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 8311: return &log_query($cname,$cdom,'courselog',%filters);
8312: }
8313:
8314: sub userlog_query {
1.858 raeburn 8315: #
8316: # possible filters:
8317: # action: log check role
8318: # start: timestamp
8319: # end: timestamp
8320: #
1.240 www 8321: my ($uname,$udom,%filters)=@_;
8322: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 8323: }
8324:
1.506 raeburn 8325: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8326:
8327: sub auto_run {
1.508 raeburn 8328: my ($cnum,$cdom) = @_;
1.876 raeburn 8329: my $response = 0;
8330: my $settings;
8331: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8332: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8333: $settings = $domconfig{'autoenroll'};
8334: if ($settings->{'run'} eq '1') {
8335: $response = 1;
8336: }
8337: } else {
1.934 raeburn 8338: my $homeserver;
8339: if (&is_course($cdom,$cnum)) {
8340: $homeserver = &homeserver($cnum,$cdom);
8341: } else {
8342: $homeserver = &domain($cdom,'primary');
8343: }
8344: if ($homeserver ne 'no_host') {
8345: $response = &reply('autorun:'.$cdom,$homeserver);
8346: }
1.876 raeburn 8347: }
1.506 raeburn 8348: return $response;
8349: }
1.776 albertel 8350:
1.506 raeburn 8351: sub auto_get_sections {
1.508 raeburn 8352: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 8353: my $homeserver;
8354: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8355: $homeserver = &homeserver($cnum,$cdom);
8356: }
8357: if (!defined($homeserver)) {
8358: if ($cdom =~ /^$match_domain$/) {
8359: $homeserver = &domain($cdom,'primary');
8360: }
8361: }
8362: my @secs;
8363: if (defined($homeserver)) {
8364: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8365: unless ($response eq 'refused') {
8366: @secs = split(/:/,$response);
8367: }
1.506 raeburn 8368: }
8369: return @secs;
8370: }
1.776 albertel 8371:
1.506 raeburn 8372: sub auto_new_course {
1.1099 raeburn 8373: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 8374: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 8375: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 8376: return $response;
8377: }
1.776 albertel 8378:
1.506 raeburn 8379: sub auto_validate_courseID {
1.508 raeburn 8380: my ($cnum,$cdom,$inst_course_id) = @_;
8381: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 8382: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 8383: return $response;
8384: }
1.776 albertel 8385:
1.1007 raeburn 8386: sub auto_validate_instcode {
1.1020 raeburn 8387: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 8388: my ($homeserver,$response);
8389: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8390: $homeserver = &homeserver($cnum,$cdom);
8391: }
8392: if (!defined($homeserver)) {
8393: if ($cdom =~ /^$match_domain$/) {
8394: $homeserver = &domain($cdom,'primary');
8395: }
8396: }
1.1065 raeburn 8397: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8398: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 8399: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
8400: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 8401: }
8402:
1.506 raeburn 8403: sub auto_create_password {
1.873 raeburn 8404: my ($cnum,$cdom,$authparam,$udom) = @_;
8405: my ($homeserver,$response);
1.506 raeburn 8406: my $create_passwd = 0;
8407: my $authchk = '';
1.873 raeburn 8408: if ($udom =~ /^$match_domain$/) {
8409: $homeserver = &domain($udom,'primary');
8410: }
8411: if ($homeserver eq '') {
8412: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8413: $homeserver = &homeserver($cnum,$cdom);
8414: }
8415: }
8416: if ($homeserver eq '') {
8417: $authchk = 'nodomain';
1.506 raeburn 8418: } else {
1.873 raeburn 8419: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8420: if ($response eq 'refused') {
8421: $authchk = 'refused';
8422: } else {
1.901 albertel 8423: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8424: }
1.506 raeburn 8425: }
8426: return ($authparam,$create_passwd,$authchk);
8427: }
8428:
1.706 raeburn 8429: sub auto_photo_permission {
8430: my ($cnum,$cdom,$students) = @_;
8431: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8432: my ($outcome,$perm_reqd,$conditions) =
8433: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8434: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8435: return (undef,undef);
8436: }
1.706 raeburn 8437: return ($outcome,$perm_reqd,$conditions);
8438: }
8439:
8440: sub auto_checkphotos {
8441: my ($uname,$udom,$pid) = @_;
8442: my $homeserver = &homeserver($uname,$udom);
8443: my ($result,$resulttype);
8444: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8445: &escape($uname).':'.&escape($pid),
8446: $homeserver));
1.709 albertel 8447: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8448: return (undef,undef);
8449: }
1.706 raeburn 8450: if ($outcome) {
8451: ($result,$resulttype) = split(/:/,$outcome);
8452: }
8453: return ($result,$resulttype);
8454: }
8455:
8456: sub auto_photochoice {
8457: my ($cnum,$cdom) = @_;
8458: my $homeserver = &homeserver($cnum,$cdom);
8459: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8460: &escape($cdom),
8461: $homeserver)));
1.709 albertel 8462: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8463: return (undef,undef);
8464: }
1.706 raeburn 8465: return ($update,$comment);
8466: }
8467:
8468: sub auto_photoupdate {
8469: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8470: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8471: my $host=&hostname($homeserver);
1.706 raeburn 8472: my $cmd = '';
8473: my $maxtries = 1;
1.800 albertel 8474: foreach my $affiliate (keys(%{$affiliatesref})) {
8475: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8476: }
8477: $cmd =~ s/%%$//;
8478: $cmd = &escape($cmd);
8479: my $query = 'institutionalphotos';
8480: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8481: unless ($queryid=~/^\Q$host\E\_/) {
8482: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8483: return 'error: '.$queryid;
8484: }
8485: my $reply = &get_query_reply($queryid);
8486: my $tries = 1;
8487: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8488: $reply = &get_query_reply($queryid);
8489: $tries ++;
8490: }
8491: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8492: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8493: } else {
8494: my @responses = split(/:/,$reply);
8495: my $outcome = shift(@responses);
8496: foreach my $item (@responses) {
8497: my ($key,$value) = split(/=/,$item);
8498: $$photo{$key} = $value;
8499: }
8500: return $outcome;
8501: }
8502: return 'error';
8503: }
8504:
1.521 raeburn 8505: sub auto_instcode_format {
1.793 albertel 8506: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8507: $cat_order) = @_;
1.521 raeburn 8508: my $courses = '';
1.772 raeburn 8509: my @homeservers;
1.521 raeburn 8510: if ($caller eq 'global') {
1.841 albertel 8511: my %servers = &get_servers($codedom,'library');
8512: foreach my $tryserver (keys(%servers)) {
8513: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8514: push(@homeservers,$tryserver);
8515: }
1.584 raeburn 8516: }
1.1022 raeburn 8517: } elsif ($caller eq 'requests') {
8518: if ($codedom =~ /^$match_domain$/) {
8519: my $chome = &domain($codedom,'primary');
8520: unless ($chome eq 'no_host') {
8521: push(@homeservers,$chome);
8522: }
8523: }
1.521 raeburn 8524: } else {
1.772 raeburn 8525: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8526: }
1.793 albertel 8527: foreach my $code (keys(%{$instcodes})) {
8528: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8529: }
8530: chop($courses);
1.772 raeburn 8531: my $ok_response = 0;
8532: my $response;
8533: while (@homeservers > 0 && $ok_response == 0) {
8534: my $server = shift(@homeservers);
8535: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8536: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8537: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8538: split(/:/,$response);
1.772 raeburn 8539: %{$codes} = (%{$codes},&str2hash($codes_str));
8540: push(@{$codetitles},&str2array($codetitles_str));
8541: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8542: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8543: $ok_response = 1;
8544: }
8545: }
8546: if ($ok_response) {
1.521 raeburn 8547: return 'ok';
1.772 raeburn 8548: } else {
8549: return $response;
1.521 raeburn 8550: }
8551: }
8552:
1.792 raeburn 8553: sub auto_instcode_defaults {
8554: my ($domain,$returnhash,$code_order) = @_;
8555: my @homeservers;
1.841 albertel 8556:
8557: my %servers = &get_servers($domain,'library');
8558: foreach my $tryserver (keys(%servers)) {
8559: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8560: push(@homeservers,$tryserver);
8561: }
1.792 raeburn 8562: }
1.841 albertel 8563:
1.792 raeburn 8564: my $response;
1.841 albertel 8565: foreach my $server (@homeservers) {
1.792 raeburn 8566: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8567: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8568:
8569: foreach my $pair (split(/\&/,$response)) {
8570: my ($name,$value)=split(/\=/,$pair);
8571: if ($name eq 'code_order') {
8572: @{$code_order} = split(/\&/,&unescape($value));
8573: } else {
8574: $returnhash->{&unescape($name)}=&unescape($value);
8575: }
8576: }
8577: return 'ok';
1.792 raeburn 8578: }
1.841 albertel 8579:
8580: return $response;
1.1003 raeburn 8581: }
8582:
8583: sub auto_possible_instcodes {
1.1007 raeburn 8584: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8585: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8586: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8587: return;
8588: }
1.1003 raeburn 8589: my (@homeservers,$uhome);
8590: if (defined(&domain($domain,'primary'))) {
8591: $uhome=&domain($domain,'primary');
8592: push(@homeservers,&domain($domain,'primary'));
8593: } else {
8594: my %servers = &get_servers($domain,'library');
8595: foreach my $tryserver (keys(%servers)) {
8596: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8597: push(@homeservers,$tryserver);
8598: }
8599: }
8600: }
8601: my $response;
8602: foreach my $server (@homeservers) {
8603: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8604: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8605: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8606: split(':',$response);
8607: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8608: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8609: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8610: my ($name,$value)=split('=',$item);
8611: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8612: }
8613: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8614: my ($name,$value)=split('=',$item);
8615: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8616: }
8617: return 'ok';
8618: }
8619: return $response;
8620: }
1.792 raeburn 8621:
1.1010 raeburn 8622: sub auto_courserequest_checks {
8623: my ($dom) = @_;
1.1020 raeburn 8624: my ($homeserver,%validations);
8625: if ($dom =~ /^$match_domain$/) {
8626: $homeserver = &domain($dom,'primary');
8627: }
8628: unless ($homeserver eq 'no_host') {
8629: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8630: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8631: my @items = split(/&/,$response);
8632: foreach my $item (@items) {
8633: my ($key,$value) = split('=',$item);
8634: $validations{&unescape($key)} = &thaw_unescape($value);
8635: }
8636: }
8637: }
1.1010 raeburn 8638: return %validations;
8639: }
8640:
1.1020 raeburn 8641: sub auto_courserequest_validation {
1.1255 raeburn 8642: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8643: my ($homeserver,$response);
8644: if ($dom =~ /^$match_domain$/) {
8645: $homeserver = &domain($dom,'primary');
8646: }
1.1255 raeburn 8647: unless ($homeserver eq 'no_host') {
8648: my $customdata;
8649: if (ref($custominfo) eq 'HASH') {
8650: $customdata = &freeze_escape($custominfo);
8651: }
1.1020 raeburn 8652: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8653: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 8654: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8655: $customdata,$homeserver));
1.1020 raeburn 8656: }
8657: return $response;
8658: }
8659:
1.777 albertel 8660: sub auto_validate_class_sec {
1.918 raeburn 8661: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8662: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8663: my $ownerlist;
8664: if (ref($owners) eq 'ARRAY') {
8665: $ownerlist = join(',',@{$owners});
8666: } else {
8667: $ownerlist = $owners;
8668: }
1.773 raeburn 8669: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8670: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8671: return $response;
8672: }
8673:
1.1248 raeburn 8674: sub auto_crsreq_update {
8675: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 8676: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 8677: my ($homeserver,%crsreqresponse);
8678: if ($cdom =~ /^$match_domain$/) {
8679: $homeserver = &domain($cdom,'primary');
8680: }
8681: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8682: my $info;
8683: if (ref($inbound) eq 'HASH') {
8684: $info = &freeze_escape($inbound);
8685: }
8686: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8687: ':'.&escape($action).':'.&escape($ownername).':'.
8688: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 8689: &escape($title).':'.&escape($code).':'.
8690: &escape($accessstart).':'.&escape($accessend).':'.$info,
8691: $homeserver);
1.1248 raeburn 8692: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8693: my @items = split(/&/,$response);
8694: foreach my $item (@items) {
8695: my ($key,$value) = split('=',$item);
8696: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8697: }
8698: }
8699: }
8700: return \%crsreqresponse;
8701: }
8702:
1.1305 raeburn 8703: sub auto_export_grades {
1.1309 raeburn 8704: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8705: my ($homeserver,%exportresponse);
8706: if ($cdom =~ /^$match_domain$/) {
8707: $homeserver = &domain($cdom,'primary');
8708: }
8709: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8710: my $info;
8711: if (ref($inforef) eq 'HASH') {
8712: $info = &freeze_escape($inforef);
8713: }
8714: if (ref($gradesref) eq 'HASH') {
8715: my $grades = &freeze_escape($gradesref);
8716: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8717: $info.':'.$grades,$homeserver);
8718: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8719: my @items = split(/&/,$response);
8720: foreach my $item (@items) {
8721: my ($key,$value) = split('=',$item);
8722: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8723: }
8724: }
8725: }
8726: }
8727: return \%exportresponse;
1.1305 raeburn 8728: }
8729:
1.1287 raeburn 8730: sub check_instcode_cloning {
8731: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8732: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8733: return;
8734: }
8735: my $canclone;
8736: if (@{$code_order} > 0) {
8737: my $instcoderegexp ='^';
8738: my @clonecodes = split(/\&/,$cloner);
8739: foreach my $item (@{$code_order}) {
8740: if (grep(/^\Q$item\E=/,@clonecodes)) {
8741: foreach my $pair (@clonecodes) {
8742: my ($key,$val) = split(/\=/,$pair,2);
8743: $val = &unescape($val);
8744: if ($key eq $item) {
8745: $instcoderegexp .= '('.$val.')';
8746: last;
8747: }
8748: }
8749: } else {
8750: $instcoderegexp .= $codedefaults->{$item};
8751: }
8752: }
8753: $instcoderegexp .= '$';
8754: my (@from,@to);
8755: eval {
8756: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8757: (@to) = ($clonetocode =~ /$instcoderegexp/);
8758: };
8759: if ((@from > 0) && (@to > 0)) {
8760: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8761: if (!@diffs) {
8762: $canclone = 1;
8763: }
8764: }
8765: }
8766: return $canclone;
8767: }
8768:
8769: sub default_instcode_cloning {
8770: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8771: my (%codedefaults,@code_order,$canclone);
8772: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8773: %codedefaults = %{$codedefaultsref};
8774: @code_order = @{$codeorderref};
8775: } elsif ($clonedom) {
8776: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8777: }
8778: if (($domdefclone) && (@code_order)) {
8779: my @clonecodes = split(/\+/,$domdefclone);
8780: my $instcoderegexp ='^';
8781: foreach my $item (@code_order) {
8782: if (grep(/^\Q$item\E$/,@clonecodes)) {
8783: $instcoderegexp .= '('.$codedefaults{$item}.')';
8784: } else {
8785: $instcoderegexp .= $codedefaults{$item};
8786: }
8787: }
8788: $instcoderegexp .= '$';
8789: my (@from,@to);
8790: eval {
8791: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8792: (@to) = ($clonetocode =~ /$instcoderegexp/);
8793: };
8794: if ((@from > 0) && (@to > 0)) {
8795: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8796: if (!@diffs) {
8797: $canclone = 1;
8798: }
8799: }
8800: }
8801: return $canclone;
8802: }
8803:
1.679 raeburn 8804: # ------------------------------------------------------- Course Group routines
8805:
8806: sub get_coursegroups {
1.809 raeburn 8807: my ($cdom,$cnum,$group,$namespace) = @_;
8808: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8809: }
8810:
1.679 raeburn 8811: sub modify_coursegroup {
8812: my ($cdom,$cnum,$groupsettings) = @_;
8813: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8814: }
8815:
1.809 raeburn 8816: sub toggle_coursegroup_status {
8817: my ($cdom,$cnum,$group,$action) = @_;
8818: my ($from_namespace,$to_namespace);
8819: if ($action eq 'delete') {
8820: $from_namespace = 'coursegroups';
8821: $to_namespace = 'deleted_groups';
8822: } else {
8823: $from_namespace = 'deleted_groups';
8824: $to_namespace = 'coursegroups';
8825: }
8826: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8827: if (my $tmp = &error(%curr_group)) {
8828: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8829: return ('read error',$tmp);
8830: } else {
8831: my %savedsettings = %curr_group;
1.809 raeburn 8832: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8833: my $deloutcome;
8834: if ($result eq 'ok') {
1.809 raeburn 8835: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8836: } else {
8837: return ('write error',$result);
8838: }
8839: if ($deloutcome eq 'ok') {
8840: return 'ok';
8841: } else {
8842: return ('delete error',$deloutcome);
8843: }
8844: }
8845: }
8846:
1.679 raeburn 8847: sub modify_group_roles {
1.957 raeburn 8848: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8849: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8850: my $role = 'gr/'.&escape($userprivs);
8851: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8852: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8853: if ($result eq 'ok') {
8854: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8855: }
1.679 raeburn 8856: return $result;
8857: }
8858:
8859: sub modify_coursegroup_membership {
8860: my ($cdom,$cnum,$membership) = @_;
8861: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8862: return $result;
8863: }
8864:
1.682 raeburn 8865: sub get_active_groups {
8866: my ($udom,$uname,$cdom,$cnum) = @_;
8867: my $now = time;
8868: my %groups = ();
8869: foreach my $key (keys(%env)) {
1.811 albertel 8870: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8871: my ($start,$end) = split(/\./,$env{$key});
8872: if (($end!=0) && ($end<$now)) { next; }
8873: if (($start!=0) && ($start>$now)) { next; }
8874: if ($1 eq $cdom && $2 eq $cnum) {
8875: $groups{$3} = $env{$key} ;
8876: }
8877: }
8878: }
8879: return %groups;
8880: }
8881:
1.683 raeburn 8882: sub get_group_membership {
8883: my ($cdom,$cnum,$group) = @_;
8884: return(&dump('groupmembership',$cdom,$cnum,$group));
8885: }
8886:
8887: sub get_users_groups {
8888: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8889: my @usersgroups;
1.683 raeburn 8890: my $cachetime=1800;
8891:
8892: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8893: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8894: if (defined($cached)) {
1.734 albertel 8895: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8896: } else {
8897: $grouplist = '';
1.816 raeburn 8898: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8899: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8900: my $access_end = $env{'course.'.$courseid.
8901: '.default_enrollment_end_date'};
8902: my $now = time;
8903: foreach my $key (keys(%roleshash)) {
8904: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8905: my $group = $1;
8906: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8907: my $start = $2;
8908: my $end = $1;
8909: if ($start == -1) { next; } # deleted from group
8910: if (($start!=0) && ($start>$now)) { next; }
8911: if (($end!=0) && ($end<$now)) {
8912: if ($access_end && $access_end < $now) {
8913: if ($access_end - $end < 86400) {
8914: push(@usersgroups,$group);
1.733 raeburn 8915: }
8916: }
1.817 raeburn 8917: next;
1.733 raeburn 8918: }
1.817 raeburn 8919: push(@usersgroups,$group);
1.683 raeburn 8920: }
8921: }
8922: }
1.817 raeburn 8923: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8924: $grouplist = join(':',@usersgroups);
8925: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8926: }
1.733 raeburn 8927: return @usersgroups;
1.683 raeburn 8928: }
8929:
8930: sub devalidate_getgroups_cache {
8931: my ($udom,$uname,$cdom,$cnum)=@_;
8932: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8933:
1.683 raeburn 8934: my $hashid="$udom:$uname:$courseid";
8935: &devalidate_cache_new('getgroups',$hashid);
8936: }
8937:
1.12 www 8938: # ------------------------------------------------------------------ Plain Text
8939:
8940: sub plaintext {
1.988 raeburn 8941: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8942: if ($short =~ m{^cr/}) {
1.758 albertel 8943: return (split('/',$short))[-1];
8944: }
1.742 raeburn 8945: if (!defined($cid)) {
8946: $cid = $env{'request.course.id'};
8947: }
8948: my %rolenames = (
1.1008 raeburn 8949: Course => 'std',
8950: Community => 'alt1',
1.1305 raeburn 8951: Placement => 'std',
1.742 raeburn 8952: );
1.1037 raeburn 8953: if ($cid ne '') {
8954: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8955: unless ($forcedefault) {
8956: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8957: &Apache::lonlocal::mt_escape(\$roletext);
8958: return &Apache::lonlocal::mt($roletext);
8959: }
8960: }
8961: }
8962: if ((defined($type)) && (defined($rolenames{$type})) &&
8963: (defined($rolenames{$type})) &&
8964: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8965: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8966: } elsif ($cid ne '') {
8967: my $crstype = $env{'course.'.$cid.'.type'};
8968: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8969: (defined($prp{$short}{$rolenames{$crstype}}))) {
8970: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8971: }
1.742 raeburn 8972: }
1.1037 raeburn 8973: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8974: }
8975:
8976: # ----------------------------------------------------------------- Assign Role
8977:
8978: sub assignrole {
1.957 raeburn 8979: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8980: $context)=@_;
1.21 www 8981: my $mrole;
8982: if ($role =~ /^cr\//) {
1.393 www 8983: my $cwosec=$url;
1.811 albertel 8984: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8985: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8986: my $refused = 1;
8987: if ($context eq 'requestcourses') {
8988: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8989: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8990: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8991: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8992: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8993: if ($crsenv{'internal.courseowner'} eq
8994: $env{'user.name'}.':'.$env{'user.domain'}) {
8995: $refused = '';
8996: }
8997: }
8998: }
8999: }
9000: }
9001: if ($refused) {
9002: &logthis('Refused custom assignrole: '.
9003: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9004: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9005: return 'refused';
9006: }
1.104 www 9007: }
1.21 www 9008: $mrole='cr';
1.678 raeburn 9009: } elsif ($role =~ /^gr\//) {
9010: my $cwogrp=$url;
1.811 albertel 9011: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 9012: unless (&allowed('mdg',$cwogrp)) {
9013: &logthis('Refused group assignrole: '.
9014: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9015: $env{'user.name'}.' at '.$env{'user.domain'});
9016: return 'refused';
9017: }
9018: $mrole='gr';
1.21 www 9019: } else {
1.82 www 9020: my $cwosec=$url;
1.811 albertel 9021: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9022: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9023: my $refused;
9024: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9025: if (!(&allowed('c'.$role,$url))) {
9026: $refused = 1;
9027: }
9028: } else {
9029: $refused = 1;
9030: }
1.947 raeburn 9031: if ($refused) {
1.1045 raeburn 9032: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9033: if (!$selfenroll && $context eq 'course') {
9034: my %crsenv;
9035: if ($role eq 'cc' || $role eq 'co') {
9036: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9037: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9038: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9039: if ($crsenv{'internal.courseowner'} eq
9040: $env{'user.name'}.':'.$env{'user.domain'}) {
9041: $refused = '';
9042: }
9043: }
9044: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9045: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9046: if ($crsenv{'internal.courseowner'} eq
9047: $env{'user.name'}.':'.$env{'user.domain'}) {
9048: $refused = '';
9049: }
9050: }
9051: }
9052: }
9053: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 9054: $refused = '';
1.1017 raeburn 9055: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9056: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9057: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9058: my $wrongcc;
9059: if ($cnum =~ /^$match_community$/) {
9060: $wrongcc = 1 if ($role eq 'cc');
9061: } else {
9062: $wrongcc = 1 if ($role eq 'co');
9063: }
9064: unless ($wrongcc) {
9065: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9066: if ($crsenv{'internal.courseowner'} eq
9067: $env{'user.name'}.':'.$env{'user.domain'}) {
9068: $refused = '';
9069: }
1.1017 raeburn 9070: }
9071: }
1.1183 raeburn 9072: } elsif ($context eq 'requestauthor') {
9073: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9074: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9075: if ($env{'environment.requestauthor'} eq 'automatic') {
9076: $refused = '';
9077: } else {
9078: my %domdefaults = &get_domain_defaults($udom);
9079: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9080: my $checkbystatus;
9081: if ($env{'user.adv'}) {
9082: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9083: if ($disposition eq 'automatic') {
9084: $refused = '';
9085: } elsif ($disposition eq '') {
9086: $checkbystatus = 1;
9087: }
9088: } else {
9089: $checkbystatus = 1;
9090: }
9091: if ($checkbystatus) {
9092: if ($env{'environment.inststatus'}) {
9093: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9094: foreach my $type (@inststatuses) {
9095: if (($type ne '') &&
9096: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9097: $refused = '';
9098: }
9099: }
9100: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9101: $refused = '';
9102: }
9103: }
9104: }
9105: }
9106: }
1.1017 raeburn 9107: }
9108: if ($refused) {
1.947 raeburn 9109: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9110: ' '.$role.' '.$end.' '.$start.' by '.
9111: $env{'user.name'}.' at '.$env{'user.domain'});
9112: return 'refused';
9113: }
1.932 raeburn 9114: }
1.1131 raeburn 9115: } elsif ($role eq 'au') {
9116: if ($url ne '/'.$udom.'/') {
9117: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9118: ' to assign author role for '.$uname.':'.$udom.
9119: ' in domain: '.$url.' refused (wrong domain).');
9120: return 'refused';
9121: }
1.104 www 9122: }
1.21 www 9123: $mrole=$role;
9124: }
1.620 albertel 9125: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9126: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9127: if ($end) { $command.='_'.$end; }
1.21 www 9128: if ($start) {
9129: if ($end) {
1.81 www 9130: $command.='_'.$start;
1.21 www 9131: } else {
1.81 www 9132: $command.='_0_'.$start;
1.21 www 9133: }
9134: }
1.739 raeburn 9135: my $origstart = $start;
9136: my $origend = $end;
1.957 raeburn 9137: my $delflag;
1.357 www 9138: # actually delete
9139: if ($deleteflag) {
1.373 www 9140: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9141: # modify command to delete the role
1.620 albertel 9142: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9143: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9144: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9145: # set start and finish to negative values for userrolelog
9146: $start=-1;
9147: $end=-1;
1.957 raeburn 9148: $delflag = 1;
1.357 www 9149: }
9150: }
9151: # send command
1.349 www 9152: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9153: # log new user role if status is ok
1.349 www 9154: if ($answer eq 'ok') {
1.663 raeburn 9155: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 9156: if (($role eq 'cc') || ($role eq 'in') ||
9157: ($role eq 'ep') || ($role eq 'ad') ||
9158: ($role eq 'ta') || ($role eq 'st') ||
9159: ($role=~/^cr/) || ($role eq 'gr') ||
9160: ($role eq 'co')) {
1.1200 raeburn 9161: # for course roles, perform group memberships changes triggered by role change.
9162: unless ($role =~ /^gr/) {
9163: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9164: $origstart,$selfenroll,$context);
9165: }
1.1184 raeburn 9166: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9167: $selfenroll,$context);
9168: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334 raeburn 9169: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9170: ($role eq 'da')) {
1.1184 raeburn 9171: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9172: $context);
9173: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9174: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9175: $context);
9176: }
1.1053 raeburn 9177: if ($role eq 'cc') {
9178: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9179: }
1.349 www 9180: }
9181: return $answer;
1.169 harris41 9182: }
9183:
1.1053 raeburn 9184: sub autoupdate_coowners {
9185: my ($url,$end,$start,$uname,$udom) = @_;
9186: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9187: if (($cdom ne '') && ($cnum ne '')) {
9188: my $now = time;
9189: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9190: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9191: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9192: my $instcode = $coursehash{'internal.coursecode'};
9193: if ($instcode ne '') {
1.1056 raeburn 9194: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9195: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 9196: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 9197: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9198: if ($result eq 'valid') {
9199: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 9200: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9201: push(@newcoowners,$coowner);
9202: }
9203: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9204: push(@newcoowners,$uname.':'.$udom);
9205: }
9206: @newcoowners = sort(@newcoowners);
9207: } else {
9208: push(@newcoowners,$uname.':'.$udom);
9209: }
9210: } else {
9211: if ($coursehash{'internal.co-owners'}) {
9212: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9213: unless ($coowner eq $uname.':'.$udom) {
9214: push(@newcoowners,$coowner);
9215: }
9216: }
9217: unless (@newcoowners > 0) {
9218: $delcoowners = 1;
9219: $coowners = '';
9220: }
9221: }
9222: }
9223: if (@newcoowners || $delcoowners) {
9224: &store_coowners($cdom,$cnum,$coursehash{'home'},
9225: $delcoowners,@newcoowners);
9226: }
9227: }
9228: }
9229: }
9230: }
9231: }
9232: }
9233:
9234: sub store_coowners {
9235: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9236: my $cid = $cdom.'_'.$cnum;
9237: my ($coowners,$delresult,$putresult);
9238: if (@newcoowners) {
9239: $coowners = join(',',@newcoowners);
9240: my %coownershash = (
9241: 'internal.co-owners' => $coowners,
9242: );
9243: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9244: if ($putresult eq 'ok') {
9245: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9246: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9247: }
9248: }
9249: }
9250: if ($delcoowners) {
9251: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9252: if ($delresult eq 'ok') {
9253: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9254: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9255: }
9256: }
9257: }
9258: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9259: my %crsinfo =
9260: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9261: if (ref($crsinfo{$cid}) eq 'HASH') {
9262: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9263: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9264: }
9265: }
9266: }
9267:
1.169 harris41 9268: # -------------------------------------------------- Modify user authentication
1.197 www 9269: # Overrides without validation
9270:
1.169 harris41 9271: sub modifyuserauth {
9272: my ($udom,$uname,$umode,$upass)=@_;
9273: my $uhome=&homeserver($uname,$udom);
1.197 www 9274: unless (&allowed('mau',$udom)) { return 'refused'; }
9275: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 9276: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9277: ' in domain '.$env{'request.role.domain'});
1.169 harris41 9278: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9279: &escape($upass),$uhome);
1.620 albertel 9280: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 9281: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9282: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9283: &log($udom,,$uname,$uhome,
1.620 albertel 9284: 'Authentication changed by '.$env{'user.domain'}.', '.
9285: $env{'user.name'}.', '.$umode.
1.197 www 9286: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 9287: unless ($reply eq 'ok') {
1.197 www 9288: &logthis('Authentication mode error: '.$reply);
1.169 harris41 9289: return 'error: '.$reply;
9290: }
1.170 harris41 9291: return 'ok';
1.80 www 9292: }
9293:
1.81 www 9294: # --------------------------------------------------------------- Modify a user
1.80 www 9295:
1.81 www 9296: sub modifyuser {
1.206 matthew 9297: my ($udom, $uname, $uid,
9298: $umode, $upass, $first,
9299: $middle, $last, $gene,
1.1058 raeburn 9300: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 9301: $udom= &LONCAPA::clean_domain($udom);
9302: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 9303: my $showcandelete = 'none';
9304: if (ref($candelete) eq 'ARRAY') {
9305: if (@{$candelete} > 0) {
9306: $showcandelete = join(', ',@{$candelete});
9307: }
9308: }
1.81 www 9309: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 9310: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 9311: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 9312: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9313: ' desiredhome not specified').
1.620 albertel 9314: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9315: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 9316: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 9317: my $newuser;
9318: if ($uhome eq 'no_host') {
9319: $newuser = 1;
9320: }
1.80 www 9321: # ----------------------------------------------------------------- Create User
1.406 albertel 9322: if (($uhome eq 'no_host') &&
9323: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 9324: my $unhome='';
1.844 albertel 9325: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 9326: $unhome = $desiredhome;
1.620 albertel 9327: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9328: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 9329: } else { # load balancing routine for determining $unhome
1.81 www 9330: my $loadm=10000000;
1.841 albertel 9331: my %servers = &get_servers($udom,'library');
9332: foreach my $tryserver (keys(%servers)) {
9333: my $answer=reply('load',$tryserver);
9334: if (($answer=~/\d+/) && ($answer<$loadm)) {
9335: $loadm=$answer;
9336: $unhome=$tryserver;
9337: }
1.80 www 9338: }
9339: }
9340: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 9341: return 'error: unable to find a home server for '.$uname.
9342: ' in domain '.$udom;
1.80 www 9343: }
9344: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9345: &escape($upass),$unhome);
9346: unless ($reply eq 'ok') {
9347: return 'error: '.$reply;
9348: }
1.230 stredwic 9349: $uhome=&homeserver($uname,$udom,'true');
1.80 www 9350: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 9351: return 'error: unable verify users home machine.';
1.80 www 9352: }
1.209 matthew 9353: } # End of creation of new user
1.80 www 9354: # ---------------------------------------------------------------------- Add ID
9355: if ($uid) {
9356: $uid=~tr/A-Z/a-z/;
9357: my %uidhash=&idrget($udom,$uname);
1.196 www 9358: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
9359: && (!$forceid)) {
1.80 www 9360: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 9361: return 'error: user id "'.$uid.'" does not match '.
9362: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 9363: }
9364: } else {
1.1300 raeburn 9365: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 9366: }
9367: }
9368: # -------------------------------------------------------------- Add names, etc
1.313 matthew 9369: my @tmp=&get('environment',
1.899 raeburn 9370: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 9371: 'permanentemail','inststatus'],
1.134 albertel 9372: $udom,$uname);
1.1075 raeburn 9373: my (%names,%oldnames);
1.313 matthew 9374: if ($tmp[0] =~ m/^error:.*/) {
9375: %names=();
9376: } else {
9377: %names = @tmp;
1.1075 raeburn 9378: %oldnames = %names;
1.313 matthew 9379: }
1.388 www 9380: #
1.1058 raeburn 9381: # If name, email and/or uid are blank (e.g., because an uploaded file
9382: # of users did not contain them), do not overwrite existing values
9383: # unless field is in $candelete array ref.
9384: #
9385:
9386: my @fields = ('firstname','middlename','lastname','generation',
9387: 'permanentemail','id');
9388: my %newvalues;
9389: if (ref($candelete) eq 'ARRAY') {
9390: foreach my $field (@fields) {
9391: if (grep(/^\Q$field\E$/,@{$candelete})) {
9392: if ($field eq 'firstname') {
9393: $names{$field} = $first;
9394: } elsif ($field eq 'middlename') {
9395: $names{$field} = $middle;
9396: } elsif ($field eq 'lastname') {
9397: $names{$field} = $last;
9398: } elsif ($field eq 'generation') {
9399: $names{$field} = $gene;
9400: } elsif ($field eq 'permanentemail') {
9401: $names{$field} = $email;
9402: } elsif ($field eq 'id') {
9403: $names{$field} = $uid;
9404: }
9405: }
9406: }
9407: }
1.388 www 9408: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 9409: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 9410: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 9411: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 9412: if ($email) {
9413: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 9414: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 9415: }
1.899 raeburn 9416: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 9417: if (defined($inststatus)) {
9418: $names{'inststatus'} = '';
9419: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9420: if (ref($usertypes) eq 'HASH') {
9421: my @okstatuses;
9422: foreach my $item (split(/:/,$inststatus)) {
9423: if (defined($usertypes->{$item})) {
9424: push(@okstatuses,$item);
9425: }
9426: }
9427: if (@okstatuses) {
9428: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9429: }
9430: }
9431: }
1.1075 raeburn 9432: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 9433: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 9434: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 9435: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9436: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9437: } else {
9438: $logmsg .= ' during self creation';
9439: }
1.1075 raeburn 9440: my $changed;
9441: if ($newuser) {
9442: $changed = 1;
9443: } else {
9444: foreach my $field (@fields) {
9445: if ($names{$field} ne $oldnames{$field}) {
9446: $changed = 1;
9447: last;
9448: }
9449: }
9450: }
9451: unless ($changed) {
9452: $logmsg = 'No changes in user information needed for: '.$logmsg;
9453: &logthis($logmsg);
9454: return 'ok';
9455: }
9456: my $reply = &put('environment', \%names, $udom,$uname);
9457: if ($reply ne 'ok') {
9458: return 'error: '.$reply;
9459: }
1.1087 raeburn 9460: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9461: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9462: }
1.1075 raeburn 9463: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9464: &devalidate_cache_new('namescache',$uname.':'.$udom);
9465: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9466: &logthis($logmsg);
1.134 albertel 9467: return 'ok';
1.80 www 9468: }
9469:
1.81 www 9470: # -------------------------------------------------------------- Modify student
1.80 www 9471:
1.81 www 9472: sub modifystudent {
9473: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9474: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 9475: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 9476: if (!$cid) {
1.620 albertel 9477: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9478: return 'not_in_class';
9479: }
1.80 www 9480: }
9481: # --------------------------------------------------------------- Make the user
1.81 www 9482: my $reply=&modifyuser
1.209 matthew 9483: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9484: $desiredhome,$email,$inststatus);
1.80 www 9485: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9486: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 9487: # student's environment
1.297 matthew 9488: $uid = undef if (!$forceid);
1.455 albertel 9489: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 9490: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 9491: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 9492: return $reply;
9493: }
9494:
9495: sub modify_student_enrollment {
1.1216 raeburn 9496: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314 raeburn 9497: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 9498: my ($cdom,$cnum,$chome);
9499: if (!$cid) {
1.620 albertel 9500: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9501: return 'not_in_class';
9502: }
1.620 albertel 9503: $cdom=$env{'course.'.$cid.'.domain'};
9504: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9505: } else {
9506: ($cdom,$cnum)=split(/_/,$cid);
9507: }
1.620 albertel 9508: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9509: if (!$chome) {
1.457 raeburn 9510: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9511: }
1.455 albertel 9512: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9513: # Make sure the user exists
1.81 www 9514: my $uhome=&homeserver($uname,$udom);
9515: if (($uhome eq '') || ($uhome eq 'no_host')) {
9516: return 'error: no such user';
9517: }
1.297 matthew 9518: # Get student data if we were not given enough information
9519: if (!defined($first) || $first eq '' ||
9520: !defined($last) || $last eq '' ||
9521: !defined($uid) || $uid eq '' ||
9522: !defined($middle) || $middle eq '' ||
9523: !defined($gene) || $gene eq '') {
1.294 matthew 9524: # They did not supply us with enough data to enroll the student, so
9525: # we need to pick up more information.
1.297 matthew 9526: my %tmp = &get('environment',
1.294 matthew 9527: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9528: ,$udom,$uname);
9529:
1.800 albertel 9530: #foreach my $key (keys(%tmp)) {
9531: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9532: #}
1.294 matthew 9533: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9534: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9535: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9536: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9537: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9538: }
1.556 albertel 9539: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9540: my $user = "$uname:$udom";
9541: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9542: my $reply=cput('classlist',
1.1148 raeburn 9543: {$user =>
1.1314 raeburn 9544: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 9545: $cdom,$cnum);
1.1148 raeburn 9546: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9547: &devalidate_getsection_cache($udom,$uname,$cid);
9548: } else {
1.81 www 9549: return 'error: '.$reply;
9550: }
1.297 matthew 9551: # Add student role to user
1.83 www 9552: my $uurl='/'.$cid;
1.81 www 9553: $uurl=~s/\_/\//g;
9554: if ($usec) {
9555: $uurl.='/'.$usec;
9556: }
1.1148 raeburn 9557: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9558: $selfenroll,$context);
9559: if ($result ne 'ok') {
9560: if ($old_entry{$user} ne '') {
9561: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9562: } else {
9563: $reply = &del('classlist',[$user],$cdom,$cnum);
9564: }
9565: }
9566: return $result;
1.21 www 9567: }
9568:
1.556 albertel 9569: sub format_name {
9570: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9571: my $name;
9572: if ($first ne 'lastname') {
9573: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9574: } else {
9575: if ($lastname=~/\S/) {
9576: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9577: $name=~s/\s+,/,/;
9578: } else {
9579: $name.= $firstname.' '.$middlename.' '.$generation;
9580: }
9581: }
9582: $name=~s/^\s+//;
9583: $name=~s/\s+$//;
9584: $name=~s/\s+/ /g;
9585: return $name;
9586: }
9587:
1.84 www 9588: # ------------------------------------------------- Write to course preferences
9589:
9590: sub writecoursepref {
9591: my ($courseid,%prefs)=@_;
9592: $courseid=~s/^\///;
9593: $courseid=~s/\_/\//g;
9594: my ($cdomain,$cnum)=split(/\//,$courseid);
9595: my $chome=homeserver($cnum,$cdomain);
9596: if (($chome eq '') || ($chome eq 'no_host')) {
9597: return 'error: no such course';
9598: }
9599: my $cstring='';
1.800 albertel 9600: foreach my $pref (keys(%prefs)) {
9601: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9602: }
1.84 www 9603: $cstring=~s/\&$//;
9604: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9605: }
9606:
9607: # ---------------------------------------------------------- Make/modify course
9608:
9609: sub createcourse {
1.741 raeburn 9610: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9611: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9612: $url=&declutter($url);
9613: my $cid='';
1.1028 raeburn 9614: if ($context eq 'requestcourses') {
9615: my $can_create = 0;
9616: my ($ownername,$ownerdom) = split(':',$course_owner);
9617: if ($udom eq $ownerdom) {
9618: if (&usertools_access($ownername,$ownerdom,$category,undef,
9619: $context)) {
9620: $can_create = 1;
9621: }
9622: } else {
9623: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9624: $category);
9625: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9626: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9627: if (@curr > 0) {
9628: my @options = qw(approval validate autolimit);
9629: my $optregex = join('|',@options);
9630: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9631: $can_create = 1;
9632: }
9633: }
9634: }
9635: }
9636: if ($can_create) {
9637: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9638: unless (&allowed('ccc',$udom)) {
9639: return 'refused';
9640: }
1.1017 raeburn 9641: }
9642: } else {
9643: return 'refused';
9644: }
1.1028 raeburn 9645: } elsif (!&allowed('ccc',$udom)) {
9646: return 'refused';
1.84 www 9647: }
1.1011 raeburn 9648: # --------------------------------------------------------------- Get Unique ID
9649: my $uname;
9650: if ($cnum =~ /^$match_courseid$/) {
9651: my $chome=&homeserver($cnum,$udom,'true');
9652: if (($chome eq '') || ($chome eq 'no_host')) {
9653: $uname = $cnum;
9654: } else {
1.1038 raeburn 9655: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9656: }
9657: } else {
1.1038 raeburn 9658: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9659: }
9660: return $uname if ($uname =~ /^error/);
9661: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9662: if (!defined($course_server)) {
9663: if (defined(&domain($udom,'primary'))) {
9664: $course_server = &domain($udom,'primary');
9665: } else {
9666: $course_server = $env{'user.home'};
9667: }
9668: }
9669: my %host_servers =
9670: &Apache::lonnet::get_servers($udom,'library');
9671: unless ($host_servers{$course_server}) {
9672: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9673: }
1.84 www 9674: # ------------------------------------------------------------- Make the course
9675: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9676: $course_server);
1.84 www 9677: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9678: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9679: if (($uhome eq '') || ($uhome eq 'no_host')) {
9680: return 'error: no such course';
9681: }
1.271 www 9682: # ----------------------------------------------------------------- Course made
1.516 raeburn 9683: # log existence
1.1029 raeburn 9684: my $now = time;
1.918 raeburn 9685: my $newcourse = {
9686: $udom.'_'.$uname => {
1.921 raeburn 9687: description => $description,
9688: inst_code => $inst_code,
9689: owner => $course_owner,
9690: type => $crstype,
1.1029 raeburn 9691: creator => $env{'user.name'}.':'.
9692: $env{'user.domain'},
9693: created => $now,
9694: context => $context,
1.918 raeburn 9695: },
9696: };
1.921 raeburn 9697: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9698: # set toplevel url
1.271 www 9699: my $topurl=$url;
9700: unless ($nonstandard) {
9701: # ------------------------------------------ For standard courses, make top url
9702: my $mapurl=&clutter($url);
1.278 www 9703: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9704: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9705: <map>
9706: <resource id="1" type="start"></resource>
9707: <resource id="2" src="$mapurl"></resource>
9708: <resource id="3" type="finish"></resource>
9709: <link index="1" from="1" to="2"></link>
9710: <link index="2" from="2" to="3"></link>
9711: </map>
9712: ENDINITMAP
9713: $topurl=&declutter(
1.638 albertel 9714: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9715: );
9716: }
9717: # ----------------------------------------------------------- Write preferences
1.84 www 9718: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9719: ('description' => $description,
9720: 'url' => $topurl,
9721: 'internal.creator' => $env{'user.name'}.':'.
9722: $env{'user.domain'},
9723: 'internal.created' => $now,
9724: 'internal.creationcontext' => $context)
9725: );
1.84 www 9726: return '/'.$udom.'/'.$uname;
9727: }
9728:
1.1011 raeburn 9729: # ------------------------------------------------------------------- Create ID
9730: sub generate_coursenum {
1.1038 raeburn 9731: my ($udom,$crstype) = @_;
1.1011 raeburn 9732: my $domdesc = &domain($udom);
9733: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9734: my $first;
9735: if ($crstype eq 'Community') {
9736: $first = '0';
9737: } else {
9738: $first = int(1+rand(9));
9739: }
9740: my $uname=$first.
1.1011 raeburn 9741: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9742: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9743: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9744: # ----------------------------------------------- Make sure that does not exist
9745: my $uhome=&homeserver($uname,$udom,'true');
9746: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9747: if ($crstype eq 'Community') {
9748: $first = '0';
9749: } else {
9750: $first = int(1+rand(9));
9751: }
9752: $uname=$first.
1.1011 raeburn 9753: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9754: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9755: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9756: $uhome=&homeserver($uname,$udom,'true');
9757: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9758: return 'error: unable to generate unique course-ID';
9759: }
9760: }
9761: return $uname;
9762: }
9763:
1.813 albertel 9764: sub is_course {
1.1167 droeschl 9765: my ($cdom, $cnum) = scalar(@_) == 1 ?
9766: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9767:
9768: return unless $cdom and $cnum;
9769:
9770: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9771: '.');
9772:
1.1219 raeburn 9773: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9774: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9775: }
9776:
1.1015 raeburn 9777: sub store_userdata {
9778: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9779: my $result;
1.1016 raeburn 9780: if ($datakey ne '') {
1.1013 raeburn 9781: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9782: if ($udom eq '' || $uname eq '') {
9783: $udom = $env{'user.domain'};
9784: $uname = $env{'user.name'};
9785: }
9786: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9787: if (($uhome eq '') || ($uhome eq 'no_host')) {
9788: $result = 'error: no_host';
9789: } else {
9790: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9791: $storehash->{'host'} = $perlvar{'lonHostID'};
9792:
9793: my $namevalue='';
9794: foreach my $key (keys(%{$storehash})) {
9795: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9796: }
9797: $namevalue=~s/\&$//;
1.1224 raeburn 9798: unless ($namespace eq 'courserequests') {
9799: $datakey = &escape($datakey);
9800: }
1.1105 raeburn 9801: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9802: $namevalue,$uhome);
1.1013 raeburn 9803: }
9804: } else {
9805: $result = 'error: data to store was not a hash reference';
9806: }
9807: } else {
9808: $result= 'error: invalid requestkey';
9809: }
9810: return $result;
9811: }
9812:
1.21 www 9813: # ---------------------------------------------------------- Assign Custom Role
9814:
9815: sub assigncustomrole {
1.957 raeburn 9816: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9817: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9818: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9819: }
9820:
9821: # ----------------------------------------------------------------- Revoke Role
9822:
9823: sub revokerole {
1.957 raeburn 9824: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9825: my $now=time;
1.965 raeburn 9826: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9827: }
9828:
9829: # ---------------------------------------------------------- Revoke Custom Role
9830:
9831: sub revokecustomrole {
1.957 raeburn 9832: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9833: my $now=time;
1.357 www 9834: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9835: $deleteflag,$selfenroll,$context);
1.17 www 9836: }
9837:
1.533 banghart 9838: # ------------------------------------------------------------ Disk usage
1.535 albertel 9839: sub diskusage {
1.955 raeburn 9840: my ($udom,$uname,$directorypath,$getpropath)=@_;
9841: $directorypath =~ s/\/$//;
9842: my $listing=&reply('du2:'.&escape($directorypath).':'
9843: .&escape($getpropath).':'.&escape($uname).':'
9844: .&escape($udom),homeserver($uname,$udom));
9845: if ($listing eq 'unknown_cmd') {
9846: if ($getpropath) {
9847: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9848: }
9849: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9850: }
1.514 albertel 9851: return $listing;
1.512 banghart 9852: }
9853:
1.566 banghart 9854: sub is_locked {
1.1096 raeburn 9855: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9856: my @check;
9857: my $is_locked;
1.1093 raeburn 9858: push (@check,$file_name);
1.613 albertel 9859: my %locked = &get('file_permissions',\@check,
1.620 albertel 9860: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9861: my ($tmp)=keys(%locked);
9862: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9863:
1.566 banghart 9864: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9865: $is_locked = 'false';
9866: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9867: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9868: $is_locked = 'true';
1.1096 raeburn 9869: if (ref($which) eq 'ARRAY') {
9870: push(@{$which},$entry);
9871: } else {
9872: last;
9873: }
1.745 raeburn 9874: }
9875: }
1.566 banghart 9876: } else {
9877: $is_locked = 'false';
9878: }
1.1093 raeburn 9879: return $is_locked;
1.566 banghart 9880: }
9881:
1.759 albertel 9882: sub declutter_portfile {
9883: my ($file) = @_;
1.833 albertel 9884: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9885: return $file;
9886: }
9887:
1.559 banghart 9888: # ------------------------------------------------------------- Mark as Read Only
9889:
9890: sub mark_as_readonly {
9891: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9892: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9893: my ($tmp)=keys(%current_permissions);
9894: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9895: foreach my $file (@{$files}) {
1.759 albertel 9896: $file = &declutter_portfile($file);
1.561 banghart 9897: push(@{$current_permissions{$file}},$what);
1.559 banghart 9898: }
1.613 albertel 9899: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9900: return;
9901: }
9902:
1.572 banghart 9903: # ------------------------------------------------------------Save Selected Files
9904:
9905: sub save_selected_files {
9906: my ($user, $path, @files) = @_;
9907: my $filename = $user."savedfiles";
1.573 banghart 9908: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9909: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9910: foreach my $file (@files) {
1.620 albertel 9911: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9912: }
9913: foreach my $file (@other_files) {
1.574 banghart 9914: print (OUT $file."\n");
1.572 banghart 9915: }
1.574 banghart 9916: close (OUT);
1.572 banghart 9917: return 'ok';
9918: }
9919:
1.574 banghart 9920: sub clear_selected_files {
9921: my ($user) = @_;
9922: my $filename = $user."savedfiles";
1.1117 foxr 9923: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9924: print (OUT undef);
9925: close (OUT);
9926: return ("ok");
9927: }
9928:
1.572 banghart 9929: sub files_in_path {
9930: my ($user, $path) = @_;
9931: my $filename = $user."savedfiles";
9932: my %return_files;
1.1117 foxr 9933: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9934: while (my $line_in = <IN>) {
1.574 banghart 9935: chomp ($line_in);
9936: my @paths_and_file = split (m!/!, $line_in);
9937: my $file_part = pop (@paths_and_file);
9938: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9939: $path_part.='/';
9940: my $path_and_file = $path_part.$file_part;
9941: if ($path_part eq $path) {
9942: $return_files{$file_part}= 'selected';
9943: }
9944: }
1.574 banghart 9945: close (IN);
9946: return (\%return_files);
1.572 banghart 9947: }
9948:
9949: # called in portfolio select mode, to show files selected NOT in current directory
9950: sub files_not_in_path {
9951: my ($user, $path) = @_;
9952: my $filename = $user."savedfiles";
9953: my @return_files;
9954: my $path_part;
1.1117 foxr 9955: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9956: while (my $line = <IN>) {
1.572 banghart 9957: #ok, I know it's clunky, but I want it to work
1.800 albertel 9958: my @paths_and_file = split(m|/|, $line);
9959: my $file_part = pop(@paths_and_file);
9960: chomp($file_part);
9961: my $path_part = join('/', @paths_and_file);
1.572 banghart 9962: $path_part .= '/';
9963: my $path_and_file = $path_part.$file_part;
9964: if ($path_part ne $path) {
1.800 albertel 9965: push(@return_files, ($path_and_file));
1.572 banghart 9966: }
9967: }
1.800 albertel 9968: close(OUT);
1.574 banghart 9969: return (@return_files);
1.572 banghart 9970: }
9971:
1.1273 raeburn 9972: #------------------------------Submitted/Handedback Portfolio Files Versioning
9973:
9974: sub portfiles_versioning {
9975: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
9976: my $portfolio_root = '/userfiles/portfolio';
9977: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
9978: foreach my $file (@{$portfiles}) {
9979: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
9980: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
9981: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
9982: my $getpropath = 1;
9983: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
9984: $stu_name,$getpropath);
9985: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
9986: my $new_answer =
9987: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
9988: if ($new_answer ne 'problem getting file') {
9989: push(@{$versioned_portfiles}, $directory.$new_answer);
9990: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
9991: [$symb,$env{'request.course.id'},'graded']);
9992: }
9993: }
9994: }
9995:
9996: sub get_next_version {
9997: my ($answer_name, $answer_ext, $dir_list) = @_;
9998: my $version;
9999: if (ref($dir_list) eq 'ARRAY') {
10000: foreach my $row (@{$dir_list}) {
10001: my ($file) = split(/\&/,$row,2);
10002: my ($file_name,$file_version,$file_ext) =
10003: &file_name_version_ext($file);
10004: if (($file_name eq $answer_name) &&
10005: ($file_ext eq $answer_ext)) {
10006: # gets here if filename and extension match,
10007: # regardless of version
10008: if ($file_version ne '') {
10009: # a versioned file is found so save it for later
10010: if ($file_version > $version) {
10011: $version = $file_version;
10012: }
10013: }
10014: }
10015: }
10016: }
10017: $version ++;
10018: return($version);
10019: }
10020:
10021: sub version_selected_portfile {
10022: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10023: my ($answer_name,$answer_ver,$answer_ext) =
10024: &file_name_version_ext($file_name);
10025: my $new_answer;
10026: $env{'form.copy'} =
10027: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10028: if($env{'form.copy'} eq '-1') {
10029: $new_answer = 'problem getting file';
10030: } else {
10031: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10032: my $copy_result =
10033: &finishuserfileupload($stu_name,$domain,'copy',
10034: '/portfolio'.$directory.$new_answer);
10035: }
10036: undef($env{'form.copy'});
10037: return ($new_answer);
10038: }
10039:
10040: sub file_name_version_ext {
10041: my ($file)=@_;
10042: my @file_parts = split(/\./, $file);
10043: my ($name,$version,$ext);
10044: if (@file_parts > 1) {
10045: $ext=pop(@file_parts);
10046: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10047: $version=pop(@file_parts);
10048: }
10049: $name=join('.',@file_parts);
10050: } else {
10051: $name=join('.',@file_parts);
10052: }
10053: return($name,$version,$ext);
10054: }
10055:
1.745 raeburn 10056: #----------------------------------------------Get portfolio file permissions
1.629 banghart 10057:
1.745 raeburn 10058: sub get_portfile_permissions {
10059: my ($domain,$user) = @_;
1.613 albertel 10060: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10061: my ($tmp)=keys(%current_permissions);
10062: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10063: return \%current_permissions;
10064: }
10065:
10066: #---------------------------------------------Get portfolio file access controls
10067:
1.749 raeburn 10068: sub get_access_controls {
1.745 raeburn 10069: my ($current_permissions,$group,$file) = @_;
1.769 albertel 10070: my %access;
10071: my $real_file = $file;
10072: $file =~ s/\.meta$//;
1.745 raeburn 10073: if (defined($file)) {
1.749 raeburn 10074: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10075: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 10076: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 10077: }
10078: }
1.745 raeburn 10079: } else {
1.749 raeburn 10080: foreach my $key (keys(%{$current_permissions})) {
10081: if ($key =~ /\0accesscontrol$/) {
10082: if (defined($group)) {
10083: if ($key !~ m-^\Q$group\E/-) {
10084: next;
10085: }
10086: }
10087: my ($fullpath) = split(/\0/,$key);
10088: if (ref($$current_permissions{$key}) eq 'HASH') {
10089: foreach my $control (keys(%{$$current_permissions{$key}})) {
10090: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10091: }
10092: }
10093: }
10094: }
10095: }
10096: return %access;
10097: }
10098:
10099: sub modify_access_controls {
10100: my ($file_name,$changes,$domain,$user)=@_;
10101: my ($outcome,$deloutcome);
10102: my %store_permissions;
10103: my %new_values;
10104: my %new_control;
10105: my %translation;
10106: my @deletions = ();
10107: my $now = time;
10108: if (exists($$changes{'activate'})) {
10109: if (ref($$changes{'activate'}) eq 'HASH') {
10110: my @newitems = sort(keys(%{$$changes{'activate'}}));
10111: my $numnew = scalar(@newitems);
10112: for (my $i=0; $i<$numnew; $i++) {
10113: my $newkey = $newitems[$i];
10114: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10115: if ($newkey =~ /^\d+:/) {
10116: $newkey =~ s/^(\d+)/$newid/;
10117: $translation{$1} = $newid;
10118: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10119: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10120: $translation{$1} = $newid;
10121: }
1.749 raeburn 10122: $new_values{$file_name."\0".$newkey} =
10123: $$changes{'activate'}{$newitems[$i]};
10124: $new_control{$newkey} = $now;
10125: }
10126: }
10127: }
10128: my %todelete;
10129: my %changed_items;
10130: foreach my $action ('delete','update') {
10131: if (exists($$changes{$action})) {
10132: if (ref($$changes{$action}) eq 'HASH') {
10133: foreach my $key (keys(%{$$changes{$action}})) {
10134: my ($itemnum) = ($key =~ /^([^:]+):/);
10135: if ($action eq 'delete') {
10136: $todelete{$itemnum} = 1;
10137: } else {
10138: $changed_items{$itemnum} = $key;
10139: }
10140: }
1.745 raeburn 10141: }
10142: }
1.749 raeburn 10143: }
10144: # get lock on access controls for file.
10145: my $lockhash = {
10146: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10147: ':'.$env{'user.domain'},
10148: };
10149: my $tries = 0;
10150: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10151:
1.1288 damieng 10152: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10153: $tries ++;
1.1289 damieng 10154: sleep(0.1);
1.749 raeburn 10155: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10156: }
10157: if ($gotlock eq 'ok') {
10158: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10159: my ($tmp)=keys(%curr_permissions);
10160: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10161: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10162: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10163: if (ref($curr_controls) eq 'HASH') {
10164: foreach my $control_item (keys(%{$curr_controls})) {
10165: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10166: if (defined($todelete{$itemnum})) {
10167: push(@deletions,$file_name."\0".$control_item);
10168: } else {
10169: if (defined($changed_items{$itemnum})) {
10170: $new_control{$changed_items{$itemnum}} = $now;
10171: push(@deletions,$file_name."\0".$control_item);
10172: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10173: } else {
10174: $new_control{$control_item} = $$curr_controls{$control_item};
10175: }
10176: }
1.745 raeburn 10177: }
10178: }
10179: }
1.970 raeburn 10180: my ($group);
10181: if (&is_course($domain,$user)) {
10182: ($group,my $file) = split(/\//,$file_name,2);
10183: }
1.749 raeburn 10184: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10185: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10186: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10187: # remove lock
10188: my @del_lock = ($file_name."\0".'locked_access_records');
10189: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 10190: my $sqlresult =
1.970 raeburn 10191: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 10192: $group);
1.749 raeburn 10193: } else {
10194: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 10195: }
1.749 raeburn 10196: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 10197: }
10198:
1.827 raeburn 10199: sub make_public_indefinitely {
1.1271 raeburn 10200: my (@requrl) = @_;
10201: return &automated_portfile_access('public',\@requrl);
10202: }
10203:
10204: sub automated_portfile_access {
10205: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 10206: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10207: return 'invalid';
10208: }
1.1271 raeburn 10209: my %urls;
10210: if (ref($addsref) eq 'ARRAY') {
10211: foreach my $requrl (@{$addsref}) {
10212: if (&is_portfolio_url($requrl)) {
10213: unless (exists($urls{$requrl})) {
10214: $urls{$requrl} = 'add';
10215: }
10216: }
10217: }
10218: }
10219: if (ref($delsref) eq 'ARRAY') {
10220: foreach my $requrl (@{$delsref}) {
10221: if (&is_portfolio_url($requrl)) {
10222: unless (exists($urls{$requrl})) {
10223: $urls{$requrl} = 'delete';
10224: }
10225: }
10226: }
10227: }
10228: unless (keys(%urls)) {
10229: return 'invalid';
10230: }
10231: my $ip;
10232: if ($accesstype eq 'ip') {
10233: if (ref($info) eq 'HASH') {
10234: if ($info->{'ip'} ne '') {
10235: $ip = $info->{'ip'};
10236: }
10237: }
10238: if ($ip eq '') {
10239: return 'invalid';
10240: }
10241: }
10242: my $errors;
1.827 raeburn 10243: my $now = time;
1.1271 raeburn 10244: my %current_perms;
10245: foreach my $requrl (sort(keys(%urls))) {
10246: my $action;
10247: if ($urls{$requrl} eq 'add') {
10248: $action = 'activate';
10249: } else {
10250: $action = 'none';
10251: }
10252: my $aclnum = 0;
1.827 raeburn 10253: my (undef,$udom,$unum,$file_name,$group) =
10254: &parse_portfolio_url($requrl);
1.1271 raeburn 10255: unless (exists($current_perms{$unum.':'.$udom})) {
10256: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10257: }
10258: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 10259: $group,$file_name);
10260: foreach my $key (keys(%{$access_controls{$file_name}})) {
10261: my ($num,$scope,$end,$start) =
10262: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 10263: if ($scope eq $accesstype) {
10264: if (($start <= $now) && ($end == 0)) {
10265: if ($accesstype eq 'ip') {
10266: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10267: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10268: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10269: if ($urls{$requrl} eq 'add') {
10270: $action = 'none';
10271: last;
10272: } else {
10273: $action = 'delete';
10274: $aclnum = $num;
10275: last;
10276: }
10277: }
10278: }
10279: }
10280: } elsif ($accesstype eq 'public') {
10281: if ($urls{$requrl} eq 'add') {
10282: $action = 'none';
10283: last;
10284: } else {
10285: $action = 'delete';
10286: $aclnum = $num;
10287: last;
10288: }
10289: }
10290: } elsif ($accesstype eq 'public') {
1.827 raeburn 10291: $action = 'update';
10292: $aclnum = $num;
1.1271 raeburn 10293: last;
1.827 raeburn 10294: }
10295: }
10296: }
10297: if ($action eq 'none') {
1.1271 raeburn 10298: next;
1.827 raeburn 10299: } else {
10300: my %changes;
10301: my $newend = 0;
10302: my $newstart = $now;
1.1271 raeburn 10303: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 10304: $changes{$action}{$newkey} = {
1.1271 raeburn 10305: type => $accesstype,
1.827 raeburn 10306: time => {
10307: start => $newstart,
10308: end => $newend,
10309: },
10310: };
1.1271 raeburn 10311: if ($accesstype eq 'ip') {
10312: $changes{$action}{$newkey}{'ip'} = [$ip];
10313: }
1.827 raeburn 10314: my ($outcome,$deloutcome,$new_values,$translation) =
10315: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 10316: unless ($outcome eq 'ok') {
10317: $errors .= $outcome.' ';
10318: }
1.827 raeburn 10319: }
1.1271 raeburn 10320: }
10321: if ($errors) {
10322: $errors =~ s/\s$//;
10323: return $errors;
1.827 raeburn 10324: } else {
1.1271 raeburn 10325: return 'ok';
1.827 raeburn 10326: }
10327: }
10328:
1.745 raeburn 10329: #------------------------------------------------------Get Marked as Read Only
10330:
10331: sub get_marked_as_readonly {
10332: my ($domain,$user,$what,$group) = @_;
10333: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 10334: my @readonly_files;
1.629 banghart 10335: my $cmp1=$what;
10336: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10337: while (my ($file_name,$value) = each(%{$current_permissions})) {
10338: if (defined($group)) {
10339: if ($file_name !~ m-^\Q$group\E/-) {
10340: next;
10341: }
10342: }
1.561 banghart 10343: if (ref($value) eq "ARRAY"){
10344: foreach my $stored_what (@{$value}) {
1.629 banghart 10345: my $cmp2=$stored_what;
1.759 albertel 10346: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 10347: $cmp2=join('',@{$stored_what});
1.745 raeburn 10348: }
1.629 banghart 10349: if ($cmp1 eq $cmp2) {
1.561 banghart 10350: push(@readonly_files, $file_name);
1.745 raeburn 10351: last;
1.563 banghart 10352: } elsif (!defined($what)) {
10353: push(@readonly_files, $file_name);
1.745 raeburn 10354: last;
1.561 banghart 10355: }
10356: }
1.745 raeburn 10357: }
1.561 banghart 10358: }
10359: return @readonly_files;
10360: }
1.577 banghart 10361: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 10362:
1.577 banghart 10363: sub get_marked_as_readonly_hash {
1.745 raeburn 10364: my ($current_permissions,$group,$what) = @_;
1.577 banghart 10365: my %readonly_files;
1.745 raeburn 10366: while (my ($file_name,$value) = each(%{$current_permissions})) {
10367: if (defined($group)) {
10368: if ($file_name !~ m-^\Q$group\E/-) {
10369: next;
10370: }
10371: }
1.577 banghart 10372: if (ref($value) eq "ARRAY"){
10373: foreach my $stored_what (@{$value}) {
1.745 raeburn 10374: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 10375: foreach my $lock_descriptor(@{$stored_what}) {
10376: if ($lock_descriptor eq 'graded') {
10377: $readonly_files{$file_name} = 'graded';
10378: } elsif ($lock_descriptor eq 'handback') {
10379: $readonly_files{$file_name} = 'handback';
10380: } else {
10381: if (!exists($readonly_files{$file_name})) {
10382: $readonly_files{$file_name} = 'locked';
10383: }
10384: }
1.745 raeburn 10385: }
1.750 banghart 10386: }
1.577 banghart 10387: }
10388: }
10389: }
10390: return %readonly_files;
10391: }
1.559 banghart 10392: # ------------------------------------------------------------ Unmark as Read Only
10393:
10394: sub unmark_as_readonly {
1.629 banghart 10395: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10396: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 10397: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 10398: $file_name = &declutter_portfile($file_name);
1.634 albertel 10399: my $symb_crs = $what;
10400: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 10401: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 10402: my ($tmp)=keys(%current_permissions);
10403: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10404: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 10405: foreach my $file (@readonly_files) {
1.759 albertel 10406: my $clean_file = &declutter_portfile($file);
10407: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 10408: my $current_locks = $current_permissions{$file};
1.563 banghart 10409: my @new_locks;
10410: my @del_keys;
10411: if (ref($current_locks) eq "ARRAY"){
10412: foreach my $locker (@{$current_locks}) {
1.632 albertel 10413: my $compare=$locker;
1.749 raeburn 10414: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 10415: $compare=join('',@{$locker});
1.746 raeburn 10416: if ($compare ne $symb_crs) {
10417: push(@new_locks, $locker);
10418: }
1.563 banghart 10419: }
10420: }
1.650 albertel 10421: if (scalar(@new_locks) > 0) {
1.563 banghart 10422: $current_permissions{$file} = \@new_locks;
10423: } else {
10424: push(@del_keys, $file);
1.613 albertel 10425: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 10426: delete($current_permissions{$file});
1.563 banghart 10427: }
10428: }
1.561 banghart 10429: }
1.613 albertel 10430: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10431: return;
10432: }
1.512 banghart 10433:
1.17 www 10434: # ------------------------------------------------------------ Directory lister
10435:
10436: sub dirlist {
1.955 raeburn 10437: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10438: $uri=~s/^\///;
10439: $uri=~s/\/$//;
1.253 stredwic 10440: my ($udom, $uname);
1.955 raeburn 10441: if ($getuserdir) {
1.253 stredwic 10442: $udom = $userdomain;
10443: $uname = $username;
1.955 raeburn 10444: } else {
10445: (undef,$udom,$uname)=split(/\//,$uri);
10446: if(defined($userdomain)) {
10447: $udom = $userdomain;
10448: }
10449: if(defined($username)) {
10450: $uname = $username;
10451: }
1.253 stredwic 10452: }
1.955 raeburn 10453: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10454:
1.955 raeburn 10455: $dirRoot = $perlvar{'lonDocRoot'};
10456: if (defined($getpropath)) {
10457: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10458: $dirRoot =~ s/\/$//;
1.955 raeburn 10459: } elsif (defined($getuserdir)) {
10460: my $subdir=$uname.'__';
10461: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10462: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10463: ."/$udom/$subdir/$uname";
10464: } elsif (defined($alternateRoot)) {
10465: $dirRoot = $alternateRoot;
1.751 banghart 10466: }
1.253 stredwic 10467:
10468: if($udom) {
10469: if($uname) {
1.1135 raeburn 10470: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10471: if ($uhome eq 'no_host') {
10472: return ([],'no_host');
10473: }
1.955 raeburn 10474: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10475: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10476: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10477: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10478: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10479: } else {
10480: @listing_results = map { &unescape($_); } split(/:/,$listing);
10481: }
1.605 matthew 10482: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10483: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10484: @listing_results = split(/:/,$listing);
10485: } else {
10486: @listing_results = map { &unescape($_); } split(/:/,$listing);
10487: }
1.1135 raeburn 10488: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10489: ($listing eq 'rejected') || ($listing eq 'refused') ||
10490: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10491: return ([],$listing);
10492: } else {
10493: return (\@listing_results);
1.1135 raeburn 10494: }
1.955 raeburn 10495: } elsif(!$alternateRoot) {
1.1136 raeburn 10496: my (%allusers,%listerror);
1.841 albertel 10497: my %servers = &get_servers($udom,'library');
1.955 raeburn 10498: foreach my $tryserver (keys(%servers)) {
10499: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10500: &escape($udom),$tryserver);
10501: if ($listing eq 'unknown_cmd') {
10502: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10503: $udom, $tryserver);
10504: } else {
10505: @listing_results = map { &unescape($_); } split(/:/,$listing);
10506: }
1.841 albertel 10507: if ($listing eq 'unknown_cmd') {
10508: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10509: $udom, $tryserver);
10510: @listing_results = split(/:/,$listing);
10511: } else {
10512: @listing_results =
10513: map { &unescape($_); } split(/:/,$listing);
10514: }
1.1136 raeburn 10515: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10516: ($listing eq 'rejected') || ($listing eq 'refused') ||
10517: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10518: $listerror{$tryserver} = $listing;
10519: } else {
1.841 albertel 10520: foreach my $line (@listing_results) {
10521: my ($entry) = split(/&/,$line,2);
10522: $allusers{$entry} = 1;
10523: }
10524: }
1.253 stredwic 10525: }
1.1136 raeburn 10526: my @alluserslist=();
1.800 albertel 10527: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 10528: push(@alluserslist,$user.'&user');
1.253 stredwic 10529: }
1.1318 droeschl 10530:
10531: if (!%listerror) {
10532: # no errors
10533: return (\@alluserslist);
10534: } elsif (scalar(keys(%servers)) == 1) {
10535: # one library server, one error
10536: my ($key) = keys(%listerror);
10537: return (\@alluserslist, $listerror{$key});
10538: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10539: # con_lost indicates that we might miss data from at least one
10540: # library server
10541: return (\@alluserslist, 'con_lost');
10542: } else {
10543: # multiple library servers and no con_lost -> data should be
10544: # complete.
10545: return (\@alluserslist);
10546: }
10547:
1.253 stredwic 10548: } else {
1.1136 raeburn 10549: return ([],'missing username');
1.253 stredwic 10550: }
1.955 raeburn 10551: } elsif(!defined($getpropath)) {
1.1136 raeburn 10552: my $path = $perlvar{'lonDocRoot'}.'/res/';
10553: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10554: return (\@all_domains);
1.955 raeburn 10555: } else {
1.1136 raeburn 10556: return ([],'missing domain');
1.275 stredwic 10557: }
10558: }
10559:
10560: # --------------------------------------------- GetFileTimestamp
10561: # This function utilizes dirlist and returns the date stamp for
10562: # when it was last modified. It will also return an error of -1
10563: # if an error occurs
10564:
10565: sub GetFileTimestamp {
1.955 raeburn 10566: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 10567: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10568: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 10569: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10570: undef,$getuserdir);
10571: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10572: return -1;
10573: }
10574: if (ref($fileref) eq 'ARRAY') {
10575: my @stats = split('&',$fileref->[0]);
1.375 matthew 10576: # @stats contains first the filename, then the stat output
10577: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 10578: } else {
10579: return -1;
1.253 stredwic 10580: }
1.26 www 10581: }
10582:
1.712 albertel 10583: sub stat_file {
10584: my ($uri) = @_;
1.787 albertel 10585: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 10586:
1.955 raeburn 10587: my ($udom,$uname,$file);
1.712 albertel 10588: if ($uri =~ m-^/(uploaded|editupload)/-) {
10589: ($udom,$uname,$file) =
1.811 albertel 10590: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 10591: $file = 'userfiles/'.$file;
10592: }
10593: if ($uri =~ m-^/res/-) {
10594: ($udom,$uname) =
1.807 albertel 10595: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 10596: $file = $uri;
10597: }
10598:
10599: if (!$udom || !$uname || !$file) {
10600: # unable to handle the uri
10601: return ();
10602: }
1.956 raeburn 10603: my $getpropath;
10604: if ($file =~ /^userfiles\//) {
10605: $getpropath = 1;
10606: }
1.1136 raeburn 10607: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10608: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10609: return ();
10610: } else {
10611: if (ref($listref) eq 'ARRAY') {
10612: my @stats = split('&',$listref->[0]);
10613: shift(@stats); #filename is first
10614: return @stats;
10615: }
1.712 albertel 10616: }
10617: return ();
10618: }
10619:
1.1313 raeburn 10620: # --------------------------------------------------------- recursedirs
10621: # Recursive function to traverse either a specific user's Authoring Space
10622: # or corresponding Published Resource Space, and populate the hash ref:
10623: # $dirhashref with URLs of all directories, and if $filehashref hash
10624: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
10625: # or .rights files in resource space, and .meta, .save, .log, and .bak
10626: # files in Authoring Space.
10627: #
10628: # Inputs:
10629: #
10630: # $is_home - true if current server is home server for user's space
10631: # $context - either: priv, or res respectively for Authoring or Resource Space.
10632: # $docroot - Document root (i.e., /home/httpd/html
10633: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
10634: # $relpath - Current path (relative to top level).
10635: # $dirhashref - reference to hash to populate with URLs of directories (Required)
10636: # $filehashref - reference to hash to populate with URLs of files (Optional)
10637: #
10638: # Returns: nothing
10639: #
10640: # Side Effects: populates $dirhashref, and $filehashref (if provided).
10641: #
10642: # Currently used by interface/londocs.pm to create linked select boxes for
10643: # directory and filename to import a Course "Author" resource into a course, and
10644: # also to create linked select boxes for Authoring Space and Directory to choose
10645: # save location for creation of a new "standard" problem from the Course Editor.
10646: #
10647:
10648: sub recursedirs {
10649: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
10650: return unless (ref($dirhashref) eq 'HASH');
10651: my $currpath = $docroot.$toppath;
10652: if ($relpath) {
10653: $currpath .= "/$relpath";
10654: }
10655: my $savefile;
10656: if (ref($filehashref)) {
10657: $savefile = 1;
10658: }
10659: if ($is_home) {
10660: if (opendir(my $dirh,$currpath)) {
10661: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
10662: next if ($item eq '');
10663: if (-d "$currpath/$item") {
10664: my $newpath;
10665: if ($relpath) {
10666: $newpath = "$relpath/$item";
10667: } else {
10668: $newpath = $item;
10669: }
10670: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10671: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10672: } elsif ($savefile) {
10673: if ($context eq 'priv') {
10674: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10675: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10676: }
10677: } else {
10678: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
10679: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10680: }
10681: }
10682: }
10683: }
10684: closedir($dirh);
10685: }
10686: } else {
10687: my ($dirlistref,$listerror) =
10688: &dirlist($toppath.$relpath);
10689: my @dir_lines;
10690: my $dirptr=16384;
10691: if (ref($dirlistref) eq 'ARRAY') {
10692: foreach my $dir_line (sort
10693: {
10694: my ($afile)=split('&',$a,2);
10695: my ($bfile)=split('&',$b,2);
10696: return (lc($afile) cmp lc($bfile));
10697: } (@{$dirlistref})) {
10698: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
10699: split(/\&/,$dir_line,16);
10700: $item =~ s/\s+$//;
10701: next if (($item =~ /^\.\.?$/) || ($obs));
10702: if ($dirptr&$testdir) {
10703: my $newpath;
10704: if ($relpath) {
10705: $newpath = "$relpath/$item";
10706: } else {
10707: $relpath = '/';
10708: $newpath = $item;
10709: }
10710: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10711: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10712: } elsif ($savefile) {
10713: if ($context eq 'priv') {
10714: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10715: $filehashref->{$relpath}{$item} = 1;
10716: }
10717: } else {
10718: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
10719: $filehashref->{$relpath}{$item} = 1;
10720: }
10721: }
10722: }
10723: }
10724: }
10725: }
10726: return;
10727: }
10728:
1.26 www 10729: # -------------------------------------------------------- Value of a Condition
10730:
1.713 albertel 10731: # gets the value of a specific preevaluated condition
10732: # stored in the string $env{user.state.<cid>}
10733: # or looks up a condition reference in the bighash and if if hasn't
10734: # already been evaluated recurses into docondval to get the value of
10735: # the condition, then memoizing it to
10736: # $env{user.state.<cid>.<condition>}
1.40 www 10737: sub directcondval {
10738: my $number=shift;
1.620 albertel 10739: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10740: &Apache::lonuserstate::evalstate();
10741: }
1.713 albertel 10742: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10743: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10744: } elsif ($number =~ /^_/) {
10745: my $sub_condition;
10746: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10747: &GDBM_READER(),0640)) {
10748: $sub_condition=$bighash{'conditions'.$number};
10749: untie(%bighash);
10750: }
10751: my $value = &docondval($sub_condition);
1.949 raeburn 10752: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10753: return $value;
10754: }
1.620 albertel 10755: if ($env{'user.state.'.$env{'request.course.id'}}) {
10756: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10757: } else {
10758: return 2;
10759: }
10760: }
10761:
1.713 albertel 10762: # get the collection of conditions for this resource
1.26 www 10763: sub condval {
10764: my $condidx=shift;
1.54 www 10765: my $allpathcond='';
1.713 albertel 10766: foreach my $cond (split(/\|/,$condidx)) {
10767: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10768: $allpathcond.=
10769: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10770: }
1.191 harris41 10771: }
1.54 www 10772: $allpathcond=~s/\|$//;
1.713 albertel 10773: return &docondval($allpathcond);
10774: }
10775:
10776: #evaluates an expression of conditions
10777: sub docondval {
10778: my ($allpathcond) = @_;
10779: my $result=0;
10780: if ($env{'request.course.id'}
10781: && defined($allpathcond)) {
10782: my $operand='|';
10783: my @stack;
10784: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10785: if ($chunk eq '(') {
10786: push @stack,($operand,$result);
10787: } elsif ($chunk eq ')') {
10788: my $before=pop @stack;
10789: if (pop @stack eq '&') {
10790: $result=$result>$before?$before:$result;
10791: } else {
10792: $result=$result>$before?$result:$before;
10793: }
10794: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10795: $operand=$chunk;
10796: } else {
10797: my $new=directcondval($chunk);
10798: if ($operand eq '&') {
10799: $result=$result>$new?$new:$result;
10800: } else {
10801: $result=$result>$new?$result:$new;
10802: }
10803: }
10804: }
1.26 www 10805: }
10806: return $result;
1.421 albertel 10807: }
10808:
10809: # ---------------------------------------------------- Devalidate courseresdata
10810:
10811: sub devalidatecourseresdata {
10812: my ($coursenum,$coursedomain)=@_;
10813: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10814: &devalidate_cache_new('courseres',$hashid);
1.28 www 10815: }
10816:
1.763 www 10817:
1.200 www 10818: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10819: #
10820: # Parameters:
10821: # $coursenum - Number of the course.
10822: # $coursedomain - Domain at which the course was created.
10823: # Returns:
10824: # A hash of the course parameters along (I think) with timestamps
10825: # and version info.
1.877 foxr 10826:
1.624 albertel 10827: sub get_courseresdata {
10828: my ($coursenum,$coursedomain)=@_;
1.200 www 10829: my $coursehom=&homeserver($coursenum,$coursedomain);
10830: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10831: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10832: my %dumpreply;
1.417 albertel 10833: unless (defined($cached)) {
1.624 albertel 10834: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10835: $result=\%dumpreply;
1.251 albertel 10836: my ($tmp) = keys(%dumpreply);
10837: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10838: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10839: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10840: return $tmp;
1.416 albertel 10841: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10842: $result=undef;
1.599 albertel 10843: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10844: }
10845: }
1.624 albertel 10846: return $result;
10847: }
10848:
1.633 albertel 10849: sub devalidateuserresdata {
10850: my ($uname,$udom)=@_;
10851: my $hashid="$udom:$uname";
10852: &devalidate_cache_new('userres',$hashid);
10853: }
10854:
1.624 albertel 10855: sub get_userresdata {
10856: my ($uname,$udom)=@_;
10857: #most student don\'t have any data set, check if there is some data
10858: if (&EXT_cache_status($udom,$uname)) { return undef; }
10859:
10860: my $hashid="$udom:$uname";
10861: my ($result,$cached)=&is_cached_new('userres',$hashid);
10862: if (!defined($cached)) {
10863: my %resourcedata=&dump('resourcedata',$udom,$uname);
10864: $result=\%resourcedata;
10865: &do_cache_new('userres',$hashid,$result,600);
10866: }
10867: my ($tmp)=keys(%$result);
10868: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10869: return $result;
10870: }
10871: #error 2 occurs when the .db doesn't exist
10872: if ($tmp!~/error: 2 /) {
1.1294 raeburn 10873: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10874: &logthis("<font color=\"blue\">WARNING:".
10875: " Trying to get resource data for ".
10876: $uname." at ".$udom.": ".
10877: $tmp."</font>");
10878: }
1.624 albertel 10879: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10880: #&EXT_cache_set($udom,$uname);
10881: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10882: undef($tmp); # not really an error so don't send it back
1.624 albertel 10883: }
10884: return $tmp;
10885: }
1.879 foxr 10886: #----------------------------------------------- resdata - return resource data
10887: # Purpose:
10888: # Return resource data for either users or for a course.
10889: # Parameters:
10890: # $name - Course/user name.
10891: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 10892: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 10893: # $mapp - decluttered URL of enclosing map
10894: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
10895: # $recurseup - Ref to array of map URLs, starting with map containing
10896: # $mapp up through hierarchy of nested maps to top level map.
10897: # $courseid - CourseID (first part of param identifier).
10898: # $modifier - Middle part of param identifier.
10899: # $what - Last part of param identifier.
1.879 foxr 10900: # @which - Array of names of resources desired.
10901: # Returns:
10902: # The value of the first reasource in @which that is found in the
10903: # resource hash.
10904: # Exceptional Conditions:
10905: # If the $type passed in is not valid (not the string 'course' or
10906: # 'user', an undefined reference is returned.
10907: # If none of the resources are found, an undef is returned
1.624 albertel 10908: sub resdata {
1.1301 raeburn 10909: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
10910: $modifier,$what,@which)=@_;
1.624 albertel 10911: my $result;
10912: if ($type eq 'course') {
10913: $result=&get_courseresdata($name,$domain);
10914: } elsif ($type eq 'user') {
10915: $result=&get_userresdata($name,$domain);
10916: }
10917: if (!ref($result)) { return $result; }
1.251 albertel 10918: foreach my $item (@which) {
1.1301 raeburn 10919: if ($item->[1] eq 'course') {
10920: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
10921: unless ($$recursed) {
1.1302 raeburn 10922: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 10923: $$recursed = 1;
10924: }
10925: foreach my $item (@${recurseup}) {
10926: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
10927: last if (defined($result->{$norecursechk}));
10928: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
10929: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
10930: }
10931: }
10932: }
10933: if (defined($result->{$item->[0]})) {
1.927 albertel 10934: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10935: }
1.250 albertel 10936: }
1.291 albertel 10937: return undef;
1.200 www 10938: }
10939:
1.1298 raeburn 10940: sub get_domain_ltitools {
10941: my ($cdom) = @_;
10942: my %ltitools;
10943: my ($result,$cached)=&is_cached_new('ltitools',$cdom);
10944: if (defined($cached)) {
10945: if (ref($result) eq 'HASH') {
10946: %ltitools = %{$result};
10947: }
10948: } else {
10949: my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
10950: if (ref($domconfig{'ltitools'}) eq 'HASH') {
10951: %ltitools = %{$domconfig{'ltitools'}};
10952: }
10953: my $cachetime = 24*60*60;
10954: &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
10955: }
10956: return %ltitools;
10957: }
10958:
1.1236 raeburn 10959: sub get_numsuppfiles {
10960: my ($cnum,$cdom,$ignorecache)=@_;
10961: my $hashid=$cnum.':'.$cdom;
10962: my ($suppcount,$cached);
10963: unless ($ignorecache) {
10964: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10965: }
10966: unless (defined($cached)) {
10967: my $chome=&homeserver($cnum,$cdom);
10968: unless ($chome eq 'no_host') {
10969: ($suppcount,my $errors) = (0,0);
10970: my $suppmap = 'supplemental.sequence';
10971: ($suppcount,$errors) =
10972: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10973: }
10974: &do_cache_new('suppcount',$hashid,$suppcount,600);
10975: }
10976: return $suppcount;
10977: }
10978:
1.379 matthew 10979: #
10980: # EXT resource caching routines
10981: #
10982:
1.1302 raeburn 10983: {
10984: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
10985: #
10986: # The course for which we cache
10987: my $cachedmapkey='';
10988: # The cached recursive maps for this course
10989: my %cachedmaps=();
10990: # When this was last done
10991: my $cachedmaptime='';
10992:
1.379 matthew 10993: sub clear_EXT_cache_status {
1.383 albertel 10994: &delenv('cache.EXT.');
1.379 matthew 10995: }
10996:
10997: sub EXT_cache_status {
10998: my ($target_domain,$target_user) = @_;
1.383 albertel 10999: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 11000: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 11001: # We know already the user has no data
11002: return 1;
11003: } else {
11004: return 0;
11005: }
11006: }
11007:
11008: sub EXT_cache_set {
11009: my ($target_domain,$target_user) = @_;
1.383 albertel 11010: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 11011: #&appenv({$cachename => time});
1.379 matthew 11012: }
11013:
1.28 www 11014: # --------------------------------------------------------- Value of a Variable
1.58 www 11015: sub EXT {
1.715 albertel 11016:
1.1228 raeburn 11017: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 11018: unless ($varname) { return ''; }
1.218 albertel 11019: #get real user name/domain, courseid and symb
11020: my $courseid;
1.359 albertel 11021: my $publicuser;
1.427 www 11022: if ($symbparm) {
11023: $symbparm=&get_symb_from_alias($symbparm);
11024: }
1.218 albertel 11025: if (!($uname && $udom)) {
1.790 albertel 11026: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 11027: if (!$symbparm) { $symbparm=$cursymb; }
11028: } else {
1.620 albertel 11029: $courseid=$env{'request.course.id'};
1.218 albertel 11030: }
1.48 www 11031: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11032: my $rest;
1.320 albertel 11033: if (defined($therest[0])) {
1.48 www 11034: $rest=join('.',@therest);
11035: } else {
11036: $rest='';
11037: }
1.320 albertel 11038:
1.57 www 11039: my $qualifierrest=$qualifier;
11040: if ($rest) { $qualifierrest.='.'.$rest; }
11041: my $spacequalifierrest=$space;
11042: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 11043: if ($realm eq 'user') {
1.48 www 11044: # --------------------------------------------------------------- user.resource
11045: if ($space eq 'resource') {
1.651 albertel 11046: if ( (defined($Apache::lonhomework::parsing_a_problem)
11047: || defined($Apache::lonhomework::parsing_a_task))
11048: &&
1.744 albertel 11049: ($symbparm eq &symbread()) ) {
11050: # if we are in the middle of processing the resource the
11051: # get the value we are planning on committing
11052: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11053: return $Apache::lonhomework::results{$qualifierrest};
11054: } else {
11055: return $Apache::lonhomework::history{$qualifierrest};
11056: }
1.335 albertel 11057: } else {
1.359 albertel 11058: my %restored;
1.620 albertel 11059: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 11060: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11061: } else {
11062: %restored=&restore($symbparm,$courseid,$udom,$uname);
11063: }
1.335 albertel 11064: return $restored{$qualifierrest};
11065: }
1.48 www 11066: # ----------------------------------------------------------------- user.access
11067: } elsif ($space eq 'access') {
1.218 albertel 11068: # FIXME - not supporting calls for a specific user
1.48 www 11069: return &allowed($qualifier,$rest);
11070: # ------------------------------------------ user.preferences, user.environment
11071: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 11072: if (($uname eq $env{'user.name'}) &&
11073: ($udom eq $env{'user.domain'})) {
11074: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 11075: } else {
1.359 albertel 11076: my %returnhash;
11077: if (!$publicuser) {
11078: %returnhash=&userenvironment($udom,$uname,
11079: $qualifierrest);
11080: }
1.218 albertel 11081: return $returnhash{$qualifierrest};
11082: }
1.48 www 11083: # ----------------------------------------------------------------- user.course
11084: } elsif ($space eq 'course') {
1.218 albertel 11085: # FIXME - not supporting calls for a specific user
1.620 albertel 11086: return $env{join('.',('request.course',$qualifier))};
1.48 www 11087: # ------------------------------------------------------------------- user.role
11088: } elsif ($space eq 'role') {
1.218 albertel 11089: # FIXME - not supporting calls for a specific user
1.620 albertel 11090: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 11091: if ($qualifier eq 'value') {
11092: return $role;
11093: } elsif ($qualifier eq 'extent') {
11094: return $where;
11095: }
11096: # ----------------------------------------------------------------- user.domain
11097: } elsif ($space eq 'domain') {
1.218 albertel 11098: return $udom;
1.48 www 11099: # ------------------------------------------------------------------- user.name
11100: } elsif ($space eq 'name') {
1.218 albertel 11101: return $uname;
1.48 www 11102: # ---------------------------------------------------- Any other user namespace
1.29 www 11103: } else {
1.359 albertel 11104: my %reply;
11105: if (!$publicuser) {
11106: %reply=&get($space,[$qualifierrest],$udom,$uname);
11107: }
11108: return $reply{$qualifierrest};
1.48 www 11109: }
1.236 www 11110: } elsif ($realm eq 'query') {
11111: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 11112: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11113: [$spacequalifierrest]);
1.620 albertel 11114: return $env{'form.'.$spacequalifierrest};
1.236 www 11115: } elsif ($realm eq 'request') {
1.48 www 11116: # ------------------------------------------------------------- request.browser
11117: if ($space eq 'browser') {
1.1145 bisitz 11118: return $env{'browser.'.$qualifier};
1.57 www 11119: # ------------------------------------------------------------ request.filename
11120: } else {
1.620 albertel 11121: return $env{'request.'.$spacequalifierrest};
1.29 www 11122: }
1.28 www 11123: } elsif ($realm eq 'course') {
1.48 www 11124: # ---------------------------------------------------------- course.description
1.620 albertel 11125: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 11126: } elsif ($realm eq 'resource') {
1.165 www 11127:
1.620 albertel 11128: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 11129: if (!$symbparm) { $symbparm=&symbread(); }
11130: }
1.693 albertel 11131:
1.1232 raeburn 11132: if ($qualifier eq '') {
11133: if ($space eq 'title') {
11134: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11135: return &gettitle($symbparm);
11136: }
1.693 albertel 11137:
1.1232 raeburn 11138: if ($space eq 'map') {
11139: my ($map) = &decode_symb($symbparm);
11140: return &symbread($map);
11141: }
11142: if ($space eq 'maptitle') {
11143: my ($map) = &decode_symb($symbparm);
11144: return &gettitle($map);
11145: }
11146: if ($space eq 'filename') {
11147: if ($symbparm) {
11148: return &clutter((&decode_symb($symbparm))[2]);
11149: }
11150: return &hreflocation('',$env{'request.filename'});
1.905 albertel 11151: }
1.1232 raeburn 11152:
1.1233 raeburn 11153: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11154: if ($space eq 'visibleparts') {
11155: my $navmap = Apache::lonnavmaps::navmap->new();
11156: my $item;
11157: if (ref($navmap)) {
11158: my $res = $navmap->getBySymb($symbparm);
11159: my $parts = $res->parts();
11160: if (ref($parts) eq 'ARRAY') {
11161: $item = join(',',@{$parts});
11162: }
11163: undef($navmap);
1.1232 raeburn 11164: }
1.1233 raeburn 11165: return $item;
1.1232 raeburn 11166: }
11167: }
11168: }
1.693 albertel 11169:
1.1301 raeburn 11170: my ($section, $group, @groups, @recurseup, $recursed);
11171: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 11172: if (($courseid eq '') && ($cid)) {
11173: $courseid = $cid;
11174: }
11175: if (($symbparm && $courseid) &&
11176: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 11177:
1.218 albertel 11178: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 11179:
1.60 www 11180: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 11181: my $symbp=$symbparm;
1.1301 raeburn 11182: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 11183: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 11184: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 11185: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 11186: if (($env{'user.name'} eq $uname) &&
11187: ($env{'user.domain'} eq $udom)) {
11188: $section=$env{'request.course.sec'};
1.733 raeburn 11189: @groups = split(/:/,$env{'request.course.groups'});
11190: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 11191: } else {
1.539 albertel 11192: if (! defined($usection)) {
1.551 albertel 11193: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 11194: } else {
11195: $section = $usection;
11196: }
1.733 raeburn 11197: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 11198: }
11199:
11200: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11201: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 11202: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 11203: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11204:
1.593 albertel 11205: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 11206: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 11207: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 11208: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 11209:
1.60 www 11210: # ----------------------------------------------------------- first, check user
1.624 albertel 11211:
1.1301 raeburn 11212: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11213: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 11214: ([$courselevelr,'resource'],
11215: [$courselevelm,'map' ],
1.1301 raeburn 11216: [$courseleveli,'map' ],
1.927 albertel 11217: [$courselevel, 'course' ]));
1.931 albertel 11218: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 11219:
1.594 albertel 11220: # ------------------------------------------------ second, check some of course
1.684 raeburn 11221: my $coursereply;
1.691 raeburn 11222: if (@groups > 0) {
11223: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 11224: $recurseparm,$mapparm,$spacequalifierrest,
11225: $mapp,\$recursed,\@recurseup);
11226: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 11227: }
1.96 www 11228:
1.684 raeburn 11229: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 11230: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 11231: 'course',$mapp,\$recursed,\@recurseup,
11232: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 11233: ([$seclevelr, 'resource'],
11234: [$seclevelm, 'map' ],
1.1301 raeburn 11235: [$secleveli, 'map' ],
1.927 albertel 11236: [$seclevel, 'course' ],
11237: [$courselevelr,'resource']));
11238: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 11239:
1.60 www 11240: # ------------------------------------------------------ third, check map parms
1.218 albertel 11241: my %parmhash=();
11242: my $thisparm='';
11243: if (tie(%parmhash,'GDBM_File',
1.620 albertel 11244: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 11245: &GDBM_READER(),0640)) {
1.218 albertel 11246: $thisparm=$parmhash{$symbparm};
11247: untie(%parmhash);
11248: }
1.927 albertel 11249: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 11250: }
1.594 albertel 11251: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 11252:
11253: my $what = $spacequalifierrest;
11254: $what=~s/\./\_/;
1.282 albertel 11255: my $filename;
11256: if (!$symbparm) { $symbparm=&symbread(); }
11257: if ($symbparm) {
1.409 www 11258: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 11259: } else {
1.620 albertel 11260: $filename=$env{'request.filename'};
1.282 albertel 11261: }
1.1301 raeburn 11262: my $metadata=&metadata($filename,$what);
1.927 albertel 11263: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301 raeburn 11264: $metadata=&metadata($filename,'parameter_'.$what);
1.927 albertel 11265: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 11266:
1.1301 raeburn 11267: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 11268: if ($symbparm && defined($courseid) &&
1.620 albertel 11269: $courseid eq $env{'request.course.id'}) {
1.624 albertel 11270: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11271: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 11272: 'course',$mapp,\$recursed,\@recurseup,
11273: $courseid,'.',$spacequalifierrest,
1.927 albertel 11274: ([$courselevelm,'map' ],
1.1301 raeburn 11275: [$courseleveli,'map' ],
1.927 albertel 11276: [$courselevel, 'course']));
11277: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 11278: }
1.145 www 11279: # ------------------------------------------------------------------ Cascade up
1.218 albertel 11280: unless ($space eq '0') {
1.336 albertel 11281: my @parts=split(/_/,$space);
11282: my $id=pop(@parts);
11283: my $part=join('_',@parts);
11284: if ($part eq '') { $part='0'; }
1.927 albertel 11285: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 11286: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 11287: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 11288: }
1.395 albertel 11289: if ($recurse) { return undef; }
11290: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 11291: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 11292: # ---------------------------------------------------- Any other user namespace
11293: } elsif ($realm eq 'environment') {
11294: # ----------------------------------------------------------------- environment
1.620 albertel 11295: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11296: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 11297: } else {
1.770 albertel 11298: if ($uname eq 'anonymous' && $udom eq '') {
11299: return '';
11300: }
1.219 albertel 11301: my %returnhash=&userenvironment($udom,$uname,
11302: $spacequalifierrest);
11303: return $returnhash{$spacequalifierrest};
11304: }
1.28 www 11305: } elsif ($realm eq 'system') {
1.48 www 11306: # ----------------------------------------------------------------- system.time
11307: if ($space eq 'time') {
11308: return time;
11309: }
1.696 albertel 11310: } elsif ($realm eq 'server') {
11311: # ----------------------------------------------------------------- system.time
11312: if ($space eq 'name') {
11313: return $ENV{'SERVER_NAME'};
11314: }
1.28 www 11315: }
1.48 www 11316: return '';
1.61 www 11317: }
11318:
1.927 albertel 11319: sub get_reply {
11320: my ($reply_value) = @_;
1.940 raeburn 11321: if (ref($reply_value) eq 'ARRAY') {
11322: if (wantarray) {
11323: return @$reply_value;
11324: }
11325: return $reply_value->[0];
11326: } else {
11327: return $reply_value;
1.927 albertel 11328: }
11329: }
11330:
1.691 raeburn 11331: sub check_group_parms {
1.1301 raeburn 11332: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11333: $recursed,$recurseupref) = @_;
11334: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11335: [$what,'course']);
11336: my $coursereply;
1.691 raeburn 11337: foreach my $group (@{$groups}) {
1.1301 raeburn 11338: my @groupitems = ();
1.691 raeburn 11339: foreach my $level (@levels) {
1.927 albertel 11340: my $item = $courseid.'.['.$group.'].'.$level->[0];
11341: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11342: }
1.1301 raeburn 11343: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11344: $env{'course.'.$courseid.'.domain'},
11345: 'course',$mapp,$recursed,$recurseupref,
11346: $courseid,'.['.$group.'].',$what,
11347: @groupitems);
11348: last if (defined($coursereply));
1.691 raeburn 11349: }
11350: return $coursereply;
11351: }
11352:
1.1301 raeburn 11353: sub get_map_hierarchy {
1.1302 raeburn 11354: my ($mapname,$courseid) = @_;
11355: my @recurseup = ();
1.1301 raeburn 11356: if ($mapname) {
1.1302 raeburn 11357: if (($cachedmapkey eq $courseid) &&
11358: (abs($cachedmaptime-time)<5)) {
11359: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11360: return @{$cachedmaps{$mapname}};
11361: }
11362: }
1.1301 raeburn 11363: my $navmap = Apache::lonnavmaps::navmap->new();
11364: if (ref($navmap)) {
11365: @recurseup = $navmap->recurseup_maps($mapname);
11366: undef($navmap);
1.1302 raeburn 11367: $cachedmaps{$mapname} = \@recurseup;
11368: $cachedmaptime=time;
11369: $cachedmapkey=$courseid;
1.1301 raeburn 11370: }
11371: }
11372: return @recurseup;
11373: }
11374:
1.1302 raeburn 11375: }
11376:
1.691 raeburn 11377: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11378: my ($courseid,@groups) = @_;
11379: @groups = sort(@groups);
1.691 raeburn 11380: return @groups;
11381: }
11382:
1.395 albertel 11383: sub packages_tab_default {
11384: my ($uri,$varname)=@_;
11385: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11386:
11387: my (@extension,@specifics,$do_default);
11388: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11389: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11390: if ($pack_type eq 'default') {
11391: $do_default=1;
11392: } elsif ($pack_type eq 'extension') {
11393: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11394: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11395: # only look at packages defaults for packages that this id is
1.738 albertel 11396: push(@specifics,[$package,$pack_type,$pack_part]);
11397: }
11398: }
11399: # first look for a package that matches the requested part id
11400: foreach my $package (@specifics) {
11401: my (undef,$pack_type,$pack_part)=@{$package};
11402: next if ($pack_part ne $part);
11403: if (defined($packagetab{"$pack_type&$name&default"})) {
11404: return $packagetab{"$pack_type&$name&default"};
11405: }
11406: }
11407: # look for any possible matching non extension_ package
11408: foreach my $package (@specifics) {
11409: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11410: if (defined($packagetab{"$pack_type&$name&default"})) {
11411: return $packagetab{"$pack_type&$name&default"};
11412: }
1.585 albertel 11413: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11414: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11415: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11416: }
11417: }
1.738 albertel 11418: # look for any posible extension_ match
11419: foreach my $package (@extension) {
11420: my ($package,$pack_type)=@{$package};
11421: if (defined($packagetab{"$pack_type&$name&default"})) {
11422: return $packagetab{"$pack_type&$name&default"};
11423: }
11424: if (defined($packagetab{$package."&$name&default"})) {
11425: return $packagetab{$package."&$name&default"};
11426: }
11427: }
11428: # look for a global default setting
11429: if ($do_default && defined($packagetab{"default&$name&default"})) {
11430: return $packagetab{"default&$name&default"};
11431: }
1.395 albertel 11432: return undef;
11433: }
11434:
1.334 albertel 11435: sub add_prefix_and_part {
11436: my ($prefix,$part)=@_;
11437: my $keyroot;
11438: if (defined($prefix) && $prefix !~ /^__/) {
11439: # prefix that has a part already
11440: $keyroot=$prefix;
11441: } elsif (defined($prefix)) {
11442: # prefix that is missing a part
11443: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11444: } else {
11445: # no prefix at all
11446: if (defined($part)) { $keyroot='_'.$part; }
11447: }
11448: return $keyroot;
11449: }
11450:
1.71 www 11451: # ---------------------------------------------------------------- Get metadata
11452:
1.599 albertel 11453: my %metaentry;
1.1070 www 11454: my %importedpartids;
1.71 www 11455: sub metadata {
1.176 www 11456: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11457: $uri=&declutter($uri);
1.288 albertel 11458: # if it is a non metadata possible uri return quickly
1.529 albertel 11459: if (($uri eq '') ||
11460: (($uri =~ m|^/*adm/|) &&
1.1298 raeburn 11461: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108 raeburn 11462: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11463: return undef;
11464: }
1.1261 raeburn 11465: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11466: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11467: return undef;
1.288 albertel 11468: }
1.73 www 11469: my $filename=$uri;
11470: $uri=~s/\.meta$//;
1.172 www 11471: #
11472: # Is the metadata already cached?
1.177 www 11473: # Look at timestamp of caching
1.172 www 11474: # Everything is cached by the main uri, libraries are never directly cached
11475: #
1.428 albertel 11476: if (!defined($liburi)) {
1.599 albertel 11477: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11478: if (defined($cached)) { return $result->{':'.$what}; }
11479: }
11480: {
1.1069 www 11481: # Imported parts would go here
1.1070 www 11482: my %importedids=();
11483: my @origfileimportpartids=();
1.1069 www 11484: my $importedparts=0;
1.172 www 11485: #
11486: # Is this a recursive call for a library?
11487: #
1.599 albertel 11488: # if (! exists($metacache{$uri})) {
11489: # $metacache{$uri}={};
11490: # }
1.924 albertel 11491: my $cachetime = 60*60;
1.171 www 11492: if ($liburi) {
11493: $liburi=&declutter($liburi);
11494: $filename=$liburi;
1.401 bowersj2 11495: } else {
1.599 albertel 11496: &devalidate_cache_new('meta',$uri);
11497: undef(%metaentry);
1.401 bowersj2 11498: }
1.140 www 11499: my %metathesekeys=();
1.73 www 11500: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 11501: my $metastring;
1.1140 www 11502: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 11503: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 11504: $metastring =
1.929 albertel 11505: &Apache::lonnet::ssi_body($which,
1.924 albertel 11506: ('grade_target' => 'meta'));
11507: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 11508: } elsif (($uri !~ m -^(editupload)/-) &&
11509: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 11510: my $file=&filelocation('',&clutter($filename));
1.599 albertel 11511: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 11512: $metastring=&getfile($file);
1.489 albertel 11513: }
1.208 albertel 11514: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 11515: my $token;
1.140 www 11516: undef %metathesekeys;
1.71 www 11517: while ($token=$parser->get_token) {
1.339 albertel 11518: if ($token->[0] eq 'S') {
11519: if (defined($token->[2]->{'package'})) {
1.172 www 11520: #
11521: # This is a package - get package info
11522: #
1.339 albertel 11523: my $package=$token->[2]->{'package'};
11524: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11525: if (defined($token->[2]->{'id'})) {
11526: $keyroot.='_'.$token->[2]->{'id'};
11527: }
1.599 albertel 11528: if ($metaentry{':packages'}) {
11529: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 11530: } else {
1.599 albertel 11531: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 11532: }
1.736 albertel 11533: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 11534: my $part=$keyroot;
11535: $part=~s/^\_//;
1.736 albertel 11536: if ($pack_entry=~/^\Q$package\E\&/ ||
11537: $pack_entry=~/^\Q$package\E_0\&/) {
11538: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11539: # ignore package.tab specified default values
11540: # here &package_tab_default() will fetch those
11541: if ($subp eq 'default') { next; }
1.736 albertel 11542: my $value=$packagetab{$pack_entry};
1.432 albertel 11543: my $unikey;
11544: if ($pack =~ /_0$/) {
11545: $unikey='parameter_0_'.$name;
11546: $part=0;
11547: } else {
11548: $unikey='parameter'.$keyroot.'_'.$name;
11549: }
1.339 albertel 11550: if ($subp eq 'display') {
11551: $value.=' [Part: '.$part.']';
11552: }
1.599 albertel 11553: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11554: $metathesekeys{$unikey}=1;
1.599 albertel 11555: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11556: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11557: }
1.599 albertel 11558: if (defined($metaentry{':'.$unikey.'.default'})) {
11559: $metaentry{':'.$unikey}=
11560: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11561: }
1.339 albertel 11562: }
11563: }
11564: } else {
1.172 www 11565: #
11566: # This is not a package - some other kind of start tag
1.339 albertel 11567: #
11568: my $entry=$token->[1];
1.1068 www 11569: my $unikey='';
1.175 www 11570:
1.339 albertel 11571: if ($entry eq 'import') {
1.175 www 11572: #
11573: # Importing a library here
1.339 albertel 11574: #
1.1067 www 11575: my $location=$parser->get_text('/import');
11576: my $dir=$filename;
11577: $dir=~s|[^/]*$||;
11578: $location=&filelocation($dir,$location);
1.1069 www 11579:
1.1068 www 11580: my $importmode=$token->[2]->{'importmode'};
11581: if ($importmode eq 'problem') {
1.1069 www 11582: # Import as problem/response
1.1068 www 11583: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11584: } elsif ($importmode eq 'part') {
11585: # Import as part(s)
1.1069 www 11586: $importedparts=1;
11587: # We need to get the original file and the imported file to get the part order correct
11588: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11589: # Load and inspect original file
1.1070 www 11590: if ($#origfileimportpartids<0) {
11591: undef(%importedpartids);
11592: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11593: my $origfile=&getfile($origfilelocation);
11594: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11595: }
11596:
1.1069 www 11597: # Load and inspect imported file
11598: my $impfile=&getfile($location);
11599: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11600: if ($#impfilepartids>=0) {
11601: # This problem had parts
1.1070 www 11602: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11603: } else {
11604: # Importing by turning a single problem into a problem part
11605: # It gets the import-tags ID as part-ID
11606: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11607: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11608: }
1.1068 www 11609: } else {
11610: # Normal import
11611: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11612: if (defined($token->[2]->{'id'})) {
11613: $unikey.='_'.$token->[2]->{'id'};
11614: }
1.1067 www 11615: }
11616:
1.339 albertel 11617: if ($depthcount<20) {
1.736 albertel 11618: my $metadata =
11619: &metadata($uri,'keys', $location,$unikey,
11620: $depthcount+1);
11621: foreach my $meta (split(',',$metadata)) {
11622: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11623: $metathesekeys{$meta}=1;
1.339 albertel 11624: }
1.1068 www 11625:
11626: }
1.1067 www 11627: } else {
11628: #
11629: # Not importing, some other kind of non-package, non-library start tag
11630: #
11631: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11632: if (defined($token->[2]->{'id'})) {
11633: $unikey.='_'.$token->[2]->{'id'};
11634: }
1.339 albertel 11635: if (defined($token->[2]->{'name'})) {
11636: $unikey.='_'.$token->[2]->{'name'};
11637: }
11638: $metathesekeys{$unikey}=1;
1.736 albertel 11639: foreach my $param (@{$token->[3]}) {
11640: $metaentry{':'.$unikey.'.'.$param} =
11641: $token->[2]->{$param};
1.339 albertel 11642: }
11643: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11644: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11645: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11646: # only ws inside the tag, and not in default, so use default
11647: # as value
1.599 albertel 11648: $metaentry{':'.$unikey}=$default;
1.908 albertel 11649: } elsif ( $internaltext =~ /\S/ ) {
11650: # something interesting inside the tag
11651: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11652: } else {
1.908 albertel 11653: # no interesting values, don't set a default
1.339 albertel 11654: }
1.172 www 11655: # end of not-a-package not-a-library import
1.339 albertel 11656: }
1.172 www 11657: # end of not-a-package start tag
1.339 albertel 11658: }
1.172 www 11659: # the next is the end of "start tag"
1.339 albertel 11660: }
11661: }
1.483 albertel 11662: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11663: $extension = lc($extension);
11664: if ($extension eq 'htm') { $extension='html'; }
11665:
1.737 albertel 11666: foreach my $key (keys(%packagetab)) {
1.483 albertel 11667: #no specific packages #how's our extension
11668: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11669: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11670: \%metathesekeys);
11671: }
1.883 albertel 11672:
11673: if (!exists($metaentry{':packages'})
11674: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11675: foreach my $key (keys(%packagetab)) {
1.483 albertel 11676: #no specific packages well let's get default then
11677: if ($key!~/^default&/) { next; }
1.488 albertel 11678: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 11679: \%metathesekeys);
11680: }
11681: }
1.338 www 11682: # are there custom rights to evaluate
1.599 albertel 11683: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 11684:
1.338 www 11685: #
11686: # Importing a rights file here
1.339 albertel 11687: #
11688: unless ($depthcount) {
1.599 albertel 11689: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 11690: my $dir=$filename;
11691: $dir=~s|[^/]*$||;
11692: $location=&filelocation($dir,$location);
1.736 albertel 11693: my $rights_metadata =
11694: &metadata($uri,'keys',$location,'_rights',
11695: $depthcount+1);
11696: foreach my $rights (split(',',$rights_metadata)) {
11697: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11698: $metathesekeys{$rights}=1;
1.339 albertel 11699: }
11700: }
11701: }
1.737 albertel 11702: # uniqifiy package listing
11703: my %seen;
11704: my @uniq_packages =
11705: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11706: $metaentry{':packages'} = join(',',@uniq_packages);
11707:
1.1070 www 11708: if ($importedparts) {
11709: # We had imported parts and need to rebuild partorder
11710: $metaentry{':partorder'}='';
11711: $metathesekeys{'partorder'}=1;
11712: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11713: if ($origfileimportpartids[$index] eq 'part') {
11714: # original part, part of the problem
11715: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11716: } else {
11717: # we have imported parts at this position
11718: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11719: }
11720: }
11721: $metaentry{':partorder'}=~s/^\,//;
11722: }
11723:
1.737 albertel 11724: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 11725: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 11726: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 11727: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 11728: # this is the end of "was not already recently cached
1.71 www 11729: }
1.599 albertel 11730: return $metaentry{':'.$what};
1.261 albertel 11731: }
11732:
1.488 albertel 11733: sub metadata_create_package_def {
1.483 albertel 11734: my ($uri,$key,$package,$metathesekeys)=@_;
11735: my ($pack,$name,$subp)=split(/\&/,$key);
11736: if ($subp eq 'default') { next; }
11737:
1.599 albertel 11738: if (defined($metaentry{':packages'})) {
11739: $metaentry{':packages'}.=','.$package;
1.483 albertel 11740: } else {
1.599 albertel 11741: $metaentry{':packages'}=$package;
1.483 albertel 11742: }
11743: my $value=$packagetab{$key};
11744: my $unikey;
11745: $unikey='parameter_0_'.$name;
1.599 albertel 11746: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 11747: $$metathesekeys{$unikey}=1;
1.599 albertel 11748: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11749: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 11750: }
1.599 albertel 11751: if (defined($metaentry{':'.$unikey.'.default'})) {
11752: $metaentry{':'.$unikey}=
11753: $metaentry{':'.$unikey.'.default'};
1.483 albertel 11754: }
11755: }
11756:
1.261 albertel 11757: sub metadata_generate_part0 {
11758: my ($metadata,$metacache,$uri) = @_;
11759: my %allnames;
1.737 albertel 11760: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 11761: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 11762: my $part=$$metacache{':'.$metakey.'.part'};
11763: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 11764: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 11765: $allnames{$name}=$part;
11766: }
11767: }
11768: }
11769: foreach my $name (keys(%allnames)) {
11770: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 11771: my $key=":parameter_0_$name";
1.261 albertel 11772: $$metacache{"$key.part"}='0';
11773: $$metacache{"$key.name"}=$name;
1.428 albertel 11774: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 11775: $allnames{$name}.'_'.$name.
11776: '.type'};
1.428 albertel 11777: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 11778: '.display'};
1.644 www 11779: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 11780: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 11781: $$metacache{"$key.display"}=$olddis;
11782: }
1.71 www 11783: }
11784:
1.764 albertel 11785: # ------------------------------------------------------ Devalidate title cache
11786:
11787: sub devalidate_title_cache {
11788: my ($url)=@_;
11789: if (!$env{'request.course.id'}) { return; }
11790: my $symb=&symbread($url);
11791: if (!$symb) { return; }
11792: my $key=$env{'request.course.id'}."\0".$symb;
11793: &devalidate_cache_new('title',$key);
11794: }
11795:
1.1014 droeschl 11796: # ------------------------------------------------- Get the title of a course
11797:
11798: sub current_course_title {
11799: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11800: }
1.301 www 11801: # ------------------------------------------------- Get the title of a resource
11802:
11803: sub gettitle {
11804: my $urlsymb=shift;
11805: my $symb=&symbread($urlsymb);
1.534 albertel 11806: if ($symb) {
1.620 albertel 11807: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 11808: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 11809: if (defined($cached)) {
11810: return $result;
11811: }
1.534 albertel 11812: my ($map,$resid,$url)=&decode_symb($symb);
11813: my $title='';
1.907 albertel 11814: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11815: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11816: } else {
11817: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11818: &GDBM_READER(),0640)) {
11819: my $mapid=$bighash{'map_pc_'.&clutter($map)};
11820: $title=$bighash{'title_'.$mapid.'.'.$resid};
11821: untie(%bighash);
11822: }
1.534 albertel 11823: }
11824: $title=~s/\&colon\;/\:/gs;
11825: if ($title) {
1.1159 www 11826: # Remember both $symb and $title for dynamic metadata
11827: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 11828: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 11829: # Cache this title and then return it
1.599 albertel 11830: return &do_cache_new('title',$key,$title,600);
1.534 albertel 11831: }
11832: $urlsymb=$url;
11833: }
11834: my $title=&metadata($urlsymb,'title');
11835: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
11836: return $title;
1.301 www 11837: }
1.613 albertel 11838:
1.614 albertel 11839: sub get_slot {
11840: my ($which,$cnum,$cdom)=@_;
11841: if (!$cnum || !$cdom) {
1.790 albertel 11842: (undef,my $courseid)=&whichuser();
1.620 albertel 11843: $cdom=$env{'course.'.$courseid.'.domain'};
11844: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11845: }
1.703 albertel 11846: my $key=join("\0",'slots',$cdom,$cnum,$which);
11847: my %slotinfo;
11848: if (exists($remembered{$key})) {
11849: $slotinfo{$which} = $remembered{$key};
11850: } else {
11851: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11852: &Apache::lonhomework::showhash(%slotinfo);
11853: my ($tmp)=keys(%slotinfo);
11854: if ($tmp=~/^error:/) { return (); }
11855: $remembered{$key} = $slotinfo{$which};
11856: }
1.616 albertel 11857: if (ref($slotinfo{$which}) eq 'HASH') {
11858: return %{$slotinfo{$which}};
11859: }
11860: return $slotinfo{$which};
1.614 albertel 11861: }
1.1150 raeburn 11862:
11863: sub get_reservable_slots {
11864: my ($cnum,$cdom,$uname,$udom) = @_;
11865: my $now = time;
11866: my $reservable_info;
11867: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11868: if (exists($remembered{$key})) {
11869: $reservable_info = $remembered{$key};
11870: } else {
11871: my %resv;
11872: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11873: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11874: $reservable_info = \%resv;
11875: $remembered{$key} = $reservable_info;
11876: }
11877: return $reservable_info;
11878: }
11879:
11880: sub get_course_slots {
11881: my ($cnum,$cdom) = @_;
11882: my $hashid=$cnum.':'.$cdom;
11883: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11884: if (defined($cached)) {
11885: if (ref($result) eq 'HASH') {
11886: return %{$result};
11887: }
11888: } else {
11889: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11890: my ($tmp) = keys(%slots);
11891: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 11892: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11893: return %slots;
11894: }
11895: }
11896: return;
11897: }
11898:
11899: sub devalidate_slots_cache {
11900: my ($cnum,$cdom)=@_;
11901: my $hashid=$cnum.':'.$cdom;
11902: &devalidate_cache_new('allslots',$hashid);
11903: }
11904:
1.1181 raeburn 11905: sub get_coursechange {
11906: my ($cdom,$cnum) = @_;
11907: if ($cdom eq '' || $cnum eq '') {
11908: return unless ($env{'request.course.id'});
11909: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11910: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11911: }
11912: my $hashid=$cdom.'_'.$cnum;
11913: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11914: if ((defined($cached)) && ($change ne '')) {
11915: return $change;
11916: } else {
11917: my %crshash;
11918: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11919: if ($crshash{'internal.contentchange'} eq '') {
11920: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11921: if ($change eq '') {
11922: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11923: $change = $crshash{'internal.created'};
11924: }
11925: } else {
11926: $change = $crshash{'internal.contentchange'};
11927: }
11928: my $cachetime = 600;
11929: &do_cache_new('crschange',$hashid,$change,$cachetime);
11930: }
11931: return $change;
11932: }
11933:
11934: sub devalidate_coursechange_cache {
11935: my ($cnum,$cdom)=@_;
11936: my $hashid=$cnum.':'.$cdom;
11937: &devalidate_cache_new('crschange',$hashid);
11938: }
11939:
1.31 www 11940: # ------------------------------------------------- Update symbolic store links
11941:
11942: sub symblist {
11943: my ($mapname,%newhash)=@_;
1.438 www 11944: $mapname=&deversion(&declutter($mapname));
1.31 www 11945: my %hash;
1.620 albertel 11946: if (($env{'request.course.fn'}) && (%newhash)) {
11947: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11948: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11949: foreach my $url (keys(%newhash)) {
1.711 albertel 11950: next if ($url eq 'last_known'
11951: && $env{'form.no_update_last_known'});
11952: $hash{declutter($url)}=&encode_symb($mapname,
11953: $newhash{$url}->[1],
11954: $newhash{$url}->[0]);
1.191 harris41 11955: }
1.31 www 11956: if (untie(%hash)) {
11957: return 'ok';
11958: }
11959: }
11960: }
11961: return 'error';
1.212 www 11962: }
11963:
11964: # --------------------------------------------------------------- Verify a symb
11965:
11966: sub symbverify {
1.1190 raeburn 11967: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11968: my $thisfn=$thisurl;
1.439 www 11969: $thisfn=&declutter($thisfn);
1.215 www 11970: # direct jump to resource in page or to a sequence - will construct own symbs
11971: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11972: # check URL part
1.409 www 11973: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 11974:
1.431 www 11975: unless ($url eq $thisfn) { return 0; }
1.213 www 11976:
1.216 www 11977: $symb=&symbclean($symb);
1.510 www 11978: $thisurl=&deversion($thisurl);
1.439 www 11979: $thisfn=&deversion($thisfn);
1.213 www 11980:
11981: my %bighash;
11982: my $okay=0;
1.431 www 11983:
1.620 albertel 11984: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 11985: &GDBM_READER(),0640)) {
1.1204 raeburn 11986: my $noclutter;
1.1032 raeburn 11987: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11988: $thisurl =~ s/\?.+$//;
1.1204 raeburn 11989: if ($map =~ m{^uploaded/.+\.page$}) {
11990: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11991: $thisurl =~ s{^\Qhttp://https://\E}{https://};
11992: $noclutter = 1;
11993: }
11994: }
11995: my $ids;
11996: if ($noclutter) {
11997: $ids=$bighash{'ids_'.$thisurl};
11998: } else {
11999: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 12000: }
1.1102 raeburn 12001: unless ($ids) {
12002: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
12003: $ids=$bighash{$idkey};
1.216 www 12004: }
12005: if ($ids) {
12006: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 12007: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 12008: $symb =~ s/\?.+$//;
1.1202 raeburn 12009: }
1.800 albertel 12010: foreach my $id (split(/\,/,$ids)) {
12011: my ($mapid,$resid)=split(/\./,$id);
1.216 www 12012: if (
12013: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 12014: eq $symb) {
12015: if (ref($encstate)) {
12016: $$encstate = $bighash{'encrypted_'.$id};
12017: }
1.620 albertel 12018: if (($env{'request.role.adv'}) ||
1.1101 raeburn 12019: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12020: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 12021: $okay=1;
1.1202 raeburn 12022: last;
1.582 albertel 12023: }
12024: }
1.216 www 12025: }
12026: }
1.213 www 12027: untie(%bighash);
12028: }
12029: return $okay;
1.31 www 12030: }
12031:
1.210 www 12032: # --------------------------------------------------------------- Clean-up symb
12033:
12034: sub symbclean {
12035: my $symb=shift;
1.568 albertel 12036: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 12037: # remove version from map
12038: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 12039:
1.210 www 12040: # remove version from URL
12041: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 12042:
1.507 www 12043: # remove wrapper
12044:
1.510 www 12045: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 12046: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 12047: return $symb;
1.409 www 12048: }
12049:
12050: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 12051:
12052: sub encode_symb {
12053: my ($map,$resid,$url)=@_;
12054: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12055: }
1.409 www 12056:
12057: sub decode_symb {
1.568 albertel 12058: my $symb=shift;
12059: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12060: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 12061: return (&fixversion($map),$resid,&fixversion($url));
12062: }
12063:
12064: sub fixversion {
12065: my $fn=shift;
1.609 banghart 12066: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 12067: my %bighash;
12068: my $uri=&clutter($fn);
1.620 albertel 12069: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 12070: # is this cached?
1.599 albertel 12071: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 12072: if (defined($cached)) { return $result; }
12073: # unfortunately not cached, or expired
1.620 albertel 12074: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 12075: &GDBM_READER(),0640)) {
12076: if ($bighash{'version_'.$uri}) {
12077: my $version=$bighash{'version_'.$uri};
1.444 www 12078: unless (($version eq 'mostrecent') ||
12079: ($version==&getversion($uri))) {
1.440 www 12080: $uri=~s/\.(\w+)$/\.$version\.$1/;
12081: }
12082: }
12083: untie %bighash;
1.413 www 12084: }
1.599 albertel 12085: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 12086: }
12087:
12088: sub deversion {
12089: my $url=shift;
12090: $url=~s/\.\d+\.(\w+)$/\.$1/;
12091: return $url;
1.210 www 12092: }
12093:
1.31 www 12094: # ------------------------------------------------------ Return symb list entry
12095:
12096: sub symbread {
1.1282 raeburn 12097: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265 raeburn 12098: my $cache_str='request.symbread.cached.'.$thisfn;
1.1282 raeburn 12099: if (defined($env{$cache_str})) {
12100: if ($ignorecachednull) {
12101: return $env{$cache_str} unless ($env{$cache_str} eq '');
12102: } else {
12103: return $env{$cache_str};
12104: }
12105: }
1.242 www 12106: # no filename provided? try from environment
1.1265 raeburn 12107: unless ($thisfn) {
1.620 albertel 12108: if ($env{'request.symb'}) {
12109: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 12110: }
1.620 albertel 12111: $thisfn=$env{'request.filename'};
1.44 www 12112: }
1.569 albertel 12113: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 12114: # is that filename actually a symb? Verify, clean, and return
12115: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 12116: if (&symbverify($thisfn,$1)) {
1.620 albertel 12117: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 12118: }
1.242 www 12119: }
1.44 www 12120: $thisfn=declutter($thisfn);
1.31 www 12121: my %hash;
1.37 www 12122: my %bighash;
12123: my $syval='';
1.620 albertel 12124: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 12125: my $targetfn = $thisfn;
1.609 banghart 12126: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 12127: $targetfn = 'adm/wrapper/'.$thisfn;
12128: }
1.687 albertel 12129: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12130: $targetfn=$1;
12131: }
1.620 albertel 12132: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12133: &GDBM_READER(),0640)) {
1.481 raeburn 12134: $syval=$hash{$targetfn};
1.37 www 12135: untie(%hash);
12136: }
12137: # ---------------------------------------------------------- There was an entry
12138: if ($syval) {
1.601 albertel 12139: #unless ($syval=~/\_\d+$/) {
1.620 albertel 12140: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 12141: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12142: #return $env{$cache_str}='';
1.601 albertel 12143: #}
12144: #$syval.=$1;
12145: #}
1.37 www 12146: } else {
12147: # ------------------------------------------------------- Was not in symb table
1.620 albertel 12148: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12149: &GDBM_READER(),0640)) {
1.37 www 12150: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 12151: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 12152: unless ($ids) {
12153: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 12154: }
12155: unless ($ids) {
12156: # alias?
12157: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 12158: }
1.37 www 12159: if ($ids) {
12160: # ------------------------------------------------------------------- Has ID(s)
12161: my @possibilities=split(/\,/,$ids);
1.39 www 12162: if ($#possibilities==0) {
12163: # ----------------------------------------------- There is only one possibility
1.37 www 12164: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 12165: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12166: $resid,$thisfn);
1.1282 raeburn 12167: if (ref($possibles) eq 'HASH') {
12168: $possibles->{$syval} = 1;
12169: }
12170: if ($checkforblock) {
12171: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12172: if (@blockers) {
12173: $syval = '';
12174: return;
12175: }
12176: }
12177: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 12178: # ------------------------------------------ There is more than one possibility
12179: my $realpossible=0;
1.800 albertel 12180: foreach my $id (@possibilities) {
12181: my $file=$bighash{'src_'.$id};
1.1282 raeburn 12182: my $canaccess;
12183: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12184: $canaccess = 1;
12185: } else {
12186: $canaccess = &allowed('bre',$file);
12187: }
12188: if ($canaccess) {
12189: my ($mapid,$resid)=split(/\./,$id);
12190: if ($bighash{'map_type_'.$mapid} ne 'page') {
12191: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12192: $resid,$thisfn);
12193: if (ref($possibles) eq 'HASH') {
12194: $possibles->{$syval} = 1;
12195: }
12196: if ($checkforblock) {
12197: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12198: unless (@blockers > 0) {
12199: $syval = $poss_syval;
12200: $realpossible++;
12201: }
12202: } else {
12203: $syval = $poss_syval;
12204: $realpossible++;
12205: }
12206: }
1.39 www 12207: }
1.191 harris41 12208: }
1.39 www 12209: if ($realpossible!=1) { $syval=''; }
1.249 www 12210: } else {
12211: $syval='';
1.37 www 12212: }
12213: }
1.1282 raeburn 12214: untie(%bighash);
1.481 raeburn 12215: }
1.31 www 12216: }
1.62 www 12217: if ($syval) {
1.620 albertel 12218: return $env{$cache_str}=$syval;
1.62 www 12219: }
1.31 www 12220: }
1.949 raeburn 12221: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12222: return $env{$cache_str}='';
1.31 www 12223: }
12224:
12225: # ---------------------------------------------------------- Return random seed
12226:
1.32 www 12227: sub numval {
12228: my $txt=shift;
12229: $txt=~tr/A-J/0-9/;
12230: $txt=~tr/a-j/0-9/;
12231: $txt=~tr/K-T/0-9/;
12232: $txt=~tr/k-t/0-9/;
12233: $txt=~tr/U-Z/0-5/;
12234: $txt=~tr/u-z/0-5/;
12235: $txt=~s/\D//g;
1.564 albertel 12236: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 12237: return int($txt);
1.368 albertel 12238: }
12239:
1.484 albertel 12240: sub numval2 {
12241: my $txt=shift;
12242: $txt=~tr/A-J/0-9/;
12243: $txt=~tr/a-j/0-9/;
12244: $txt=~tr/K-T/0-9/;
12245: $txt=~tr/k-t/0-9/;
12246: $txt=~tr/U-Z/0-5/;
12247: $txt=~tr/u-z/0-5/;
12248: $txt=~s/\D//g;
12249: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12250: my $total;
12251: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 12252: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 12253: return int($total);
12254: }
12255:
1.575 albertel 12256: sub numval3 {
12257: use integer;
12258: my $txt=shift;
12259: $txt=~tr/A-J/0-9/;
12260: $txt=~tr/a-j/0-9/;
12261: $txt=~tr/K-T/0-9/;
12262: $txt=~tr/k-t/0-9/;
12263: $txt=~tr/U-Z/0-5/;
12264: $txt=~tr/u-z/0-5/;
12265: $txt=~s/\D//g;
12266: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12267: my $total;
12268: foreach my $val (@txts) { $total+=$val; }
12269: if ($_64bit) { $total=(($total<<32)>>32); }
12270: return $total;
12271: }
12272:
1.675 albertel 12273: sub digest {
12274: my ($data)=@_;
12275: my $digest=&Digest::MD5::md5($data);
12276: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12277: my ($e,$f);
12278: {
12279: use integer;
12280: $e=($a+$b);
12281: $f=($c+$d);
12282: if ($_64bit) {
12283: $e=(($e<<32)>>32);
12284: $f=(($f<<32)>>32);
12285: }
12286: }
12287: if (wantarray) {
12288: return ($e,$f);
12289: } else {
12290: my $g;
12291: {
12292: use integer;
12293: $g=($e+$f);
12294: if ($_64bit) {
12295: $g=(($g<<32)>>32);
12296: }
12297: }
12298: return $g;
12299: }
12300: }
12301:
1.368 albertel 12302: sub latest_rnd_algorithm_id {
1.675 albertel 12303: return '64bit5';
1.366 albertel 12304: }
1.32 www 12305:
1.503 albertel 12306: sub get_rand_alg {
12307: my ($courseid)=@_;
1.790 albertel 12308: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12309: if ($courseid) {
1.620 albertel 12310: return $env{"course.$courseid.rndseed"};
1.503 albertel 12311: }
12312: return &latest_rnd_algorithm_id();
12313: }
12314:
1.562 albertel 12315: sub validCODE {
12316: my ($CODE)=@_;
12317: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12318: return 0;
12319: }
12320:
1.491 albertel 12321: sub getCODE {
1.620 albertel 12322: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12323: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12324: defined($Apache::lonhomework::parsing_a_task) ) &&
12325: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12326: return $Apache::lonhomework::history{'resource.CODE'};
12327: }
12328: return undef;
12329: }
1.1133 foxr 12330: #
12331: # Determines the random seed for a specific context:
12332: #
12333: # parameters:
12334: # symb - in course context the symb for the seed.
12335: # course_id - The course id of the form domain_coursenum.
12336: # domain - Domain for the user.
12337: # course - Course for the user.
12338: # cenv - environment of the course.
12339: #
12340: # NOTE:
12341: # All parameters are picked out of the environment if missing
12342: # or not defined.
12343: # If a symb cannot be determined the current time is used instead.
12344: #
12345: # For a given well defined symb, courside, domain, username,
12346: # and course environment, the seed is reproducible.
12347: #
1.31 www 12348: sub rndseed {
1.1133 foxr 12349: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12350: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12351: if (!defined($symb)) {
1.366 albertel 12352: unless ($symb=$wsymb) { return time; }
12353: }
1.1146 foxr 12354: if (!defined $courseid) {
12355: $courseid=$wcourseid;
12356: }
12357: if (!defined $domain) { $domain=$wdomain; }
12358: if (!defined $username) { $username=$wusername }
1.1133 foxr 12359:
12360: my $which;
12361: if (defined($cenv->{'rndseed'})) {
12362: $which = $cenv->{'rndseed'};
12363: } else {
12364: $which =&get_rand_alg($courseid);
12365: }
1.491 albertel 12366: if (defined(&getCODE())) {
1.1133 foxr 12367:
1.675 albertel 12368: if ($which eq '64bit5') {
12369: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12370: } elsif ($which eq '64bit4') {
1.575 albertel 12371: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12372: } else {
12373: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12374: }
1.675 albertel 12375: } elsif ($which eq '64bit5') {
12376: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12377: } elsif ($which eq '64bit4') {
12378: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12379: } elsif ($which eq '64bit3') {
12380: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12381: } elsif ($which eq '64bit2') {
12382: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12383: } elsif ($which eq '64bit') {
12384: return &rndseed_64bit($symb,$courseid,$domain,$username);
12385: }
12386: return &rndseed_32bit($symb,$courseid,$domain,$username);
12387: }
12388:
12389: sub rndseed_32bit {
12390: my ($symb,$courseid,$domain,$username)=@_;
12391: {
12392: use integer;
12393: my $symbchck=unpack("%32C*",$symb) << 27;
12394: my $symbseed=numval($symb) << 22;
12395: my $namechck=unpack("%32C*",$username) << 17;
12396: my $nameseed=numval($username) << 12;
12397: my $domainseed=unpack("%32C*",$domain) << 7;
12398: my $courseseed=unpack("%32C*",$courseid);
12399: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12400: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12401: #&logthis("rndseed :$num:$symb");
1.564 albertel 12402: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 12403: return $num;
12404: }
12405: }
12406:
12407: sub rndseed_64bit {
12408: my ($symb,$courseid,$domain,$username)=@_;
12409: {
12410: use integer;
12411: my $symbchck=unpack("%32S*",$symb) << 21;
12412: my $symbseed=numval($symb) << 10;
12413: my $namechck=unpack("%32S*",$username);
12414:
12415: my $nameseed=numval($username) << 21;
12416: my $domainseed=unpack("%32S*",$domain) << 10;
12417: my $courseseed=unpack("%32S*",$courseid);
12418:
12419: my $num1=$symbchck+$symbseed+$namechck;
12420: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12421: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12422: #&logthis("rndseed :$num:$symb");
1.564 albertel 12423: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 12424: return "$num1,$num2";
1.155 albertel 12425: }
1.366 albertel 12426: }
12427:
1.443 albertel 12428: sub rndseed_64bit2 {
12429: my ($symb,$courseid,$domain,$username)=@_;
12430: {
12431: use integer;
12432: # strings need to be an even # of cahracters long, it it is odd the
12433: # last characters gets thrown away
12434: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12435: my $symbseed=numval($symb) << 10;
12436: my $namechck=unpack("%32S*",$username.' ');
12437:
12438: my $nameseed=numval($username) << 21;
1.501 albertel 12439: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12440: my $courseseed=unpack("%32S*",$courseid.' ');
12441:
12442: my $num1=$symbchck+$symbseed+$namechck;
12443: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12444: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12445: #&logthis("rndseed :$num:$symb");
1.803 albertel 12446: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 12447: return "$num1,$num2";
12448: }
12449: }
12450:
12451: sub rndseed_64bit3 {
12452: my ($symb,$courseid,$domain,$username)=@_;
12453: {
12454: use integer;
12455: # strings need to be an even # of cahracters long, it it is odd the
12456: # last characters gets thrown away
12457: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12458: my $symbseed=numval2($symb) << 10;
12459: my $namechck=unpack("%32S*",$username.' ');
12460:
12461: my $nameseed=numval2($username) << 21;
1.443 albertel 12462: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12463: my $courseseed=unpack("%32S*",$courseid.' ');
12464:
12465: my $num1=$symbchck+$symbseed+$namechck;
12466: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12467: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12468: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 12469: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12470:
1.503 albertel 12471: return "$num1:$num2";
1.443 albertel 12472: }
12473: }
12474:
1.575 albertel 12475: sub rndseed_64bit4 {
12476: my ($symb,$courseid,$domain,$username)=@_;
12477: {
12478: use integer;
12479: # strings need to be an even # of cahracters long, it it is odd the
12480: # last characters gets thrown away
12481: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12482: my $symbseed=numval3($symb) << 10;
12483: my $namechck=unpack("%32S*",$username.' ');
12484:
12485: my $nameseed=numval3($username) << 21;
12486: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12487: my $courseseed=unpack("%32S*",$courseid.' ');
12488:
12489: my $num1=$symbchck+$symbseed+$namechck;
12490: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12491: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12492: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 12493: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12494:
1.575 albertel 12495: return "$num1:$num2";
12496: }
12497: }
12498:
1.675 albertel 12499: sub rndseed_64bit5 {
12500: my ($symb,$courseid,$domain,$username)=@_;
12501: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12502: return "$num1:$num2";
12503: }
12504:
1.366 albertel 12505: sub rndseed_CODE_64bit {
12506: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 12507: {
1.366 albertel 12508: use integer;
1.443 albertel 12509: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 12510: my $symbseed=numval2($symb);
1.491 albertel 12511: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12512: my $CODEseed=numval(&getCODE());
1.443 albertel 12513: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 12514: my $num1=$symbseed+$CODEchck;
12515: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12516: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12517: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 12518: if ($_64bit) { $num1=(($num1<<32)>>32); }
12519: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 12520: return "$num1:$num2";
1.366 albertel 12521: }
12522: }
12523:
1.575 albertel 12524: sub rndseed_CODE_64bit4 {
12525: my ($symb,$courseid,$domain,$username)=@_;
12526: {
12527: use integer;
12528: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12529: my $symbseed=numval3($symb);
12530: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12531: my $CODEseed=numval3(&getCODE());
12532: my $courseseed=unpack("%32S*",$courseid.' ');
12533: my $num1=$symbseed+$CODEchck;
12534: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12535: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12536: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 12537: if ($_64bit) { $num1=(($num1<<32)>>32); }
12538: if ($_64bit) { $num2=(($num2<<32)>>32); }
12539: return "$num1:$num2";
12540: }
12541: }
12542:
1.675 albertel 12543: sub rndseed_CODE_64bit5 {
12544: my ($symb,$courseid,$domain,$username)=@_;
12545: my $code = &getCODE();
12546: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12547: return "$num1:$num2";
12548: }
12549:
1.366 albertel 12550: sub setup_random_from_rndseed {
12551: my ($rndseed)=@_;
1.503 albertel 12552: if ($rndseed =~/([,:])/) {
1.1262 raeburn 12553: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12554: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12555: &Math::Random::random_set_seed_from_phrase($rndseed);
12556: } else {
12557: &Math::Random::random_set_seed($num1,$num2);
12558: }
1.366 albertel 12559: } else {
12560: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12561: }
1.36 albertel 12562: }
12563:
1.474 albertel 12564: sub latest_receipt_algorithm_id {
1.835 albertel 12565: return 'receipt3';
1.474 albertel 12566: }
12567:
1.480 www 12568: sub recunique {
12569: my $fucourseid=shift;
12570: my $unique;
1.835 albertel 12571: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12572: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12573: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12574: } else {
12575: $unique=$perlvar{'lonReceipt'};
12576: }
12577: return unpack("%32C*",$unique);
12578: }
12579:
12580: sub recprefix {
12581: my $fucourseid=shift;
12582: my $prefix;
1.835 albertel 12583: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12584: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12585: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12586: } else {
12587: $prefix=$perlvar{'lonHostID'};
12588: }
12589: return unpack("%32C*",$prefix);
12590: }
12591:
1.76 www 12592: sub ireceipt {
1.474 albertel 12593: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12594:
12595: my $return =&recprefix($fucourseid).'-';
12596:
12597: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12598: $env{'request.state'} eq 'construct') {
12599: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12600: return $return;
12601: }
12602:
1.76 www 12603: my $cuname=unpack("%32C*",$funame);
12604: my $cudom=unpack("%32C*",$fudom);
12605: my $cucourseid=unpack("%32C*",$fucourseid);
12606: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12607: my $cunique=&recunique($fucourseid);
1.474 albertel 12608: my $cpart=unpack("%32S*",$part);
1.835 albertel 12609: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12610:
1.790 albertel 12611: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12612:
12613: $return.= ($cunique%$cuname+
12614: $cunique%$cudom+
12615: $cusymb%$cuname+
12616: $cusymb%$cudom+
12617: $cucourseid%$cuname+
12618: $cucourseid%$cudom+
12619: $cpart%$cuname+
12620: $cpart%$cudom);
12621: } else {
12622: $return.= ($cunique%$cuname+
12623: $cunique%$cudom+
12624: $cusymb%$cuname+
12625: $cusymb%$cudom+
12626: $cucourseid%$cuname+
12627: $cucourseid%$cudom);
12628: }
12629: return $return;
1.76 www 12630: }
12631:
12632: sub receipt {
1.474 albertel 12633: my ($part)=@_;
1.790 albertel 12634: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 12635: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 12636: }
1.260 ng 12637:
1.790 albertel 12638: sub whichuser {
12639: my ($passedsymb)=@_;
12640: my ($symb,$courseid,$domain,$name,$publicuser);
12641: if (defined($env{'form.grade_symb'})) {
12642: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12643: my $allowed=&allowed('vgr',$tmp_courseid);
12644: if (!$allowed &&
12645: exists($env{'request.course.sec'}) &&
12646: $env{'request.course.sec'} !~ /^\s*$/) {
12647: $allowed=&allowed('vgr',$tmp_courseid.
12648: '/'.$env{'request.course.sec'});
12649: }
12650: if ($allowed) {
12651: ($symb)=&get_env_multiple('form.grade_symb');
12652: $courseid=$tmp_courseid;
12653: ($domain)=&get_env_multiple('form.grade_domain');
12654: ($name)=&get_env_multiple('form.grade_username');
12655: return ($symb,$courseid,$domain,$name,$publicuser);
12656: }
12657: }
12658: if (!$passedsymb) {
12659: $symb=&symbread();
12660: } else {
12661: $symb=$passedsymb;
12662: }
12663: $courseid=$env{'request.course.id'};
12664: $domain=$env{'user.domain'};
12665: $name=$env{'user.name'};
12666: if ($name eq 'public' && $domain eq 'public') {
12667: if (!defined($env{'form.username'})) {
12668: $env{'form.username'}.=time.rand(10000000);
12669: }
12670: $name.=$env{'form.username'};
12671: }
12672: return ($symb,$courseid,$domain,$name,$publicuser);
12673:
12674: }
12675:
1.36 albertel 12676: # ------------------------------------------------------------ Serves up a file
1.472 albertel 12677: # returns either the contents of the file or
12678: # -1 if the file doesn't exist
1.481 raeburn 12679: #
12680: # if the target is a file that was uploaded via DOCS,
12681: # a check will be made to see if a current copy exists on the local server,
12682: # if it does this will be served, otherwise a copy will be retrieved from
12683: # the home server for the course and stored in /home/httpd/html/userfiles on
12684: # the local server.
1.472 albertel 12685:
1.36 albertel 12686: sub getfile {
1.538 albertel 12687: my ($file) = @_;
1.609 banghart 12688: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 12689: &repcopy($file);
12690: return &readfile($file);
12691: }
12692:
12693: sub repcopy_userfile {
12694: my ($file)=@_;
1.1142 raeburn 12695: my $londocroot = $perlvar{'lonDocRoot'};
12696: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 12697: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 12698: my ($cdom,$cnum,$filename) =
1.811 albertel 12699: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 12700: my $uri="/uploaded/$cdom/$cnum/$filename";
12701: if (-e "$file") {
1.828 www 12702: # we already have a local copy, check it out
1.538 albertel 12703: my @fileinfo = stat($file);
1.828 www 12704: my $rtncode;
12705: my $info;
1.538 albertel 12706: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 12707: if ($lwpresp ne 'ok') {
1.828 www 12708: # there is no such file anymore, even though we had a local copy
1.482 albertel 12709: if ($rtncode eq '404') {
1.538 albertel 12710: unlink($file);
1.482 albertel 12711: }
12712: return -1;
12713: }
12714: if ($info < $fileinfo[9]) {
1.828 www 12715: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 12716: return 'ok';
1.828 www 12717: } else {
12718: # the file is outdated, get rid of it
12719: unlink($file);
1.482 albertel 12720: }
1.828 www 12721: }
12722: # one way or the other, at this point, we don't have the file
12723: # construct the correct path for the file
12724: my @parts = ($cdom,$cnum);
12725: if ($filename =~ m|^(.+)/[^/]+$|) {
12726: push @parts, split(/\//,$1);
12727: }
12728: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12729: foreach my $part (@parts) {
12730: $path .= '/'.$part;
12731: if (!-e $path) {
12732: mkdir($path,0770);
1.482 albertel 12733: }
12734: }
1.828 www 12735: # now the path exists for sure
12736: # get a user agent
12737: my $ua=new LWP::UserAgent;
12738: my $transferfile=$file.'.in.transfer';
12739: # FIXME: this should flock
12740: if (-e $transferfile) { return 'ok'; }
12741: my $request;
12742: $uri=~s/^\///;
1.980 raeburn 12743: my $homeserver = &homeserver($cnum,$cdom);
12744: my $protocol = $protocol{$homeserver};
12745: $protocol = 'http' if ($protocol ne 'https');
12746: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 12747: my $response=$ua->request($request,$transferfile);
12748: # did it work?
12749: if ($response->is_error()) {
12750: unlink($transferfile);
12751: &logthis("Userfile repcopy failed for $uri");
12752: return -1;
12753: }
12754: # worked, rename the transfer file
12755: rename($transferfile,$file);
1.607 raeburn 12756: return 'ok';
1.481 raeburn 12757: }
12758:
1.517 albertel 12759: sub tokenwrapper {
12760: my $uri=shift;
1.980 raeburn 12761: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 12762: $uri=~s|^/||;
1.620 albertel 12763: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 12764: my $token=$1;
1.552 albertel 12765: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12766: if ($udom && $uname && $file) {
12767: $file=~s|(\?\.*)*$||;
1.949 raeburn 12768: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 12769: my $homeserver = &homeserver($uname,$udom);
12770: my $protocol = $protocol{$homeserver};
12771: $protocol = 'http' if ($protocol ne 'https');
12772: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 12773: (($uri=~/\?/)?'&':'?').'token='.$token.
12774: '&tokenissued='.$perlvar{'lonHostID'};
12775: } else {
12776: return '/adm/notfound.html';
12777: }
12778: }
12779:
1.828 www 12780: # call with reqtype HEAD: get last modification time
12781: # call with reqtype GET: get the file contents
12782: # Do not call this with reqtype GET for large files! It loads everything into memory
12783: #
1.481 raeburn 12784: sub getuploaded {
12785: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12786: $uri=~s/^\///;
1.980 raeburn 12787: my $homeserver = &homeserver($cnum,$cdom);
12788: my $protocol = $protocol{$homeserver};
12789: $protocol = 'http' if ($protocol ne 'https');
12790: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 12791: my $ua=new LWP::UserAgent;
12792: my $request=new HTTP::Request($reqtype,$uri);
12793: my $response=$ua->request($request);
12794: $$rtncode = $response->code;
1.482 albertel 12795: if (! $response->is_success()) {
12796: return 'failed';
12797: }
12798: if ($reqtype eq 'HEAD') {
1.486 www 12799: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 12800: } elsif ($reqtype eq 'GET') {
12801: $$info = $response->content;
1.472 albertel 12802: }
1.482 albertel 12803: return 'ok';
1.36 albertel 12804: }
12805:
1.481 raeburn 12806: sub readfile {
12807: my $file = shift;
12808: if ( (! -e $file ) || ($file eq '') ) { return -1; };
12809: my $fh;
12810: open($fh,"<$file");
12811: my $a='';
1.800 albertel 12812: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 12813: return $a;
12814: }
12815:
1.36 albertel 12816: sub filelocation {
1.590 banghart 12817: my ($dir,$file) = @_;
12818: my $location;
12819: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 12820:
12821: if ($file =~ m-^/adm/-) {
12822: $file=~s-^/adm/wrapper/-/-;
12823: $file=~s-^/adm/coursedocs/showdoc/-/-;
12824: }
1.882 albertel 12825:
1.1139 www 12826: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 12827: $location = $file;
1.609 banghart 12828: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 12829: my ($udom,$uname,$filename)=
1.811 albertel 12830: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 12831: my $home=&homeserver($uname,$udom);
12832: my $is_me=0;
12833: my @ids=¤t_machine_ids();
12834: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12835: if ($is_me) {
1.1117 foxr 12836: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 12837: } else {
12838: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12839: $udom.'/'.$uname.'/'.$filename;
12840: }
1.882 albertel 12841: } elsif ($file =~ m-^/adm/-) {
12842: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 12843: } else {
12844: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12845: $file=~s:^/(res|priv)/:/:;
12846: my $space=$1;
1.590 banghart 12847: if ( !( $file =~ m:^/:) ) {
12848: $location = $dir. '/'.$file;
12849: } else {
1.1142 raeburn 12850: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12851: }
1.59 albertel 12852: }
1.590 banghart 12853: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12854: while ($location=~m{/\.\./}) {
12855: if ($location =~ m{/[^/]+/\.\./}) {
12856: $location=~ s{/[^/]+/\.\./}{/}g;
12857: } else {
12858: $location=~ s{/\.\./}{/}g;
12859: }
12860: } #remove dir/..
1.590 banghart 12861: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12862: return $location;
1.46 www 12863: }
1.36 albertel 12864:
1.46 www 12865: sub hreflocation {
12866: my ($dir,$file)=@_;
1.980 raeburn 12867: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12868: $file=filelocation($dir,$file);
1.700 albertel 12869: } elsif ($file=~m-^/adm/-) {
12870: $file=~s-^/adm/wrapper/-/-;
12871: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12872: }
12873: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12874: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12875: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12876: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12877: {/uploaded/$1/$2/}x;
1.46 www 12878: }
1.913 albertel 12879: if ($file=~ m{^/userfiles/}) {
12880: $file =~ s{^/userfiles/}{/uploaded/};
12881: }
1.462 albertel 12882: return $file;
1.465 albertel 12883: }
12884:
1.1139 www 12885:
12886:
12887:
12888:
1.465 albertel 12889: sub current_machine_domains {
1.853 albertel 12890: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12891: }
12892:
12893: sub machine_domains {
12894: my ($hostname) = @_;
1.465 albertel 12895: my @domains;
1.838 albertel 12896: my %hostname = &all_hostnames();
1.465 albertel 12897: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12898: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12899: if ($hostname eq $name) {
1.844 albertel 12900: push(@domains,&host_domain($id));
1.465 albertel 12901: }
12902: }
12903: return @domains;
12904: }
12905:
12906: sub current_machine_ids {
1.853 albertel 12907: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12908: }
12909:
12910: sub machine_ids {
12911: my ($hostname) = @_;
12912: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12913: my @ids;
1.888 albertel 12914: my %name_to_host = &all_names();
1.889 albertel 12915: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12916: return @{ $name_to_host{$hostname} };
12917: }
12918: return;
1.31 www 12919: }
12920:
1.824 raeburn 12921: sub additional_machine_domains {
12922: my @domains;
12923: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12924: while( my $line = <$fh>) {
12925: $line =~ s/\s//g;
12926: push(@domains,$line);
12927: }
12928: return @domains;
12929: }
12930:
12931: sub default_login_domain {
12932: my $domain = $perlvar{'lonDefDomain'};
12933: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12934: foreach my $posdom (¤t_machine_domains(),
12935: &additional_machine_domains()) {
12936: if (lc($posdom) eq lc($testdomain)) {
12937: $domain=$posdom;
12938: last;
12939: }
12940: }
12941: return $domain;
12942: }
12943:
1.31 www 12944: # ------------------------------------------------------------- Declutters URLs
12945:
12946: sub declutter {
12947: my $thisfn=shift;
1.569 albertel 12948: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 12949: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12950: $thisfn=~s{^/home/httpd/html}{};
12951: }
1.31 www 12952: $thisfn=~s/^\///;
1.697 albertel 12953: $thisfn=~s|^adm/wrapper/||;
12954: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12955: $thisfn=~s/^res\///;
1.1172 bisitz 12956: $thisfn=~s/^priv\///;
1.1032 raeburn 12957: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12958: $thisfn=~s/\?.+$//;
12959: }
1.268 www 12960: return $thisfn;
12961: }
12962:
12963: # ------------------------------------------------------------- Clutter up URLs
12964:
12965: sub clutter {
12966: my $thisfn='/'.&declutter(shift);
1.887 albertel 12967: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12968: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12969: $thisfn='/res'.$thisfn;
12970: }
1.1031 raeburn 12971: if ($thisfn !~m|^/adm|) {
12972: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12973: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 12974: } else {
12975: my ($ext) = ($thisfn =~ /\.(\w+)$/);
12976: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 12977: if ($embstyle eq 'ssi'
12978: || ($embstyle eq 'hdn')
12979: || ($embstyle eq 'rat')
12980: || ($embstyle eq 'prv')
12981: || ($embstyle eq 'ign')) {
12982: #do nothing with these
12983: } elsif (($embstyle eq 'img')
1.695 albertel 12984: || ($embstyle eq 'emb')
12985: || ($embstyle eq 'wrp')) {
12986: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 12987: } elsif ($embstyle eq 'unk'
12988: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 12989: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 12990: } else {
1.718 www 12991: # &logthis("Got a blank emb style");
1.695 albertel 12992: }
1.694 albertel 12993: }
1.1298 raeburn 12994: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
12995: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 12996: }
1.31 www 12997: return $thisfn;
1.12 www 12998: }
12999:
1.787 albertel 13000: sub clutter_with_no_wrapper {
13001: my $uri = &clutter(shift);
13002: if ($uri =~ m-^/adm/-) {
13003: $uri =~ s-^/adm/wrapper/-/-;
13004: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
13005: }
13006: return $uri;
13007: }
13008:
1.557 albertel 13009: sub freeze_escape {
13010: my ($value)=@_;
13011: if (ref($value)) {
13012: $value=&nfreeze($value);
13013: return '__FROZEN__'.&escape($value);
13014: }
13015: return &escape($value);
13016: }
13017:
1.11 www 13018:
1.557 albertel 13019: sub thaw_unescape {
13020: my ($value)=@_;
13021: if ($value =~ /^__FROZEN__/) {
13022: substr($value,0,10,undef);
13023: $value=&unescape($value);
13024: return &thaw($value);
13025: }
13026: return &unescape($value);
13027: }
13028:
1.436 albertel 13029: sub correct_line_ends {
13030: my ($result)=@_;
13031: $$result =~s/\r\n/\n/mg;
13032: $$result =~s/\r/\n/mg;
1.415 albertel 13033: }
1.1 albertel 13034: # ================================================================ Main Program
13035:
1.184 www 13036: sub goodbye {
1.204 albertel 13037: &logthis("Starting Shut down");
1.443 albertel 13038: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 13039: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 13040: #converted
1.599 albertel 13041: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 13042: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13043: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13044: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 13045: #1.1 only
1.870 albertel 13046: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13047: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13048: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13049: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13050: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 13051: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13052: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 13053: &flushcourselogs();
13054: &logthis("Shutting down");
13055: }
13056:
1.852 albertel 13057: sub get_dns {
1.1210 raeburn 13058: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 13059: if (!$ignore_cache) {
13060: my ($content,$cached)=
13061: &Apache::lonnet::is_cached_new('dns',$url);
13062: if ($cached) {
1.1210 raeburn 13063: &$func($content,$hashref);
1.869 albertel 13064: return;
13065: }
13066: }
13067:
13068: my %alldns;
1.852 albertel 13069: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13070: foreach my $dns (<$config>) {
13071: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 13072: my $line = $1;
13073: my ($host,$protocol) = split(/:/,$line);
13074: if ($protocol ne 'https') {
13075: $protocol = 'http';
13076: }
13077: $alldns{$host} = $protocol;
1.869 albertel 13078: }
13079: while (%alldns) {
1.1263 raeburn 13080: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 13081: my $ua=new LWP::UserAgent;
1.1134 raeburn 13082: $ua->timeout(30);
1.979 raeburn 13083: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 13084: my $response=$ua->request($request);
1.979 raeburn 13085: delete($alldns{$dns});
1.852 albertel 13086: next if ($response->is_error());
13087: my @content = split("\n",$response->content);
1.1210 raeburn 13088: unless ($nocache) {
1.1219 raeburn 13089: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 13090: }
13091: &$func(\@content,$hashref);
1.869 albertel 13092: return;
1.852 albertel 13093: }
13094: close($config);
1.871 albertel 13095: my $which = (split('/',$url))[3];
13096: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13097: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 13098: my @content = <$config>;
1.1210 raeburn 13099: &$func(\@content,$hashref);
13100: return;
13101: }
13102:
13103: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 13104: sub parse_dns_checksums_tab {
1.1210 raeburn 13105: my ($lines,$hashref) = @_;
1.1264 raeburn 13106: my $lonhost = $perlvar{'lonHostID'};
13107: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 13108: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 13109: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13110: my $webconfdir = '/etc/httpd/conf';
13111: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13112: $webconfdir = '/etc/apache2';
13113: } elsif ($distro =~ /^sles(\d+)$/) {
13114: if ($1 >= 10) {
13115: $webconfdir = '/etc/apache2';
13116: }
13117: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13118: if ($1 >= 10.0) {
13119: $webconfdir = '/etc/apache2';
13120: }
13121: }
1.1210 raeburn 13122: my ($release,$timestamp) = split(/\-/,$loncaparev);
13123: my (%chksum,%revnum);
13124: if (ref($lines) eq 'ARRAY') {
13125: chomp(@{$lines});
1.1238 raeburn 13126: my $version = shift(@{$lines});
13127: if ($version eq $release) {
1.1210 raeburn 13128: foreach my $line (@{$lines}) {
1.1238 raeburn 13129: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 13130: if ($file =~ m{^/etc/httpd/conf}) {
13131: if ($webconfdir eq '/etc/apache2') {
13132: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13133: }
13134: }
1.1238 raeburn 13135: $chksum{$file} = $shasum;
13136: $revnum{$file} = $version;
1.1210 raeburn 13137: }
13138: if (ref($hashref) eq 'HASH') {
13139: %{$hashref} = (
13140: sums => \%chksum,
13141: versions => \%revnum,
13142: );
13143: }
13144: }
13145: }
1.869 albertel 13146: return;
1.852 albertel 13147: }
1.1210 raeburn 13148:
13149: sub fetch_dns_checksums {
1.1238 raeburn 13150: my %checksums;
13151: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 13152: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 13153: my ($release,$timestamp) = split(/\-/,$loncaparev);
13154: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 13155: \%checksums);
1.1210 raeburn 13156: return \%checksums;
13157: }
13158:
1.327 albertel 13159: # ------------------------------------------------------------ Read domain file
13160: {
1.852 albertel 13161: my $loaded;
1.846 albertel 13162: my %domain;
13163:
1.852 albertel 13164: sub parse_domain_tab {
13165: my ($lines) = @_;
13166: foreach my $line (@$lines) {
13167: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 13168:
1.846 albertel 13169: chomp($line);
1.852 albertel 13170: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 13171: my %this_domain;
13172: foreach my $field ('description', 'auth_def', 'auth_arg_def',
13173: 'lang_def', 'city', 'longi', 'lati',
13174: 'primary') {
13175: $this_domain{$field} = shift(@elements);
13176: }
13177: $domain{$name} = \%this_domain;
1.852 albertel 13178: }
13179: }
1.864 albertel 13180:
13181: sub reset_domain_info {
13182: undef($loaded);
13183: undef(%domain);
13184: }
13185:
1.852 albertel 13186: sub load_domain_tab {
1.1293 raeburn 13187: my ($ignore_cache,$nocache) = @_;
13188: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 13189: my $fh;
13190: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
13191: my @lines = <$fh>;
13192: &parse_domain_tab(\@lines);
1.448 albertel 13193: }
1.852 albertel 13194: close($fh);
13195: $loaded = 1;
1.327 albertel 13196: }
1.846 albertel 13197:
13198: sub domain {
1.852 albertel 13199: &load_domain_tab() if (!$loaded);
13200:
1.846 albertel 13201: my ($name,$what) = @_;
13202: return if ( !exists($domain{$name}) );
13203:
13204: if (!$what) {
13205: return $domain{$name}{'description'};
13206: }
13207: return $domain{$name}{$what};
13208: }
1.974 raeburn 13209:
13210: sub domain_info {
13211: &load_domain_tab() if (!$loaded);
13212: return %domain;
13213: }
13214:
1.327 albertel 13215: }
13216:
13217:
1.1 albertel 13218: # ------------------------------------------------------------- Read hosts file
13219: {
1.838 albertel 13220: my %hostname;
1.844 albertel 13221: my %hostdom;
1.845 albertel 13222: my %libserv;
1.852 albertel 13223: my $loaded;
1.888 albertel 13224: my %name_to_host;
1.1074 raeburn 13225: my %internetdom;
1.1107 raeburn 13226: my %LC_dns_serv;
1.852 albertel 13227:
13228: sub parse_hosts_tab {
13229: my ($file) = @_;
13230: foreach my $configline (@$file) {
13231: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 13232: chomp($configline);
13233: if ($configline =~ /^\^/) {
13234: if ($configline =~ /^\^([\w.\-]+)/) {
13235: $LC_dns_serv{$1} = 1;
13236: }
13237: next;
13238: }
1.1074 raeburn 13239: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 13240: $name=~s/\s//g;
13241: if ($id && $domain && $role && $name) {
13242: $hostname{$id}=$name;
1.888 albertel 13243: push(@{$name_to_host{$name}}, $id);
1.852 albertel 13244: $hostdom{$id}=$domain;
13245: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 13246: if (defined($protocol)) {
13247: if ($protocol eq 'https') {
13248: $protocol{$id} = $protocol;
13249: } else {
13250: $protocol{$id} = 'http';
13251: }
1.968 raeburn 13252: } else {
1.969 raeburn 13253: $protocol{$id} = 'http';
1.968 raeburn 13254: }
1.1074 raeburn 13255: if (defined($intdom)) {
13256: $internetdom{$id} = $intdom;
13257: }
1.852 albertel 13258: }
13259: }
13260: }
1.864 albertel 13261:
13262: sub reset_hosts_info {
1.897 albertel 13263: &purge_remembered();
1.864 albertel 13264: &reset_domain_info();
13265: &reset_hosts_ip_info();
1.1339 ! raeburn 13266: undef(%internetdom);
1.892 albertel 13267: undef(%name_to_host);
1.864 albertel 13268: undef(%hostname);
13269: undef(%hostdom);
13270: undef(%libserv);
13271: undef($loaded);
13272: }
1.1 albertel 13273:
1.852 albertel 13274: sub load_hosts_tab {
1.1293 raeburn 13275: my ($ignore_cache,$nocache) = @_;
13276: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852 albertel 13277: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13278: my @config = <$config>;
13279: &parse_hosts_tab(\@config);
13280: close($config);
13281: $loaded=1;
1.1 albertel 13282: }
1.852 albertel 13283:
1.838 albertel 13284: sub hostname {
1.852 albertel 13285: &load_hosts_tab() if (!$loaded);
13286:
1.838 albertel 13287: my ($lonid) = @_;
13288: return $hostname{$lonid};
13289: }
1.845 albertel 13290:
1.838 albertel 13291: sub all_hostnames {
1.852 albertel 13292: &load_hosts_tab() if (!$loaded);
13293:
1.838 albertel 13294: return %hostname;
13295: }
1.845 albertel 13296:
1.888 albertel 13297: sub all_names {
1.1293 raeburn 13298: my ($ignore_cache,$nocache) = @_;
13299: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 13300:
13301: return %name_to_host;
13302: }
13303:
1.974 raeburn 13304: sub all_host_domain {
13305: &load_hosts_tab() if (!$loaded);
13306: return %hostdom;
13307: }
13308:
1.1339 ! raeburn 13309: sub all_host_intdom {
! 13310: &load_hosts_tab() if (!$loaded);
! 13311: return %internetdom;
! 13312: }
! 13313:
1.845 albertel 13314: sub is_library {
1.852 albertel 13315: &load_hosts_tab() if (!$loaded);
13316:
1.845 albertel 13317: return exists($libserv{$_[0]});
13318: }
13319:
13320: sub all_library {
1.852 albertel 13321: &load_hosts_tab() if (!$loaded);
13322:
1.845 albertel 13323: return %libserv;
13324: }
13325:
1.1062 droeschl 13326: sub unique_library {
13327: #2x reverse removes all hostnames that appear more than once
13328: my %unique = reverse &all_library();
13329: return reverse %unique;
13330: }
13331:
1.841 albertel 13332: sub get_servers {
1.852 albertel 13333: &load_hosts_tab() if (!$loaded);
13334:
1.841 albertel 13335: my ($domain,$type) = @_;
13336: my %possible_hosts = ($type eq 'library') ? %libserv
13337: : %hostname;
13338: my %result;
1.842 albertel 13339: if (ref($domain) eq 'ARRAY') {
13340: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 13341: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 13342: $result{$host} = $hostname;
13343: }
13344: }
13345: } else {
13346: while ( my ($host,$hostname) = each(%possible_hosts)) {
13347: if ($hostdom{$host} eq $domain) {
13348: $result{$host} = $hostname;
13349: }
1.841 albertel 13350: }
13351: }
13352: return %result;
13353: }
1.845 albertel 13354:
1.1062 droeschl 13355: sub get_unique_servers {
13356: my %unique = reverse &get_servers(@_);
13357: return reverse %unique;
13358: }
13359:
1.844 albertel 13360: sub host_domain {
1.852 albertel 13361: &load_hosts_tab() if (!$loaded);
13362:
1.844 albertel 13363: my ($lonid) = @_;
13364: return $hostdom{$lonid};
13365: }
13366:
1.841 albertel 13367: sub all_domains {
1.852 albertel 13368: &load_hosts_tab() if (!$loaded);
13369:
1.841 albertel 13370: my %seen;
13371: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13372: return @uniq;
13373: }
1.1074 raeburn 13374:
13375: sub internet_dom {
13376: &load_hosts_tab() if (!$loaded);
13377:
13378: my ($lonid) = @_;
13379: return $internetdom{$lonid};
13380: }
1.1107 raeburn 13381:
13382: sub is_LC_dns {
13383: &load_hosts_tab() if (!$loaded);
13384:
13385: my ($hostname) = @_;
13386: return exists($LC_dns_serv{$hostname});
13387: }
13388:
1.1 albertel 13389: }
13390:
1.847 albertel 13391: {
13392: my %iphost;
1.856 albertel 13393: my %name_to_ip;
13394: my %lonid_to_ip;
1.869 albertel 13395:
1.847 albertel 13396: sub get_hosts_from_ip {
13397: my ($ip) = @_;
13398: my %iphosts = &get_iphost();
13399: if (ref($iphosts{$ip})) {
13400: return @{$iphosts{$ip}};
13401: }
13402: return;
1.839 albertel 13403: }
1.864 albertel 13404:
13405: sub reset_hosts_ip_info {
13406: undef(%iphost);
13407: undef(%name_to_ip);
13408: undef(%lonid_to_ip);
13409: }
1.856 albertel 13410:
13411: sub get_host_ip {
13412: my ($lonid) = @_;
13413: if (exists($lonid_to_ip{$lonid})) {
13414: return $lonid_to_ip{$lonid};
13415: }
13416: my $name=&hostname($lonid);
13417: my $ip = gethostbyname($name);
13418: return if (!$ip || length($ip) ne 4);
13419: $ip=inet_ntoa($ip);
13420: $name_to_ip{$name} = $ip;
13421: $lonid_to_ip{$lonid} = $ip;
13422: return $ip;
13423: }
1.847 albertel 13424:
13425: sub get_iphost {
1.1293 raeburn 13426: my ($ignore_cache,$nocache) = @_;
1.894 albertel 13427:
1.869 albertel 13428: if (!$ignore_cache) {
13429: if (%iphost) {
13430: return %iphost;
13431: }
13432: my ($ip_info,$cached)=
13433: &Apache::lonnet::is_cached_new('iphost','iphost');
13434: if ($cached) {
13435: %iphost = %{$ip_info->[0]};
13436: %name_to_ip = %{$ip_info->[1]};
13437: %lonid_to_ip = %{$ip_info->[2]};
13438: return %iphost;
13439: }
13440: }
1.894 albertel 13441:
13442: # get yesterday's info for fallback
13443: my %old_name_to_ip;
13444: my ($ip_info,$cached)=
13445: &Apache::lonnet::is_cached_new('iphost','iphost');
13446: if ($cached) {
13447: %old_name_to_ip = %{$ip_info->[1]};
13448: }
13449:
1.1293 raeburn 13450: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 13451: foreach my $name (keys(%name_to_host)) {
1.847 albertel 13452: my $ip;
13453: if (!exists($name_to_ip{$name})) {
13454: $ip = gethostbyname($name);
13455: if (!$ip || length($ip) ne 4) {
1.894 albertel 13456: if (defined($old_name_to_ip{$name})) {
13457: $ip = $old_name_to_ip{$name};
13458: &logthis("Can't find $name defaulting to old $ip");
13459: } else {
13460: &logthis("Name $name no IP found");
13461: next;
13462: }
13463: } else {
13464: $ip=inet_ntoa($ip);
1.847 albertel 13465: }
13466: $name_to_ip{$name} = $ip;
13467: } else {
13468: $ip = $name_to_ip{$name};
1.653 albertel 13469: }
1.888 albertel 13470: foreach my $id (@{ $name_to_host{$name} }) {
13471: $lonid_to_ip{$id} = $ip;
13472: }
13473: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 13474: }
1.1293 raeburn 13475: unless ($nocache) {
13476: &do_cache_new('iphost','iphost',
13477: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13478: 48*60*60);
13479: }
1.869 albertel 13480:
1.847 albertel 13481: return %iphost;
1.598 albertel 13482: }
13483:
1.992 raeburn 13484: #
13485: # Given a DNS returns the loncapa host name for that DNS
13486: #
13487: sub host_from_dns {
13488: my ($dns) = @_;
13489: my @hosts;
13490: my $ip;
13491:
1.993 raeburn 13492: if (exists($name_to_ip{$dns})) {
1.992 raeburn 13493: $ip = $name_to_ip{$dns};
13494: }
13495: if (!$ip) {
13496: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13497: if (length($ip) == 4) {
13498: $ip = &IO::Socket::inet_ntoa($ip);
13499: }
13500: }
13501: if ($ip) {
13502: @hosts = get_hosts_from_ip($ip);
13503: return $hosts[0];
13504: }
13505: return undef;
1.986 foxr 13506: }
1.992 raeburn 13507:
1.1074 raeburn 13508: sub get_internet_names {
13509: my ($lonid) = @_;
13510: return if ($lonid eq '');
13511: my ($idnref,$cached)=
13512: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13513: if ($cached) {
13514: return $idnref;
13515: }
13516: my $ip = &get_host_ip($lonid);
13517: my @hosts = &get_hosts_from_ip($ip);
13518: my %iphost = &get_iphost();
13519: my (@idns,%seen);
13520: foreach my $id (@hosts) {
13521: my $dom = &host_domain($id);
13522: my $prim_id = &domain($dom,'primary');
13523: my $prim_ip = &get_host_ip($prim_id);
13524: next if ($seen{$prim_ip});
13525: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13526: foreach my $id (@{$iphost{$prim_ip}}) {
13527: my $intdom = &internet_dom($id);
13528: unless (grep(/^\Q$intdom\E$/,@idns)) {
13529: push(@idns,$intdom);
13530: }
13531: }
13532: }
13533: $seen{$prim_ip} = 1;
13534: }
1.1219 raeburn 13535: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 13536: }
13537:
1.986 foxr 13538: }
13539:
1.1079 raeburn 13540: sub all_loncaparevs {
1.1249 raeburn 13541: 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 13542: }
13543:
1.1227 raeburn 13544: # ---------------------------------------------------------- Read loncaparev table
13545: {
13546: sub load_loncaparevs {
13547: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13548: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13549: while (my $configline=<$config>) {
13550: chomp($configline);
13551: my ($hostid,$loncaparev)=split(/:/,$configline);
13552: $loncaparevs{$hostid}=$loncaparev;
13553: }
13554: close($config);
13555: }
13556: }
13557: }
13558: }
13559:
13560: # ---------------------------------------------------------- Read serverhostID table
13561: {
13562: sub load_serverhomeIDs {
13563: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13564: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13565: while (my $configline=<$config>) {
13566: chomp($configline);
13567: my ($name,$id)=split(/:/,$configline);
13568: $serverhomeIDs{$name}=$id;
13569: }
13570: close($config);
13571: }
13572: }
13573: }
13574: }
13575:
13576:
1.862 albertel 13577: BEGIN {
13578:
13579: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13580: unless ($readit) {
13581: {
13582: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13583: %perlvar = (%perlvar,%{$configvars});
13584: }
13585:
13586:
1.1 albertel 13587: # ------------------------------------------------------ Read spare server file
13588: {
1.448 albertel 13589: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 13590:
13591: while (my $configline=<$config>) {
13592: chomp($configline);
1.284 matthew 13593: if ($configline) {
1.784 albertel 13594: my ($host,$type) = split(':',$configline,2);
1.785 albertel 13595: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 13596: push(@{ $spareid{$type} }, $host);
1.1 albertel 13597: }
13598: }
1.448 albertel 13599: close($config);
1.1 albertel 13600: }
1.11 www 13601: # ------------------------------------------------------------ Read permissions
13602: {
1.448 albertel 13603: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 13604:
13605: while (my $configline=<$config>) {
1.448 albertel 13606: chomp($configline);
13607: if ($configline) {
13608: my ($role,$perm)=split(/ /,$configline);
13609: if ($perm ne '') { $pr{$role}=$perm; }
13610: }
1.11 www 13611: }
1.448 albertel 13612: close($config);
1.11 www 13613: }
13614:
13615: # -------------------------------------------- Read plain texts for permissions
13616: {
1.448 albertel 13617: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 13618:
13619: while (my $configline=<$config>) {
1.448 albertel 13620: chomp($configline);
13621: if ($configline) {
1.742 raeburn 13622: my ($short,@plain)=split(/:/,$configline);
13623: %{$prp{$short}} = ();
13624: if (@plain > 0) {
13625: $prp{$short}{'std'} = $plain[0];
13626: for (my $i=1; $i<@plain; $i++) {
13627: $prp{$short}{'alt'.$i} = $plain[$i];
13628: }
13629: }
1.448 albertel 13630: }
1.135 www 13631: }
1.448 albertel 13632: close($config);
1.135 www 13633: }
13634:
13635: # ---------------------------------------------------------- Read package table
13636: {
1.448 albertel 13637: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 13638:
13639: while (my $configline=<$config>) {
1.483 albertel 13640: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 13641: chomp($configline);
13642: my ($short,$plain)=split(/:/,$configline);
13643: my ($pack,$name)=split(/\&/,$short);
13644: if ($plain ne '') {
13645: $packagetab{$pack.'&'.$name.'&name'}=$name;
13646: $packagetab{$short}=$plain;
13647: }
1.11 www 13648: }
1.448 albertel 13649: close($config);
1.329 matthew 13650: }
13651:
1.1073 raeburn 13652: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 13653:
13654: &load_loncaparevs();
1.1073 raeburn 13655:
1.1074 raeburn 13656: # ---------------------------------------------------------- Read serverhostID table
13657:
1.1227 raeburn 13658: &load_serverhomeIDs();
13659:
13660: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 13661: {
13662: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13663: if (-e $file) {
13664: my $parser = HTML::LCParser->new($file);
13665: while (my $token = $parser->get_token()) {
13666: if ($token->[0] eq 'S') {
13667: my $item = $token->[1];
13668: my $name = $token->[2]{'name'};
13669: my $value = $token->[2]{'value'};
1.1285 raeburn 13670: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 13671: my $namematch = $token->[2]{'namematch'};
13672: if ($item eq 'parameter') {
13673: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
13674: my $release = $parser->get_text();
13675: $release =~ s/(^\s*|\s*$ )//gx;
13676: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
13677: }
13678: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 13679: my $release = $parser->get_text();
13680: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 13681: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 13682: }
13683: }
13684: }
13685: }
1.1073 raeburn 13686: }
13687:
1.1138 raeburn 13688: # ---------------------------------------------------------- Read managers table
13689: {
13690: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13691: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
13692: while (my $configline=<$config>) {
13693: chomp($configline);
13694: next if ($configline =~ /^\#/);
13695: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13696: $managerstab{$configline} = 1;
13697: }
13698: }
13699: close($config);
13700: }
13701: }
13702: }
13703:
1.329 matthew 13704: # ------------- set up temporary directory
13705: {
1.1117 foxr 13706: $tmpdir = LONCAPA::tempdir();
1.329 matthew 13707:
1.11 www 13708: }
13709:
1.794 albertel 13710: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13711: 'compress_threshold'=> 20_000,
13712: });
1.185 www 13713:
1.281 www 13714: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 13715: $dumpcount=0;
1.958 www 13716: $locknum=0;
1.22 www 13717:
1.163 harris41 13718: &logtouch();
1.672 albertel 13719: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 13720: $readit=1;
1.564 albertel 13721: {
13722: use integer;
13723: my $test=(2**32)+1;
1.568 albertel 13724: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 13725: &logthis(" Detected 64bit platform ($_64bit)");
13726: }
1.195 www 13727: }
1.1 albertel 13728: }
1.179 www 13729:
1.1 albertel 13730: 1;
1.191 harris41 13731: __END__
13732:
1.243 albertel 13733: =pod
13734:
1.191 harris41 13735: =head1 NAME
13736:
1.243 albertel 13737: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 13738:
13739: =head1 SYNOPSIS
13740:
1.243 albertel 13741: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 13742:
13743: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13744:
1.243 albertel 13745: Common parameters:
13746:
13747: =over 4
13748:
13749: =item *
13750:
13751: $uname : an internal username (if $cname expecting a course Id specifically)
13752:
13753: =item *
13754:
13755: $udom : a domain (if $cdom expecting a course's domain specifically)
13756:
13757: =item *
13758:
13759: $symb : a resource instance identifier
13760:
13761: =item *
13762:
13763: $namespace : the name of a .db file that contains the data needed or
13764: being set.
13765:
13766: =back
13767:
1.394 bowersj2 13768: =head1 OVERVIEW
1.191 harris41 13769:
1.394 bowersj2 13770: lonnet provides subroutines which interact with the
13771: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13772: about classes, users, and resources.
1.243 albertel 13773:
13774: For many of these objects you can also use this to store data about
13775: them or modify them in various ways.
1.191 harris41 13776:
1.394 bowersj2 13777: =head2 Symbs
1.191 harris41 13778:
1.394 bowersj2 13779: To identify a specific instance of a resource, LON-CAPA uses symbols
13780: or "symbs"X<symb>. These identifiers are built from the URL of the
13781: map, the resource number of the resource in the map, and the URL of
13782: the resource itself. The latter is somewhat redundant, but might help
13783: if maps change.
13784:
13785: An example is
13786:
13787: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13788:
13789: The respective map entry is
13790:
13791: <resource id="19" src="/res/msu/korte/tests/part12.problem"
13792: title="Problem 2">
13793: </resource>
13794:
13795: Symbs are used by the random number generator, as well as to store and
13796: restore data specific to a certain instance of for example a problem.
13797:
13798: =head2 Storing And Retrieving Data
13799:
13800: X<store()>X<cstore()>X<restore()>Three of the most important functions
13801: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13802: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13803: is is the non-critical message twin of cstore. These functions are for
13804: handlers to store a perl hash to a user's permanent data space in an
13805: easy manner, and to retrieve it again on another call. It is expected
13806: that a handler would use this once at the beginning to retrieve data,
13807: and then again once at the end to send only the new data back.
13808:
13809: The data is stored in the user's data directory on the user's
13810: homeserver under the ID of the course.
13811:
13812: The hash that is returned by restore will have all of the previous
13813: value for all of the elements of the hash.
13814:
13815: Example:
13816:
13817: #creating a hash
13818: my %hash;
13819: $hash{'foo'}='bar';
13820:
13821: #storing it
13822: &Apache::lonnet::cstore(\%hash);
13823:
13824: #changing a value
13825: $hash{'foo'}='notbar';
13826:
13827: #adding a new value
13828: $hash{'bar'}='foo';
13829: &Apache::lonnet::cstore(\%hash);
13830:
13831: #retrieving the hash
13832: my %history=&Apache::lonnet::restore();
13833:
13834: #print the hash
13835: foreach my $key (sort(keys(%history))) {
13836: print("\%history{$key} = $history{$key}");
13837: }
13838:
13839: Will print out:
1.191 harris41 13840:
1.394 bowersj2 13841: %history{1:foo} = bar
13842: %history{1:keys} = foo:timestamp
13843: %history{1:timestamp} = 990455579
13844: %history{2:bar} = foo
13845: %history{2:foo} = notbar
13846: %history{2:keys} = foo:bar:timestamp
13847: %history{2:timestamp} = 990455580
13848: %history{bar} = foo
13849: %history{foo} = notbar
13850: %history{timestamp} = 990455580
13851: %history{version} = 2
13852:
13853: Note that the special hash entries C<keys>, C<version> and
13854: C<timestamp> were added to the hash. C<version> will be equal to the
13855: total number of versions of the data that have been stored. The
13856: C<timestamp> attribute will be the UNIX time the hash was
13857: stored. C<keys> is available in every historical section to list which
13858: keys were added or changed at a specific historical revision of a
13859: hash.
13860:
13861: B<Warning>: do not store the hash that restore returns directly. This
13862: will cause a mess since it will restore the historical keys as if the
13863: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13864:
1.394 bowersj2 13865: Calling convention:
1.191 harris41 13866:
1.1225 raeburn 13867: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 13868: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13869:
1.394 bowersj2 13870: For more detailed information, see lonnet specific documentation.
1.191 harris41 13871:
1.394 bowersj2 13872: =head1 RETURN MESSAGES
1.191 harris41 13873:
1.394 bowersj2 13874: =over 4
1.191 harris41 13875:
1.394 bowersj2 13876: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13877:
1.394 bowersj2 13878: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13879: when the connection is brought back up
1.191 harris41 13880:
1.394 bowersj2 13881: =item * B<con_failed>: unable to contact remote host and unable to save message
13882: for later delivery
1.191 harris41 13883:
1.967 bisitz 13884: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13885:
1.394 bowersj2 13886: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13887: that was requested
1.191 harris41 13888:
1.243 albertel 13889: =back
1.191 harris41 13890:
1.243 albertel 13891: =head1 PUBLIC SUBROUTINES
1.191 harris41 13892:
1.243 albertel 13893: =head2 Session Environment Functions
1.191 harris41 13894:
1.243 albertel 13895: =over 4
1.191 harris41 13896:
1.394 bowersj2 13897: =item *
13898: X<appenv()>
1.949 raeburn 13899: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13900: the user envirnoment file, and will be restored for each access this
1.620 albertel 13901: user makes during this session, also modifies the %env for the current
1.949 raeburn 13902: process. Optional rolesarrayref - if defined contains a reference to an array
13903: of roles which are exempt from the restriction on modifying user.role entries
13904: in the user's environment.db and in %env.
1.191 harris41 13905:
13906: =item *
1.394 bowersj2 13907: X<delenv()>
1.987 raeburn 13908: B<delenv($delthis,$regexp)>: removes all items from the session
13909: environment file that begin with $delthis. If the
13910: optional second arg - $regexp - is true, $delthis is treated as a
13911: regular expression, otherwise \Q$delthis\E is used.
13912: The values are also deleted from the current processes %env.
1.191 harris41 13913:
1.795 albertel 13914: =item * get_env_multiple($name)
13915:
13916: gets $name from the %env hash, it seemlessly handles the cases where multiple
13917: values may be defined and end up as an array ref.
13918:
13919: returns an array of values
13920:
1.243 albertel 13921: =back
13922:
13923: =head2 User Information
1.191 harris41 13924:
1.243 albertel 13925: =over 4
1.191 harris41 13926:
13927: =item *
1.394 bowersj2 13928: X<queryauthenticate()>
13929: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13930: authentication scheme
13931:
13932: =item *
1.394 bowersj2 13933: X<authenticate()>
1.1073 raeburn 13934: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13935: authenticate user from domain's lib servers (first use the current
13936: one). C<$upass> should be the users password.
1.1073 raeburn 13937: $checkdefauth is optional (value is 1 if a check should be made to
13938: authenticate user using default authentication method, and allow
13939: account creation if username does not have account in the domain).
13940: $clientcancheckhost is optional (value is 1 if checking whether the
13941: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13942:
13943: =item *
1.394 bowersj2 13944: X<homeserver()>
13945: B<homeserver($uname,$udom)>: find the server which has
13946: the user's directory and files (there must be only one), this caches
13947: the answer, and also caches if there is a borken connection.
1.191 harris41 13948:
13949: =item *
1.394 bowersj2 13950: X<idget()>
1.1300 raeburn 13951: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
13952: a list of student/employee IDs or clicker IDs
13953: (student/employee IDs are a unique resource in a domain, there must be
13954: only 1 ID per username, and only 1 username per ID in a specific domain).
13955: clickerIDs are not necessarily unique, as students might share clickers.
13956: (returns hash: id=>name,id=>name)
1.191 harris41 13957:
13958: =item *
1.394 bowersj2 13959: X<idrget()>
13960: B<idrget($udom,@unames)>: find the IDs behind a list of
13961: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13962:
13963: =item *
1.394 bowersj2 13964: X<idput()>
1.1300 raeburn 13965: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
13966: names and associated student/employee IDs or clicker IDs.
13967:
13968: =item *
13969: X<iddel()>
13970: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
13971: student/employee ID or clicker ID username look-ups from domain.
13972: The homeserver ($uhome) and namespace ($namespace) are optional.
13973: If no $uhome is provided, it will be determined usig &homeserver()
13974: for each user. If no $namespace is provided, the default is ids.
13975:
13976: =item *
13977: X<updateclickers()>
13978: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
13979: clicker ID-to-username look-ups in clickers.db on library server.
13980: Permitted actions are add or del (i.e., add or delete). The
13981: clickers.db contains clickerID as keys (escaped), and each corresponding
13982: value is an escaped comma-separated list of usernames (for whom the
13983: library server is the homeserver), who registered that particular ID.
13984: If $critical is true, the update will be sent via &critical, otherwise
13985: &reply() will be used.
1.191 harris41 13986:
13987: =item *
1.394 bowersj2 13988: X<rolesinit()>
1.1169 droeschl 13989: B<rolesinit($udom,$username)>: get user privileges.
13990: returns user role, first access and timer interval hashes
1.243 albertel 13991:
13992: =item *
1.1171 droeschl 13993: X<privileged()>
13994: B<privileged($username,$domain)>: returns a true if user has a
13995: privileged and active role (i.e. su or dc), false otherwise.
13996:
13997: =item *
1.551 albertel 13998: X<getsection()>
13999: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 14000: course $cname, return section name/number or '' for "not in course"
14001: and '-1' for "no section"
14002:
14003: =item *
1.394 bowersj2 14004: X<userenvironment()>
14005: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 14006: passed in @what from the requested user's environment, returns a hash
14007:
1.858 raeburn 14008: =item *
14009: X<userlog_query()>
1.859 albertel 14010: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14011: activity.log file. %filters defines filters applied when parsing the
14012: log file. These can be start or end timestamps, or the type of action
14013: - log to look for Login or Logout events, check for Checkin or
14014: Checkout, role for role selection. The response is in the form
14015: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
14016: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 14017:
1.243 albertel 14018: =back
14019:
14020: =head2 User Roles
14021:
14022: =over 4
14023:
14024: =item *
14025:
1.1284 raeburn 14026: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14027: returns codes for allowed actions.
14028:
14029: The first argument is required, all others are optional.
14030:
14031: $priv is the privilege being checked.
14032: $uri contains additional information about what is being checked for access (e.g.,
14033: URL, course ID etc.).
14034: $symb is the unique resource instance identifier in a course; if needed,
14035: but not provided, it will be retrieved via a call to &symbread().
14036: $role is the role for which a priv is being checked (only used if priv is evb).
14037: $clientip is the user's IP address (only used when checking for access to portfolio
14038: files).
14039: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14040: prevents recursive calls to &allowed.
14041:
1.243 albertel 14042: F: full access
14043: U,I,K: authentication modes (cxx only)
14044: '': forbidden
14045: 1: user needs to choose course
14046: 2: browse allowed
1.766 albertel 14047: A: passphrase authentication needed
1.1284 raeburn 14048: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 14049:
14050: =item *
14051:
1.1192 raeburn 14052: constructaccess($url,$setpriv) : check for access to construction space URL
14053:
14054: See if the owner domain and name in the URL match those in the
14055: expected environment. If so, return three element list
14056: ($ownername,$ownerdomain,$ownerhome).
14057:
14058: Otherwise return the null string.
14059:
14060: If second argument 'setpriv' is true, it assigns the privileges,
14061: and returns the same three element list, unless the owner has
14062: blocked "ad hoc" Domain Coordinator access to the Author Space,
14063: in which case the null string is returned.
14064:
14065: =item *
14066:
1.1326 raeburn 14067: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14068: define a custom role rolename set privileges in format of lonTabs/roles.tab
14069: for system, domain, and course level. $uname and $udom are optional (current
14070: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 14071:
14072: =item *
14073:
1.988 raeburn 14074: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
14075: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 14076: $type is Course (default) or Community.
1.988 raeburn 14077: If $forcedefault evaluates to true, text returned will be default
14078: text for $type. Otherwise, if this is a course, the text returned
14079: will be a custom name for the role (if defined in the course's
14080: environment). If no custom name is defined the default is returned.
14081:
1.832 raeburn 14082: =item *
14083:
1.1219 raeburn 14084: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 14085: All arguments are optional. Returns a hash of a roles, either for
14086: co-author/assistant author roles for a user's Construction Space
1.906 albertel 14087: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 14088: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14089: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14090: For each key, value is set to colon-separated start and end times for
14091: the role. If no username and domain are specified, will default to
1.934 raeburn 14092: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 14093: of role statuses (active, future or previous), roles
14094: (e.g., cc,in, st etc.) and domains of the roles which can be used
14095: to restrict the list of roles reported. If no array ref is
14096: provided for types, will default to return only active roles.
1.834 albertel 14097:
1.1195 raeburn 14098: =item *
14099:
14100: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 14101: user: $uname:$udom has a role in the course: $cdom_$cnum.
14102:
14103: Additional optional arguments are: $type (if role checking is to be restricted
14104: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 14105: available roles) or future (roles available in the future), and
14106: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 14107: have active Domain Coordinator role in course's domain or in additional
14108: domains (specified in 'Domains to check for privileged users' in course
14109: environment -- set via: Course Settings -> Classlists and staff listing).
14110:
14111: =item *
14112:
14113: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14114: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14115: $possdomains and $possroles are optional array refs -- to domains to check and
14116: roles to check. If $possdomains is not specified, a dump will be done of the
14117: users' roles.db to check for a dc or su role in any domain. This can be
14118: time consuming if &privileged is called repeatedly (e.g., when displaying a
14119: classlist), so in such cases, supplying a $possdomains array is preferred, as
14120: this then allows &privileged_by_domain() to be used, which caches the identity
14121: of privileged users, eliminating the need for repeated calls to &dump().
14122:
14123: =item *
14124:
14125: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14126: where the outer hash keys are domains specified in the $possdomains array ref,
14127: next inner hash keys are privileged roles specified in the $roles array ref,
14128: and the innermost hash contains key = value pairs for username:domain = end:start
14129: for active or future "privileged" users with that role in that domain. To avoid
14130: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14131: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 14132:
1.243 albertel 14133: =back
14134:
14135: =head2 User Modification
14136:
14137: =over 4
14138:
14139: =item *
14140:
1.957 raeburn 14141: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 14142: user for the level given by URL. Optional start and end dates (leave empty
14143: string or zero for "no date")
1.191 harris41 14144:
14145: =item *
14146:
1.243 albertel 14147: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14148: change a users, password, possible return values are: ok,
14149: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14150: refused
1.191 harris41 14151:
14152: =item *
14153:
1.243 albertel 14154: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 14155:
14156: =item *
14157:
1.1058 raeburn 14158: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14159: $forceid,$desiredhome,$email,$inststatus,$candelete) :
14160:
14161: will update user information (firstname,middlename,lastname,generation,
14162: permanentemail), and if forceid is true, student/employee ID also.
14163: A user's institutional affiliation(s) can also be updated.
14164: User information fields will not be overwritten with empty entries
14165: unless the field is included in the $candelete array reference.
14166: This array is included when a single user is modified via "Manage Users",
14167: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 14168:
14169: =item *
14170:
1.286 matthew 14171: modifystudent
14172:
1.957 raeburn 14173: modify a student's enrollment and identification information.
1.1235 raeburn 14174: The course id is resolved based on the current user's environment.
14175: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 14176: associated with a course.
14177:
1.297 matthew 14178: This call is essentially a wrapper for lonnet::modifyuser and
14179: lonnet::modify_student_enrollment
1.286 matthew 14180:
14181: Inputs:
14182:
14183: =over 4
14184:
1.957 raeburn 14185: =item B<$udom> Student's loncapa domain
1.286 matthew 14186:
1.957 raeburn 14187: =item B<$uname> Student's loncapa login name
1.286 matthew 14188:
1.964 bisitz 14189: =item B<$uid> Student/Employee ID
1.286 matthew 14190:
1.957 raeburn 14191: =item B<$umode> Student's authentication mode
1.286 matthew 14192:
1.957 raeburn 14193: =item B<$upass> Student's password
1.286 matthew 14194:
1.957 raeburn 14195: =item B<$first> Student's first name
1.286 matthew 14196:
1.957 raeburn 14197: =item B<$middle> Student's middle name
1.286 matthew 14198:
1.957 raeburn 14199: =item B<$last> Student's last name
1.286 matthew 14200:
1.957 raeburn 14201: =item B<$gene> Student's generation
1.286 matthew 14202:
1.957 raeburn 14203: =item B<$usec> Student's section in course
1.286 matthew 14204:
14205: =item B<$end> Unix time of the roles expiration
14206:
14207: =item B<$start> Unix time of the roles start date
14208:
14209: =item B<$forceid> If defined, allow $uid to be changed
14210:
14211: =item B<$desiredhome> server to use as home server for student
14212:
1.957 raeburn 14213: =item B<$email> Student's permanent e-mail address
14214:
14215: =item B<$type> Type of enrollment (auto or manual)
14216:
1.963 raeburn 14217: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
14218:
14219: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 14220:
1.963 raeburn 14221: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 14222:
1.963 raeburn 14223: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 14224:
1.1216 raeburn 14225: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14226:
14227: =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 14228:
1.286 matthew 14229: =back
1.297 matthew 14230:
14231: =item *
14232:
14233: modify_student_enrollment
14234:
1.1235 raeburn 14235: Change a student's enrollment status in a class. The environment variable
1.297 matthew 14236: 'role.request.course' must be defined for this function to proceed.
14237:
14238: Inputs:
14239:
14240: =over 4
14241:
1.1235 raeburn 14242: =item $udom, student's domain
1.297 matthew 14243:
1.1235 raeburn 14244: =item $uname, student's name
1.297 matthew 14245:
1.1235 raeburn 14246: =item $uid, student's user id
1.297 matthew 14247:
1.1235 raeburn 14248: =item $first, student's first name
1.297 matthew 14249:
14250: =item $middle
14251:
14252: =item $last
14253:
14254: =item $gene
14255:
14256: =item $usec
14257:
14258: =item $end
14259:
14260: =item $start
14261:
1.957 raeburn 14262: =item $type
14263:
14264: =item $locktype
14265:
14266: =item $cid
14267:
14268: =item $selfenroll
14269:
14270: =item $context
14271:
1.1216 raeburn 14272: =item $credits, number of credits student will earn from this class
14273:
1.1314 raeburn 14274: =item $instsec, institutional course section code for student
14275:
1.297 matthew 14276: =back
14277:
1.191 harris41 14278:
14279: =item *
14280:
1.243 albertel 14281: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14282: custom role; give a custom role to a user for the level given by URL. Specify
14283: name and domain of role author, and role name
1.191 harris41 14284:
14285: =item *
14286:
1.243 albertel 14287: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 14288:
14289: =item *
14290:
1.243 albertel 14291: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14292:
14293: =back
14294:
14295: =head2 Course Infomation
14296:
14297: =over 4
1.191 harris41 14298:
14299: =item *
14300:
1.1118 foxr 14301: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 14302: specified course id, including all environment settings for the
14303: course, the description of the course will be in the hash under the
14304: key 'description'
1.191 harris41 14305:
1.1118 foxr 14306: $options is an optional parameter that if supplied is a hash reference that controls
14307: what how this function works. It has the following key/values:
14308:
14309: =over 4
14310:
14311: =item freshen_cache
14312:
14313: If defined, and the environment cache for the course is valid, it is
14314: returned in the returned hash.
14315:
14316: =item one_time
14317:
14318: If defined, the last cache time is set to _now_
14319:
14320: =item user
14321:
14322: If defined, the supplied username is used instead of the current user.
14323:
14324:
14325: =back
14326:
1.191 harris41 14327: =item *
14328:
1.624 albertel 14329: resdata($name,$domain,$type,@which) : request for current parameter
14330: setting for a specific $type, where $type is either 'course' or 'user',
14331: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 14332: answers for 10 minutes.
1.243 albertel 14333:
1.877 foxr 14334: =item *
14335:
14336: get_courseresdata($courseid, $domain) : dump the entire course resource
14337: data base, returning a hash that is keyed by the resource name and has
14338: values that are the resource value. I believe that the timestamps and
14339: versions are also returned.
14340:
1.1236 raeburn 14341: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14342: supplemental content area. This routine caches the number of files for
14343: 10 minutes.
14344:
1.243 albertel 14345: =back
14346:
14347: =head2 Course Modification
14348:
14349: =over 4
1.191 harris41 14350:
14351: =item *
14352:
1.243 albertel 14353: writecoursepref($courseid,%prefs) : write preferences (environment
14354: database) for a course
1.191 harris41 14355:
14356: =item *
14357:
1.1011 raeburn 14358: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14359:
14360: =item *
14361:
1.1038 raeburn 14362: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 14363:
1.1167 droeschl 14364: =item *
14365:
14366: is_course($courseid), is_course($cdom, $cnum)
14367:
14368: Accepts either a combined $courseid (in the form of domain_courseid) or the
14369: two component version $cdom, $cnum. It checks if the specified course exists.
14370:
14371: Returns:
14372: undef if the course doesn't exist, otherwise
14373: in scalar context the combined courseid.
14374: in list context the two components of the course identifier, domain and
14375: courseid.
14376:
1.243 albertel 14377: =back
14378:
14379: =head2 Resource Subroutines
14380:
14381: =over 4
1.191 harris41 14382:
14383: =item *
14384:
1.243 albertel 14385: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 14386:
14387: =item *
14388:
1.243 albertel 14389: repcopy($filename) : subscribes to the requested file, and attempts to
14390: replicate from the owning library server, Might return
1.607 raeburn 14391: 'unavailable', 'not_found', 'forbidden', 'ok', or
14392: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 14393: resource. Expects the local filesystem pathname
14394: (/home/httpd/html/res/....)
14395:
14396: =back
14397:
14398: =head2 Resource Information
14399:
14400: =over 4
1.191 harris41 14401:
14402: =item *
14403:
1.1228 raeburn 14404: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
14405: and returns the value of a variety of different possible values,
14406: $varname should be a request string, and the other parameters can be
14407: used to specify who and what one is asking about. Ordinarily, $cid
14408: does not need to be specified, as it is retrived from
14409: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14410: within lonuserstate::loadmap() when initializing a course, before
14411: $env{'request.course.id'} has been set, so it needs to be provided
14412: in that one case.
1.243 albertel 14413:
14414: Possible values for $varname are environment.lastname (or other item
14415: from the envirnment hash), user.name (or someother aspect about the
14416: user), resource.0.maxtries (or some other part and parameter of a
14417: resource)
1.204 albertel 14418:
14419: =item *
14420:
1.243 albertel 14421: directcondval($number) : get current value of a condition; reads from a state
14422: string
1.204 albertel 14423:
14424: =item *
14425:
1.243 albertel 14426: condval($condidx) : value of condition index based on state
1.204 albertel 14427:
14428: =item *
14429:
1.243 albertel 14430: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14431: resource's metadata, $what should be either a specific key, or either
14432: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14433: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14434:
14435: this function automatically caches all requests
1.191 harris41 14436:
14437: =item *
14438:
1.243 albertel 14439: metadata_query($query,$custom,$customshow) : make a metadata query against the
14440: network of library servers; returns file handle of where SQL and regex results
14441: will be stored for query
1.191 harris41 14442:
14443: =item *
14444:
1.1282 raeburn 14445: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14446: return symbolic list entry (all arguments optional).
14447:
14448: Args: filename is the filename (including path) for the file for which a symb
14449: is required; donotrecurse, if true will prevent calls to allowed() being made
14450: to check access status if more than one resource was found in the bighash
14451: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14452: a randompick); ignorecachednull, if true will prevent a symb of '' being
14453: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14454: cause possible symbs to be checked to determine if they are subject to content
14455: blocking, if so they will not be included as possible symbs; possibles is a
14456: ref to a hash, which, as a side effect, will be populated with all possible
14457: symbs (content blocking not tested).
14458:
1.243 albertel 14459: returns the data handle
1.191 harris41 14460:
14461: =item *
14462:
1.1190 raeburn 14463: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
14464: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 14465: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 14466: on failure, user must be in a course, as it assumes the existence of
14467: the course initial hash, and uses $env('request.course.id'}. The third
14468: arg is an optional reference to a scalar. If this arg is passed in the
14469: call to symbverify, it will be set to 1 if the symb has been set to be
14470: encrypted; otherwise it will be null.
1.191 harris41 14471:
14472: =item *
14473:
1.243 albertel 14474: symbclean($symb) : removes versions numbers from a symb, returns the
14475: cleaned symb
1.191 harris41 14476:
14477: =item *
14478:
1.243 albertel 14479: is_on_map($uri) : checks if the $uri is somewhere on the current
14480: course map, user must be in a course for it to work.
1.191 harris41 14481:
14482: =item *
14483:
1.243 albertel 14484: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 14485:
14486: =item *
14487:
1.243 albertel 14488: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14489: a random seed, all arguments are optional, if they aren't sent it uses the
14490: environment to derive them. Note: if symb isn't sent and it can't get one
14491: from &symbread it will use the current time as its return value
1.191 harris41 14492:
14493: =item *
14494:
1.243 albertel 14495: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14496: unfakeable, receipt
1.191 harris41 14497:
14498: =item *
14499:
1.620 albertel 14500: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 14501:
14502: =item *
14503:
1.243 albertel 14504: countacc($url) : count the number of accesses to a given URL
1.191 harris41 14505:
14506: =item *
14507:
1.243 albertel 14508: 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 14509:
14510: =item *
14511:
1.243 albertel 14512: 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 14513:
14514: =item *
14515:
1.243 albertel 14516: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 14517:
14518: =item *
14519:
1.243 albertel 14520: devalidate($symb) : devalidate temporary spreadsheet calculations,
14521: forcing spreadsheet to reevaluate the resource scores next time.
14522:
1.1195 raeburn 14523: =item *
14524:
1.1196 raeburn 14525: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14526: when viewing in course context.
1.1195 raeburn 14527:
1.1196 raeburn 14528: input: six args -- filename (decluttered), course number, course domain,
14529: url, symb (if registered) and group (if this is a
14530: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 14531:
1.1196 raeburn 14532: output: array of five scalars --
1.1195 raeburn 14533: $cfile -- url for file editing if editable on current server
14534: $home -- homeserver of resource (i.e., for author if published,
14535: or course if uploaded.).
14536: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 14537: $forceedit -- 1 if icon/link should be to go to edit mode
14538: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 14539:
14540: =item *
14541:
14542: is_course_upload($file,$cnum,$cdom)
14543:
14544: Used in course context to determine if current file was uploaded to
14545: the course (i.e., would be found in /userfiles/docs on the course's
14546: homeserver.
14547:
14548: input: 3 args -- filename (decluttered), course number and course domain.
14549: output: boolean -- 1 if file was uploaded.
14550:
1.243 albertel 14551: =back
14552:
14553: =head2 Storing/Retreiving Data
14554:
14555: =over 4
1.191 harris41 14556:
14557: =item *
14558:
1.1269 raeburn 14559: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14560: permanently for this url; hashref needs to be given and should be a \%hashname;
14561: the remaining args aren't required and if they aren't passed or are '' they will
14562: be derived from the env (with the exception of $laststore, which is an
14563: optional arg used when a user's submission is stored in grading).
14564: $laststore is $version=$timestamp, where $version is the most recent version
14565: number retrieved for the corresponding $symb in the $namespace db file, and
14566: $timestamp is the timestamp for that transaction (UNIX time).
14567: $laststore is currently only passed when cstore() is called by
14568: structuretags::finalize_storage().
1.191 harris41 14569:
14570: =item *
14571:
1.1269 raeburn 14572: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14573: but uses critical subroutine
1.191 harris41 14574:
14575: =item *
14576:
1.243 albertel 14577: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14578: all args are optional
1.191 harris41 14579:
14580: =item *
14581:
1.717 albertel 14582: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14583: dumps the complete (or key matching regexp) namespace into a hash
14584: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14585: normally &store()ed into
14586:
14587: $range should be either an integer '100' (give me the first 100
14588: matching records)
14589: or be two integers sperated by a - with no spaces
14590: '30-50' (give me the 30th through the 50th matching
14591: records)
14592:
14593:
14594: =item *
14595:
1.1269 raeburn 14596: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 14597: replaces a &store() version of data with a replacement set of data
14598: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 14599: reference. If $tolog is true, the transaction is logged in the courselog
14600: with an action=PUTSTORE.
1.717 albertel 14601:
14602: =item *
14603:
1.243 albertel 14604: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14605: works very similar to store/cstore, but all data is stored in a
14606: temporary location and can be reset using tmpreset, $storehash should
14607: be a hash reference, returns nothing on success
1.191 harris41 14608:
14609: =item *
14610:
1.243 albertel 14611: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14612: similar to restore, but all data is stored in a temporary location and
14613: can be reset using tmpreset. Returns a hash of values on success,
14614: error string otherwise.
1.191 harris41 14615:
14616: =item *
14617:
1.243 albertel 14618: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14619: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 14620:
14621: =item *
14622:
1.243 albertel 14623: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14624: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 14625:
14626: =item *
14627:
1.243 albertel 14628: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14629: namesp ($udom and $uname are optional)
1.191 harris41 14630:
14631: =item *
14632:
1.702 albertel 14633: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 14634: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 14635: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 14636:
1.702 albertel 14637: $range should be either an integer '100' (give me the first 100
14638: matching records)
14639: or be two integers sperated by a - with no spaces
14640: '30-50' (give me the 30th through the 50th matching
14641: records)
1.449 matthew 14642: =item *
14643:
14644: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14645: $store can be a scalar, an array reference, or if the amount to be
14646: incremented is > 1, a hash reference.
14647:
14648: ($udom and $uname are optional)
1.191 harris41 14649:
14650: =item *
14651:
1.243 albertel 14652: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14653: ($udom and $uname are optional)
1.191 harris41 14654:
14655: =item *
14656:
1.243 albertel 14657: cput($namespace,$storehash,$udom,$uname) : critical put
14658: ($udom and $uname are optional)
1.191 harris41 14659:
14660: =item *
14661:
1.748 albertel 14662: newput($namespace,$storehash,$udom,$uname) :
14663:
14664: Attempts to store the items in the $storehash, but only if they don't
14665: currently exist, if this succeeds you can be certain that you have
14666: successfully created a new key value pair in the $namespace db.
14667:
14668:
14669: Args:
14670: $namespace: name of database to store values to
14671: $storehash: hashref to store to the db
14672: $udom: (optional) domain of user containing the db
14673: $uname: (optional) name of user caontaining the db
14674:
14675: Returns:
14676: 'ok' -> succeeded in storing all keys of $storehash
14677: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14678: least <key> already existed in the db (other
14679: requested keys may also already exist)
1.967 bisitz 14680: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 14681: 'con_lost' -> unable to contact request server
14682: 'refused' -> action was not allowed by remote machine
14683:
14684:
14685: =item *
14686:
1.243 albertel 14687: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14688: reference filled in from namesp (encrypts the return communication)
14689: ($udom and $uname are optional)
1.191 harris41 14690:
14691: =item *
14692:
1.243 albertel 14693: log($udom,$name,$home,$message) : write to permanent log for user; use
14694: critical subroutine
14695:
1.806 raeburn 14696: =item *
14697:
1.860 raeburn 14698: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14699: array reference filled in from namespace found in domain level on either
14700: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 14701:
14702: =item *
14703:
1.860 raeburn 14704: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14705: domain level either on specified domain server ($uhome) or primary domain
14706: server ($udom and $uhome are optional)
1.806 raeburn 14707:
1.943 raeburn 14708: =item *
14709:
1.1240 raeburn 14710: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14711: for: authentication, language, quotas, timezone, date locale, and portal URL in
14712: the target domain.
14713:
14714: May also include additional key => value pairs for the following groups:
14715:
14716: =over
14717:
14718: =item
14719: disk quotas (MB allocated by default to portfolios and authoring spaces).
14720:
14721: =over
14722:
14723: =item defaultquota, authorquota
14724:
14725: =back
14726:
14727: =item
14728: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14729: portfolio for users).
14730:
14731: =over
14732:
14733: =item
14734: aboutme, blog, webdav, portfolio
14735:
14736: =back
14737:
14738: =item
14739: requestcourses: ability to request courses, and how requests are processed.
14740:
14741: =over
14742:
14743: =item
1.1305 raeburn 14744: official, unofficial, community, textbook, placement
1.1240 raeburn 14745:
14746: =back
14747:
14748: =item
14749: inststatus: types of institutional affiliation, and order in which they are displayed.
14750:
14751: =over
14752:
14753: =item
1.1256 raeburn 14754: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 14755:
14756: =back
14757:
14758: =item
14759: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14760: for course's uploaded content.
14761:
14762: =over
14763:
14764: =item
1.1246 raeburn 14765: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 14766: communityquota, textbookquota, placementquota
1.1240 raeburn 14767:
14768: =back
14769:
14770: =item
14771: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14772: on your servers.
14773:
14774: =over
14775:
14776: =item
14777: remotesessions, hostedsessions
14778:
14779: =back
14780:
14781: =back
14782:
14783: In cases where a domain coordinator has never used the "Set Domain Configuration"
14784: utility to create a configuration.db file on a domain's primary library server
14785: only the following domain defaults: auth_def, auth_arg_def, lang_def
14786: -- corresponding values are authentication type (internal, krb4, krb5,
14787: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
14788: will be available. Values are retrieved from cache (if current), unless the
14789: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14790: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14791:
14792: Typical usage:
1.943 raeburn 14793:
1.1240 raeburn 14794: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 14795:
1.243 albertel 14796: =back
14797:
14798: =head2 Network Status Functions
14799:
14800: =over 4
1.191 harris41 14801:
14802: =item *
14803:
1.1137 raeburn 14804: dirlist() : return directory list based on URI (first arg).
14805:
14806: Inputs: 1 required, 5 optional.
14807:
14808: =over
14809:
14810: =item
14811: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14812:
14813: =item
14814: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
14815:
14816: =item
14817: $username - username of user/course to be listed. Extracted from $uri if absent.
14818:
14819: =item
14820: $getpropath - boolean: 1 if prepend path using &propath().
14821:
14822: =item
14823: $getuserdir - boolean: 1 if prepend path for "userfiles".
14824:
14825: =item
14826: $alternateRoot - path to prepend in place of path from $uri.
14827:
14828: =back
14829:
14830: Returns: Array of up to two items.
14831:
14832: =over
14833:
14834: a reference to an array of files/subdirectories
14835:
14836: =over
14837:
14838: Each element in the array of files/subdirectories is a & separated list of
14839: item name and the result of running stat on the item. If dirlist was requested
14840: for a file instead of a directory, the item name will be ''. For a directory
14841: listing, if the item is a metadata file, the element will end &N&M
14842: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14843: default copyright set (1).
14844:
14845: =back
14846:
14847: a scalar containing error condition (if encountered).
14848:
14849: =over
14850:
14851: =item
14852: no_host (no homeserver identified for $username:$domain).
14853:
14854: =item
14855: no_such_host (server contacted for listing not identified as valid host).
14856:
14857: =item
14858: con_lost (connection to remote server failed).
14859:
14860: =item
14861: refused (invalid $username:$domain received on lond side).
14862:
14863: =item
14864: no_such_dir (directory at specified path on lond side does not exist).
14865:
14866: =item
14867: empty (directory at specified path on lond side is empty).
14868:
14869: =over
14870:
14871: This is currently not encountered because the &ls3, &ls2,
14872: &ls (_handler) routines on the lond side do not filter out
14873: . and .. from a directory listing.
14874:
14875: =back
14876:
14877: =back
14878:
14879: =back
1.191 harris41 14880:
14881: =item *
14882:
1.243 albertel 14883: spareserver() : find server with least workload from spare.tab
14884:
1.986 foxr 14885:
14886: =item *
14887:
14888: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14889: if there is no corresponding loncapa host.
14890:
1.243 albertel 14891: =back
14892:
1.986 foxr 14893:
1.243 albertel 14894: =head2 Apache Request
14895:
14896: =over 4
1.191 harris41 14897:
14898: =item *
14899:
1.243 albertel 14900: ssi($url,%hash) : server side include, does a complete request cycle on url to
14901: localhost, posts hash
14902:
14903: =back
14904:
14905: =head2 Data to String to Data
14906:
14907: =over 4
1.191 harris41 14908:
14909: =item *
14910:
1.243 albertel 14911: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14912: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14913:
14914: =item *
14915:
1.243 albertel 14916: hashref2str($hashref) : convert a hashref into a string complete with
14917: escaping and '=' and '&' separators, supports elements that are
14918: arrayrefs and hashrefs
1.191 harris41 14919:
14920: =item *
14921:
1.243 albertel 14922: arrayref2str($arrayref) : convert an arrayref into a string complete
14923: with escaping and '&' separators, supports elements that are arrayrefs
14924: and hashrefs
1.191 harris41 14925:
14926: =item *
14927:
1.243 albertel 14928: str2hash($string) : convert string to hash using unescaping and
14929: splitting on '=' and '&', supports elements that are arrayrefs and
14930: hashrefs
1.191 harris41 14931:
14932: =item *
14933:
1.243 albertel 14934: str2array($string) : convert string to hash using unescaping and
14935: splitting on '&', supports elements that are arrayrefs and hashrefs
14936:
14937: =back
14938:
14939: =head2 Logging Routines
14940:
14941:
14942: These routines allow one to make log messages in the lonnet.log and
14943: lonnet.perm logfiles.
1.191 harris41 14944:
1.1119 foxr 14945: =over 4
14946:
1.191 harris41 14947: =item *
14948:
1.243 albertel 14949: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14950:
14951: =item *
14952:
1.243 albertel 14953: logthis() : append message to the normal lonnet.log file, it gets
14954: preiodically rolled over and deleted.
1.191 harris41 14955:
14956: =item *
14957:
1.243 albertel 14958: logperm() : append a permanent message to lonnet.perm.log, this log
14959: file never gets deleted by any automated portion of the system, only
14960: messages of critical importance should go in here.
14961:
1.1119 foxr 14962:
1.243 albertel 14963: =back
14964:
14965: =head2 General File Helper Routines
14966:
14967: =over 4
1.191 harris41 14968:
14969: =item *
14970:
1.481 raeburn 14971: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14972: (a) files in /uploaded
14973: (i) If a local copy of the file exists -
14974: compares modification date of local copy with last-modified date for
14975: definitive version stored on home server for course. If local copy is
14976: stale, requests a new version from the home server and stores it.
14977: If the original has been removed from the home server, then local copy
14978: is unlinked.
14979: (ii) If local copy does not exist -
14980: requests the file from the home server and stores it.
14981:
14982: If $caller is 'uploadrep':
14983: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14984: for request for files originally uploaded via DOCS.
14985: - returns 'ok' if fresh local copy now available, -1 otherwise.
14986:
14987: Otherwise:
14988: This indicates a call from the content generation phase of the request.
14989: - returns the entire contents of the file or -1.
14990:
14991: (b) files in /res
14992: - returns the entire contents of a file or -1;
14993: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 14994:
1.712 albertel 14995:
14996: =item *
14997:
14998: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14999: reference
15000:
15001: returns either a stat() list of data about the file or an empty list
15002: if the file doesn't exist or couldn't find out about it (connection
15003: problems or user unknown)
15004:
1.191 harris41 15005: =item *
15006:
1.243 albertel 15007: filelocation($dir,$file) : returns file system location of a file
15008: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15009: directory that relative $file lookups are to looked in ($dir of /a/dir
15010: and a file of ../bob will become /a/bob)
1.191 harris41 15011:
15012: =item *
15013:
15014: hreflocation($dir,$file) : returns file system location or a URL; same as
15015: filelocation except for hrefs
15016:
15017: =item *
15018:
1.1261 raeburn 15019: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15020: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 15021:
1.243 albertel 15022: =back
15023:
1.608 albertel 15024: =head2 Usererfile file routines (/uploaded*)
15025:
15026: =over 4
15027:
15028: =item *
15029:
15030: userfileupload(): main rotine for putting a file in a user or course's
15031: filespace, arguments are,
15032:
1.620 albertel 15033: formname - required - this is the name of the element in $env where the
1.608 albertel 15034: filename, and the contents of the file to create/modifed exist
1.620 albertel 15035: the filename is in $env{'form.'.$formname.'.filename'} and the
15036: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 15037: context - if coursedoc, store the file in the course of the active role
15038: of the current user;
15039: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15040: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 15041: subdir - required - subdirectory to put the file in under ../userfiles/
15042: if undefined, it will be placed in "unknown"
15043:
15044: (This routine calls clean_filename() to remove any dangerous
15045: characters from the filename, and then calls finuserfileupload() to
15046: complete the transaction)
15047:
15048: returns either the url of the uploaded file (/uploaded/....) if successful
15049: and /adm/notfound.html if unsuccessful
15050:
15051: =item *
15052:
15053: clean_filename(): routine for cleaing a filename up for storage in
15054: userfile space, argument is:
15055:
15056: filename - proposed filename
15057:
15058: returns: the new clean filename
15059:
15060: =item *
15061:
1.1090 raeburn 15062: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 15063: userspace, probably shouldn't be called directly
15064:
15065: docuname: username or courseid of destination for the file
15066: docudom: domain of user/course of destination for the file
15067: formname: same as for userfileupload()
1.1090 raeburn 15068: fname: filename (including subdirectories) for the file
15069: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15070: allfiles: reference to hash used to store objects found by parser
15071: codebase: reference to hash used for codebases of java objects found by parser
15072: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15073: thumbheight: height (pixels) of thumbnail to be created for uploaded image
15074: resizewidth: width to be used to resize image using resizeImage from ImageMagick
15075: resizeheight: height to be used to resize image using resizeImage from ImageMagick
15076: context: if 'overwrite', will move the uploaded file from its temporary location to
15077: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 15078: mimetype: reference to scalar to accommodate mime type determined
15079: from File::MMagic if $parser = parse.
1.608 albertel 15080:
15081: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 15082: and /adm/notfound.html if unsuccessful (or an error message if context
15083: was 'overwrite').
15084:
1.608 albertel 15085:
15086: =item *
15087:
15088: renameuserfile(): renames an existing userfile to a new name
15089:
15090: Args:
15091: docuname: username or courseid of destination for the file
15092: docudom: domain of user/course of destination for the file
15093: old: current file name (including any subdirs under userfiles)
15094: new: desired file name (including any subdirs under userfiles)
15095:
15096: =item *
15097:
15098: mkdiruserfile(): creates a directory is a userfiles dir
15099:
15100: Args:
15101: docuname: username or courseid of destination for the file
15102: docudom: domain of user/course of destination for the file
15103: dir: dir to create (including any subdirs under userfiles)
15104:
15105: =item *
15106:
15107: removeuserfile(): removes a file that exists in userfiles
15108:
15109: Args:
15110: docuname: username or courseid of destination for the file
15111: docudom: domain of user/course of destination for the file
15112: fname: filname to delete (including any subdirs under userfiles)
15113:
15114: =item *
15115:
15116: removeuploadedurl(): convience function for removeuserfile()
15117:
15118: Args:
15119: url: a full /uploaded/... url to delete
15120:
1.747 albertel 15121: =item *
15122:
15123: get_portfile_permissions():
15124: Args:
15125: domain: domain of user or course contain the portfolio files
15126: user: name of user or num of course contain the portfolio files
15127: Returns:
15128: hashref of a dump of the proper file_permissions.db
15129:
15130:
15131: =item *
15132:
15133: get_access_controls():
15134:
15135: Args:
15136: current_permissions: the hash ref returned from get_portfile_permissions()
15137: group: (optional) the group you want the files associated with
15138: file: (optional) the file you want access info on
15139:
15140: Returns:
1.749 raeburn 15141: a hash (keys are file names) of hashes containing
15142: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15143: values are XML containing access control settings (see below)
1.747 albertel 15144:
15145: Internal notes:
15146:
1.749 raeburn 15147: access controls are stored in file_permissions.db as key=value pairs.
15148: key -> path to file/file_name\0uniqueID:scope_end_start
15149: where scope -> public,guest,course,group,domains or users.
15150: end -> UNIX time for end of access (0 -> no end date)
15151: start -> UNIX time for start of access
15152:
15153: value -> XML description of access control
15154: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15155: <start></start>
15156: <end></end>
15157:
15158: <password></password> for scope type = guest
15159:
15160: <domain></domain> for scope type = course or group
15161: <number></number>
15162: <roles id="">
15163: <role></role>
15164: <access></access>
15165: <section></section>
15166: <group></group>
15167: </roles>
15168:
15169: <dom></dom> for scope type = domains
15170:
15171: <users> for scope type = users
15172: <user>
15173: <uname></uname>
15174: <udom></udom>
15175: </user>
15176: </users>
15177: </scope>
15178:
15179: Access data is also aggregated for each file in an additional key=value pair:
15180: key -> path to file/file_name\0accesscontrol
15181: value -> reference to hash
15182: hash contains key = value pairs
15183: where key = uniqueID:scope_end_start
15184: value = UNIX time record was last updated
15185:
15186: Used to improve speed of look-ups of access controls for each file.
15187:
15188: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15189:
1.1198 raeburn 15190: =item *
15191:
1.749 raeburn 15192: modify_access_controls():
15193:
15194: Modifies access controls for a portfolio file
15195: Args
15196: 1. file name
15197: 2. reference to hash of required changes,
15198: 3. domain
15199: 4. username
15200: where domain,username are the domain of the portfolio owner
15201: (either a user or a course)
15202:
15203: Returns:
15204: 1. result of additions or updates ('ok' or 'error', with error message).
15205: 2. result of deletions ('ok' or 'error', with error message).
15206: 3. reference to hash of any new or updated access controls.
15207: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15208: key = integer (inbound ID)
1.1198 raeburn 15209: value = uniqueID
15210:
15211: =item *
15212:
15213: get_timebased_id():
15214:
15215: Attempts to get a unique timestamp-based suffix for use with items added to a
15216: course via the Course Editor (e.g., folders, composite pages,
15217: group bulletin boards).
15218:
15219: Args: (first three required; six others optional)
15220:
15221: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15222: docssequence, or name of group
15223:
15224: 2. keyid (alphanumeric): name of temporary locking key in hash,
15225: e.g., num, boardids
15226:
15227: 3. namespace: name of gdbm file used to store suffixes already assigned;
15228: file will be named nohist_namespace.db
15229:
15230: 4. cdom: domain of course; default is current course domain from %env
15231:
15232: 5. cnum: course number; default is current course number from %env
15233:
15234: 6. idtype: set to concat if an additional digit is to be appended to the
15235: unix timestamp to form the suffix, if the plain timestamp is already
15236: in use. Default is to not do this, but simply increment the unix
15237: timestamp by 1 until a unique key is obtained.
15238:
15239: 7. who: holder of locking key; defaults to user:domain for user.
15240:
15241: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15242: retrying); default is 3.
15243:
15244: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15245:
15246: Returns:
15247:
15248: 1. suffix obtained (numeric)
15249:
15250: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15251:
15252: 3. error: contains (localized) error message if an error occurred.
15253:
1.747 albertel 15254:
1.608 albertel 15255: =back
15256:
1.243 albertel 15257: =head2 HTTP Helper Routines
15258:
15259: =over 4
15260:
1.191 harris41 15261: =item *
15262:
15263: escape() : unpack non-word characters into CGI-compatible hex codes
15264:
15265: =item *
15266:
15267: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15268:
1.243 albertel 15269: =back
15270:
15271: =head1 PRIVATE SUBROUTINES
15272:
15273: =head2 Underlying communication routines (Shouldn't call)
15274:
15275: =over 4
15276:
15277: =item *
15278:
15279: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15280:
15281: =item *
15282:
15283: reply() : uses subreply to send a message to remote machine, logs all failures
15284:
15285: =item *
15286:
15287: critical() : passes a critical message to another server; if cannot
15288: get through then place message in connection buffer directory and
15289: returns con_delayed, if incapable of saving message, returns
15290: con_failed
15291:
15292: =item *
15293:
15294: reconlonc() : tries to reconnect lonc client processes.
15295:
15296: =back
15297:
15298: =head2 Resource Access Logging
15299:
15300: =over 4
15301:
15302: =item *
15303:
15304: flushcourselogs() : flush (save) buffer logs and access logs
15305:
15306: =item *
15307:
15308: courselog($what) : save message for course in hash
15309:
15310: =item *
15311:
15312: courseacclog($what) : save message for course using &courselog(). Perform
15313: special processing for specific resource types (problems, exams, quizzes, etc).
15314:
1.191 harris41 15315: =item *
15316:
15317: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15318: as a PerlChildExitHandler
1.243 albertel 15319:
15320: =back
15321:
15322: =head2 Other
15323:
15324: =over 4
15325:
15326: =item *
15327:
15328: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 15329:
15330: =back
15331:
15332: =cut
1.877 foxr 15333:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>