Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1344
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1344 ! raeburn 4: # $Id: lonnet.pm,v 1.1343 2017/05/08 14:20:26 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.1344 ! raeburn 1848: my $rep;
! 1849: if ($namespace =~ /^enc/) {
! 1850: $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
! 1851: } else {
! 1852: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
! 1853: }
1.866 raeburn 1854: my %returnhash;
1.875 albertel 1855: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1856: return %returnhash;
1857: }
1.806 raeburn 1858: my @pairs=split(/\&/,$rep);
1859: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1860: return @pairs;
1861: }
1862: my $i=0;
1863: foreach my $item (@$storearr) {
1864: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1865: $i++;
1866: }
1867: return %returnhash;
1868: } else {
1.880 banghart 1869: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1870: }
1871: }
1872:
1873: # -------------------------------------------- put items in domain db files
1874:
1875: sub put_dom {
1.860 raeburn 1876: my ($namespace,$storehash,$udom,$uhome)=@_;
1877: if (!$udom) {
1878: $udom=$env{'user.domain'};
1879: if (defined(&domain($udom,'primary'))) {
1880: $uhome=&domain($udom,'primary');
1881: } else {
1.874 albertel 1882: undef($uhome);
1.860 raeburn 1883: }
1884: } else {
1885: if (!$uhome) {
1886: if (defined(&domain($udom,'primary'))) {
1887: $uhome=&domain($udom,'primary');
1888: }
1889: }
1890: }
1891: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1892: my $items='';
1893: foreach my $item (keys(%$storehash)) {
1894: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1895: }
1896: $items=~s/\&$//;
1.1344 ! raeburn 1897: if ($namespace =~ /^enc/) {
! 1898: return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
! 1899: } else {
! 1900: return &reply("putdom:$udom:$namespace:$items",$uhome);
! 1901: }
1.806 raeburn 1902: } else {
1.860 raeburn 1903: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1904: }
1905: }
1906:
1.1023 raeburn 1907: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1908: sub newput_dom {
1.1023 raeburn 1909: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1910: my $result;
1911: if (!$udom) {
1912: $udom=$env{'user.domain'};
1913: }
1.1023 raeburn 1914: if ($udom) {
1915: my $uname = &get_domainconfiguser($udom);
1916: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1917: }
1918: return $result;
1919: }
1920:
1.1023 raeburn 1921: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1922: sub del_dom {
1.1023 raeburn 1923: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1924: if (ref($storearr) eq 'ARRAY') {
1925: if (!$udom) {
1926: $udom=$env{'user.domain'};
1927: }
1.1023 raeburn 1928: if ($udom) {
1929: my $uname = &get_domainconfiguser($udom);
1930: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1931: }
1932: }
1933: }
1934:
1.1023 raeburn 1935: # ----------------------------------construct domainconfig user for a domain
1936: sub get_domainconfiguser {
1937: my ($udom) = @_;
1938: return $udom.'-domainconfig';
1939: }
1940:
1.837 raeburn 1941: sub retrieve_inst_usertypes {
1942: my ($udom) = @_;
1943: my (%returnhash,@order);
1.989 raeburn 1944: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1945: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1946: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 1947: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1948: } else {
1949: if (defined(&domain($udom,'primary'))) {
1950: my $uhome=&domain($udom,'primary');
1951: my $rep=&reply("inst_usertypes:$udom",$uhome);
1952: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 1953: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1954: return (\%returnhash,\@order);
1955: }
1956: my ($hashitems,$orderitems) = split(/:/,$rep);
1957: my @pairs=split(/\&/,$hashitems);
1958: foreach my $item (@pairs) {
1959: my ($key,$value)=split(/=/,$item,2);
1960: $key = &unescape($key);
1961: next if ($key =~ /^error: 2 /);
1962: $returnhash{$key}=&thaw_unescape($value);
1963: }
1964: my @esc_order = split(/\&/,$orderitems);
1965: foreach my $item (@esc_order) {
1966: push(@order,&unescape($item));
1967: }
1968: } else {
1.1256 raeburn 1969: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1970: }
1.1256 raeburn 1971: return (\%returnhash,\@order);
1.837 raeburn 1972: }
1973: }
1974:
1.868 raeburn 1975: sub is_domainimage {
1976: my ($url) = @_;
1.1306 raeburn 1977: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868 raeburn 1978: if (&domain($1) ne '') {
1979: return '1';
1980: }
1981: }
1982: return;
1983: }
1984:
1.899 raeburn 1985: sub inst_directory_query {
1986: my ($srch) = @_;
1987: my $udom = $srch->{'srchdomain'};
1988: my %results;
1989: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1990: my $outcome;
1.899 raeburn 1991: if ($homeserver ne '') {
1.904 albertel 1992: my $queryid=&reply("querysend:instdirsearch:".
1993: &escape($srch->{'srchby'}).':'.
1994: &escape($srch->{'srchterm'}).':'.
1995: &escape($srch->{'srchtype'}),$homeserver);
1996: my $host=&hostname($homeserver);
1997: if ($queryid !~/^\Q$host\E\_/) {
1.1343 raeburn 1998: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904 albertel 1999: return;
2000: }
2001: my $response = &get_query_reply($queryid);
2002: my $maxtries = 5;
2003: my $tries = 1;
2004: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2005: $response = &get_query_reply($queryid);
2006: $tries ++;
2007: }
2008:
2009: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 2010: if ($response eq 'unavailable') {
2011: $outcome = $response;
2012: } else {
2013: $outcome = 'ok';
2014: my @matches = split(/\n/,$response);
2015: foreach my $match (@matches) {
2016: my ($key,$value) = split(/=/,$match);
2017: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2018: }
1.899 raeburn 2019: }
2020: }
2021: }
1.909 raeburn 2022: return ($outcome,%results);
1.899 raeburn 2023: }
2024:
2025: sub usersearch {
2026: my ($srch) = @_;
2027: my $dom = $srch->{'srchdomain'};
2028: my %results;
2029: my %libserv = &all_library();
2030: my $query = 'usersearch';
2031: foreach my $tryserver (keys(%libserv)) {
2032: if (&host_domain($tryserver) eq $dom) {
2033: my $host=&hostname($tryserver);
2034: my $queryid=
1.911 raeburn 2035: &reply("querysend:".&escape($query).':'.
2036: &escape($srch->{'srchby'}).':'.
1.899 raeburn 2037: &escape($srch->{'srchtype'}).':'.
2038: &escape($srch->{'srchterm'}),$tryserver);
2039: if ($queryid !~/^\Q$host\E\_/) {
2040: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 2041: next;
1.899 raeburn 2042: }
2043: my $reply = &get_query_reply($queryid);
2044: my $maxtries = 1;
2045: my $tries = 1;
2046: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2047: $reply = &get_query_reply($queryid);
2048: $tries ++;
2049: }
2050: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2051: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2052: } else {
1.911 raeburn 2053: my @matches;
2054: if ($reply =~ /\n/) {
2055: @matches = split(/\n/,$reply);
2056: } else {
2057: @matches = split(/\&/,$reply);
2058: }
1.899 raeburn 2059: foreach my $match (@matches) {
2060: my ($uname,$udom,%userhash);
1.911 raeburn 2061: foreach my $entry (split(/:/,$match)) {
2062: my ($key,$value) =
2063: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 2064: $userhash{$key} = $value;
2065: if ($key eq 'username') {
2066: $uname = $value;
2067: } elsif ($key eq 'domain') {
2068: $udom = $value;
1.911 raeburn 2069: }
1.899 raeburn 2070: }
2071: $results{$uname.':'.$udom} = \%userhash;
2072: }
2073: }
2074: }
2075: }
2076: return %results;
2077: }
2078:
1.912 raeburn 2079: sub get_instuser {
2080: my ($udom,$uname,$id) = @_;
2081: my $homeserver = &domain($udom,'primary');
2082: my ($outcome,%results);
2083: if ($homeserver ne '') {
2084: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2085: &escape($id).':'.&escape($udom),$homeserver);
2086: my $host=&hostname($homeserver);
2087: if ($queryid !~/^\Q$host\E\_/) {
2088: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2089: return;
2090: }
2091: my $response = &get_query_reply($queryid);
2092: my $maxtries = 5;
2093: my $tries = 1;
2094: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2095: $response = &get_query_reply($queryid);
2096: $tries ++;
2097: }
2098: if (!&error($response) && $response ne 'refused') {
2099: if ($response eq 'unavailable') {
2100: $outcome = $response;
2101: } else {
2102: $outcome = 'ok';
2103: my @matches = split(/\n/,$response);
2104: foreach my $match (@matches) {
2105: my ($key,$value) = split(/=/,$match);
2106: $results{&unescape($key)} = &thaw_unescape($value);
2107: }
2108: }
2109: }
2110: }
2111: my %userinfo;
2112: if (ref($results{$uname}) eq 'HASH') {
2113: %userinfo = %{$results{$uname}};
2114: }
2115: return ($outcome,%userinfo);
2116: }
2117:
1.1290 raeburn 2118: sub get_multiple_instusers {
2119: my ($udom,$users,$caller) = @_;
2120: my ($outcome,$results);
2121: if (ref($users) eq 'HASH') {
2122: my $count = keys(%{$users});
2123: my $requested = &freeze_escape($users);
2124: my $homeserver = &domain($udom,'primary');
2125: if ($homeserver ne '') {
2126: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2127: my $host=&hostname($homeserver);
2128: if ($queryid !~/^\Q$host\E\_/) {
2129: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2130: ' for host: '.$homeserver.'in domain '.$udom);
2131: return ($outcome,$results);
2132: }
2133: my $response = &get_query_reply($queryid);
2134: my $maxtries = 5;
2135: if ($count > 100) {
2136: $maxtries = 1+int($count/20);
2137: }
2138: my $tries = 1;
2139: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2140: $response = &get_query_reply($queryid);
2141: $tries ++;
2142: }
2143: if ($response eq '') {
2144: $results = {};
2145: foreach my $key (keys(%{$users})) {
2146: my ($uname,$id);
2147: if ($caller eq 'id') {
2148: $id = $key;
2149: } else {
2150: $uname = $key;
2151: }
2152: my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291 raeburn 2153: $outcome = $resp;
1.1290 raeburn 2154: if ($resp eq 'ok') {
2155: %{$results} = (%{$results}, %info);
2156: } else {
2157: last;
2158: }
2159: }
2160: } elsif(!&error($response) && ($response ne 'refused')) {
2161: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2162: $outcome = $response;
2163: } else {
1.1291 raeburn 2164: ($outcome,my $userdata) = split(/=/,$response,2);
1.1290 raeburn 2165: if ($outcome eq 'ok') {
2166: $results = &thaw_unescape($userdata);
2167: }
2168: }
2169: }
2170: }
2171: }
2172: return ($outcome,$results);
2173: }
2174:
1.912 raeburn 2175: sub inst_rulecheck {
1.923 raeburn 2176: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 2177: my %returnhash;
2178: if ($udom ne '') {
2179: if (ref($rules) eq 'ARRAY') {
2180: @{$rules} = map {&escape($_);} (@{$rules});
2181: my $rulestr = join(':',@{$rules});
2182: my $homeserver=&domain($udom,'primary');
2183: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2184: my $response;
2185: if ($item eq 'username') {
2186: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2187: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 2188: $homeserver));
1.923 raeburn 2189: } elsif ($item eq 'id') {
2190: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2191: ':'.&escape($id).':'.$rulestr,
2192: $homeserver));
1.945 raeburn 2193: } elsif ($item eq 'selfcreate') {
2194: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 2195: &escape($udom).':'.&escape($uname).
2196: ':'.$rulestr,$homeserver));
1.923 raeburn 2197: }
1.912 raeburn 2198: if ($response ne 'refused') {
2199: my @pairs=split(/\&/,$response);
2200: foreach my $item (@pairs) {
2201: my ($key,$value)=split(/=/,$item,2);
2202: $key = &unescape($key);
2203: next if ($key =~ /^error: 2 /);
2204: $returnhash{$key}=&thaw_unescape($value);
2205: }
2206: }
2207: }
2208: }
2209: }
2210: return %returnhash;
2211: }
2212:
2213: sub inst_userrules {
1.923 raeburn 2214: my ($udom,$check) = @_;
1.912 raeburn 2215: my (%ruleshash,@ruleorder);
2216: if ($udom ne '') {
2217: my $homeserver=&domain($udom,'primary');
2218: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 2219: my $response;
2220: if ($check eq 'id') {
2221: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 2222: $homeserver);
1.943 raeburn 2223: } elsif ($check eq 'email') {
2224: $response=&reply('instemailrules:'.&escape($udom),
2225: $homeserver);
1.923 raeburn 2226: } else {
2227: $response=&reply('instuserrules:'.&escape($udom),
2228: $homeserver);
2229: }
1.912 raeburn 2230: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 2231: ($response ne 'unknown_cmd') &&
1.912 raeburn 2232: ($response ne 'no_such_host')) {
2233: my ($hashitems,$orderitems) = split(/:/,$response);
2234: my @pairs=split(/\&/,$hashitems);
2235: foreach my $item (@pairs) {
2236: my ($key,$value)=split(/=/,$item,2);
2237: $key = &unescape($key);
2238: next if ($key =~ /^error: 2 /);
2239: $ruleshash{$key}=&thaw_unescape($value);
2240: }
2241: my @esc_order = split(/\&/,$orderitems);
2242: foreach my $item (@esc_order) {
2243: push(@ruleorder,&unescape($item));
2244: }
2245: }
2246: }
2247: }
2248: return (\%ruleshash,\@ruleorder);
2249: }
2250:
1.976 raeburn 2251: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 2252:
2253: sub get_domain_defaults {
1.1240 raeburn 2254: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 2255: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2256: my $cachetime = 60*60*24;
1.1240 raeburn 2257: unless ($ignore_cache) {
2258: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2259: if (defined($cached)) {
2260: if (ref($result) eq 'HASH') {
2261: return %{$result};
2262: }
1.943 raeburn 2263: }
2264: }
2265: my %domdefaults;
2266: my %domconfig =
1.989 raeburn 2267: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2268: 'requestcourses','inststatus',
1.1183 raeburn 2269: 'coursedefaults','usersessions',
1.1258 raeburn 2270: 'requestauthor','selfenrollment',
1.1320 raeburn 2271: 'coursecategories','ssl','autoenroll',
1.1332 raeburn 2272: 'trust','helpsettings'],$domain);
1.1305 raeburn 2273: my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943 raeburn 2274: if (ref($domconfig{'defaults'}) eq 'HASH') {
2275: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2276: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2277: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2278: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2279: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2280: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340 raeburn 2281: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2282: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2283: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943 raeburn 2284: } else {
2285: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2286: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2287: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2288: }
1.976 raeburn 2289: if (ref($domconfig{'quotas'}) eq 'HASH') {
2290: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2291: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2292: } else {
2293: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2294: }
1.1177 raeburn 2295: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2296: foreach my $item (@usertools) {
2297: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2298: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2299: }
2300: }
1.1229 raeburn 2301: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2302: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2303: }
1.976 raeburn 2304: }
1.985 raeburn 2305: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305 raeburn 2306: foreach my $item ('official','unofficial','community','textbook','placement') {
1.985 raeburn 2307: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2308: }
2309: }
1.1183 raeburn 2310: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2311: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2312: }
1.989 raeburn 2313: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2314: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2315: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2316: }
2317: }
1.1047 raeburn 2318: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2319: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277 raeburn 2320: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2321: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2322: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2323: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2324: }
1.1254 raeburn 2325: foreach my $type (@coursetypes) {
2326: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2327: unless ($type eq 'community') {
2328: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2329: }
2330: }
2331: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2332: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2333: }
1.1277 raeburn 2334: if ($domdefaults{'postsubmit'} eq 'on') {
2335: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2336: $domdefaults{$type.'postsubtimeout'} =
2337: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2338: }
2339: }
1.1230 raeburn 2340: }
1.1286 raeburn 2341: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2342: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2343: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2344: if (@clonecodes) {
2345: $domdefaults{'canclone'} = join('+',@clonecodes);
2346: }
2347: }
2348: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2349: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2350: }
1.1047 raeburn 2351: }
1.1073 raeburn 2352: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2353: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2354: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2355: }
2356: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2357: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2358: }
1.1279 raeburn 2359: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2360: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2361: }
1.1073 raeburn 2362: }
1.1254 raeburn 2363: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2364: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2365: my @settings = ('types','registered','enroll_dates','access_dates','section',
2366: 'approval','limit');
2367: foreach my $type (@coursetypes) {
2368: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2369: my @mgrdc = ();
2370: foreach my $item (@settings) {
2371: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2372: push(@mgrdc,$item);
2373: }
2374: }
2375: if (@mgrdc) {
2376: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2377: }
2378: }
2379: }
2380: }
2381: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2382: foreach my $type (@coursetypes) {
2383: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2384: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2385: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2386: }
2387: }
2388: }
2389: }
2390: }
1.1258 raeburn 2391: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2392: $domdefaults{'catauth'} = 'std';
2393: $domdefaults{'catunauth'} = 'std';
2394: if ($domconfig{'coursecategories'}{'auth'}) {
2395: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2396: }
2397: if ($domconfig{'coursecategories'}{'unauth'}) {
2398: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2399: }
2400: }
1.1315 raeburn 2401: if (ref($domconfig{'ssl'}) eq 'HASH') {
2402: if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
2403: $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
2404: }
1.1338 raeburn 2405: if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
2406: $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
2407: }
2408: if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
2409: $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315 raeburn 2410: }
2411: }
1.1320 raeburn 2412: if (ref($domconfig{'trust'}) eq 'HASH') {
2413: my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
2414: foreach my $prefix (@prefixes) {
2415: if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
2416: $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
2417: }
2418: }
2419: }
1.1314 raeburn 2420: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2421: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2422: }
1.1332 raeburn 2423: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2424: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2425: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2426: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2427: }
2428: }
1.1219 raeburn 2429: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2430: return %domdefaults;
2431: }
2432:
1.1311 raeburn 2433: sub course_portal_url {
2434: my ($cnum,$cdom) = @_;
2435: my $chome = &homeserver($cnum,$cdom);
2436: my $hostname = &hostname($chome);
2437: my $protocol = $protocol{$chome};
2438: $protocol = 'http' if ($protocol ne 'https');
2439: my %domdefaults = &get_domain_defaults($cdom);
2440: my $firsturl;
2441: if ($domdefaults{'portal_def'}) {
2442: $firsturl = $domdefaults{'portal_def'};
2443: } else {
2444: $firsturl = $protocol.'://'.$hostname;
2445: }
2446: return $firsturl;
2447: }
2448:
1.344 www 2449: # --------------------------------------------------- Assign a key to a student
2450:
2451: sub assign_access_key {
1.364 www 2452: #
2453: # a valid key looks like uname:udom#comments
2454: # comments are being appended
2455: #
1.498 www 2456: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2457: $kdom=
1.620 albertel 2458: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2459: $knum=
1.620 albertel 2460: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2461: $cdom=
1.620 albertel 2462: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2463: $cnum=
1.620 albertel 2464: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2465: $udom=$env{'user.name'} unless (defined($udom));
2466: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2467: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2468: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2469: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2470: # assigned to this person
2471: # - this should not happen,
1.345 www 2472: # unless something went wrong
2473: # the first time around
2474: # ready to assign
1.364 www 2475: $logentry=$1.'; '.$logentry;
1.496 www 2476: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2477: $kdom,$knum) eq 'ok') {
1.345 www 2478: # key now belongs to user
1.346 www 2479: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2480: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2481: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2482: return 'ok';
2483: } else {
2484: return
2485: 'error: Count not permanently assign key, will need to be re-entered later.';
2486: }
2487: } else {
2488: return 'error: Could not assign key, try again later.';
2489: }
1.364 www 2490: } elsif (!$existing{$ckey}) {
1.345 www 2491: # the key does not exist
2492: return 'error: The key does not exist';
2493: } else {
2494: # the key is somebody else's
2495: return 'error: The key is already in use';
2496: }
1.344 www 2497: }
2498:
1.364 www 2499: # ------------------------------------------ put an additional comment on a key
2500:
2501: sub comment_access_key {
2502: #
2503: # a valid key looks like uname:udom#comments
2504: # comments are being appended
2505: #
2506: my ($ckey,$cdom,$cnum,$logentry)=@_;
2507: $cdom=
1.620 albertel 2508: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2509: $cnum=
1.620 albertel 2510: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2511: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2512: if ($existing{$ckey}) {
2513: $existing{$ckey}.='; '.$logentry;
2514: # ready to assign
1.367 www 2515: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2516: $cdom,$cnum) eq 'ok') {
2517: return 'ok';
2518: } else {
2519: return 'error: Count not store comment.';
2520: }
2521: } else {
2522: # the key does not exist
2523: return 'error: The key does not exist';
2524: }
2525: }
2526:
1.344 www 2527: # ------------------------------------------------------ Generate a set of keys
2528:
2529: sub generate_access_keys {
1.364 www 2530: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2531: $cdom=
1.620 albertel 2532: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2533: $cnum=
1.620 albertel 2534: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2535: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2536: unless (($cdom) && ($cnum)) { return 0; }
2537: if ($number>10000) { return 0; }
2538: sleep(2); # make sure don't get same seed twice
2539: srand(time()^($$+($$<<15))); # from "Programming Perl"
2540: my $total=0;
2541: for (my $i=1;$i<=$number;$i++) {
2542: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2543: sprintf("%lx",int(100000*rand)).'-'.
2544: sprintf("%lx",int(100000*rand));
2545: $newkey=~s/1/g/g; # folks mix up 1 and l
2546: $newkey=~s/0/h/g; # and also 0 and O
2547: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2548: if ($existing{$newkey}) {
2549: $i--;
2550: } else {
1.364 www 2551: if (&put('accesskeys',
2552: { $newkey => '# generated '.localtime().
1.620 albertel 2553: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2554: '; '.$logentry },
2555: $cdom,$cnum) eq 'ok') {
1.344 www 2556: $total++;
2557: }
2558: }
2559: }
1.620 albertel 2560: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2561: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2562: return $total;
2563: }
2564:
2565: # ------------------------------------------------------- Validate an accesskey
2566:
2567: sub validate_access_key {
2568: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2569: $cdom=
1.620 albertel 2570: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2571: $cnum=
1.620 albertel 2572: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2573: $udom=$env{'user.domain'} unless (defined($udom));
2574: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2575: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2576: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2577: }
2578:
2579: # ------------------------------------- Find the section of student in a course
1.652 albertel 2580: sub devalidate_getsection_cache {
2581: my ($udom,$unam,$courseid)=@_;
2582: my $hashid="$udom:$unam:$courseid";
2583: &devalidate_cache_new('getsection',$hashid);
2584: }
1.298 matthew 2585:
1.815 albertel 2586: sub courseid_to_courseurl {
2587: my ($courseid) = @_;
2588: #already url style courseid
2589: return $courseid if ($courseid =~ m{^/});
2590:
2591: if (exists($env{'course.'.$courseid.'.num'})) {
2592: my $cnum = $env{'course.'.$courseid.'.num'};
2593: my $cdom = $env{'course.'.$courseid.'.domain'};
2594: return "/$cdom/$cnum";
2595: }
2596:
2597: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2598: if (exists($courseinfo{'num'})) {
2599: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2600: }
2601:
2602: return undef;
2603: }
2604:
1.298 matthew 2605: sub getsection {
2606: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2607: my $cachetime=1800;
1.551 albertel 2608:
2609: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2610: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2611: if (defined($cached)) { return $result; }
2612:
1.298 matthew 2613: my %Pending;
2614: my %Expired;
2615: #
2616: # Each role can either have not started yet (pending), be active,
2617: # or have expired.
2618: #
2619: # If there is an active role, we are done.
2620: #
2621: # If there is more than one role which has not started yet,
2622: # choose the one which will start sooner
2623: # If there is one role which has not started yet, return it.
2624: #
2625: # If there is more than one expired role, choose the one which ended last.
2626: # If there is a role which has expired, return it.
2627: #
1.815 albertel 2628: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2629: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2630: foreach my $key (keys(%roleshash)) {
1.479 albertel 2631: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2632: my $section=$1;
2633: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2634: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2635: my $now=time;
1.548 albertel 2636: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2637: $Expired{$end}=$section;
2638: next;
2639: }
1.548 albertel 2640: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2641: $Pending{$start}=$section;
2642: next;
2643: }
1.599 albertel 2644: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2645: }
2646: #
2647: # Presumedly there will be few matching roles from the above
2648: # loop and the sorting time will be negligible.
2649: if (scalar(keys(%Pending))) {
2650: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2651: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2652: }
2653: if (scalar(keys(%Expired))) {
2654: my @sorted = sort {$a <=> $b} keys(%Expired);
2655: my $time = pop(@sorted);
1.599 albertel 2656: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2657: }
1.599 albertel 2658: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2659: }
1.70 www 2660:
1.599 albertel 2661: sub save_cache {
2662: &purge_remembered();
1.722 albertel 2663: #&Apache::loncommon::validate_page();
1.620 albertel 2664: undef(%env);
1.780 albertel 2665: undef($env_loaded);
1.599 albertel 2666: }
1.452 albertel 2667:
1.599 albertel 2668: my $to_remember=-1;
2669: my %remembered;
2670: my %accessed;
2671: my $kicks=0;
2672: my $hits=0;
1.849 albertel 2673: sub make_key {
2674: my ($name,$id) = @_;
1.872 albertel 2675: if (length($id) > 65
2676: && length(&escape($id)) > 200) {
2677: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2678: }
1.849 albertel 2679: return &escape($name.':'.$id);
2680: }
2681:
1.599 albertel 2682: sub devalidate_cache_new {
2683: my ($name,$id,$debug) = @_;
2684: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319 damieng 2685: my $remembered_id=$name.':'.$id;
1.849 albertel 2686: $id=&make_key($name,$id);
1.599 albertel 2687: $memcache->delete($id);
1.1319 damieng 2688: delete($remembered{$remembered_id});
2689: delete($accessed{$remembered_id});
1.599 albertel 2690: }
2691:
2692: sub is_cached_new {
2693: my ($name,$id,$debug) = @_;
1.1319 damieng 2694: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
2695: if (exists($remembered{$remembered_id})) {
2696: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2697: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2698: $hits++;
1.1319 damieng 2699: return ($remembered{$remembered_id},1);
1.599 albertel 2700: }
1.1319 damieng 2701: $id=&make_key($name,$id);
1.599 albertel 2702: my $value = $memcache->get($id);
2703: if (!(defined($value))) {
2704: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2705: return (undef,undef);
1.416 albertel 2706: }
1.599 albertel 2707: if ($value eq '__undef__') {
2708: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2709: $value=undef;
2710: }
1.1319 damieng 2711: &make_room($remembered_id,$value,$debug);
1.599 albertel 2712: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2713: return ($value,1);
2714: }
2715:
2716: sub do_cache_new {
2717: my ($name,$id,$value,$time,$debug) = @_;
1.1319 damieng 2718: my $remembered_id=$name.':'.$id;
1.849 albertel 2719: $id=&make_key($name,$id);
1.599 albertel 2720: my $setvalue=$value;
2721: if (!defined($setvalue)) {
2722: $setvalue='__undef__';
2723: }
1.623 albertel 2724: if (!defined($time) ) {
2725: $time=600;
2726: }
1.599 albertel 2727: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2728: my $result = $memcache->set($id,$setvalue,$time);
2729: if (! $result) {
1.872 albertel 2730: &logthis("caching of id -> $id failed");
1.910 albertel 2731: $memcache->disconnect_all();
1.872 albertel 2732: }
1.600 albertel 2733: # need to make a copy of $value
1.1319 damieng 2734: &make_room($remembered_id,$value,$debug);
1.599 albertel 2735: return $value;
2736: }
2737:
2738: sub make_room {
1.1319 damieng 2739: my ($remembered_id,$value,$debug)=@_;
1.919 albertel 2740:
1.1319 damieng 2741: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919 albertel 2742: : $value;
1.599 albertel 2743: if ($to_remember<0) { return; }
1.1319 damieng 2744: $accessed{$remembered_id}=[&gettimeofday()];
1.599 albertel 2745: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2746: my $to_kick;
2747: my $max_time=0;
2748: foreach my $other (keys(%accessed)) {
2749: if (&tv_interval($accessed{$other}) > $max_time) {
2750: $to_kick=$other;
2751: $max_time=&tv_interval($accessed{$other});
2752: }
2753: }
2754: delete($remembered{$to_kick});
2755: delete($accessed{$to_kick});
2756: $kicks++;
2757: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2758: return;
2759: }
2760:
1.599 albertel 2761: sub purge_remembered {
1.604 albertel 2762: #&logthis("Tossing ".scalar(keys(%remembered)));
2763: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2764: undef(%remembered);
2765: undef(%accessed);
1.428 albertel 2766: }
1.70 www 2767: # ------------------------------------- Read an entry from a user's environment
2768:
2769: sub userenvironment {
2770: my ($udom,$unam,@what)=@_;
1.976 raeburn 2771: my $items;
2772: foreach my $item (@what) {
2773: $items.=&escape($item).'&';
2774: }
2775: $items=~s/\&$//;
1.70 www 2776: my %returnhash=();
1.1009 raeburn 2777: my $uhome = &homeserver($unam,$udom);
2778: unless ($uhome eq 'no_host') {
2779: my @answer=split(/\&/,
2780: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2781: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2782: return %returnhash;
2783: }
1.1009 raeburn 2784: my $i;
2785: for ($i=0;$i<=$#what;$i++) {
2786: $returnhash{$what[$i]}=&unescape($answer[$i]);
2787: }
1.70 www 2788: }
2789: return %returnhash;
1.1 albertel 2790: }
2791:
1.617 albertel 2792: # ---------------------------------------------------------- Get a studentphoto
2793: sub studentphoto {
2794: my ($udom,$unam,$ext) = @_;
2795: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2796: if (defined($env{'request.course.id'})) {
1.708 raeburn 2797: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2798: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2799: return(&retrievestudentphoto($udom,$unam,$ext));
2800: } else {
2801: my ($result,$perm_reqd)=
1.707 albertel 2802: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2803: if ($result eq 'ok') {
2804: if (!($perm_reqd eq 'yes')) {
2805: return(&retrievestudentphoto($udom,$unam,$ext));
2806: }
2807: }
2808: }
2809: }
2810: } else {
2811: my ($result,$perm_reqd) =
1.707 albertel 2812: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2813: if ($result eq 'ok') {
2814: if (!($perm_reqd eq 'yes')) {
2815: return(&retrievestudentphoto($udom,$unam,$ext));
2816: }
2817: }
2818: }
2819: return '/adm/lonKaputt/lonlogo_broken.gif';
2820: }
2821:
2822: sub retrievestudentphoto {
2823: my ($udom,$unam,$ext,$type) = @_;
2824: my $home=&Apache::lonnet::homeserver($unam,$udom);
2825: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2826: if ($ret eq 'ok') {
2827: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2828: if ($type eq 'thumbnail') {
2829: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2830: }
2831: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2832: return $tokenurl;
2833: } else {
2834: if ($type eq 'thumbnail') {
2835: return '/adm/lonKaputt/genericstudent_tn.gif';
2836: } else {
2837: return '/adm/lonKaputt/lonlogo_broken.gif';
2838: }
1.617 albertel 2839: }
2840: }
2841:
1.263 www 2842: # -------------------------------------------------------------------- New chat
2843:
2844: sub chatsend {
1.724 raeburn 2845: my ($newentry,$anon,$group)=@_;
1.620 albertel 2846: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2847: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2848: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2849: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2850: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2851: &escape($newentry)).':'.$group,$chome);
1.292 www 2852: }
2853:
2854: # ------------------------------------------ Find current version of a resource
2855:
2856: sub getversion {
2857: my $fname=&clutter(shift);
1.1189 raeburn 2858: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2859: return ¤tversion(&filelocation('',$fname));
2860: }
2861:
2862: sub currentversion {
2863: my $fname=shift;
2864: my $author=$fname;
2865: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2866: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2867: my $home=&homeserver($uname,$udom);
1.292 www 2868: if ($home eq 'no_host') {
2869: return -1;
2870: }
1.1112 www 2871: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2872: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2873: return -1;
2874: }
1.1112 www 2875: return $answer;
1.263 www 2876: }
2877:
1.1111 www 2878: #
2879: # Return special version number of resource if set by override, empty otherwise
2880: #
2881: sub usedversion {
2882: my $fname=shift;
2883: unless ($fname) { $fname=$env{'request.uri'}; }
2884: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2885: if ($urlversion) { return $urlversion; }
2886: return '';
2887: }
2888:
1.1 albertel 2889: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2890:
1.1 albertel 2891: sub subscribe {
2892: my $fname=shift;
1.761 raeburn 2893: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2894: $fname=~s/[\n\r]//g;
1.1 albertel 2895: my $author=$fname;
2896: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2897: my ($udom,$uname)=split(/\//,$author);
2898: my $home=homeserver($uname,$udom);
1.335 albertel 2899: if ($home eq 'no_host') {
2900: return 'not_found';
1.1 albertel 2901: }
2902: my $answer=reply("sub:$fname",$home);
1.64 www 2903: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2904: $answer.=' by '.$home;
2905: }
1.1 albertel 2906: return $answer;
2907: }
2908:
1.8 www 2909: # -------------------------------------------------------------- Replicate file
2910:
2911: sub repcopy {
2912: my $filename=shift;
1.23 www 2913: $filename=~s/\/+/\//g;
1.1142 raeburn 2914: my $londocroot = $perlvar{'lonDocRoot'};
2915: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2916: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2917: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2918: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2919: return &repcopy_userfile($filename);
2920: }
1.532 albertel 2921: $filename=~s/[\n\r]//g;
1.8 www 2922: my $transname="$filename.in.transfer";
1.828 www 2923: # FIXME: this should flock
1.607 raeburn 2924: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2925: my $remoteurl=subscribe($filename);
1.64 www 2926: if ($remoteurl =~ /^con_lost by/) {
2927: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2928: return 'unavailable';
1.8 www 2929: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2930: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2931: return 'not_found';
1.64 www 2932: } elsif ($remoteurl =~ /^rejected by/) {
2933: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2934: return 'forbidden';
1.20 www 2935: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2936: return 'ok';
1.8 www 2937: } else {
1.290 www 2938: my $author=$filename;
2939: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2940: my ($udom,$uname)=split(/\//,$author);
2941: my $home=homeserver($uname,$udom);
2942: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2943: my @parts=split(/\//,$filename);
2944: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2945: if ($path ne "$londocroot/res") {
1.8 www 2946: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2947: return 'bad_request';
1.8 www 2948: }
2949: my $count;
2950: for ($count=5;$count<$#parts;$count++) {
2951: $path.="/$parts[$count]";
2952: if ((-e $path)!=1) {
2953: mkdir($path,0777);
2954: }
2955: }
2956: my $ua=new LWP::UserAgent;
2957: my $request=new HTTP::Request('GET',"$remoteurl");
2958: my $response=$ua->request($request,$transname);
2959: if ($response->is_error()) {
2960: unlink($transname);
2961: my $message=$response->status_line;
1.672 albertel 2962: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2963: ." LWP get: $message: $filename</font>");
1.607 raeburn 2964: return 'unavailable';
1.8 www 2965: } else {
1.16 www 2966: if ($remoteurl!~/\.meta$/) {
2967: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2968: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2969: if ($mresponse->is_error()) {
2970: unlink($filename.'.meta');
2971: &logthis(
1.672 albertel 2972: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2973: }
2974: }
1.8 www 2975: rename($transname,$filename);
1.607 raeburn 2976: return 'ok';
1.8 www 2977: }
1.290 www 2978: }
1.8 www 2979: }
1.330 www 2980: }
2981:
2982: # ------------------------------------------------ Get server side include body
2983: sub ssi_body {
1.381 albertel 2984: my ($filelink,%form)=@_;
1.606 matthew 2985: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2986: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2987: }
1.953 www 2988: my $output='';
2989: my $response;
1.980 raeburn 2990: if ($filelink=~/^https?\:/) {
1.954 raeburn 2991: ($output,$response)=&externalssi($filelink);
1.953 www 2992: } else {
1.1004 droeschl 2993: $filelink .= $filelink=~/\?/ ? '&' : '?';
2994: $filelink .= 'inhibitmenu=yes';
1.953 www 2995: ($output,$response)=&ssi($filelink,%form);
2996: }
1.778 albertel 2997: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2998: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2999: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 3000: if (wantarray) {
3001: return ($output, $response);
3002: } else {
3003: return $output;
3004: }
1.8 www 3005: }
3006:
1.15 www 3007: # --------------------------------------------------------- Server Side Include
3008:
1.782 albertel 3009: sub absolute_url {
3010: my ($host_name) = @_;
3011: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3012: if ($host_name eq '') {
3013: $host_name = $ENV{'SERVER_NAME'};
3014: }
3015: return $protocol.$host_name;
3016: }
3017:
1.942 foxr 3018: #
3019: # Server side include.
3020: # Parameters:
3021: # fn Possibly encrypted resource name/id.
3022: # form Hash that describes how the rendering should be done
3023: # and other things.
1.944 foxr 3024: # Returns:
1.950 raeburn 3025: # Scalar context: The content of the response.
3026: # Array context: 2 element list of the content and the full response object.
1.942 foxr 3027: #
1.15 www 3028: sub ssi {
3029:
1.944 foxr 3030: my ($fn,%form)=@_;
1.15 www 3031: my $ua=new LWP::UserAgent;
1.23 www 3032: my $request;
1.711 albertel 3033:
3034: $form{'no_update_last_known'}=1;
1.895 albertel 3035: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 3036: if (%form) {
1.782 albertel 3037: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272 droeschl 3038: $request->content(join('&',map {
3039: my $name = escape($_);
3040: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3041: ? join("&$name=", map {escape($_) } @{$form{$_}})
3042: : &escape($form{$_}) );
3043: } keys(%form)));
1.23 www 3044: } else {
1.782 albertel 3045: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 3046: }
3047:
1.15 www 3048: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 3049: my $response= $ua->request($request);
1.1182 foxr 3050: my $content = $response->content;
3051:
3052:
1.944 foxr 3053: if (wantarray) {
1.1173 foxr 3054: return ($content, $response);
1.944 foxr 3055: } else {
1.1173 foxr 3056: return $content;
1.942 foxr 3057: }
1.324 www 3058: }
3059:
3060: sub externalssi {
3061: my ($url)=@_;
3062: my $ua=new LWP::UserAgent;
3063: my $request=new HTTP::Request('GET',$url);
3064: my $response=$ua->request($request);
1.954 raeburn 3065: if (wantarray) {
3066: return ($response->content, $response);
3067: } else {
3068: return $response->content;
3069: }
1.15 www 3070: }
1.254 www 3071:
1.492 albertel 3072: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3073:
3074: sub allowuploaded {
3075: my ($srcurl,$url)=@_;
3076: $url=&clutter(&declutter($url));
3077: my $dir=$url;
3078: $dir=~s/\/[^\/]+$//;
3079: my %httpref=();
3080: my $httpurl=&hreflocation('',$url);
3081: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 3082: &Apache::lonnet::appenv(\%httpref);
1.254 www 3083: }
1.477 raeburn 3084:
1.1193 raeburn 3085: #
3086: # Determine if the current user should be able to edit a particular resource,
3087: # when viewing in course context.
3088: # (a) When viewing resource used to determine if "Edit" item is included in
3089: # Functions.
3090: # (b) When displaying folder contents in course editor, used to determine if
3091: # "Edit" link will be displayed alongside resource.
3092: #
1.1196 raeburn 3093: # input: six args -- filename (decluttered), course number, course domain,
3094: # url, symb (if registered) and group (if this is a group
3095: # item -- e.g., bulletin board, group page etc.).
3096: # output: array of five scalars --
1.1193 raeburn 3097: # $cfile -- url for file editing if editable on current server
3098: # $home -- homeserver of resource (i.e., for author if published,
3099: # or course if uploaded.).
3100: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 3101: # $forceedit -- 1 if icon/link should be to go to edit mode
3102: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 3103: #
3104:
3105: sub can_edit_resource {
1.1194 raeburn 3106: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3107: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3108: #
3109: # For aboutme pages user can only edit his/her own.
3110: #
1.1199 raeburn 3111: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 3112: my ($sdom,$sname) = ($1,$2);
3113: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3114: $home = $env{'user.home'};
3115: $cfile = $resurl;
3116: if ($env{'form.forceedit'}) {
3117: $forceview = 1;
3118: } else {
3119: $forceedit = 1;
3120: }
3121: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3122: } else {
3123: return;
3124: }
3125: }
3126:
3127: if ($env{'request.course.id'}) {
3128: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3129: if ($group ne '') {
3130: # if this is a group homepage or group bulletin board, check group privs
3131: my $allowed = 0;
1.1197 raeburn 3132: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3133: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 3134: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 3135: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3136: $allowed = 1;
3137: }
1.1197 raeburn 3138: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3139: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3140: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 3141: $allowed = 1;
3142: }
3143: }
3144: if ($allowed) {
3145: $home=&homeserver($cnum,$cdom);
3146: if ($env{'form.forceedit'}) {
3147: $forceview = 1;
3148: } else {
3149: $forceedit = 1;
3150: }
3151: $cfile = $resurl;
3152: } else {
3153: return;
3154: }
3155: } else {
1.1208 raeburn 3156: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3157: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3158: return;
3159: }
3160: } elsif (!$crsedit) {
1.1194 raeburn 3161: #
3162: # No edit allowed where CC has switched to student role.
3163: #
3164: return;
3165: }
3166: }
3167: }
3168:
1.1193 raeburn 3169: if ($file ne '') {
3170: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 3171: if (&is_course_upload($file,$cnum,$cdom)) {
3172: $uploaded = 1;
3173: $incourse = 1;
1.1193 raeburn 3174: if ($file =~/\.(htm|html|css|js|txt)$/) {
3175: $cfile = &hreflocation('',$file);
1.1201 raeburn 3176: if ($env{'form.forceedit'}) {
3177: $forceview = 1;
3178: } else {
3179: $forceedit = 1;
3180: }
1.1194 raeburn 3181: }
3182: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3183: $incourse = 1;
3184: if ($env{'form.forceedit'}) {
3185: $forceview = 1;
3186: } else {
3187: $forceedit = 1;
3188: }
3189: $cfile = $resurl;
3190: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3191: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3192: $incourse = 1;
3193: if ($env{'form.forceedit'}) {
3194: $forceview = 1;
3195: } else {
3196: $forceedit = 1;
3197: }
3198: $cfile = $resurl;
1.1199 raeburn 3199: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 3200: $incourse = 1;
3201: $cfile = $resurl.'/smpedit';
1.1199 raeburn 3202: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 3203: $incourse = 1;
1.1199 raeburn 3204: if ($env{'form.forceedit'}) {
3205: $forceview = 1;
3206: } else {
3207: $forceedit = 1;
3208: }
3209: $cfile = $resurl;
1.1343 raeburn 3210: } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3211: $incourse = 1;
3212: if ($env{'form.forceedit'}) {
3213: $forceview = 1;
3214: } else {
3215: $forceedit = 1;
3216: }
3217: $cfile = $resurl;
1.1208 raeburn 3218: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3219: $incourse = 1;
3220: if ($env{'form.forceedit'}) {
3221: $forceview = 1;
3222: } else {
3223: $forceedit = 1;
3224: }
3225: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 3226: }
3227: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3228: my $template = '/res/lib/templates/simpleproblem.problem';
3229: if (&is_on_map($template)) {
3230: $incourse = 1;
3231: $forceview = 1;
3232: $cfile = $template;
1.1193 raeburn 3233: }
1.1199 raeburn 3234: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3235: $incourse = 1;
3236: if ($env{'form.forceedit'}) {
3237: $forceview = 1;
3238: } else {
3239: $forceedit = 1;
3240: }
3241: $cfile = $resurl;
1.1343 raeburn 3242: } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298 raeburn 3243: $incourse = 1;
3244: if ($env{'form.forceedit'}) {
3245: $forceview = 1;
3246: } else {
3247: $forceedit = 1;
3248: }
3249: $cfile = $resurl;
1.1199 raeburn 3250: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3251: $incourse = 1;
3252: $forceview = 1;
3253: if ($symb) {
3254: my ($map,$id,$res)=&decode_symb($symb);
3255: $env{'request.symb'} = $symb;
3256: $cfile = &clutter($res);
3257: } else {
3258: $cfile = $env{'form.suppurl'};
1.1298 raeburn 3259: my $escfile = &unescape($cfile);
1.1343 raeburn 3260: if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298 raeburn 3261: $cfile = '/adm/wrapper'.$escfile;
3262: } else {
3263: $escfile =~ s{^http://}{};
3264: $cfile = &escape("/adm/wrapper/ext/$escfile");
3265: }
1.1199 raeburn 3266: }
1.1234 raeburn 3267: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3268: if ($env{'form.forceedit'}) {
3269: $forceview = 1;
3270: } else {
3271: $forceedit = 1;
3272: }
3273: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 3274: }
3275: }
1.1194 raeburn 3276: if ($uploaded || $incourse) {
3277: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 3278: } elsif ($file !~ m{/$}) {
1.1193 raeburn 3279: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3280: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3281: # Check that the user has permission to edit this resource
3282: my $setpriv = 1;
3283: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3284: if (defined($cfudom)) {
3285: $home=&homeserver($cfuname,$cfudom);
3286: $cfile=$file;
3287: }
3288: }
1.1194 raeburn 3289: if (($cfile ne '') && (!$incourse || $uploaded) &&
3290: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 3291: my @ids=¤t_machine_ids();
3292: unless (grep(/^\Q$home\E$/,@ids)) {
3293: $switchserver=1;
3294: }
3295: }
3296: }
1.1194 raeburn 3297: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 3298: }
3299:
3300: sub is_course_upload {
3301: my ($file,$cnum,$cdom) = @_;
3302: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3303: $uploadpath =~ s{^\/}{};
1.1201 raeburn 3304: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3305: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 3306: return 1;
3307: }
3308: return;
3309: }
3310:
1.1194 raeburn 3311: sub in_course {
1.1195 raeburn 3312: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3313: if ($hideprivileged) {
3314: my $skipuser;
1.1219 raeburn 3315: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3316: my @possdoms = ($cdom);
3317: if ($coursehash{'checkforpriv'}) {
3318: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3319: }
3320: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 3321: $skipuser = 1;
3322: if ($coursehash{'nothideprivileged'}) {
3323: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3324: my $user;
3325: if ($item =~ /:/) {
3326: $user = $item;
3327: } else {
3328: $user = join(':',split(/[\@]/,$item));
3329: }
3330: if ($user eq $uname.':'.$udom) {
3331: undef($skipuser);
3332: last;
3333: }
3334: }
3335: }
3336: if ($skipuser) {
3337: return 0;
3338: }
3339: }
3340: }
1.1194 raeburn 3341: $type ||= 'any';
3342: if (!defined($cdom) || !defined($cnum)) {
3343: my $cid = $env{'request.course.id'};
3344: $cdom = $env{'course.'.$cid.'.domain'};
3345: $cnum = $env{'course.'.$cid.'.num'};
3346: }
3347: my $typesref;
1.1195 raeburn 3348: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 3349: $typesref = ['active','previous','future'];
3350: } elsif ($type eq 'previous' || $type eq 'future') {
3351: $typesref = [$type];
3352: }
3353: my %roles = &get_my_roles($uname,$udom,'userroles',
3354: $typesref,undef,[$cdom]);
3355: my ($tmp) = keys(%roles);
3356: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3357: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3358: if (@course_roles > 0) {
3359: return 1;
3360: }
3361: return 0;
3362: }
3363:
1.478 albertel 3364: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 3365: # input: action, courseID, current domain, intended
1.637 raeburn 3366: # path to file, source of file, instruction to parse file for objects,
3367: # ref to hash for embedded objects,
3368: # ref to hash for codebase of java objects.
1.1095 raeburn 3369: # reference to scalar to accommodate mime type determined
3370: # from File::MMagic if $parser = parse.
1.637 raeburn 3371: #
1.485 raeburn 3372: # output: url to file (if action was uploaddoc),
3373: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3374: #
1.478 albertel 3375: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3376: # course.
1.477 raeburn 3377: #
1.478 albertel 3378: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3379: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3380: # course's home server.
1.477 raeburn 3381: #
1.478 albertel 3382: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3383: # be copied from $source (current location) to
3384: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3385: # and will then be copied to
3386: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3387: # course's home server.
1.485 raeburn 3388: #
1.481 raeburn 3389: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3390: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3391: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3392: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3393: # in course's home server.
1.637 raeburn 3394: #
1.477 raeburn 3395:
3396: sub process_coursefile {
1.1095 raeburn 3397: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3398: $mimetype)=@_;
1.477 raeburn 3399: my $fetchresult;
1.638 albertel 3400: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3401: if ($action eq 'propagate') {
1.638 albertel 3402: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3403: $home);
1.481 raeburn 3404: } else {
1.477 raeburn 3405: my $fpath = '';
3406: my $fname = $file;
1.478 albertel 3407: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3408: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3409: my $filepath = &build_filepath($fpath);
1.481 raeburn 3410: if ($action eq 'copy') {
3411: if ($source eq '') {
3412: $fetchresult = 'no source file';
3413: return $fetchresult;
3414: } else {
3415: my $destination = $filepath.'/'.$fname;
3416: rename($source,$destination);
3417: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3418: $home);
1.481 raeburn 3419: }
3420: } elsif ($action eq 'uploaddoc') {
3421: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3422: print $fh $env{'form.'.$source};
1.481 raeburn 3423: close($fh);
1.637 raeburn 3424: if ($parser eq 'parse') {
1.1024 raeburn 3425: my $mm = new File::MMagic;
1.1095 raeburn 3426: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3427: if ($type eq 'text/html') {
1.1024 raeburn 3428: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3429: unless ($parse_result eq 'ok') {
3430: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3431: }
1.637 raeburn 3432: }
1.1095 raeburn 3433: if (ref($mimetype)) {
3434: $$mimetype = $type;
3435: }
1.637 raeburn 3436: }
1.477 raeburn 3437: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3438: $home);
1.481 raeburn 3439: if ($fetchresult eq 'ok') {
3440: return '/uploaded/'.$fpath.'/'.$fname;
3441: } else {
3442: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3443: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3444: return '/adm/notfound.html';
3445: }
1.477 raeburn 3446: }
3447: }
1.485 raeburn 3448: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3449: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3450: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3451: }
3452: return $fetchresult;
3453: }
3454:
1.637 raeburn 3455: sub build_filepath {
3456: my ($fpath) = @_;
3457: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3458: unless ($fpath eq '') {
3459: my @parts=split('/',$fpath);
3460: foreach my $part (@parts) {
3461: $filepath.= '/'.$part;
3462: if ((-e $filepath)!=1) {
3463: mkdir($filepath,0777);
3464: }
3465: }
3466: }
3467: return $filepath;
3468: }
3469:
3470: sub store_edited_file {
1.638 albertel 3471: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3472: my $file = $primary_url;
3473: $file =~ s#^/uploaded/$docudom/$docuname/##;
3474: my $fpath = '';
3475: my $fname = $file;
3476: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3477: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3478: my $filepath = &build_filepath($fpath);
3479: open(my $fh,'>'.$filepath.'/'.$fname);
3480: print $fh $content;
3481: close($fh);
1.638 albertel 3482: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3483: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3484: $home);
1.637 raeburn 3485: if ($$fetchresult eq 'ok') {
3486: return '/uploaded/'.$fpath.'/'.$fname;
3487: } else {
1.638 albertel 3488: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3489: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3490: return '/adm/notfound.html';
3491: }
3492: }
3493:
1.531 albertel 3494: sub clean_filename {
1.831 albertel 3495: my ($fname,$args)=@_;
1.315 www 3496: # Replace Windows backslashes by forward slashes
1.257 www 3497: $fname=~s/\\/\//g;
1.831 albertel 3498: if (!$args->{'keep_path'}) {
3499: # Get rid of everything but the actual filename
3500: $fname=~s/^.*\/([^\/]+)$/$1/;
3501: }
1.315 www 3502: # Replace spaces by underscores
3503: $fname=~s/\s+/\_/g;
3504: # Replace all other weird characters by nothing
1.831 albertel 3505: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3506: # Replace all .\d. sequences with _\d. so they no longer look like version
3507: # numbers
3508: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3509: return $fname;
3510: }
1.1051 raeburn 3511: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3512: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3513: # image with the same aspect ratio as the original, but with dimensions which do
3514: # not exceed $resizewidth and $resizeheight.
3515:
1.984 neumanie 3516: sub resizeImage {
1.1051 raeburn 3517: my ($img_path,$resizewidth,$resizeheight) = @_;
3518: my $ima = Image::Magick->new;
3519: my $resized;
3520: if (-e $img_path) {
3521: $ima->Read($img_path);
3522: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3523: my $width = $ima->Get('width');
3524: my $height = $ima->Get('height');
3525: if ($width > $resizewidth) {
3526: my $factor = $width/$resizewidth;
3527: my $newheight = $height/$factor;
3528: $ima->Scale(width=>$resizewidth,height=>$newheight);
3529: $resized = 1;
3530: }
3531: }
3532: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3533: my $width = $ima->Get('width');
3534: my $height = $ima->Get('height');
3535: if ($height > $resizeheight) {
3536: my $factor = $height/$resizeheight;
3537: my $newwidth = $width/$factor;
3538: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3539: $resized = 1;
3540: }
3541: }
3542: if ($resized) {
3543: $ima->Write($img_path);
3544: }
3545: }
3546: return;
1.977 amueller 3547: }
3548:
1.608 albertel 3549: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3550: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3551: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3552: # $context - possible values: coursedoc, existingfile, overwrite,
3553: # canceloverwrite, or ''.
3554: # if 'coursedoc': upload to the current course
3555: # if 'existingfile': write file to tmp/overwrites directory
3556: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3557: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3558: # $subdir - directory in userfile to store the file into
1.858 raeburn 3559: # $parser - instruction to parse file for objects ($parser = parse)
3560: # $allfiles - reference to hash for embedded objects
3561: # $codebase - reference to hash for codebase of java objects
3562: # $desuname - username for permanent storage of uploaded file
3563: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3564: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3565: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3566: # $resizewidth - width (pixels) to which to resize uploaded image
3567: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3568: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3569: # from File::MMagic.
1.858 raeburn 3570: #
1.686 albertel 3571: # output: url of file in userspace, or error: <message>
3572: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3573:
1.531 albertel 3574: sub userfileupload {
1.1090 raeburn 3575: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3576: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3577: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3578: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3579: $fname=&clean_filename($fname);
1.1090 raeburn 3580: # See if there is anything left
1.257 www 3581: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3582: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3583: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3584: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3585: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3586: my $now = time;
1.1090 raeburn 3587: my $filepath;
1.1095 raeburn 3588: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3589: $filepath = 'tmp/helprequests/'.$now;
3590: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3591: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3592: '_'.$env{'user.domain'}.'/pending';
3593: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3594: my ($docuname,$docudom);
3595: if ($destudom) {
3596: $docudom = $destudom;
3597: } else {
3598: $docudom = $env{'user.domain'};
3599: }
3600: if ($destuname) {
3601: $docuname = $destuname;
3602: } else {
3603: $docuname = $env{'user.name'};
3604: }
3605: if (exists($env{'form.group'})) {
3606: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3607: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3608: }
3609: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3610: if ($context eq 'canceloverwrite') {
3611: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3612: if (-e $tempfile) {
3613: my @info = stat($tempfile);
3614: if ($info[9] eq $env{'form.timestamp'}) {
3615: unlink($tempfile);
3616: }
3617: }
3618: return;
1.523 raeburn 3619: }
3620: }
1.1090 raeburn 3621: # Create the directory if not present
1.741 raeburn 3622: my @parts=split(/\//,$filepath);
3623: my $fullpath = $perlvar{'lonDaemons'};
3624: for (my $i=0;$i<@parts;$i++) {
3625: $fullpath .= '/'.$parts[$i];
3626: if ((-e $fullpath)!=1) {
3627: mkdir($fullpath,0777);
3628: }
3629: }
3630: open(my $fh,'>'.$fullpath.'/'.$fname);
3631: print $fh $env{'form.'.$formname};
3632: close($fh);
1.1090 raeburn 3633: if ($context eq 'existingfile') {
3634: my @info = stat($fullpath.'/'.$fname);
3635: return ($fullpath.'/'.$fname,$info[9]);
3636: } else {
3637: return $fullpath.'/'.$fname;
3638: }
1.523 raeburn 3639: }
1.995 raeburn 3640: if ($subdir eq 'scantron') {
3641: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3642: } else {
1.995 raeburn 3643: $fname="$subdir/$fname";
3644: }
1.1090 raeburn 3645: if ($context eq 'coursedoc') {
1.638 albertel 3646: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3647: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3648: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3649: return &finishuserfileupload($docuname,$docudom,
3650: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3651: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3652: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3653: } else {
1.1218 raeburn 3654: if ($env{'form.folder'}) {
3655: $fname=$env{'form.folder'}.'/'.$fname;
3656: }
1.638 albertel 3657: return &process_coursefile('uploaddoc',$docuname,$docudom,
3658: $fname,$formname,$parser,
1.1095 raeburn 3659: $allfiles,$codebase,$mimetype);
1.481 raeburn 3660: }
1.719 banghart 3661: } elsif (defined($destuname)) {
3662: my $docuname=$destuname;
3663: my $docudom=$destudom;
1.860 raeburn 3664: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3665: $parser,$allfiles,$codebase,
1.1051 raeburn 3666: $thumbwidth,$thumbheight,
1.1095 raeburn 3667: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3668: } else {
1.638 albertel 3669: my $docuname=$env{'user.name'};
3670: my $docudom=$env{'user.domain'};
1.1220 raeburn 3671: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3672: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3673: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3674: }
1.860 raeburn 3675: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3676: $parser,$allfiles,$codebase,
1.1051 raeburn 3677: $thumbwidth,$thumbheight,
1.1095 raeburn 3678: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3679: }
1.271 www 3680: }
3681:
3682: sub finishuserfileupload {
1.860 raeburn 3683: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3684: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3685: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3686: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3687:
1.860 raeburn 3688: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3689: $file=$fname;
3690: if ($fname=~m|/|) {
3691: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3692: $path.=$fnamepath.'/';
3693: }
1.259 www 3694: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3695: my $count;
3696: for ($count=4;$count<=$#parts;$count++) {
3697: $filepath.="/$parts[$count]";
3698: if ((-e $filepath)!=1) {
3699: mkdir($filepath,0777);
3700: }
3701: }
1.984 neumanie 3702:
1.258 www 3703: # Save the file
3704: {
1.701 albertel 3705: if (!open(FH,'>'.$filepath.'/'.$file)) {
3706: &logthis('Failed to create '.$filepath.'/'.$file);
3707: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3708: return '/adm/notfound.html';
3709: }
1.1090 raeburn 3710: if ($context eq 'overwrite') {
1.1117 foxr 3711: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3712: my $target = $filepath.'/'.$file;
3713: if (-e $source) {
3714: my @info = stat($source);
3715: if ($info[9] eq $env{'form.timestamp'}) {
3716: unless (&File::Copy::move($source,$target)) {
3717: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3718: return "Moving from $source failed";
3719: }
3720: } else {
3721: return "Temporary file: $source had unexpected date/time for last modification";
3722: }
3723: } else {
3724: return "Temporary file: $source missing";
3725: }
3726: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3727: &logthis('Failed to write to '.$filepath.'/'.$file);
3728: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3729: return '/adm/notfound.html';
3730: }
1.570 albertel 3731: close(FH);
1.1051 raeburn 3732: if ($resizewidth && $resizeheight) {
3733: my $mm = new File::MMagic;
3734: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3735: if ($mime_type =~ m{^image/}) {
3736: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3737: }
1.977 amueller 3738: }
1.258 www 3739: }
1.1152 raeburn 3740: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3741: if (ref($mimetype)) {
3742: if ($$mimetype eq '') {
3743: my $mm = new File::MMagic;
3744: my $type = $mm->checktype_filename($filepath.'/'.$file);
3745: $$mimetype = $type;
3746: }
3747: }
3748: }
1.637 raeburn 3749: if ($parser eq 'parse') {
1.1152 raeburn 3750: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3751: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3752: $allfiles,$codebase);
3753: unless ($parse_result eq 'ok') {
3754: &logthis('Failed to parse '.$filepath.$file.
3755: ' for embedded media: '.$parse_result);
3756: }
1.637 raeburn 3757: }
3758: }
1.860 raeburn 3759: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3760: my $input = $filepath.'/'.$file;
3761: my $output = $filepath.'/'.'tn-'.$file;
3762: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3763: system("convert -sample $thumbsize $input $output");
3764: if (-e $filepath.'/'.'tn-'.$file) {
3765: $fetchthumb = 1;
3766: }
3767: }
1.858 raeburn 3768:
1.259 www 3769: # Notify homeserver to grep it
3770: #
1.984 neumanie 3771: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3772: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3773: if ($fetchresult eq 'ok') {
1.860 raeburn 3774: if ($fetchthumb) {
3775: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3776: if ($thumbresult ne 'ok') {
3777: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3778: $docuhome.': '.$thumbresult);
3779: }
3780: }
1.259 www 3781: #
1.258 www 3782: # Return the URL to it
1.494 albertel 3783: return '/uploaded/'.$path.$file;
1.263 www 3784: } else {
1.494 albertel 3785: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3786: ': '.$fetchresult);
1.263 www 3787: return '/adm/notfound.html';
1.858 raeburn 3788: }
1.493 albertel 3789: }
3790:
1.637 raeburn 3791: sub extract_embedded_items {
1.961 raeburn 3792: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3793: my @state = ();
1.1164 raeburn 3794: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3795: my %javafiles = (
3796: codebase => '',
3797: code => '',
3798: archive => ''
3799: );
3800: my %mediafiles = (
3801: src => '',
3802: movie => '',
3803: );
1.648 raeburn 3804: my $p;
3805: if ($content) {
3806: $p = HTML::LCParser->new($content);
3807: } else {
1.961 raeburn 3808: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3809: }
1.641 albertel 3810: while (my $t=$p->get_token()) {
1.640 albertel 3811: if ($t->[0] eq 'S') {
3812: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3813: push(@state, $tagname);
1.648 raeburn 3814: if (lc($tagname) eq 'allow') {
3815: &add_filetype($allfiles,$attr->{'src'},'src');
3816: }
1.640 albertel 3817: if (lc($tagname) eq 'img') {
3818: &add_filetype($allfiles,$attr->{'src'},'src');
3819: }
1.886 albertel 3820: if (lc($tagname) eq 'a') {
1.1222 raeburn 3821: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3822: &add_filetype($allfiles,$attr->{'href'},'href');
3823: }
1.886 albertel 3824: }
1.645 raeburn 3825: if (lc($tagname) eq 'script') {
1.1164 raeburn 3826: my $src;
1.645 raeburn 3827: if ($attr->{'archive'} =~ /\.jar$/i) {
3828: &add_filetype($allfiles,$attr->{'archive'},'archive');
3829: } else {
1.1164 raeburn 3830: if ($attr->{'src'} ne '') {
3831: $src = $attr->{'src'};
3832: &add_filetype($allfiles,$src,'src');
3833: }
3834: }
3835: my $text = $p->get_trimmed_text();
3836: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3837: my @swfargs = split(/,/,$1);
3838: foreach my $item (@swfargs) {
3839: $item =~ s/["']//g;
3840: $item =~ s/^\s+//;
3841: $item =~ s/\s+$//;
3842: }
3843: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3844: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3845: push(@{$related{$swfargs[0]}},$swfargs[2]);
3846: } else {
3847: $related{$swfargs[0]} = [$swfargs[2]];
3848: }
3849: }
1.645 raeburn 3850: }
3851: }
3852: if (lc($tagname) eq 'link') {
3853: if (lc($attr->{'rel'}) eq 'stylesheet') {
3854: &add_filetype($allfiles,$attr->{'href'},'href');
3855: }
3856: }
1.640 albertel 3857: if (lc($tagname) eq 'object' ||
3858: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3859: foreach my $item (keys(%javafiles)) {
3860: $javafiles{$item} = '';
3861: }
1.1164 raeburn 3862: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3863: $lastids{lc($tagname)} = $attr->{'id'};
3864: }
1.640 albertel 3865: }
3866: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3867: my $name = lc($attr->{'name'});
3868: foreach my $item (keys(%javafiles)) {
3869: if ($name eq $item) {
3870: $javafiles{$item} = $attr->{'value'};
3871: last;
3872: }
3873: }
1.1164 raeburn 3874: my $pathfrom;
1.640 albertel 3875: foreach my $item (keys(%mediafiles)) {
3876: if ($name eq $item) {
1.1164 raeburn 3877: $pathfrom = $attr->{'value'};
3878: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3879: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3880: last;
3881: }
3882: }
1.1164 raeburn 3883: if ($name eq 'flashvars') {
3884: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3885: }
3886: if ($pathfrom ne '') {
3887: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3888: $pathfrom);
3889: }
1.640 albertel 3890: }
3891: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3892: foreach my $item (keys(%javafiles)) {
3893: if ($attr->{$item}) {
3894: $javafiles{$item} = $attr->{$item};
3895: last;
3896: }
3897: }
3898: foreach my $item (keys(%mediafiles)) {
3899: if ($attr->{$item}) {
3900: &add_filetype($allfiles,$attr->{$item},$item);
3901: last;
3902: }
3903: }
1.1164 raeburn 3904: if (lc($tagname) eq 'embed') {
3905: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3906: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3907: $attr->{'src'});
3908: }
3909: }
1.640 albertel 3910: }
1.1243 raeburn 3911: if (lc($tagname) eq 'iframe') {
3912: my $src = $attr->{'src'} ;
3913: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3914: &add_filetype($allfiles,$src,'src');
3915: } elsif ($src =~ m{^/}) {
3916: if ($env{'request.course.id'}) {
3917: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3918: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3919: my $url = &hreflocation('',$fullpath);
3920: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3921: my $relpath = $1;
3922: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3923: &add_filetype($allfiles,$1,'src');
3924: }
3925: }
3926: }
3927: }
3928: }
1.1164 raeburn 3929: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3930: pop(@state);
1.1164 raeburn 3931: }
1.640 albertel 3932: } elsif ($t->[0] eq 'E') {
3933: my ($tagname) = ($t->[1]);
3934: if ($javafiles{'codebase'} ne '') {
3935: $javafiles{'codebase'} .= '/';
3936: }
3937: if (lc($tagname) eq 'applet' ||
3938: lc($tagname) eq 'object' ||
3939: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3940: ) {
3941: foreach my $item (keys(%javafiles)) {
3942: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3943: my $file=$javafiles{'codebase'}.$javafiles{$item};
3944: &add_filetype($allfiles,$file,$item);
3945: }
3946: }
3947: }
3948: pop @state;
3949: }
3950: }
1.1164 raeburn 3951: foreach my $id (sort(keys(%flashvars))) {
3952: if ($shockwave{$id} ne '') {
3953: my @pairs = split(/\&/,$flashvars{$id});
3954: foreach my $pair (@pairs) {
3955: my ($key,$value) = split(/\=/,$pair);
3956: if ($key eq 'thumb') {
3957: &add_filetype($allfiles,$value,$key);
3958: } elsif ($key eq 'content') {
3959: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3960: my ($ext) = ($value =~ /\.([^.]+)$/);
3961: if ($ext ne '') {
3962: &add_filetype($allfiles,$path.$value,$ext);
3963: }
3964: }
3965: }
3966: }
3967: }
1.637 raeburn 3968: return 'ok';
3969: }
3970:
1.639 albertel 3971: sub add_filetype {
3972: my ($allfiles,$file,$type)=@_;
3973: if (exists($allfiles->{$file})) {
3974: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3975: push(@{$allfiles->{$file}}, &escape($type));
3976: }
3977: } else {
3978: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3979: }
3980: }
3981:
1.1164 raeburn 3982: sub embedded_dependency {
3983: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3984: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3985: if (($identifier ne '') &&
3986: (ref($related->{$identifier}) eq 'ARRAY') &&
3987: ($pathfrom ne '')) {
3988: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3989: foreach my $dep (@{$related->{$identifier}}) {
3990: &add_filetype($allfiles,$path.$dep,'object');
3991: }
3992: }
3993: }
3994: return;
3995: }
3996:
1.493 albertel 3997: sub removeuploadedurl {
1.984 neumanie 3998: my ($url)=@_;
3999: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 4000: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 4001: }
4002:
4003: sub removeuserfile {
4004: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 4005: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4006: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 4007: if ($result eq 'ok') {
1.798 raeburn 4008: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4009: my $metafile = $fname.'.meta';
4010: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 4011: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 4012: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4013: my $sqlresult =
1.823 albertel 4014: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4015: 'portfolio_metadata',$group,
4016: 'delete');
1.798 raeburn 4017: }
4018: }
4019: return $result;
1.257 www 4020: }
1.15 www 4021:
1.530 albertel 4022: sub mkdiruserfile {
4023: my ($docuname,$docudom,$dir)=@_;
4024: my $home=&homeserver($docuname,$docudom);
4025: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4026: }
4027:
1.531 albertel 4028: sub renameuserfile {
4029: my ($docuname,$docudom,$old,$new)=@_;
4030: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 4031: my $result = &reply("renameuserfile:$docudom:$docuname:".
4032: &escape("$old").':'.&escape("$new"),$home);
4033: if ($result eq 'ok') {
4034: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4035: my $oldmeta = $old.'.meta';
4036: my $newmeta = $new.'.meta';
4037: my $metaresult =
4038: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 4039: my $url = "/uploaded/$docudom/$docuname/$old";
4040: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 4041: my $sqlresult =
1.823 albertel 4042: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 4043: 'portfolio_metadata',$group,
4044: 'delete');
1.798 raeburn 4045: }
4046: }
4047: return $result;
1.531 albertel 4048: }
4049:
1.14 www 4050: # ------------------------------------------------------------------------- Log
4051:
4052: sub log {
4053: my ($dom,$nam,$hom,$what)=@_;
1.47 www 4054: return critical("log:$dom:$nam:$what",$hom);
1.157 www 4055: }
4056:
4057: # ------------------------------------------------------------------ Course Log
1.352 www 4058: #
4059: # This routine flushes several buffers of non-mission-critical nature
4060: #
1.157 www 4061:
4062: sub flushcourselogs {
1.352 www 4063: &logthis('Flushing log buffers');
4064: #
4065: # course logs
4066: # This is a log of all transactions in a course, which can be used
4067: # for data mining purposes
4068: #
4069: # It also collects the courseid database, which lists last transaction
4070: # times and course titles for all courseids
4071: #
4072: my %courseidbuffer=();
1.921 raeburn 4073: foreach my $crsid (keys(%courselogs)) {
1.352 www 4074: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 4075: &escape($courselogs{$crsid}),
4076: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 4077: delete $courselogs{$crsid};
4078: } else {
4079: &logthis('Failed to flush log buffer for '.$crsid);
4080: if (length($courselogs{$crsid})>40000) {
1.672 albertel 4081: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 4082: " exceeded maximum size, deleting.</font>");
4083: delete $courselogs{$crsid};
4084: }
1.352 www 4085: }
1.920 raeburn 4086: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 4087: 'description' => $coursedescrbuf{$crsid},
4088: 'inst_code' => $courseinstcodebuf{$crsid},
4089: 'type' => $coursetypebuf{$crsid},
4090: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 4091: };
1.191 harris41 4092: }
1.352 www 4093: #
4094: # Write course id database (reverse lookup) to homeserver of courses
4095: # Is used in pickcourse
4096: #
1.840 albertel 4097: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 4098: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 4099: $courseidbuffer{$crs_home},
4100: $crs_home,'timeonly');
1.352 www 4101: }
4102: #
4103: # File accesses
4104: # Writes to the dynamic metadata of resources to get hit counts, etc.
4105: #
1.449 matthew 4106: foreach my $entry (keys(%accesshash)) {
1.458 matthew 4107: if ($entry =~ /___count$/) {
4108: my ($dom,$name);
1.807 albertel 4109: ($dom,$name,undef)=
1.811 albertel 4110: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 4111: if (! defined($dom) || $dom eq '' ||
4112: ! defined($name) || $name eq '') {
1.620 albertel 4113: my $cid = $env{'request.course.id'};
4114: $dom = $env{'request.'.$cid.'.domain'};
4115: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 4116: }
1.450 matthew 4117: my $value = $accesshash{$entry};
4118: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4119: my %temphash=($url => $value);
1.449 matthew 4120: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4121: if ($result eq 'ok') {
4122: delete $accesshash{$entry};
4123: }
4124: } else {
1.811 albertel 4125: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 4126: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 4127: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 4128: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4129: delete $accesshash{$entry};
4130: }
1.185 www 4131: }
1.191 harris41 4132: }
1.352 www 4133: #
4134: # Roles
4135: # Reverse lookup of user roles for course faculty/staff and co-authorship
4136: #
1.800 albertel 4137: foreach my $entry (keys(%userrolehash)) {
1.351 www 4138: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 4139: split(/\:/,$entry);
4140: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 4141: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 4142: $rudom,$runame) eq 'ok') {
4143: delete $userrolehash{$entry};
4144: }
4145: }
1.662 raeburn 4146: #
1.1334 raeburn 4147: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662 raeburn 4148: #
4149: my %domrolebuffer = ();
1.1000 raeburn 4150: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 4151: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 4152: if ($domrolebuffer{$rudom}) {
4153: $domrolebuffer{$rudom}.='&'.&escape($entry).
4154: '='.&escape($domainrolehash{$entry});
4155: } else {
4156: $domrolebuffer{$rudom}.=&escape($entry).
4157: '='.&escape($domainrolehash{$entry});
4158: }
4159: delete $domainrolehash{$entry};
4160: }
4161: foreach my $dom (keys(%domrolebuffer)) {
1.1324 raeburn 4162: my %servers;
4163: if (defined(&domain($dom,'primary'))) {
4164: my $primary=&domain($dom,'primary');
4165: my $hostname=&hostname($primary);
4166: $servers{$primary} = $hostname;
4167: } else {
4168: %servers = &get_servers($dom,'library');
4169: }
1.841 albertel 4170: foreach my $tryserver (keys(%servers)) {
1.1324 raeburn 4171: if (&reply('domroleput:'.$dom.':'.
4172: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4173: last;
4174: } else {
1.841 albertel 4175: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4176: }
1.662 raeburn 4177: }
4178: }
1.186 www 4179: $dumpcount++;
1.157 www 4180: }
4181:
4182: sub courselog {
4183: my $what=shift;
1.158 www 4184: $what=time.':'.$what;
1.620 albertel 4185: unless ($env{'request.course.id'}) { return ''; }
4186: $coursedombuf{$env{'request.course.id'}}=
4187: $env{'course.'.$env{'request.course.id'}.'.domain'};
4188: $coursenumbuf{$env{'request.course.id'}}=
4189: $env{'course.'.$env{'request.course.id'}.'.num'};
4190: $coursehombuf{$env{'request.course.id'}}=
4191: $env{'course.'.$env{'request.course.id'}.'.home'};
4192: $coursedescrbuf{$env{'request.course.id'}}=
4193: $env{'course.'.$env{'request.course.id'}.'.description'};
4194: $courseinstcodebuf{$env{'request.course.id'}}=
4195: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4196: $courseownerbuf{$env{'request.course.id'}}=
4197: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 4198: $coursetypebuf{$env{'request.course.id'}}=
4199: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 4200: if (defined $courselogs{$env{'request.course.id'}}) {
4201: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 4202: } else {
1.620 albertel 4203: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 4204: }
1.620 albertel 4205: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 4206: &flushcourselogs();
4207: }
1.158 www 4208: }
4209:
4210: sub courseacclog {
4211: my $fnsymb=shift;
1.620 albertel 4212: unless ($env{'request.course.id'}) { return ''; }
4213: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 4214: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 4215: $what.=':POST';
1.583 matthew 4216: # FIXME: Probably ought to escape things....
1.800 albertel 4217: foreach my $key (keys(%env)) {
4218: if ($key=~/^form\.(.*)/) {
1.975 raeburn 4219: my $formitem = $1;
4220: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4221: $what.=':'.$formitem.'='.$env{$key};
4222: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4223: $what.=':'.$formitem.'='.$env{$key};
4224: }
1.158 www 4225: }
1.191 harris41 4226: }
1.583 matthew 4227: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4228: # FIXME: We should not be depending on a form parameter that someone
4229: # editing lonsearchcat.pm might change in the future.
1.620 albertel 4230: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 4231: $what.= ':POST';
4232: # FIXME: Probably ought to escape things....
4233: foreach my $element ('courseexp','crsfulltext','crsrelated',
4234: 'crsdiscuss') {
1.620 albertel 4235: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 4236: }
4237: }
1.158 www 4238: }
4239: &courselog($what);
1.149 www 4240: }
4241:
1.185 www 4242: sub countacc {
4243: my $url=&declutter(shift);
1.458 matthew 4244: return if (! defined($url) || $url eq '');
1.620 albertel 4245: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 4246: #
4247: # Mark that this url was used in this course
4248: #
1.620 albertel 4249: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 4250: #
4251: # Increase the access count for this resource in this child process
4252: #
1.281 www 4253: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 4254: $accesshash{$key}++;
1.185 www 4255: }
1.349 www 4256:
1.361 www 4257: sub linklog {
4258: my ($from,$to)=@_;
4259: $from=&declutter($from);
4260: $to=&declutter($to);
4261: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4262: $accesshash{$to.'___'.$from.'___goto'}=1;
4263: }
1.1160 www 4264:
4265: sub statslog {
4266: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4267: if ($users<2) { return; }
4268: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4269: 'course' => $env{'request.course.id'},
4270: 'sections' => '"all"',
4271: 'num_students' => $users,
4272: 'part' => $part,
4273: 'symb' => $symb,
4274: 'mean_tries' => $av_attempts,
4275: 'deg_of_diff' => $degdiff});
4276: foreach my $key (keys(%dynstore)) {
4277: $accesshash{$key}=$dynstore{$key};
4278: }
4279: }
1.361 www 4280:
1.349 www 4281: sub userrolelog {
4282: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 4283: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 4284: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4285: $userrolehash
4286: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 4287: =$tend.':'.$tstart;
1.662 raeburn 4288: }
1.1169 droeschl 4289: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 4290: $userrolehash
4291: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4292: =$tend.':'.$tstart;
4293: }
1.1334 raeburn 4294: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662 raeburn 4295: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4296: $domainrolehash
4297: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4298: = $tend.':'.$tstart;
4299: }
1.351 www 4300: }
4301:
1.957 raeburn 4302: sub courserolelog {
4303: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 4304: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4305: my $cdom = $1;
4306: my $cnum = $2;
4307: my $sec = $3;
4308: my $namespace = 'rolelog';
4309: my %storehash = (
4310: role => $trole,
4311: start => $tstart,
4312: end => $tend,
4313: selfenroll => $selfenroll,
4314: context => $context,
4315: );
4316: if ($trole eq 'gr') {
4317: $namespace = 'groupslog';
4318: $storehash{'group'} = $sec;
4319: } else {
4320: $storehash{'section'} = $sec;
4321: }
1.1188 raeburn 4322: &write_log('course',$namespace,\%storehash,$delflag,$username,
4323: $domain,$cnum,$cdom);
1.1184 raeburn 4324: if (($trole ne 'st') || ($sec ne '')) {
4325: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 4326: }
4327: }
4328: return;
4329: }
4330:
1.1184 raeburn 4331: sub domainrolelog {
4332: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4333: if ($area =~ m{^/($match_domain)/$}) {
4334: my $cdom = $1;
4335: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4336: my $namespace = 'rolelog';
4337: my %storehash = (
4338: role => $trole,
4339: start => $tstart,
4340: end => $tend,
4341: context => $context,
4342: );
1.1188 raeburn 4343: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4344: $domain,$domconfiguser,$cdom);
1.1184 raeburn 4345: }
4346: return;
4347:
4348: }
4349:
4350: sub coauthorrolelog {
4351: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4352: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4353: my $audom = $1;
4354: my $auname = $2;
4355: my $namespace = 'rolelog';
4356: my %storehash = (
4357: role => $trole,
4358: start => $tstart,
4359: end => $tend,
4360: context => $context,
4361: );
1.1188 raeburn 4362: &write_log('author',$namespace,\%storehash,$delflag,$username,
4363: $domain,$auname,$audom);
1.1184 raeburn 4364: }
4365: return;
4366: }
4367:
1.351 www 4368: sub get_course_adv_roles {
1.948 raeburn 4369: my ($cid,$codes) = @_;
1.620 albertel 4370: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 4371: my %coursehash=&coursedescription($cid);
1.988 raeburn 4372: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 4373: my %nothide=();
1.800 albertel 4374: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 4375: if ($user !~ /:/) {
4376: $nothide{join(':',split(/[\@]/,$user))}=1;
4377: } else {
4378: $nothide{$user}=1;
4379: }
1.470 www 4380: }
1.1219 raeburn 4381: my @possdoms = ($coursehash{'domain'});
4382: if ($coursehash{'checkforpriv'}) {
4383: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4384: }
1.351 www 4385: my %returnhash=();
4386: my %dumphash=
4387: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4388: my $now=time;
1.997 raeburn 4389: my %privileged;
1.1000 raeburn 4390: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4391: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4392: if (($tstart) && ($tstart<0)) { next; }
4393: if (($tend) && ($tend<$now)) { next; }
4394: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4395: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4396: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 4397: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4398: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4399: if ($role eq 'cr') { next; }
1.948 raeburn 4400: if ($codes) {
4401: if ($section) { $role .= ':'.$section; }
4402: if ($returnhash{$role}) {
4403: $returnhash{$role}.=','.$username.':'.$domain;
4404: } else {
4405: $returnhash{$role}=$username.':'.$domain;
4406: }
1.351 www 4407: } else {
1.988 raeburn 4408: my $key=&plaintext($role,$crstype);
1.973 bisitz 4409: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4410: if ($returnhash{$key}) {
4411: $returnhash{$key}.=','.$username.':'.$domain;
4412: } else {
4413: $returnhash{$key}=$username.':'.$domain;
4414: }
1.351 www 4415: }
1.948 raeburn 4416: }
1.400 www 4417: return %returnhash;
4418: }
4419:
4420: sub get_my_roles {
1.937 raeburn 4421: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4422: unless (defined($uname)) { $uname=$env{'user.name'}; }
4423: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4424: my (%dumphash,%nothide);
1.1086 raeburn 4425: if ($context eq 'userroles') {
1.1166 raeburn 4426: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4427: } else {
1.1219 raeburn 4428: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4429: if ($hidepriv) {
4430: my %coursehash=&coursedescription($udom.'_'.$uname);
4431: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4432: if ($user !~ /:/) {
4433: $nothide{join(':',split(/[\@]/,$user))} = 1;
4434: } else {
4435: $nothide{$user} = 1;
4436: }
4437: }
4438: }
1.858 raeburn 4439: }
1.400 www 4440: my %returnhash=();
4441: my $now=time;
1.999 raeburn 4442: my %privileged;
1.800 albertel 4443: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4444: my ($role,$tend,$tstart);
4445: if ($context eq 'userroles') {
1.1149 raeburn 4446: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4447: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4448: } else {
4449: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4450: }
1.400 www 4451: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4452: my $status = 'active';
1.939 raeburn 4453: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4454: $status = 'previous';
4455: }
4456: if (($tstart) && ($now<$tstart)) {
4457: $status = 'future';
4458: }
4459: if (ref($types) eq 'ARRAY') {
4460: if (!grep(/^\Q$status\E$/,@{$types})) {
4461: next;
4462: }
4463: } else {
4464: if ($status ne 'active') {
4465: next;
4466: }
4467: }
1.867 raeburn 4468: my ($rolecode,$username,$domain,$section,$area);
4469: if ($context eq 'userroles') {
1.1186 raeburn 4470: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4471: (undef,$domain,$username,$section) = split(/\//,$area);
4472: } else {
4473: ($role,$username,$domain,$section) = split(/\:/,$entry);
4474: }
1.832 raeburn 4475: if (ref($roledoms) eq 'ARRAY') {
4476: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4477: next;
4478: }
4479: }
4480: if (ref($roles) eq 'ARRAY') {
4481: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4482: if ($role =~ /^cr\//) {
4483: if (!grep(/^cr$/,@{$roles})) {
4484: next;
4485: }
1.1104 raeburn 4486: } elsif ($role =~ /^gr\//) {
4487: if (!grep(/^gr$/,@{$roles})) {
4488: next;
4489: }
1.922 raeburn 4490: } else {
4491: next;
4492: }
1.832 raeburn 4493: }
1.867 raeburn 4494: }
1.937 raeburn 4495: if ($hidepriv) {
1.1219 raeburn 4496: my @privroles = ('dc','su');
1.999 raeburn 4497: if ($context eq 'userroles') {
1.1219 raeburn 4498: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4499: } else {
1.1219 raeburn 4500: my $possdoms = [$domain];
4501: if (ref($roledoms) eq 'ARRAY') {
4502: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4503: }
1.1219 raeburn 4504: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4505: if (!$nothide{$username.':'.$domain}) {
4506: next;
4507: }
4508: }
1.937 raeburn 4509: }
4510: }
1.933 raeburn 4511: if ($withsec) {
4512: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4513: $tstart.':'.$tend;
4514: } else {
4515: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4516: }
1.832 raeburn 4517: }
1.373 www 4518: return %returnhash;
1.399 www 4519: }
4520:
1.1333 raeburn 4521: sub get_all_adhocroles {
4522: my ($dom) = @_;
4523: my @roles_by_num = ();
4524: my %domdefaults = &get_domain_defaults($dom);
4525: my (%description,%access_in_dom,%access_info);
4526: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
4527: my $count = 0;
4528: my %domcurrent = %{$domdefaults{'adhocroles'}};
4529: my %ordered;
4530: foreach my $role (sort(keys(%domcurrent))) {
4531: my ($order,$desc,$access_in_dom);
4532: if (ref($domcurrent{$role}) eq 'HASH') {
4533: $order = $domcurrent{$role}{'order'};
4534: $desc = $domcurrent{$role}{'desc'};
4535: $access_in_dom{$role} = $domcurrent{$role}{'access'};
4536: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
4537: }
4538: if ($order eq '') {
4539: $order = $count;
4540: }
4541: $ordered{$order} = $role;
4542: if ($desc ne '') {
4543: $description{$role} = $desc;
4544: } else {
4545: $description{$role}= $role;
4546: }
4547: $count++;
4548: }
4549: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
4550: push(@roles_by_num,$ordered{$item});
4551: }
4552: }
4553: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
4554: }
4555:
1.1332 raeburn 4556: sub get_my_adhocroles {
1.1333 raeburn 4557: my ($cid,$checkreg) = @_;
4558: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
4559: if ($env{'request.course.id'} eq $cid) {
4560: $cdom = $env{'course.'.$cid.'.domain'};
4561: $cnum = $env{'course.'.$cid.'.num'};
4562: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
4563: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
4564: $cdom = $1;
4565: $cnum = $2;
4566: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
4567: $cdom,$cnum);
4568: }
4569: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
4570: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4571: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
4572: if ($rosterhash{$user} ne '') {
4573: my $type = (split(/:/,$rosterhash{$user}))[5];
4574: return ([],{}) if ($type eq 'auto');
4575: }
4576: }
4577: if (($cdom ne '') && ($cnum ne '')) {
1.1334 raeburn 4578: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332 raeburn 4579: my $then=$env{'user.login.time'};
4580: my $update=$env{'user.update.time'};
1.1335 raeburn 4581: if (!$update) {
4582: $update = $then;
4583: }
4584: my @liveroles;
1.1334 raeburn 4585: foreach my $role ('dh','da') {
4586: if ($env{"user.role.$role./$cdom/"}) {
1.1335 raeburn 4587: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334 raeburn 4588: my $limit = $update;
4589: if ($env{'request.role'} eq "$role./$cdom/") {
4590: $limit = $then;
4591: }
1.1335 raeburn 4592: my $activerole = 1;
4593: if ($tstart && $tstart>$limit) { $activerole = 0; }
4594: if ($tend && $tend <$limit) { $activerole = 0; }
4595: if ($activerole) {
4596: push(@liveroles,$role);
4597: }
1.1334 raeburn 4598: }
1.1332 raeburn 4599: }
1.1335 raeburn 4600: if (@liveroles) {
1.1332 raeburn 4601: if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333 raeburn 4602: my ($accessref,$accessinfo,%access_in_dom);
4603: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
4604: if (ref($roles_by_num) eq 'ARRAY') {
4605: if (@{$roles_by_num}) {
1.1332 raeburn 4606: my %settings;
4607: if ($env{'request.course.id'} eq $cid) {
4608: foreach my $envkey (keys(%env)) {
4609: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
4610: $settings{$1} = $env{$envkey};
4611: }
4612: }
4613: } else {
4614: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
4615: }
4616: my %setincrs;
4617: if ($settings{'internal.adhocaccess'}) {
4618: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
4619: }
4620: my @statuses;
4621: if ($env{'environment.inststatus'}) {
4622: @statuses = split(/,/,$env{'environment.inststatus'});
4623: }
4624: my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333 raeburn 4625: if (ref($accessref) eq 'HASH') {
4626: %access_in_dom = %{$accessref};
4627: }
4628: foreach my $role (@{$roles_by_num}) {
1.1332 raeburn 4629: my ($curraccess,@okstatus,@personnel);
4630: if ($setincrs{$role}) {
4631: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
4632: if ($curraccess eq 'status') {
4633: @okstatus = split(/\&/,$rest);
4634: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4635: @personnel = split(/\&/,$rest);
4636: }
4637: } else {
4638: $curraccess = $access_in_dom{$role};
1.1333 raeburn 4639: if (ref($accessinfo) eq 'HASH') {
4640: if ($curraccess eq 'status') {
4641: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4642: @okstatus = @{$accessinfo->{$role}};
4643: }
4644: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4645: if (ref($accessinfo->{$role}) eq 'ARRAY') {
4646: @personnel = @{$accessinfo->{$role}};
4647: }
1.1332 raeburn 4648: }
4649: }
4650: }
4651: if ($curraccess eq 'none') {
4652: next;
4653: } elsif ($curraccess eq 'all') {
4654: push(@possroles,$role);
1.1336 raeburn 4655: } elsif ($curraccess eq 'dh') {
1.1335 raeburn 4656: if (grep(/^dh$/,@liveroles)) {
4657: push(@possroles,$role);
4658: } else {
4659: next;
4660: }
1.1336 raeburn 4661: } elsif ($curraccess eq 'da') {
1.1335 raeburn 4662: if (grep(/^da$/,@liveroles)) {
4663: push(@possroles,$role);
4664: } else {
4665: next;
4666: }
1.1332 raeburn 4667: } elsif ($curraccess eq 'status') {
4668: if (@okstatus) {
4669: if (!@statuses) {
4670: if (grep(/^default$/,@okstatus)) {
4671: push(@possroles,$role);
4672: }
4673: } else {
4674: foreach my $status (@okstatus) {
4675: if (grep(/^\Q$status\E$/,@statuses)) {
4676: push(@possroles,$role);
4677: last;
4678: }
4679: }
4680: }
4681: }
4682: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
4683: if (grep(/^\Q$user\E$/,@personnel)) {
4684: if ($curraccess eq 'exc') {
4685: push(@possroles,$role);
4686: }
4687: } elsif ($curraccess eq 'inc') {
4688: push(@possroles,$role);
4689: }
4690: }
4691: }
4692: }
4693: }
4694: }
4695: }
4696: }
4697: }
1.1333 raeburn 4698: unless (ref($description) eq 'HASH') {
4699: if (ref($roles_by_num) eq 'ARRAY') {
4700: my %desc;
4701: map { $desc{$_} = $_; } (@{$roles_by_num});
4702: $description = \%desc;
4703: } else {
4704: $description = {};
4705: }
4706: }
4707: return (\@possroles,$description);
1.1332 raeburn 4708: }
4709:
1.399 www 4710: # ----------------------------------------------------- Frontpage Announcements
4711: #
4712: #
4713:
4714: sub postannounce {
4715: my ($server,$text)=@_;
1.844 albertel 4716: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4717: unless ($text=~/\w/) { $text=''; }
4718: return &reply('setannounce:'.&escape($text),$server);
4719: }
4720:
4721: sub getannounce {
1.448 albertel 4722:
4723: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4724: my $announcement='';
1.800 albertel 4725: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4726: close($fh);
1.399 www 4727: if ($announcement=~/\w/) {
4728: return
4729: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4730: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4731: } else {
4732: return '';
4733: }
4734: } else {
4735: return '';
4736: }
1.351 www 4737: }
1.353 www 4738:
4739: # ---------------------------------------------------------- Course ID routines
4740: # Deal with domain's nohist_courseid.db files
4741: #
4742:
4743: sub courseidput {
1.921 raeburn 4744: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4745: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4746: my $outcome;
4747: if ($caller eq 'timeonly') {
4748: my $cids = '';
4749: foreach my $item (keys(%$storehash)) {
4750: $cids.=&escape($item).'&';
4751: }
4752: $cids=~s/\&$//;
4753: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4754: $coursehome);
4755: } else {
4756: my $items = '';
4757: foreach my $item (keys(%$storehash)) {
4758: $items.= &escape($item).'='.
4759: &freeze_escape($$storehash{$item}).'&';
4760: }
4761: $items=~s/\&$//;
4762: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4763: $coursehome);
1.918 raeburn 4764: }
4765: if ($outcome eq 'unknown_cmd') {
4766: my $what;
4767: foreach my $cid (keys(%$storehash)) {
4768: $what .= &escape($cid).'=';
1.921 raeburn 4769: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4770: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4771: }
4772: $what =~ s/\:$/&/;
4773: }
4774: $what =~ s/\&$//;
4775: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4776: } else {
4777: return $outcome;
4778: }
1.353 www 4779: }
4780:
4781: sub courseiddump {
1.921 raeburn 4782: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4783: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4784: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4785: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287 raeburn 4786: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918 raeburn 4787: my $as_hash = 1;
4788: my %returnhash;
4789: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4790: my %libserv = &all_library();
4791: foreach my $tryserver (keys(%libserv)) {
4792: if ( ( $hostidflag == 1
4793: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4794: || (!defined($hostidflag)) ) {
4795:
1.918 raeburn 4796: if (($domfilter eq '') ||
4797: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4798: my $rep;
4799: if (grep { $_ eq $tryserver } current_machine_ids()) {
4800: $rep = LONCAPA::Lond::dump_course_id_handler(
4801: join(":", (&host_domain($tryserver), $sincefilter,
4802: &escape($descfilter), &escape($instcodefilter),
4803: &escape($ownerfilter), &escape($coursefilter),
4804: &escape($typefilter), &escape($regexp_ok),
4805: $as_hash, &escape($selfenrollonly),
4806: &escape($catfilter), $showhidden, $caller,
4807: &escape($cloner), &escape($cc_clone), $cloneonly,
4808: &escape($createdbefore), &escape($createdafter),
1.1287 raeburn 4809: &escape($creationcontext),$domcloner,$hasuniquecode,
4810: $reqcrsdom,&escape($reqinstcode))));
1.1180 droeschl 4811: } else {
4812: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4813: $sincefilter.':'.&escape($descfilter).':'.
4814: &escape($instcodefilter).':'.&escape($ownerfilter).
4815: ':'.&escape($coursefilter).':'.&escape($typefilter).
4816: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4817: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4818: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4819: &escape($cc_clone).':'.$cloneonly.':'.
4820: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287 raeburn 4821: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
4822: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180 droeschl 4823: }
4824:
1.918 raeburn 4825: my @pairs=split(/\&/,$rep);
4826: foreach my $item (@pairs) {
4827: my ($key,$value)=split(/\=/,$item,2);
4828: $key = &unescape($key);
4829: next if ($key =~ /^error: 2 /);
4830: my $result = &thaw_unescape($value);
4831: if (ref($result) eq 'HASH') {
4832: $returnhash{$key}=$result;
4833: } else {
1.921 raeburn 4834: my @responses = split(/:/,$value);
4835: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4836: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4837: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4838: }
1.1008 raeburn 4839: }
1.353 www 4840: }
4841: }
4842: }
4843: }
4844: return %returnhash;
4845: }
4846:
1.1055 raeburn 4847: sub courselastaccess {
4848: my ($cdom,$cnum,$hostidref) = @_;
4849: my %returnhash;
4850: if ($cdom && $cnum) {
4851: my $chome = &homeserver($cnum,$cdom);
4852: if ($chome ne 'no_host') {
4853: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4854: &extract_lastaccess(\%returnhash,$rep);
4855: }
4856: } else {
4857: if (!$cdom) { $cdom=''; }
4858: my %libserv = &all_library();
4859: foreach my $tryserver (keys(%libserv)) {
4860: if (ref($hostidref) eq 'ARRAY') {
4861: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4862: }
4863: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4864: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4865: &extract_lastaccess(\%returnhash,$rep);
4866: }
4867: }
4868: }
4869: return %returnhash;
4870: }
4871:
4872: sub extract_lastaccess {
4873: my ($returnhash,$rep) = @_;
4874: if (ref($returnhash) eq 'HASH') {
4875: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4876: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4877: $rep eq '') {
4878: my @pairs=split(/\&/,$rep);
4879: foreach my $item (@pairs) {
4880: my ($key,$value)=split(/\=/,$item,2);
4881: $key = &unescape($key);
4882: next if ($key =~ /^error: 2 /);
4883: $returnhash->{$key} = &thaw_unescape($value);
4884: }
4885: }
4886: }
4887: return;
4888: }
4889:
1.658 raeburn 4890: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4891:
4892: sub dcmailput {
1.685 raeburn 4893: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4894: my $status = &Apache::lonnet::critical(
1.740 www 4895: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4896: &escape($message),$server);
1.662 raeburn 4897: return $status;
4898: }
4899:
1.658 raeburn 4900: sub dcmaildump {
4901: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4902: my %returnhash=();
1.846 albertel 4903:
4904: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4905: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4906: &escape($enddate).':';
4907: my @esc_senders=map { &escape($_)} @$senders;
4908: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4909: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4910: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4911: if (($key) && ($value)) {
4912: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4913: }
4914: }
4915: }
4916: return %returnhash;
4917: }
1.662 raeburn 4918: # ---------------------------------------------------------- Domain roles
4919:
4920: sub get_domain_roles {
4921: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4922: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4923: $startdate = '.';
4924: }
1.1018 raeburn 4925: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4926: $enddate = '.';
4927: }
1.922 raeburn 4928: my $rolelist;
4929: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4930: $rolelist = join('&',@{$roles});
1.922 raeburn 4931: }
1.662 raeburn 4932: my %personnel = ();
1.841 albertel 4933:
4934: my %servers = &get_servers($dom,'library');
4935: foreach my $tryserver (keys(%servers)) {
4936: %{$personnel{$tryserver}}=();
4937: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4938: &escape($startdate).':'.
4939: &escape($enddate).':'.
4940: &escape($rolelist), $tryserver))) {
4941: my ($key,$value) = split(/\=/,$line,2);
4942: if (($key) && ($value)) {
4943: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4944: }
4945: }
1.662 raeburn 4946: }
4947: return %personnel;
4948: }
1.658 raeburn 4949:
1.1332 raeburn 4950: sub get_active_domroles {
4951: my ($dom,$roles) = @_;
4952: return () unless (ref($roles) eq 'ARRAY');
4953: my $now = time;
4954: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
4955: my %domroles;
4956: foreach my $server (keys(%dompersonnel)) {
4957: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
4958: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
4959: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
4960: }
4961: }
4962: return %domroles;
4963: }
4964:
1.1057 www 4965: # ----------------------------------------------------------- Interval timing
1.149 www 4966:
1.1153 www 4967: {
4968: # Caches needed for speedup of navmaps
4969: # We don't want to cache this for very long at all (5 seconds at most)
4970: #
4971: # The user for whom we cache
4972: my $cachedkey='';
4973: # The cached times for this user
4974: my %cachedtimes=();
4975: # When this was last done
1.1282 raeburn 4976: my $cachedtime='';
1.1153 www 4977:
4978: sub load_all_first_access {
1.1308 raeburn 4979: my ($uname,$udom,$ignorecache)=@_;
1.1156 www 4980: if (($cachedkey eq $uname.':'.$udom) &&
1.1308 raeburn 4981: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
4982: (!$ignorecache)) {
1.1154 raeburn 4983: return;
4984: }
4985: $cachedtime=time;
4986: $cachedkey=$uname.':'.$udom;
4987: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4988: }
4989:
1.504 albertel 4990: sub get_first_access {
1.1308 raeburn 4991: my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790 albertel 4992: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4993: if ($argsymb) { $symb=$argsymb; }
4994: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4995: if ($argmap) { $map = $argmap; }
1.926 albertel 4996: if ($type eq 'course') {
4997: $res='course';
4998: } elsif ($type eq 'map') {
1.588 albertel 4999: $res=&symbread($map);
5000: } else {
5001: $res=$symb;
5002: }
1.1308 raeburn 5003: &load_all_first_access($uname,$udom,$ignorecache);
1.1153 www 5004: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 5005: }
5006:
5007: sub set_first_access {
1.1162 raeburn 5008: my ($type,$interval)=@_;
1.790 albertel 5009: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 5010: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 5011: if ($type eq 'course') {
5012: $res='course';
5013: } elsif ($type eq 'map') {
1.588 albertel 5014: $res=&symbread($map);
5015: } else {
5016: $res=$symb;
5017: }
1.1153 www 5018: $cachedkey='';
1.1162 raeburn 5019: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 5020: if (!$firstaccess) {
1.1162 raeburn 5021: my $start = time;
5022: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5023: $udom,$uname);
5024: if ($putres eq 'ok') {
5025: &put('timerinterval',{"$courseid\0$res"=>$interval},
5026: $udom,$uname);
5027: &appenv(
5028: {
5029: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5030: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5031: }
5032: );
5033: }
5034: return $putres;
1.505 albertel 5035: }
5036: return 'already_set';
1.504 albertel 5037: }
1.1153 www 5038: }
1.1282 raeburn 5039:
1.110 www 5040: # --------------------------------------------- Set Expire Date for Spreadsheet
5041:
5042: sub expirespread {
5043: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 5044: my $cid=$env{'request.course.id'};
1.110 www 5045: if ($cid) {
5046: my $now=time;
5047: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 5048: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5049: $env{'course.'.$cid.'.num'}.
1.110 www 5050: ':nohist_expirationdates:'.
5051: &escape($key).'='.$now,
1.620 albertel 5052: $env{'course.'.$cid.'.home'})
1.110 www 5053: }
5054: return 'ok';
1.14 www 5055: }
5056:
1.109 www 5057: # ----------------------------------------------------- Devalidate Spreadsheets
5058:
5059: sub devalidate {
1.325 www 5060: my ($symb,$uname,$udom)=@_;
1.620 albertel 5061: my $cid=$env{'request.course.id'};
1.109 www 5062: if ($cid) {
1.391 matthew 5063: # delete the stored spreadsheets for
5064: # - the student level sheet of this user in course's homespace
5065: # - the assessment level sheet for this resource
5066: # for this user in user's homespace
1.553 albertel 5067: # - current conditional state info
1.325 www 5068: my $key=$uname.':'.$udom.':';
1.109 www 5069: my $status=
1.299 matthew 5070: &del('nohist_calculatedsheets',
1.391 matthew 5071: [$key.'studentcalc:'],
1.620 albertel 5072: $env{'course.'.$cid.'.domain'},
5073: $env{'course.'.$cid.'.num'})
1.133 albertel 5074: .' '.
5075: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 5076: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 5077: unless ($status eq 'ok ok') {
5078: &logthis('Could not devalidate spreadsheet '.
1.325 www 5079: $uname.' at '.$udom.' for '.
1.109 www 5080: $symb.': '.$status);
1.133 albertel 5081: }
1.553 albertel 5082: &delenv('user.state.'.$cid);
1.109 www 5083: }
5084: }
5085:
1.265 albertel 5086: sub get_scalar {
5087: my ($string,$end) = @_;
5088: my $value;
5089: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5090: $value = $1;
5091: } elsif ($$string =~ s/^([^&]*?)&//) {
5092: $value = $1;
5093: }
5094: return &unescape($value);
5095: }
5096:
5097: sub array2str {
5098: my (@array) = @_;
5099: my $result=&arrayref2str(\@array);
5100: $result=~s/^__ARRAY_REF__//;
5101: $result=~s/__END_ARRAY_REF__$//;
5102: return $result;
5103: }
5104:
1.204 albertel 5105: sub arrayref2str {
5106: my ($arrayref) = @_;
1.265 albertel 5107: my $result='__ARRAY_REF__';
1.204 albertel 5108: foreach my $elem (@$arrayref) {
1.265 albertel 5109: if(ref($elem) eq 'ARRAY') {
5110: $result.=&arrayref2str($elem).'&';
5111: } elsif(ref($elem) eq 'HASH') {
5112: $result.=&hashref2str($elem).'&';
5113: } elsif(ref($elem)) {
5114: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 5115: } else {
5116: $result.=&escape($elem).'&';
5117: }
5118: }
5119: $result=~s/\&$//;
1.265 albertel 5120: $result .= '__END_ARRAY_REF__';
1.204 albertel 5121: return $result;
5122: }
5123:
1.168 albertel 5124: sub hash2str {
1.204 albertel 5125: my (%hash) = @_;
5126: my $result=&hashref2str(\%hash);
1.265 albertel 5127: $result=~s/^__HASH_REF__//;
5128: $result=~s/__END_HASH_REF__$//;
1.204 albertel 5129: return $result;
5130: }
5131:
5132: sub hashref2str {
5133: my ($hashref)=@_;
1.265 albertel 5134: my $result='__HASH_REF__';
1.800 albertel 5135: foreach my $key (sort(keys(%$hashref))) {
5136: if (ref($key) eq 'ARRAY') {
5137: $result.=&arrayref2str($key).'=';
5138: } elsif (ref($key) eq 'HASH') {
5139: $result.=&hashref2str($key).'=';
5140: } elsif (ref($key)) {
1.265 albertel 5141: $result.='=';
1.800 albertel 5142: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 5143: } else {
1.1132 raeburn 5144: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 5145: }
5146:
1.800 albertel 5147: if(ref($hashref->{$key}) eq 'ARRAY') {
5148: $result.=&arrayref2str($hashref->{$key}).'&';
5149: } elsif(ref($hashref->{$key}) eq 'HASH') {
5150: $result.=&hashref2str($hashref->{$key}).'&';
5151: } elsif(ref($hashref->{$key})) {
1.265 albertel 5152: $result.='&';
1.800 albertel 5153: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 5154: } else {
1.800 albertel 5155: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 5156: }
5157: }
1.168 albertel 5158: $result=~s/\&$//;
1.265 albertel 5159: $result .= '__END_HASH_REF__';
1.168 albertel 5160: return $result;
5161: }
5162:
5163: sub str2hash {
1.265 albertel 5164: my ($string)=@_;
5165: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5166: return %$hash;
5167: }
5168:
5169: sub str2hashref {
1.168 albertel 5170: my ($string) = @_;
1.265 albertel 5171:
5172: my %hash;
5173:
5174: if($string !~ /^__HASH_REF__/) {
5175: if (! ($string eq '' || !defined($string))) {
5176: $hash{'error'}='Not hash reference';
5177: }
5178: return (\%hash, $string);
5179: }
5180:
5181: $string =~ s/^__HASH_REF__//;
5182:
5183: while($string !~ /^__END_HASH_REF__/) {
5184: #key
5185: my $key='';
5186: if($string =~ /^__HASH_REF__/) {
5187: ($key, $string)=&str2hashref($string);
5188: if(defined($key->{'error'})) {
5189: $hash{'error'}='Bad data';
5190: return (\%hash, $string);
5191: }
5192: } elsif($string =~ /^__ARRAY_REF__/) {
5193: ($key, $string)=&str2arrayref($string);
5194: if($key->[0] eq 'Array reference error') {
5195: $hash{'error'}='Bad data';
5196: return (\%hash, $string);
5197: }
5198: } else {
5199: $string =~ s/^(.*?)=//;
1.267 albertel 5200: $key=&unescape($1);
1.265 albertel 5201: }
5202: $string =~ s/^=//;
5203:
5204: #value
5205: my $value='';
5206: if($string =~ /^__HASH_REF__/) {
5207: ($value, $string)=&str2hashref($string);
5208: if(defined($value->{'error'})) {
5209: $hash{'error'}='Bad data';
5210: return (\%hash, $string);
5211: }
5212: } elsif($string =~ /^__ARRAY_REF__/) {
5213: ($value, $string)=&str2arrayref($string);
5214: if($value->[0] eq 'Array reference error') {
5215: $hash{'error'}='Bad data';
5216: return (\%hash, $string);
5217: }
5218: } else {
5219: $value=&get_scalar(\$string,'__END_HASH_REF__');
5220: }
5221: $string =~ s/^&//;
5222:
5223: $hash{$key}=$value;
1.204 albertel 5224: }
1.265 albertel 5225:
5226: $string =~ s/^__END_HASH_REF__//;
5227:
5228: return (\%hash, $string);
1.204 albertel 5229: }
5230:
5231: sub str2array {
1.265 albertel 5232: my ($string)=@_;
5233: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5234: return @$array;
5235: }
5236:
5237: sub str2arrayref {
1.204 albertel 5238: my ($string) = @_;
1.265 albertel 5239: my @array;
5240:
5241: if($string !~ /^__ARRAY_REF__/) {
5242: if (! ($string eq '' || !defined($string))) {
5243: $array[0]='Array reference error';
5244: }
5245: return (\@array, $string);
5246: }
5247:
5248: $string =~ s/^__ARRAY_REF__//;
5249:
5250: while($string !~ /^__END_ARRAY_REF__/) {
5251: my $value='';
5252: if($string =~ /^__HASH_REF__/) {
5253: ($value, $string)=&str2hashref($string);
5254: if(defined($value->{'error'})) {
5255: $array[0] ='Array reference error';
5256: return (\@array, $string);
5257: }
5258: } elsif($string =~ /^__ARRAY_REF__/) {
5259: ($value, $string)=&str2arrayref($string);
5260: if($value->[0] eq 'Array reference error') {
5261: $array[0] ='Array reference error';
5262: return (\@array, $string);
5263: }
5264: } else {
5265: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5266: }
5267: $string =~ s/^&//;
5268:
5269: push(@array, $value);
1.191 harris41 5270: }
1.265 albertel 5271:
5272: $string =~ s/^__END_ARRAY_REF__//;
5273:
5274: return (\@array, $string);
1.168 albertel 5275: }
5276:
1.167 albertel 5277: # -------------------------------------------------------------------Temp Store
5278:
1.168 albertel 5279: sub tmpreset {
5280: my ($symb,$namespace,$domain,$stuname) = @_;
5281: if (!$symb) {
5282: $symb=&symbread();
1.620 albertel 5283: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5284: }
5285: $symb=escape($symb);
5286:
1.620 albertel 5287: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 5288: $namespace=~s/\//\_/g;
5289: $namespace=~s/\W//g;
5290:
1.620 albertel 5291: if (!$domain) { $domain=$env{'user.domain'}; }
5292: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5293: if ($domain eq 'public' && $stuname eq 'public') {
5294: $stuname=$ENV{'REMOTE_ADDR'};
5295: }
1.1117 foxr 5296: my $path=LONCAPA::tempdir();
1.168 albertel 5297: my %hash;
5298: if (tie(%hash,'GDBM_File',
5299: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5300: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 5301: foreach my $key (keys(%hash)) {
1.180 albertel 5302: if ($key=~ /:$symb/) {
1.168 albertel 5303: delete($hash{$key});
5304: }
5305: }
5306: }
5307: }
5308:
1.167 albertel 5309: sub tmpstore {
1.168 albertel 5310: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5311:
5312: if (!$symb) {
5313: $symb=&symbread();
1.620 albertel 5314: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5315: }
5316: $symb=escape($symb);
5317:
5318: if (!$namespace) {
5319: # I don't think we would ever want to store this for a course.
5320: # it seems this will only be used if we don't have a course.
1.620 albertel 5321: #$namespace=$env{'request.course.id'};
1.168 albertel 5322: #if (!$namespace) {
1.620 albertel 5323: $namespace=$env{'request.state'};
1.168 albertel 5324: #}
5325: }
5326: $namespace=~s/\//\_/g;
5327: $namespace=~s/\W//g;
1.620 albertel 5328: if (!$domain) { $domain=$env{'user.domain'}; }
5329: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5330: if ($domain eq 'public' && $stuname eq 'public') {
5331: $stuname=$ENV{'REMOTE_ADDR'};
5332: }
1.168 albertel 5333: my $now=time;
5334: my %hash;
1.1117 foxr 5335: my $path=LONCAPA::tempdir();
1.168 albertel 5336: if (tie(%hash,'GDBM_File',
5337: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5338: &GDBM_WRCREAT(),0640)) {
1.168 albertel 5339: $hash{"version:$symb"}++;
5340: my $version=$hash{"version:$symb"};
5341: my $allkeys='';
5342: foreach my $key (keys(%$storehash)) {
5343: $allkeys.=$key.':';
1.591 albertel 5344: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 5345: }
5346: $hash{"$version:$symb:timestamp"}=$now;
5347: $allkeys.='timestamp';
5348: $hash{"$version:keys:$symb"}=$allkeys;
5349: if (untie(%hash)) {
5350: return 'ok';
5351: } else {
5352: return "error:$!";
5353: }
5354: } else {
5355: return "error:$!";
5356: }
5357: }
1.167 albertel 5358:
1.168 albertel 5359: # -----------------------------------------------------------------Temp Restore
1.167 albertel 5360:
1.168 albertel 5361: sub tmprestore {
5362: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 5363:
1.168 albertel 5364: if (!$symb) {
5365: $symb=&symbread();
1.620 albertel 5366: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 5367: }
5368: $symb=escape($symb);
5369:
1.620 albertel 5370: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 5371:
1.620 albertel 5372: if (!$domain) { $domain=$env{'user.domain'}; }
5373: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 5374: if ($domain eq 'public' && $stuname eq 'public') {
5375: $stuname=$ENV{'REMOTE_ADDR'};
5376: }
1.168 albertel 5377: my %returnhash;
5378: $namespace=~s/\//\_/g;
5379: $namespace=~s/\W//g;
5380: my %hash;
1.1117 foxr 5381: my $path=LONCAPA::tempdir();
1.168 albertel 5382: if (tie(%hash,'GDBM_File',
5383: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 5384: &GDBM_READER(),0640)) {
1.168 albertel 5385: my $version=$hash{"version:$symb"};
5386: $returnhash{'version'}=$version;
5387: my $scope;
5388: for ($scope=1;$scope<=$version;$scope++) {
5389: my $vkeys=$hash{"$scope:keys:$symb"};
5390: my @keys=split(/:/,$vkeys);
5391: my $key;
5392: $returnhash{"$scope:keys"}=$vkeys;
5393: foreach $key (@keys) {
1.591 albertel 5394: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5395: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 5396: }
5397: }
1.168 albertel 5398: if (!(untie(%hash))) {
5399: return "error:$!";
5400: }
5401: } else {
5402: return "error:$!";
5403: }
5404: return %returnhash;
1.167 albertel 5405: }
5406:
1.9 www 5407: # ----------------------------------------------------------------------- Store
5408:
5409: sub store {
1.1269 raeburn 5410: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5411: my $home='';
5412:
1.168 albertel 5413: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5414:
1.213 www 5415: $symb=&symbclean($symb);
1.122 albertel 5416: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5417:
1.620 albertel 5418: if (!$domain) { $domain=$env{'user.domain'}; }
5419: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5420:
5421: &devalidate($symb,$stuname,$domain);
1.109 www 5422:
5423: $symb=escape($symb);
1.187 www 5424: if (!$namespace) {
1.620 albertel 5425: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5426: return '';
5427: }
5428: }
1.620 albertel 5429: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5430:
5431: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5432: $$storehash{'host'}=$perlvar{'lonHostID'};
5433:
1.12 www 5434: my $namevalue='';
1.800 albertel 5435: foreach my $key (keys(%$storehash)) {
5436: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5437: }
1.12 www 5438: $namevalue=~s/\&$//;
1.187 www 5439: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269 raeburn 5440: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9 www 5441: }
5442:
1.47 www 5443: # -------------------------------------------------------------- Critical Store
5444:
5445: sub cstore {
1.1269 raeburn 5446: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124 www 5447: my $home='';
5448:
1.168 albertel 5449: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5450:
1.213 www 5451: $symb=&symbclean($symb);
1.122 albertel 5452: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 5453:
1.620 albertel 5454: if (!$domain) { $domain=$env{'user.domain'}; }
5455: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 5456:
5457: &devalidate($symb,$stuname,$domain);
1.109 www 5458:
5459: $symb=escape($symb);
1.187 www 5460: if (!$namespace) {
1.620 albertel 5461: unless ($namespace=$env{'request.course.id'}) {
1.187 www 5462: return '';
5463: }
5464: }
1.620 albertel 5465: if (!$home) { $home=$env{'user.home'}; }
1.447 www 5466:
5467: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5468: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 5469:
1.47 www 5470: my $namevalue='';
1.800 albertel 5471: foreach my $key (keys(%$storehash)) {
5472: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 5473: }
1.47 www 5474: $namevalue=~s/\&$//;
1.187 www 5475: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 5476: return critical
1.1269 raeburn 5477: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47 www 5478: }
5479:
1.9 www 5480: # --------------------------------------------------------------------- Restore
5481:
5482: sub restore {
1.124 www 5483: my ($symb,$namespace,$domain,$stuname) = @_;
5484: my $home='';
5485:
1.168 albertel 5486: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 5487:
1.122 albertel 5488: if (!$symb) {
1.1224 raeburn 5489: return if ($namespace eq 'courserequests');
5490: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 5491: } else {
1.1224 raeburn 5492: unless ($namespace eq 'courserequests') {
5493: $symb=&escape(&symbclean($symb));
5494: }
1.122 albertel 5495: }
1.188 www 5496: if (!$namespace) {
1.620 albertel 5497: unless ($namespace=$env{'request.course.id'}) {
1.188 www 5498: return '';
5499: }
5500: }
1.620 albertel 5501: if (!$domain) { $domain=$env{'user.domain'}; }
5502: if (!$stuname) { $stuname=$env{'user.name'}; }
5503: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 5504: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
5505:
1.12 www 5506: my %returnhash=();
1.800 albertel 5507: foreach my $line (split(/\&/,$answer)) {
5508: my ($name,$value)=split(/\=/,$line);
1.591 albertel 5509: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 5510: }
1.75 www 5511: my $version;
5512: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 5513: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
5514: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 5515: }
1.75 www 5516: }
1.13 www 5517: return %returnhash;
1.34 www 5518: }
5519:
5520: # ---------------------------------------------------------- Course Description
1.1118 foxr 5521: #
5522: #
1.34 www 5523:
5524: sub coursedescription {
1.731 albertel 5525: my ($courseid,$args)=@_;
1.34 www 5526: $courseid=~s/^\///;
1.49 www 5527: $courseid=~s/\_/\//g;
1.34 www 5528: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 5529: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 5530: my $normalid=$cdomain.'_'.$cnum;
5531: # need to always cache even if we get errors otherwise we keep
5532: # trying and trying and trying to get the course description.
5533: my %envhash=();
5534: my %returnhash=();
1.731 albertel 5535:
5536: my $expiretime=600;
5537: if ($env{'request.course.id'} eq $normalid) {
5538: $expiretime=120;
5539: }
5540:
5541: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5542: if (!$args->{'freshen_cache'}
5543: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5544: foreach my $key (keys(%env)) {
5545: next if ($key !~ /^\Q$prefix\E(.*)/);
5546: my ($setting) = $1;
5547: $returnhash{$setting} = $env{$key};
5548: }
5549: return %returnhash;
5550: }
5551:
1.1118 foxr 5552: # get the data again
5553:
1.731 albertel 5554: if (!$args->{'one_time'}) {
5555: $envhash{'course.'.$normalid.'.last_cache'}=time;
5556: }
1.811 albertel 5557:
1.34 www 5558: if ($chome ne 'no_host') {
1.302 albertel 5559: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 5560: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 5561: my $username = $env{'user.name'}; # Defult username
5562: if(defined $args->{'user'}) {
5563: $username = $args->{'user'};
5564: }
1.129 albertel 5565: $returnhash{'home'}= $chome;
5566: $returnhash{'domain'} = $cdomain;
5567: $returnhash{'num'} = $cnum;
1.741 raeburn 5568: if (!defined($returnhash{'type'})) {
5569: $returnhash{'type'} = 'Course';
5570: }
1.130 albertel 5571: while (my ($name,$value) = each %returnhash) {
1.53 www 5572: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 5573: }
1.270 www 5574: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 5575: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 5576: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 5577: $envhash{'course.'.$normalid.'.home'}=$chome;
5578: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5579: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 5580: }
5581: }
1.731 albertel 5582: if (!$args->{'one_time'}) {
1.949 raeburn 5583: &appenv(\%envhash);
1.731 albertel 5584: }
1.302 albertel 5585: return %returnhash;
1.461 www 5586: }
5587:
1.1080 raeburn 5588: sub update_released_required {
5589: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5590: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5591: $cid = $env{'request.course.id'};
5592: $cdom = $env{'course.'.$cid.'.domain'};
5593: $cnum = $env{'course.'.$cid.'.num'};
5594: $chome = $env{'course.'.$cid.'.home'};
5595: }
5596: if ($needsrelease) {
5597: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5598: my $needsupdate;
5599: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5600: $needsupdate = 1;
5601: } else {
5602: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5603: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5604: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5605: $needsupdate = 1;
5606: }
5607: }
5608: if ($needsupdate) {
5609: my %needshash = (
5610: 'internal.releaserequired' => $needsrelease,
5611: );
5612: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5613: if ($putresult eq 'ok') {
5614: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5615: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5616: if (ref($crsinfo{$cid}) eq 'HASH') {
5617: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5618: &courseidput($cdom,\%crsinfo,$chome,'notime');
5619: }
5620: }
5621: }
5622: }
5623: return;
5624: }
5625:
1.461 www 5626: # -------------------------------------------------See if a user is privileged
5627:
5628: sub privileged {
1.1219 raeburn 5629: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5630: my $now = time;
1.1219 raeburn 5631: my $roles;
5632: if (ref($possroles) eq 'ARRAY') {
5633: $roles = $possroles;
5634: } else {
5635: $roles = ['dc','su'];
5636: }
5637: if (ref($possdomains) eq 'ARRAY') {
5638: my %privileged = &privileged_by_domain($possdomains,$roles);
5639: foreach my $dom (@{$possdomains}) {
5640: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5641: (ref($privileged{$dom}) eq 'HASH')) {
5642: foreach my $role (@{$roles}) {
5643: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5644: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5645: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5646: return 1 unless (($end && $end < $now) ||
5647: ($start && $start > $now));
5648: }
5649: }
5650: }
5651: }
5652: }
5653: } else {
5654: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5655: my $now = time;
1.1170 droeschl 5656:
1.1275 musolffc 5657: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170 droeschl 5658: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5659: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5660: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5661: or ($tstart && $tstart > $now);
1.1170 droeschl 5662: }
1.1219 raeburn 5663: }
5664: }
5665: return 0;
5666: }
1.1170 droeschl 5667:
1.1219 raeburn 5668: sub privileged_by_domain {
5669: my ($domains,$roles) = @_;
5670: my %privileged = ();
5671: my $cachetime = 60*60*24;
5672: my $now = time;
5673: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5674: return %privileged;
5675: }
5676: foreach my $dom (@{$domains}) {
5677: next if (ref($privileged{$dom}) eq 'HASH');
5678: my $needroles;
5679: foreach my $role (@{$roles}) {
5680: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5681: if (defined($cached)) {
5682: if (ref($result) eq 'HASH') {
5683: $privileged{$dom}{$role} = $result;
5684: }
5685: } else {
5686: $needroles = 1;
5687: }
5688: }
5689: if ($needroles) {
5690: my %dompersonnel = &get_domain_roles($dom,$roles);
5691: $privileged{$dom} = {};
5692: foreach my $server (keys(%dompersonnel)) {
5693: if (ref($dompersonnel{$server}) eq 'HASH') {
5694: foreach my $item (keys(%{$dompersonnel{$server}})) {
5695: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5696: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5697: next if ($end && $end < $now);
5698: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5699: $dompersonnel{$server}{$item};
5700: }
5701: }
5702: }
5703: if (ref($privileged{$dom}) eq 'HASH') {
5704: foreach my $role (@{$roles}) {
5705: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5706: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5707: } else {
5708: my %hash = ();
5709: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5710: }
5711: }
5712: }
5713: }
5714: }
5715: return %privileged;
1.9 www 5716: }
1.1 albertel 5717:
1.103 harris41 5718: # -------------------------------------------------------- Get user privileges
1.11 www 5719:
5720: sub rolesinit {
1.1169 droeschl 5721: my ($domain, $username) = @_;
5722: my %userroles = ('user.login.time' => time);
5723: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5724:
5725: # firstaccess and timerinterval are related to timed maps/resources.
5726: # also, blocking can be triggered by an activating timer
5727: # it's saved in the user's %env.
5728: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5729: my %timerinterval = &dump('timerinterval', $domain, $username);
5730: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5731: %timerintchk, %timerintenv);
5732:
1.1162 raeburn 5733: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5734: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5735: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5736: }
1.1169 droeschl 5737:
1.1162 raeburn 5738: foreach my $key (keys(%timerinterval)) {
5739: my ($cid,$rest) = split(/\0/,$key);
5740: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5741: }
1.1169 droeschl 5742:
1.11 www 5743: my %allroles=();
1.1162 raeburn 5744: my %allgroups=();
1.11 www 5745:
1.1274 raeburn 5746: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169 droeschl 5747: my $role = $rolesdump{$area};
5748: $area =~ s/\_\w\w$//;
5749:
5750: my ($trole, $tend, $tstart, $group_privs);
5751:
5752: if ($role =~ /^cr/) {
5753: # Custom role, defined by a user
5754: # e.g., user.role.cr/msu/smith/mynewrole
5755: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5756: $trole = $1;
5757: ($tend, $tstart) = split('_', $2);
5758: } else {
5759: $trole = $role;
5760: }
5761: } elsif ($role =~ m|^gr/|) {
5762: # Role of member in a group, defined within a course/community
5763: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5764: ($trole, $tend, $tstart) = split(/_/, $role);
5765: next if $tstart eq '-1';
5766: ($trole, $group_privs) = split(/\//, $trole);
5767: $group_privs = &unescape($group_privs);
5768: } else {
5769: # Just a normal role, defined in roles.tab
5770: ($trole, $tend, $tstart) = split(/_/,$role);
5771: }
5772:
5773: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5774: $username);
5775: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5776:
5777: # role expired or not available yet?
5778: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5779: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5780:
5781: next if $area eq '' or $trole eq '';
5782:
5783: my $spec = "$trole.$area";
5784: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5785:
5786: if ($trole =~ /^cr\//) {
5787: # Custom role, defined by a user
5788: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5789: } elsif ($trole eq 'gr') {
5790: # Role of a member in a group, defined within a course/community
5791: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5792: next;
5793: } else {
5794: # Normal role, defined in roles.tab
5795: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5796: }
5797:
5798: my $cid = $tdomain.'_'.$trest;
5799: unless ($firstaccchk{$cid}) {
5800: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5801: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5802: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5803: $coursetimerstarts{$cid}{$item};
5804: }
5805: }
5806: $firstaccchk{$cid} = 1;
5807: }
5808: unless ($timerintchk{$cid}) {
5809: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5810: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5811: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5812: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5813: }
1.12 www 5814: }
1.1169 droeschl 5815: $timerintchk{$cid} = 1;
1.191 harris41 5816: }
1.11 www 5817: }
1.1169 droeschl 5818:
1.1341 raeburn 5819: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
5820: \%allroles, \%allgroups);
1.1169 droeschl 5821: $env{'user.adv'} = $userroles{'user.adv'};
1.1341 raeburn 5822: $env{'user.rar'} = $userroles{'user.rar'};
1.1169 droeschl 5823:
1.1162 raeburn 5824: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5825: }
5826:
1.567 raeburn 5827: sub set_arearole {
1.1215 raeburn 5828: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5829: unless ($nolog) {
1.567 raeburn 5830: # log the associated role with the area
1.1215 raeburn 5831: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5832: }
1.743 albertel 5833: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5834: }
5835:
5836: sub custom_roleprivs {
5837: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5838: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 5839: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5840: if (&hostname($homsvr) ne '') {
1.567 raeburn 5841: my ($rdummy,$roledef)=
5842: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5843: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5844: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5845: if (defined($syspriv)) {
1.1043 raeburn 5846: if ($trest =~ /^$match_community$/) {
5847: $syspriv =~ s/bre\&S//;
5848: }
1.567 raeburn 5849: $$allroles{'cm./'}.=':'.$syspriv;
5850: $$allroles{$spec.'./'}.=':'.$syspriv;
5851: }
5852: if ($tdomain ne '') {
5853: if (defined($dompriv)) {
5854: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5855: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5856: }
5857: if (($trest ne '') && (defined($coursepriv))) {
1.1332 raeburn 5858: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
5859: my $rolename = $1;
5860: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
5861: }
1.567 raeburn 5862: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5863: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5864: }
5865: }
5866: }
5867: }
5868: }
5869:
1.1332 raeburn 5870: sub course_adhocrole_privs {
5871: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
5872: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
5873: if ($overrides{"internal.adhocpriv.$rolename"}) {
5874: my (%currprivs,%storeprivs);
5875: foreach my $item (split(/:/,$coursepriv)) {
5876: my ($priv,$restrict) = split(/\&/,$item);
5877: $currprivs{$priv} = $restrict;
5878: }
5879: my (%possadd,%possremove,%full);
5880: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
5881: my ($priv,$restrict)=split(/\&/,$item);
5882: $full{$priv} = $restrict;
5883: }
5884: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
5885: next if ($item eq '');
5886: my ($rule,$rest) = split(/=/,$item);
5887: next unless (($rule eq 'off') || ($rule eq 'on'));
5888: foreach my $priv (split(/:/,$rest)) {
5889: if ($priv ne '') {
5890: if ($rule eq 'off') {
5891: $possremove{$priv} = 1;
5892: } else {
5893: $possadd{$priv} = 1;
5894: }
5895: }
5896: }
5897: }
5898: foreach my $priv (sort(keys(%full))) {
5899: if (exists($currprivs{$priv})) {
5900: unless (exists($possremove{$priv})) {
5901: $storeprivs{$priv} = $currprivs{$priv};
5902: }
5903: } elsif (exists($possadd{$priv})) {
5904: $storeprivs{$priv} = $full{$priv};
5905: }
5906: }
5907: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
5908: }
5909: return $coursepriv;
5910: }
5911:
1.678 raeburn 5912: sub group_roleprivs {
5913: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5914: my $access = 1;
5915: my $now = time;
5916: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5917: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5918: if ($access) {
1.811 albertel 5919: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5920: $$allgroups{$course}{$group} .=':'.$group_privs;
5921: }
5922: }
1.567 raeburn 5923:
5924: sub standard_roleprivs {
5925: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5926: if (defined($pr{$trole.':s'})) {
5927: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5928: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5929: }
5930: if ($tdomain ne '') {
5931: if (defined($pr{$trole.':d'})) {
5932: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5933: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5934: }
5935: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5936: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5937: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5938: }
5939: }
5940: }
5941:
5942: sub set_userprivs {
1.1064 raeburn 5943: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5944: my $author=0;
5945: my $adv=0;
1.1341 raeburn 5946: my $rar=0;
1.678 raeburn 5947: my %grouproles = ();
5948: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5949: my @groupkeys;
1.1000 raeburn 5950: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5951: push(@groupkeys,$role);
5952: }
5953: if (ref($groups_roles) eq 'HASH') {
5954: foreach my $key (keys(%{$groups_roles})) {
5955: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5956: push(@groupkeys,$key);
5957: }
5958: }
5959: }
5960: if (@groupkeys > 0) {
5961: foreach my $role (@groupkeys) {
5962: my ($trole,$area,$sec,$extendedarea);
5963: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5964: $trole = $1;
5965: $area = $2;
5966: $sec = $3;
5967: $extendedarea = $area.$sec;
5968: if (exists($$allgroups{$area})) {
5969: foreach my $group (keys(%{$$allgroups{$area}})) {
5970: my $spec = $trole.'.'.$extendedarea;
5971: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5972: $$allgroups{$area}{$group};
1.1064 raeburn 5973: }
1.678 raeburn 5974: }
5975: }
5976: }
5977: }
5978: }
1.800 albertel 5979: foreach my $group (keys(%grouproles)) {
5980: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5981: }
1.800 albertel 5982: foreach my $role (keys(%{$allroles})) {
5983: my %thesepriv;
1.941 raeburn 5984: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5985: foreach my $item (split(/:/,$$allroles{$role})) {
5986: if ($item ne '') {
5987: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5988: if ($restrictions eq '') {
5989: $thesepriv{$privilege}='F';
5990: } elsif ($thesepriv{$privilege} ne 'F') {
5991: $thesepriv{$privilege}.=$restrictions;
5992: }
5993: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341 raeburn 5994: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567 raeburn 5995: }
5996: }
5997: my $thesestr='';
1.1104 raeburn 5998: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5999: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6000: }
6001: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 6002: }
1.1341 raeburn 6003: return ($author,$adv,$rar);
1.567 raeburn 6004: }
6005:
1.994 raeburn 6006: sub role_status {
1.1104 raeburn 6007: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 6008: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 6009: my ($one,$two) = split(m{\./},$rolekey,2);
6010: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 6011: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 6012: $$where = '/'.$two;
1.994 raeburn 6013: $$trolecode=$$role.'.'.$$where;
6014: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6015: $$tstatus='is';
1.1104 raeburn 6016: if ($$tstart && $$tstart>$update) {
1.994 raeburn 6017: $$tstatus='future';
1.1034 raeburn 6018: if ($$tstart<$now) {
6019: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 6020: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 6021: my (%allroles,%allgroups,$group_privs,
6022: %groups_roles,@rolecodes);
1.1002 raeburn 6023: my %userroles = (
6024: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6025: );
1.1064 raeburn 6026: @rolecodes = ('cm');
1.1002 raeburn 6027: my $spec=$$role.'.'.$$where;
6028: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6029: if ($$role =~ /^cr\//) {
6030: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 6031: push(@rolecodes,'cr');
1.1002 raeburn 6032: } elsif ($$role eq 'gr') {
1.1064 raeburn 6033: push(@rolecodes,$$role);
1.1002 raeburn 6034: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6035: $env{'user.name'});
1.1064 raeburn 6036: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 6037: (undef,my $group_privs) = split(/\//,$trole);
6038: $group_privs = &unescape($group_privs);
6039: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 6040: 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 6041: &get_groups_roles($tdomain,$trest,
6042: \%course_roles,\@rolecodes,
6043: \%groups_roles);
1.1002 raeburn 6044: } else {
1.1064 raeburn 6045: push(@rolecodes,$$role);
1.1002 raeburn 6046: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6047: }
1.1341 raeburn 6048: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6049: \%groups_roles);
1.1064 raeburn 6050: &appenv(\%userroles,\@rolecodes);
1.1342 raeburn 6051: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002 raeburn 6052: }
6053: }
1.1034 raeburn 6054: $$tstatus = 'is';
1.1002 raeburn 6055: }
1.994 raeburn 6056: }
6057: if ($$tend) {
1.1104 raeburn 6058: if ($$tend<$update) {
1.994 raeburn 6059: $$tstatus='expired';
6060: } elsif ($$tend<$now) {
6061: $$tstatus='will_not';
6062: }
6063: }
6064: }
6065: }
6066: }
6067:
1.1104 raeburn 6068: sub get_groups_roles {
6069: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6070: return unless((ref($cdom_courseroles) eq 'HASH') &&
6071: (ref($rolecodes) eq 'ARRAY') &&
6072: (ref($groups_roles) eq 'HASH'));
6073: if (keys(%{$cdom_courseroles}) > 0) {
6074: my ($cnum) = ($rest =~ /^($match_courseid)/);
6075: if ($cdom ne '' && $cnum ne '') {
6076: foreach my $key (keys(%{$cdom_courseroles})) {
6077: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6078: my $crsrole = $1;
6079: my $crssec = $2;
6080: if ($crsrole =~ /^cr/) {
6081: unless (grep(/^cr$/,@{$rolecodes})) {
6082: push(@{$rolecodes},'cr');
6083: }
6084: } else {
6085: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6086: push(@{$rolecodes},$crsrole);
6087: }
6088: }
6089: my $rolekey = "$crsrole./$cdom/$cnum";
6090: if ($crssec ne '') {
6091: $rolekey .= "/$crssec";
6092: }
6093: $rolekey .= './';
6094: $groups_roles->{$rolekey} = $rolecodes;
6095: }
6096: }
6097: }
6098: }
6099: return;
6100: }
6101:
6102: sub delete_env_groupprivs {
6103: my ($where,$courseroles,$possroles) = @_;
6104: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6105: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6106: unless (ref($courseroles->{$udom}) eq 'HASH') {
6107: %{$courseroles->{$udom}} =
6108: &get_my_roles('','','userroles',['active'],
6109: $possroles,[$udom],1);
6110: }
6111: if (ref($courseroles->{$udom}) eq 'HASH') {
6112: foreach my $item (keys(%{$courseroles->{$udom}})) {
6113: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6114: my $area = '/'.$cdom.'/'.$cnum;
6115: my $privkey = "user.priv.$crsrole.$area";
6116: if ($crssec ne '') {
6117: $privkey .= '/'.$crssec;
6118: }
6119: $privkey .= ".$area/$group";
6120: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6121: }
6122: }
6123: return;
6124: }
6125:
1.994 raeburn 6126: sub check_adhoc_privs {
1.1329 raeburn 6127: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994 raeburn 6128: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329 raeburn 6129: if ($sec) {
6130: $cckey .= '/'.$sec;
6131: }
1.1185 raeburn 6132: my $setprivs;
1.994 raeburn 6133: if ($env{$cckey}) {
6134: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 6135: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 6136: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329 raeburn 6137: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 6138: $setprivs = 1;
1.994 raeburn 6139: }
6140: } else {
1.1330 raeburn 6141: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185 raeburn 6142: $setprivs = 1;
1.994 raeburn 6143: }
1.1185 raeburn 6144: return $setprivs;
1.994 raeburn 6145: }
6146:
6147: sub set_adhoc_privileges {
1.1326 raeburn 6148: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329 raeburn 6149: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994 raeburn 6150: my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329 raeburn 6151: if ($sec ne '') {
6152: $area .= '/'.$sec;
6153: }
1.994 raeburn 6154: my $spec = $role.'.'.$area;
6155: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 6156: $env{'user.name'},1);
1.1326 raeburn 6157: my %rolehash = ();
1.1332 raeburn 6158: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6159: my $rolename = $1;
1.1326 raeburn 6160: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332 raeburn 6161: my %domdef = &get_domain_defaults($dcdom);
6162: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6163: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6164: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6165: }
6166: }
1.1326 raeburn 6167: } else {
6168: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6169: }
1.1341 raeburn 6170: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994 raeburn 6171: &appenv(\%userroles,[$role,'cm']);
1.1342 raeburn 6172: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088 raeburn 6173: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6174: &appenv( {'request.role' => $spec,
6175: 'request.role.domain' => $dcdom,
1.1332 raeburn 6176: 'request.course.sec' => $sec,
1.1088 raeburn 6177: }
6178: );
6179: my $tadv=0;
6180: if (&allowed('adv') eq 'F') { $tadv=1; }
6181: &appenv({'request.role.adv' => $tadv});
6182: }
1.994 raeburn 6183: }
6184:
1.12 www 6185: # --------------------------------------------------------------- get interface
6186:
6187: sub get {
1.131 albertel 6188: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6189: my $items='';
1.800 albertel 6190: foreach my $item (@$storearr) {
6191: $items.=&escape($item).'&';
1.191 harris41 6192: }
1.12 www 6193: $items=~s/\&$//;
1.620 albertel 6194: if (!$udomain) { $udomain=$env{'user.domain'}; }
6195: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 6196: my $uhome=&homeserver($uname,$udomain);
6197:
1.133 albertel 6198: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6199: my @pairs=split(/\&/,$rep);
1.273 albertel 6200: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6201: return @pairs;
6202: }
1.15 www 6203: my %returnhash=();
1.42 www 6204: my $i=0;
1.800 albertel 6205: foreach my $item (@$storearr) {
6206: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6207: $i++;
1.191 harris41 6208: }
1.15 www 6209: return %returnhash;
1.27 www 6210: }
6211:
6212: # --------------------------------------------------------------- del interface
6213:
6214: sub del {
1.133 albertel 6215: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 6216: my $items='';
1.800 albertel 6217: foreach my $item (@$storearr) {
6218: $items.=&escape($item).'&';
1.191 harris41 6219: }
1.984 neumanie 6220:
1.27 www 6221: $items=~s/\&$//;
1.620 albertel 6222: if (!$udomain) { $udomain=$env{'user.domain'}; }
6223: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6224: my $uhome=&homeserver($uname,$udomain);
6225: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 6226: }
6227:
6228: # -------------------------------------------------------------- dump interface
6229:
1.1180 droeschl 6230: sub unserialize {
6231: my ($rep, $escapedkeys) = @_;
6232:
6233: return {} if $rep =~ /^error/;
6234:
6235: my %returnhash=();
1.1252 raeburn 6236: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 6237: my ($key, $value) = split(/=/, $item, 2);
6238: $key = unescape($key) unless $escapedkeys;
6239: next if $key =~ /^error: 2 /;
1.1252 raeburn 6240: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 6241: }
6242: #return %returnhash;
6243: return \%returnhash;
6244: }
6245:
6246: # see Lond::dump_with_regexp
6247: # if $escapedkeys hash keys won't get unescaped.
1.15 www 6248: sub dump {
1.1180 droeschl 6249: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 6250: if (!$udomain) { $udomain=$env{'user.domain'}; }
6251: if (!$uname) { $uname=$env{'user.name'}; }
6252: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 6253:
1.1266 raeburn 6254: if ($regexp) {
6255: $regexp=&escape($regexp);
6256: } else {
6257: $regexp='.';
6258: }
1.1180 droeschl 6259: if (grep { $_ eq $uhome } current_machine_ids()) {
6260: # user is hosted on this machine
1.1266 raeburn 6261: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 6262: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 6263: return %{unserialize($reply, $escapedkeys)};
6264: }
1.1166 raeburn 6265: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 6266: my @pairs=split(/\&/,$rep);
6267: my %returnhash=();
1.1098 foxr 6268: if (!($rep =~ /^error/ )) {
6269: foreach my $item (@pairs) {
6270: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 6271: $key = unescape($key) unless $escapedkeys;
6272: #$key = &unescape($key);
1.1098 foxr 6273: next if ($key =~ /^error: 2 /);
6274: $returnhash{$key}=&thaw_unescape($value);
6275: }
1.755 albertel 6276: }
6277: return %returnhash;
1.407 www 6278: }
6279:
1.1098 foxr 6280:
1.717 albertel 6281: # --------------------------------------------------------- dumpstore interface
6282:
6283: sub dumpstore {
6284: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 6285: # same as dump but keys must be escaped. They may contain colon separated
6286: # lists of values that may themself contain colons (e.g. symbs).
6287: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 6288: }
6289:
1.407 www 6290: # -------------------------------------------------------------- keys interface
6291:
6292: sub getkeys {
6293: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 6294: if (!$udomain) { $udomain=$env{'user.domain'}; }
6295: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 6296: my $uhome=&homeserver($uname,$udomain);
6297: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6298: my @keyarray=();
1.800 albertel 6299: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 6300: next if ($key =~ /^error: 2 /);
1.800 albertel 6301: push(@keyarray,&unescape($key));
1.407 www 6302: }
6303: return @keyarray;
1.318 matthew 6304: }
6305:
1.319 matthew 6306: # --------------------------------------------------------------- currentdump
6307: sub currentdump {
1.328 matthew 6308: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 6309: $courseid = $env{'request.course.id'} if (! defined($courseid));
6310: $sdom = $env{'user.domain'} if (! defined($sdom));
6311: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 6312: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 6313: my $rep;
6314:
6315: if (grep { $_ eq $uhome } current_machine_ids()) {
6316: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6317: $courseid)));
6318: } else {
6319: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6320: }
6321:
1.318 matthew 6322: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 6323: #
1.318 matthew 6324: my %returnhash=();
1.319 matthew 6325: #
1.1343 raeburn 6326: if ($rep eq 'unknown_cmd') {
1.319 matthew 6327: # an old lond will not know currentdump
6328: # Do a dump and make it look like a currentdump
1.822 albertel 6329: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 6330: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6331: my %hash = @tmp;
6332: @tmp=();
1.424 matthew 6333: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 6334: } else {
6335: my @pairs=split(/\&/,$rep);
1.800 albertel 6336: foreach my $pair (@pairs) {
6337: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 6338: my ($symb,$param) = split(/:/,$key);
6339: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 6340: &thaw_unescape($value);
1.319 matthew 6341: }
1.191 harris41 6342: }
1.12 www 6343: return %returnhash;
1.424 matthew 6344: }
6345:
6346: sub convert_dump_to_currentdump{
6347: my %hash = %{shift()};
6348: my %returnhash;
6349: # Code ripped from lond, essentially. The only difference
6350: # here is the unescaping done by lonnet::dump(). Conceivably
6351: # we might run in to problems with parameter names =~ /^v\./
6352: while (my ($key,$value) = each(%hash)) {
6353: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 6354: $symb = &unescape($symb);
6355: $param = &unescape($param);
1.424 matthew 6356: next if ($v eq 'version' || $symb eq 'keys');
6357: next if (exists($returnhash{$symb}) &&
6358: exists($returnhash{$symb}->{$param}) &&
6359: $returnhash{$symb}->{'v.'.$param} > $v);
6360: $returnhash{$symb}->{$param}=$value;
6361: $returnhash{$symb}->{'v.'.$param}=$v;
6362: }
6363: #
6364: # Remove all of the keys in the hashes which keep track of
6365: # the version of the parameter.
6366: while (my ($symb,$param_hash) = each(%returnhash)) {
6367: # use a foreach because we are going to delete from the hash.
6368: foreach my $key (keys(%$param_hash)) {
6369: delete($param_hash->{$key}) if ($key =~ /^v\./);
6370: }
6371: }
6372: return \%returnhash;
1.12 www 6373: }
6374:
1.627 albertel 6375: # ------------------------------------------------------ critical inc interface
6376:
6377: sub cinc {
6378: return &inc(@_,'critical');
6379: }
6380:
1.449 matthew 6381: # --------------------------------------------------------------- inc interface
6382:
6383: sub inc {
1.627 albertel 6384: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 6385: if (!$udomain) { $udomain=$env{'user.domain'}; }
6386: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 6387: my $uhome=&homeserver($uname,$udomain);
6388: my $items='';
6389: if (! ref($store)) {
6390: # got a single value, so use that instead
6391: $items = &escape($store).'=&';
6392: } elsif (ref($store) eq 'SCALAR') {
6393: $items = &escape($$store).'=&';
6394: } elsif (ref($store) eq 'ARRAY') {
6395: $items = join('=&',map {&escape($_);} @{$store});
6396: } elsif (ref($store) eq 'HASH') {
6397: while (my($key,$value) = each(%{$store})) {
6398: $items.= &escape($key).'='.&escape($value).'&';
6399: }
6400: }
6401: $items=~s/\&$//;
1.627 albertel 6402: if ($critical) {
6403: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6404: } else {
6405: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6406: }
1.449 matthew 6407: }
6408:
1.12 www 6409: # --------------------------------------------------------------- put interface
6410:
6411: sub put {
1.134 albertel 6412: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6413: if (!$udomain) { $udomain=$env{'user.domain'}; }
6414: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6415: my $uhome=&homeserver($uname,$udomain);
1.12 www 6416: my $items='';
1.800 albertel 6417: foreach my $item (keys(%$storehash)) {
6418: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6419: }
1.12 www 6420: $items=~s/\&$//;
1.134 albertel 6421: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 6422: }
6423:
1.631 albertel 6424: # ------------------------------------------------------------ newput interface
6425:
6426: sub newput {
6427: my ($namespace,$storehash,$udomain,$uname)=@_;
6428: if (!$udomain) { $udomain=$env{'user.domain'}; }
6429: if (!$uname) { $uname=$env{'user.name'}; }
6430: my $uhome=&homeserver($uname,$udomain);
6431: my $items='';
6432: foreach my $key (keys(%$storehash)) {
6433: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6434: }
6435: $items=~s/\&$//;
6436: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6437: }
6438:
6439: # --------------------------------------------------------- putstore interface
6440:
1.524 raeburn 6441: sub putstore {
1.1269 raeburn 6442: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620 albertel 6443: if (!$udomain) { $udomain=$env{'user.domain'}; }
6444: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 6445: my $uhome=&homeserver($uname,$udomain);
6446: my $items='';
1.715 albertel 6447: foreach my $key (keys(%$storehash)) {
6448: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 6449: }
1.715 albertel 6450: $items=~s/\&$//;
1.716 albertel 6451: my $esc_symb=&escape($symb);
6452: my $esc_v=&escape($version);
1.715 albertel 6453: my $reply =
1.716 albertel 6454: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 6455: $uhome);
1.1269 raeburn 6456: if (($tolog) && ($reply eq 'ok')) {
6457: my $namevalue='';
6458: foreach my $key (keys(%{$storehash})) {
6459: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6460: }
6461: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6462: '&host='.&escape($perlvar{'lonHostID'}).
6463: '&version='.$esc_v.
6464: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6465: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6466: }
1.715 albertel 6467: if ($reply eq 'unknown_cmd') {
1.716 albertel 6468: # gfall back to way things use to be done
1.715 albertel 6469: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6470: $uname);
1.524 raeburn 6471: }
1.715 albertel 6472: return $reply;
6473: }
6474:
6475: sub old_putstore {
1.716 albertel 6476: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6477: if (!$udomain) { $udomain=$env{'user.domain'}; }
6478: if (!$uname) { $uname=$env{'user.name'}; }
6479: my $uhome=&homeserver($uname,$udomain);
6480: my %newstorehash;
1.800 albertel 6481: foreach my $item (keys(%$storehash)) {
6482: my $key = $version.':'.&escape($symb).':'.$item;
6483: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 6484: }
6485: my $items='';
6486: my %allitems = ();
1.800 albertel 6487: foreach my $item (keys(%newstorehash)) {
6488: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 6489: my $key = $1.':keys:'.$2;
6490: $allitems{$key} .= $3.':';
6491: }
1.800 albertel 6492: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 6493: }
1.800 albertel 6494: foreach my $item (keys(%allitems)) {
6495: $allitems{$item} =~ s/\:$//;
6496: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 6497: }
6498: $items=~s/\&$//;
6499: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 6500: }
6501:
1.47 www 6502: # ------------------------------------------------------ critical put interface
6503:
6504: sub cput {
1.134 albertel 6505: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 6506: if (!$udomain) { $udomain=$env{'user.domain'}; }
6507: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 6508: my $uhome=&homeserver($uname,$udomain);
1.47 www 6509: my $items='';
1.800 albertel 6510: foreach my $item (keys(%$storehash)) {
6511: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 6512: }
1.47 www 6513: $items=~s/\&$//;
1.134 albertel 6514: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6515: }
6516:
6517: # -------------------------------------------------------------- eget interface
6518:
6519: sub eget {
1.133 albertel 6520: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 6521: my $items='';
1.800 albertel 6522: foreach my $item (@$storearr) {
6523: $items.=&escape($item).'&';
1.191 harris41 6524: }
1.12 www 6525: $items=~s/\&$//;
1.620 albertel 6526: if (!$udomain) { $udomain=$env{'user.domain'}; }
6527: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 6528: my $uhome=&homeserver($uname,$udomain);
6529: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 6530: my @pairs=split(/\&/,$rep);
6531: my %returnhash=();
1.42 www 6532: my $i=0;
1.800 albertel 6533: foreach my $item (@$storearr) {
6534: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 6535: $i++;
1.191 harris41 6536: }
1.12 www 6537: return %returnhash;
6538: }
6539:
1.667 albertel 6540: # ------------------------------------------------------------ tmpput interface
6541: sub tmpput {
1.802 raeburn 6542: my ($storehash,$server,$context)=@_;
1.667 albertel 6543: my $items='';
1.800 albertel 6544: foreach my $item (keys(%$storehash)) {
6545: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 6546: }
6547: $items=~s/\&$//;
1.802 raeburn 6548: if (defined($context)) {
6549: $items .= ':'.&escape($context);
6550: }
1.667 albertel 6551: return &reply("tmpput:$items",$server);
6552: }
6553:
6554: # ------------------------------------------------------------ tmpget interface
6555: sub tmpget {
1.688 albertel 6556: my ($token,$server)=@_;
6557: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6558: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 6559: my %returnhash;
1.1328 raeburn 6560: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
6561: return %returnhash;
6562: }
1.667 albertel 6563: foreach my $item (split(/\&/,$rep)) {
6564: my ($key,$value)=split(/=/,$item);
6565: $returnhash{&unescape($key)}=&thaw_unescape($value);
6566: }
6567: return %returnhash;
6568: }
6569:
1.1113 raeburn 6570: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 6571: sub tmpdel {
6572: my ($token,$server)=@_;
6573: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
6574: return &reply("tmpdel:$token",$server);
6575: }
6576:
1.1198 raeburn 6577: # ------------------------------------------------------------ get_timebased_id
6578:
6579: sub get_timebased_id {
6580: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
6581: $maxtries) = @_;
6582: my ($newid,$error,$dellock);
6583: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
6584: return ('','ok','invalid call to get suffix');
6585: }
6586:
6587: # set defaults for any optional args for which values were not supplied
6588: if ($who eq '') {
6589: $who = $env{'user.name'}.':'.$env{'user.domain'};
6590: }
6591: if (!$locktries) {
6592: $locktries = 3;
6593: }
6594: if (!$maxtries) {
6595: $maxtries = 10;
6596: }
6597:
6598: if (($cdom eq '') || ($cnum eq '')) {
6599: if ($env{'request.course.id'}) {
6600: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6601: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6602: }
6603: if (($cdom eq '') || ($cnum eq '')) {
6604: return ('','ok','call to get suffix not in course context');
6605: }
6606: }
6607:
6608: # construct locking item
6609: my $lockhash = {
6610: $prefix."\0".'locked_'.$keyid => $who,
6611: };
6612: my $tries = 0;
6613:
6614: # attempt to get lock on nohist_$namespace file
6615: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6616: while (($gotlock ne 'ok') && $tries <$locktries) {
6617: $tries ++;
6618: sleep 1;
6619: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6620: }
6621:
6622: # attempt to get unique identifier, based on current timestamp
6623: if ($gotlock eq 'ok') {
6624: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6625: my $id = time;
6626: $newid = $id;
1.1268 raeburn 6627: if ($idtype eq 'addcode') {
6628: $newid .= &sixnum_code();
6629: }
1.1198 raeburn 6630: my $idtries = 0;
6631: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6632: if ($idtype eq 'concat') {
6633: $newid = $id.$idtries;
1.1268 raeburn 6634: } elsif ($idtype eq 'addcode') {
6635: $newid = $newid.&sixnum_code();
1.1198 raeburn 6636: } else {
6637: $newid ++;
6638: }
6639: $idtries ++;
6640: }
6641: if (!exists($inuse{$prefix."\0".$newid})) {
6642: my %new_item = (
6643: $prefix."\0".$newid => $who,
6644: );
6645: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6646: $cdom,$cnum);
6647: if ($putresult ne 'ok') {
6648: undef($newid);
6649: $error = 'error saving new item: '.$putresult;
6650: }
6651: } else {
1.1268 raeburn 6652: undef($newid);
1.1198 raeburn 6653: $error = ('error: no unique suffix available for the new item ');
6654: }
6655: # remove lock
6656: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6657: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6658: } else {
6659: $error = "error: could not obtain lockfile\n";
6660: $dellock = 'ok';
1.1276 raeburn 6661: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6662: $dellock = 'nolock';
6663: }
1.1198 raeburn 6664: }
6665: return ($newid,$dellock,$error);
6666: }
6667:
1.1268 raeburn 6668: sub sixnum_code {
6669: my $code;
6670: for (0..6) {
6671: $code .= int( rand(9) );
6672: }
6673: return $code;
6674: }
6675:
1.765 albertel 6676: # -------------------------------------------------- portfolio access checking
6677:
6678: sub portfolio_access {
1.1270 raeburn 6679: my ($requrl,$clientip) = @_;
1.765 albertel 6680: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270 raeburn 6681: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814 raeburn 6682: if ($result) {
6683: my %setters;
6684: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6685: my ($startblock,$endblock) =
6686: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6687: if ($startblock && $endblock) {
6688: return 'B';
6689: }
6690: } else {
6691: my ($startblock,$endblock) =
6692: &Apache::loncommon::blockcheck(\%setters,'port');
6693: if ($startblock && $endblock) {
6694: return 'B';
6695: }
6696: }
6697: }
1.765 albertel 6698: if ($result eq 'ok') {
1.766 albertel 6699: return 'F';
1.765 albertel 6700: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6701: return 'A';
1.765 albertel 6702: }
1.766 albertel 6703: return '';
1.765 albertel 6704: }
6705:
6706: sub get_portfolio_access {
1.1270 raeburn 6707: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767 albertel 6708:
6709: if (!ref($access_hash)) {
6710: my $current_perms = &get_portfile_permissions($udom,$unum);
6711: my %access_controls = &get_access_controls($current_perms,$group,
6712: $file_name);
6713: $access_hash = $access_controls{$file_name};
6714: }
6715:
1.1270 raeburn 6716: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765 albertel 6717: my $now = time;
6718: if (ref($access_hash) eq 'HASH') {
6719: foreach my $key (keys(%{$access_hash})) {
6720: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6721: if ($start > $now) {
6722: next;
6723: }
6724: if ($end && $end<$now) {
6725: next;
6726: }
6727: if ($scope eq 'public') {
6728: $public = $key;
6729: last;
6730: } elsif ($scope eq 'guest') {
6731: $guest = $key;
6732: } elsif ($scope eq 'domains') {
6733: push(@domains,$key);
6734: } elsif ($scope eq 'users') {
6735: push(@users,$key);
6736: } elsif ($scope eq 'course') {
6737: push(@courses,$key);
6738: } elsif ($scope eq 'group') {
6739: push(@groups,$key);
1.1270 raeburn 6740: } elsif ($scope eq 'ip') {
6741: push(@ips,$key);
1.765 albertel 6742: }
6743: }
6744: if ($public) {
6745: return 'ok';
1.1270 raeburn 6746: } elsif (@ips > 0) {
6747: my $allowed;
6748: foreach my $ipkey (@ips) {
6749: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6750: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6751: $allowed = 1;
6752: last;
6753: }
6754: }
6755: }
6756: if ($allowed) {
6757: return 'ok';
6758: }
1.765 albertel 6759: }
6760: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6761: if ($guest) {
6762: return $guest;
6763: }
6764: } else {
6765: if (@domains > 0) {
6766: foreach my $domkey (@domains) {
6767: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6768: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6769: return 'ok';
6770: }
6771: }
6772: }
6773: }
6774: if (@users > 0) {
6775: foreach my $userkey (@users) {
1.865 raeburn 6776: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6777: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6778: if (ref($item) eq 'HASH') {
6779: if (($item->{'uname'} eq $env{'user.name'}) &&
6780: ($item->{'udom'} eq $env{'user.domain'})) {
6781: return 'ok';
6782: }
6783: }
6784: }
6785: }
1.765 albertel 6786: }
6787: }
6788: my %roleshash;
6789: my @courses_and_groups = @courses;
6790: push(@courses_and_groups,@groups);
6791: if (@courses_and_groups > 0) {
6792: my (%allgroups,%allroles);
6793: my ($start,$end,$role,$sec,$group);
6794: foreach my $envkey (%env) {
1.1060 raeburn 6795: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6796: my $cid = $2.'_'.$3;
6797: if ($1 eq 'gr') {
6798: $group = $4;
6799: $allgroups{$cid}{$group} = $env{$envkey};
6800: } else {
6801: if ($4 eq '') {
6802: $sec = 'none';
6803: } else {
6804: $sec = $4;
6805: }
6806: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6807: }
1.811 albertel 6808: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6809: my $cid = $2.'_'.$3;
6810: if ($4 eq '') {
6811: $sec = 'none';
6812: } else {
6813: $sec = $4;
6814: }
6815: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6816: }
6817: }
6818: if (keys(%allroles) == 0) {
6819: return;
6820: }
6821: foreach my $key (@courses_and_groups) {
6822: my %content = %{$$access_hash{$key}};
6823: my $cnum = $content{'number'};
6824: my $cdom = $content{'domain'};
6825: my $cid = $cdom.'_'.$cnum;
6826: if (!exists($allroles{$cid})) {
6827: next;
6828: }
6829: foreach my $role_id (keys(%{$content{'roles'}})) {
6830: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6831: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6832: my @status = @{$content{'roles'}{$role_id}{'access'}};
6833: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6834: foreach my $role (keys(%{$allroles{$cid}})) {
6835: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6836: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6837: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6838: if (grep/^all$/,@sections) {
6839: return 'ok';
6840: } else {
6841: if (grep/^$sec$/,@sections) {
6842: return 'ok';
6843: }
6844: }
6845: }
6846: }
6847: if (keys(%{$allgroups{$cid}}) == 0) {
6848: if (grep/^none$/,@groups) {
6849: return 'ok';
6850: }
6851: } else {
6852: if (grep/^all$/,@groups) {
6853: return 'ok';
6854: }
6855: foreach my $group (keys(%{$allgroups{$cid}})) {
6856: if (grep/^$group$/,@groups) {
6857: return 'ok';
6858: }
6859: }
6860: }
6861: }
6862: }
6863: }
6864: }
6865: }
6866: if ($guest) {
6867: return $guest;
6868: }
6869: }
6870: }
6871: return;
6872: }
6873:
6874: sub course_group_datechecker {
6875: my ($dates,$now,$status) = @_;
6876: my ($start,$end) = split(/\./,$dates);
6877: if (!$start && !$end) {
6878: return 'ok';
6879: }
6880: if (grep/^active$/,@{$status}) {
6881: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6882: return 'ok';
6883: }
6884: }
6885: if (grep/^previous$/,@{$status}) {
6886: if ($end > $now ) {
6887: return 'ok';
6888: }
6889: }
6890: if (grep/^future$/,@{$status}) {
6891: if ($start > $now) {
6892: return 'ok';
6893: }
6894: }
6895: return;
6896: }
6897:
6898: sub parse_portfolio_url {
6899: my ($url) = @_;
6900:
6901: my ($type,$udom,$unum,$group,$file_name);
6902:
1.823 albertel 6903: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6904: $type = 1;
6905: $udom = $1;
6906: $unum = $2;
6907: $file_name = $3;
1.823 albertel 6908: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6909: $type = 2;
6910: $udom = $1;
6911: $unum = $2;
6912: $group = $3;
6913: $file_name = $3.'/'.$4;
6914: }
6915: if (wantarray) {
6916: return ($type,$udom,$unum,$file_name,$group);
6917: }
6918: return $type;
6919: }
6920:
6921: sub is_portfolio_url {
6922: my ($url) = @_;
6923: return scalar(&parse_portfolio_url($url));
6924: }
6925:
1.798 raeburn 6926: sub is_portfolio_file {
6927: my ($file) = @_;
1.820 raeburn 6928: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6929: return 1;
6930: }
6931: return;
6932: }
6933:
1.976 raeburn 6934: sub usertools_access {
1.1084 raeburn 6935: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6936: my ($access,%tools);
6937: if ($context eq '') {
6938: $context = 'tools';
6939: }
6940: if ($context eq 'requestcourses') {
6941: %tools = (
6942: official => 1,
6943: unofficial => 1,
1.1006 raeburn 6944: community => 1,
1.1246 raeburn 6945: textbook => 1,
1.1305 raeburn 6946: placement => 1,
1.985 raeburn 6947: );
1.1183 raeburn 6948: } elsif ($context eq 'requestauthor') {
6949: %tools = (
6950: requestauthor => 1,
6951: );
1.985 raeburn 6952: } else {
6953: %tools = (
6954: aboutme => 1,
6955: blog => 1,
1.1177 raeburn 6956: webdav => 1,
1.985 raeburn 6957: portfolio => 1,
6958: );
6959: }
1.976 raeburn 6960: return if (!defined($tools{$tool}));
6961:
1.1242 raeburn 6962: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6963: $udom = $env{'user.domain'};
6964: $uname = $env{'user.name'};
6965: }
6966:
1.978 raeburn 6967: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6968: if ($action ne 'reload') {
1.985 raeburn 6969: if ($context eq 'requestcourses') {
6970: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6971: } elsif ($context eq 'requestauthor') {
6972: return $env{'environment.canrequest.author'};
1.985 raeburn 6973: } else {
6974: return $env{'environment.availabletools.'.$tool};
6975: }
6976: }
1.976 raeburn 6977: }
6978:
1.1183 raeburn 6979: my ($toolstatus,$inststatus,$envkey);
6980: if ($context eq 'requestauthor') {
6981: $envkey = $context;
6982: } else {
6983: $envkey = $context.'.'.$tool;
6984: }
1.976 raeburn 6985:
1.985 raeburn 6986: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6987: ($action ne 'reload')) {
1.1183 raeburn 6988: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6989: $inststatus = $env{'environment.inststatus'};
6990: } else {
1.1084 raeburn 6991: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6992: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6993: $inststatus = $userenvref->{'inststatus'};
6994: } else {
1.1183 raeburn 6995: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6996: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6997: $inststatus = $userenv{'inststatus'};
6998: }
1.976 raeburn 6999: }
7000:
7001: if ($toolstatus ne '') {
7002: if ($toolstatus) {
7003: $access = 1;
7004: } else {
7005: $access = 0;
7006: }
7007: return $access;
7008: }
7009:
1.1084 raeburn 7010: my ($is_adv,%domdef);
7011: if (ref($is_advref) eq 'HASH') {
7012: $is_adv = $is_advref->{'is_adv'};
7013: } else {
7014: $is_adv = &is_advanced_user($udom,$uname);
7015: }
7016: if (ref($domdefref) eq 'HASH') {
7017: %domdef = %{$domdefref};
7018: } else {
7019: %domdef = &get_domain_defaults($udom);
7020: }
1.976 raeburn 7021: if (ref($domdef{$tool}) eq 'HASH') {
7022: if ($is_adv) {
7023: if ($domdef{$tool}{'_LC_adv'} ne '') {
7024: if ($domdef{$tool}{'_LC_adv'}) {
7025: $access = 1;
7026: } else {
7027: $access = 0;
7028: }
7029: return $access;
7030: }
7031: }
7032: if ($inststatus ne '') {
7033: my ($hasaccess,$hasnoaccess);
7034: foreach my $affiliation (split(/:/,$inststatus)) {
7035: if ($domdef{$tool}{$affiliation} ne '') {
7036: if ($domdef{$tool}{$affiliation}) {
7037: $hasaccess = 1;
7038: } else {
7039: $hasnoaccess = 1;
7040: }
7041: }
7042: }
7043: if ($hasaccess || $hasnoaccess) {
7044: if ($hasaccess) {
7045: $access = 1;
7046: } elsif ($hasnoaccess) {
7047: $access = 0;
7048: }
7049: return $access;
7050: }
7051: } else {
7052: if ($domdef{$tool}{'default'} ne '') {
7053: if ($domdef{$tool}{'default'}) {
7054: $access = 1;
7055: } elsif ($domdef{$tool}{'default'} == 0) {
7056: $access = 0;
7057: }
7058: return $access;
7059: }
7060: }
7061: } else {
1.1177 raeburn 7062: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 7063: $access = 1;
7064: } else {
7065: $access = 0;
7066: }
1.976 raeburn 7067: return $access;
7068: }
7069: }
7070:
1.1050 raeburn 7071: sub is_course_owner {
7072: my ($cdom,$cnum,$udom,$uname) = @_;
7073: if (($udom eq '') || ($uname eq '')) {
7074: $udom = $env{'user.domain'};
7075: $uname = $env{'user.name'};
7076: }
7077: unless (($udom eq '') || ($uname eq '')) {
7078: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7079: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7080: return 1;
7081: } else {
7082: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7083: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7084: return 1;
7085: }
7086: }
7087: }
7088: }
7089: return;
7090: }
7091:
1.976 raeburn 7092: sub is_advanced_user {
7093: my ($udom,$uname) = @_;
1.1085 raeburn 7094: if ($udom ne '' && $uname ne '') {
7095: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 7096: if (wantarray) {
7097: return ($env{'user.adv'},$env{'user.author'});
7098: } else {
7099: return $env{'user.adv'};
7100: }
1.1085 raeburn 7101: }
7102: }
1.976 raeburn 7103: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7104: my %allroles;
1.1128 raeburn 7105: my ($is_adv,$is_author);
1.976 raeburn 7106: foreach my $role (keys(%roleshash)) {
7107: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7108: my $area = '/'.$tdomain.'/'.$trest;
7109: if ($sec ne '') {
7110: $area .= '/'.$sec;
7111: }
7112: if (($area ne '') && ($trole ne '')) {
7113: my $spec=$trole.'.'.$area;
7114: if ($trole =~ /^cr\//) {
7115: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7116: } elsif ($trole ne 'gr') {
7117: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7118: }
1.1128 raeburn 7119: if ($trole eq 'au') {
7120: $is_author = 1;
7121: }
1.976 raeburn 7122: }
7123: }
7124: foreach my $role (keys(%allroles)) {
7125: last if ($is_adv);
7126: foreach my $item (split(/:/,$allroles{$role})) {
7127: if ($item ne '') {
7128: my ($privilege,$restrictions)=split(/&/,$item);
7129: if ($privilege eq 'adv') {
7130: $is_adv = 1;
7131: last;
7132: }
7133: }
7134: }
7135: }
1.1128 raeburn 7136: if (wantarray) {
7137: return ($is_adv,$is_author);
7138: }
1.976 raeburn 7139: return $is_adv;
7140: }
1.798 raeburn 7141:
1.1035 raeburn 7142: sub check_can_request {
1.1036 raeburn 7143: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 7144: my $canreq = 0;
7145: my ($types,$typename) = &Apache::loncommon::course_types();
7146: my @options = ('approval','validate','autolimit');
7147: my $optregex = join('|',@options);
7148: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7149: foreach my $type (@{$types}) {
7150: if (&usertools_access($env{'user.name'},
7151: $env{'user.domain'},
7152: $type,undef,'requestcourses')) {
7153: $canreq ++;
1.1036 raeburn 7154: if (ref($request_domains) eq 'HASH') {
7155: push(@{$request_domains->{$type}},$env{'user.domain'});
7156: }
1.1035 raeburn 7157: if ($dom eq $env{'user.domain'}) {
7158: $can_request->{$type} = 1;
7159: }
7160: }
7161: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7162: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7163: if (@curr > 0) {
1.1036 raeburn 7164: foreach my $item (@curr) {
7165: if (ref($request_domains) eq 'HASH') {
7166: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7167: if ($otherdom ne '') {
7168: if (ref($request_domains->{$type}) eq 'ARRAY') {
7169: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7170: push(@{$request_domains->{$type}},$otherdom);
7171: }
7172: } else {
7173: push(@{$request_domains->{$type}},$otherdom);
7174: }
7175: }
7176: }
7177: }
7178: unless($dom eq $env{'user.domain'}) {
7179: $canreq ++;
1.1035 raeburn 7180: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7181: $can_request->{$type} = 1;
7182: }
7183: }
7184: }
7185: }
7186: }
7187: }
7188: return $canreq;
7189: }
7190:
1.341 www 7191: # ---------------------------------------------- Custom access rule evaluation
7192:
7193: sub customaccess {
7194: my ($priv,$uri)=@_;
1.807 albertel 7195: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 7196: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 7197: $udom = &LONCAPA::clean_domain($udom);
7198: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 7199: my $access=0;
1.800 albertel 7200: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 7201: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7202: if ($type eq 'user') {
7203: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 7204: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 7205: if ($tdom) {
7206: if ($tdom ne $env{'user.domain'}) { next; }
7207: }
1.896 albertel 7208: if ($tuname) {
7209: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 7210: }
7211: $access=($effect eq 'allow');
7212: last;
7213: }
7214: } else {
7215: if ($role) {
7216: if ($role ne $urole) { next; }
7217: }
7218: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7219: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7220: if ($tdom) {
7221: if ($tdom ne $udom) { next; }
7222: }
7223: if ($tcrs) {
7224: if ($tcrs ne $ucrs) { next; }
7225: }
7226: if ($tsec) {
7227: if ($tsec ne $usec) { next; }
7228: }
7229: $access=($effect eq 'allow');
7230: last;
7231: }
7232: if ($realm eq '' && $role eq '') {
7233: $access=($effect eq 'allow');
7234: }
1.402 bowersj2 7235: }
1.341 www 7236: }
7237: return $access;
7238: }
7239:
1.103 harris41 7240: # ------------------------------------------------- Check for a user privilege
1.12 www 7241:
7242: sub allowed {
1.1281 raeburn 7243: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705 albertel 7244: my $ver_orguri=$uri;
1.439 www 7245: $uri=&deversion($uri);
1.152 www 7246: my $orguri=$uri;
1.52 www 7247: $uri=&declutter($uri);
1.809 raeburn 7248:
1.810 raeburn 7249: if ($priv eq 'evb') {
7250: # Evade communication block restrictions for specified role in a course
7251: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7252: return $1;
7253: } else {
7254: return;
7255: }
7256: }
7257:
1.620 albertel 7258: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 7259: # Free bre access to adm and meta resources
1.1343 raeburn 7260: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$}))
1.769 albertel 7261: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7262: && ($priv eq 'bre')) {
1.14 www 7263: return 'F';
1.159 www 7264: }
7265:
1.545 banghart 7266: # Free bre access to user's own portfolio contents
1.714 raeburn 7267: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 7268: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 7269: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 7270: my %setters;
7271: my ($startblock,$endblock) =
7272: &Apache::loncommon::blockcheck(\%setters,'port');
7273: if ($startblock && $endblock) {
7274: return 'B';
7275: } else {
7276: return 'F';
7277: }
1.545 banghart 7278: }
7279:
1.762 raeburn 7280: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 7281: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7282: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7283: if (exists($env{'request.course.id'})) {
7284: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7285: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7286: if (($domain eq $cdom) && ($name eq $cnum)) {
7287: my $courseprivid=$env{'request.course.id'};
7288: $courseprivid=~s/\_/\//;
7289: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7290: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7291: return $1;
1.762 raeburn 7292: } else {
7293: if ($env{'request.course.sec'}) {
7294: $courseprivid.='/'.$env{'request.course.sec'};
7295: }
7296: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7297: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7298: return $2;
7299: }
1.714 raeburn 7300: }
7301: }
7302: }
7303: }
7304:
1.159 www 7305: # Free bre to public access
7306:
7307: if ($priv eq 'bre') {
1.238 www 7308: my $copyright=&metadata($uri,'copyright');
1.620 albertel 7309: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 7310: return 'F';
7311: }
1.238 www 7312: if ($copyright eq 'priv') {
7313: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7314: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 7315: return '';
7316: }
7317: }
7318: if ($copyright eq 'domain') {
7319: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 7320: unless (($env{'user.domain'} eq $1) ||
7321: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 7322: return '';
7323: }
1.262 matthew 7324: }
1.620 albertel 7325: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 7326: # Library role, so allow browsing of resources in this domain.
7327: return 'F';
1.238 www 7328: }
1.341 www 7329: if ($copyright eq 'custom') {
7330: unless (&customaccess($priv,$uri)) { return ''; }
7331: }
1.14 www 7332: }
1.264 matthew 7333: # Domain coordinator is trying to create a course
1.620 albertel 7334: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 7335: # uri is the requested domain in this case.
7336: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 7337: # a role of dc for the domain in question.
1.620 albertel 7338: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 7339: }
1.29 www 7340:
1.52 www 7341: my $thisallowed='';
7342: my $statecond=0;
7343: my $courseprivid='';
7344:
1.1039 raeburn 7345: my $ownaccess;
1.1043 raeburn 7346: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 7347: if (($priv eq 'bro') && ($env{'user.author'})) {
7348: if ($uri eq '') {
7349: $ownaccess = 1;
7350: } else {
7351: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7352: my $udom = $env{'user.domain'};
7353: my $uname = $env{'user.name'};
7354: if ($uri =~ m{^\Q$udom\E/?$}) {
7355: $ownaccess = 1;
1.1040 raeburn 7356: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 7357: unless ($uri =~ m{\.\./}) {
7358: $ownaccess = 1;
7359: }
7360: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7361: my $now = time;
7362: if ($uri =~ m{^([^/]+)/?$}) {
7363: my $adom = $1;
7364: foreach my $key (keys(%env)) {
1.1042 raeburn 7365: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 7366: my ($start,$end) = split('.',$env{$key});
7367: if (($now >= $start) && (!$end || $end < $now)) {
7368: $ownaccess = 1;
7369: last;
7370: }
7371: }
7372: }
7373: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7374: my $adom = $1;
7375: my $aname = $2;
1.1042 raeburn 7376: foreach my $role ('ca','aa') {
7377: if ($env{"user.role.$role./$adom/$aname"}) {
7378: my ($start,$end) =
7379: split('.',$env{"user.role.$role./$adom/$aname"});
7380: if (($now >= $start) && (!$end || $end < $now)) {
7381: $ownaccess = 1;
7382: last;
7383: }
1.1039 raeburn 7384: }
7385: }
7386: }
7387: }
7388: }
7389: }
7390: }
7391:
1.52 www 7392: # Course
7393:
1.620 albertel 7394: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7395: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7396: $thisallowed.=$1;
7397: }
1.52 www 7398: }
1.29 www 7399:
1.52 www 7400: # Domain
7401:
1.620 albertel 7402: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 7403: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7404: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7405: $thisallowed.=$1;
7406: }
1.12 www 7407: }
1.52 www 7408:
1.1141 raeburn 7409: # User who is not author or co-author might still be able to edit
7410: # resource of an author in the domain (e.g., if Domain Coordinator).
7411: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7412: (&allowed('mdc',$env{'request.course.id'}))) {
7413: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7414: $thisallowed.=$1;
7415: }
7416: }
7417:
1.52 www 7418: # Course: uri itself is a course
1.66 www 7419: my $courseuri=$uri;
7420: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 7421: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 7422:
1.620 albertel 7423: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 7424: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 7425: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 7426: $thisallowed.=$1;
7427: }
1.12 www 7428: }
1.29 www 7429:
1.665 albertel 7430: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 7431: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 7432: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 7433: $thisallowed='';
1.671 raeburn 7434: my ($match)=&is_on_map($uri);
7435: if ($match) {
7436: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7437: =~/\Q$priv\E\&([^\:]*)/) {
1.1281 raeburn 7438: my $value = $1;
7439: if ($noblockcheck) {
7440: $thisallowed.=$value;
1.1162 raeburn 7441: } else {
1.1281 raeburn 7442: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7443: if (@blockers > 0) {
7444: $thisallowed = 'B';
7445: } else {
7446: $thisallowed.=$value;
7447: }
1.1162 raeburn 7448: }
1.671 raeburn 7449: }
7450: } else {
1.705 albertel 7451: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 7452: if ($refuri) {
7453: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 7454: $thisallowed='F';
1.671 raeburn 7455: } else {
7456: $refuri=&declutter($refuri);
7457: my ($match) = &is_on_map($refuri);
7458: if ($match) {
1.1281 raeburn 7459: if ($noblockcheck) {
7460: $thisallowed='F';
1.1162 raeburn 7461: } else {
1.1281 raeburn 7462: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7463: if (@blockers > 0) {
7464: $thisallowed = 'B';
7465: } else {
7466: $thisallowed='F';
7467: }
1.1162 raeburn 7468: }
1.671 raeburn 7469: }
1.669 raeburn 7470: }
1.671 raeburn 7471: }
7472: }
1.314 www 7473: }
1.492 albertel 7474:
1.766 albertel 7475: if ($priv eq 'bre'
7476: && $thisallowed ne 'F'
7477: && $thisallowed ne '2'
7478: && &is_portfolio_url($uri)) {
1.1270 raeburn 7479: $thisallowed = &portfolio_access($uri,$clientip);
1.766 albertel 7480: }
1.1250 raeburn 7481:
1.52 www 7482: # Full access at system, domain or course-wide level? Exit.
1.29 www 7483: if ($thisallowed=~/F/) {
7484: return 'F';
7485: }
7486:
1.52 www 7487: # If this is generating or modifying users, exit with special codes
1.29 www 7488:
1.643 www 7489: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
7490: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 7491: my ($audom,$auname)=split('/',$uri);
1.643 www 7492: # no author name given, so this just checks on the general right to make a co-author in this domain
7493: unless ($auname) { return $thisallowed; }
7494: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 7495: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
7496: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
7497: ($audom ne $env{'request.role.domain'}))) { return ''; }
7498: }
1.52 www 7499: return $thisallowed;
7500: }
7501: #
1.103 harris41 7502: # Gathered so far: system, domain and course wide privileges
1.52 www 7503: #
7504: # Course: See if uri or referer is an individual resource that is part of
7505: # the course
7506:
1.620 albertel 7507: if ($env{'request.course.id'}) {
1.232 www 7508:
1.620 albertel 7509: $courseprivid=$env{'request.course.id'};
7510: if ($env{'request.course.sec'}) {
7511: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 7512: }
7513: $courseprivid=~s/\_/\//;
7514: my $checkreferer=1;
1.232 www 7515: my ($match,$cond)=&is_on_map($uri);
7516: if ($match) {
7517: $statecond=$cond;
1.620 albertel 7518: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7519: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7520: my $value = $1;
7521: if ($priv eq 'bre') {
1.1281 raeburn 7522: if ($noblockcheck) {
7523: $thisallowed.=$value;
1.1162 raeburn 7524: } else {
1.1281 raeburn 7525: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7526: if (@blockers > 0) {
7527: $thisallowed = 'B';
7528: } else {
7529: $thisallowed.=$value;
7530: }
1.1162 raeburn 7531: }
7532: } else {
7533: $thisallowed.=$value;
7534: }
1.52 www 7535: $checkreferer=0;
7536: }
1.29 www 7537: }
1.83 www 7538:
1.148 www 7539: if ($checkreferer) {
1.620 albertel 7540: my $refuri=$env{'httpref.'.$orguri};
1.148 www 7541: unless ($refuri) {
1.800 albertel 7542: foreach my $key (keys(%env)) {
7543: if ($key=~/^httpref\..*\*/) {
7544: my $pattern=$key;
1.156 www 7545: $pattern=~s/^httpref\.\/res\///;
1.148 www 7546: $pattern=~s/\*/\[\^\/\]\+/g;
7547: $pattern=~s/\//\\\//g;
1.152 www 7548: if ($orguri=~/$pattern/) {
1.800 albertel 7549: $refuri=$env{$key};
1.148 www 7550: }
7551: }
1.191 harris41 7552: }
1.148 www 7553: }
1.232 www 7554:
1.148 www 7555: if ($refuri) {
1.152 www 7556: $refuri=&declutter($refuri);
1.232 www 7557: my ($match,$cond)=&is_on_map($refuri);
7558: if ($match) {
7559: my $refstatecond=$cond;
1.620 albertel 7560: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 7561: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 7562: my $value = $1;
7563: if ($priv eq 'bre') {
1.1281 raeburn 7564: if ($noblockcheck) {
7565: $thisallowed.=$value;
1.1162 raeburn 7566: } else {
1.1281 raeburn 7567: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
7568: if (@blockers > 0) {
7569: $thisallowed = 'B';
7570: } else {
7571: $thisallowed.=$value;
7572: }
1.1162 raeburn 7573: }
7574: } else {
7575: $thisallowed.=$value;
7576: }
1.53 www 7577: $uri=$refuri;
7578: $statecond=$refstatecond;
1.52 www 7579: }
7580: }
1.148 www 7581: }
1.29 www 7582: }
1.52 www 7583: }
1.29 www 7584:
1.52 www 7585: #
1.103 harris41 7586: # Gathered now: all privileges that could apply, and condition number
1.52 www 7587: #
7588: #
7589: # Full or no access?
7590: #
1.29 www 7591:
1.52 www 7592: if ($thisallowed=~/F/) {
7593: return 'F';
7594: }
1.29 www 7595:
1.52 www 7596: unless ($thisallowed) {
7597: return '';
7598: }
1.29 www 7599:
1.52 www 7600: # Restrictions exist, deal with them
7601: #
7602: # C:according to course preferences
7603: # R:according to resource settings
7604: # L:unless locked
7605: # X:according to user session state
7606: #
7607:
7608: # Possibly locked functionality, check all courses
1.54 www 7609: # Locks might take effect only after 10 minutes cache expiration for other
7610: # courses, and 2 minutes for current course
1.52 www 7611:
7612: my $envkey;
7613: if ($thisallowed=~/L/) {
1.1000 raeburn 7614: foreach $envkey (keys(%env)) {
1.54 www 7615: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
7616: my $courseid=$2;
7617: my $roleid=$1.'.'.$2;
1.92 www 7618: $courseid=~s/^\///;
1.54 www 7619: my $expiretime=600;
1.620 albertel 7620: if ($env{'request.role'} eq $roleid) {
1.54 www 7621: $expiretime=120;
7622: }
7623: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
7624: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 7625: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 7626: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 7627: }
1.620 albertel 7628: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7629: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7630: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7631: &log($env{'user.domain'},$env{'user.name'},
7632: $env{'user.home'},
1.57 www 7633: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 7634: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7635: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7636: return '';
7637: }
7638: }
1.620 albertel 7639: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7640: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7641: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7642: &log($env{'user.domain'},$env{'user.name'},
7643: $env{'user.home'},
1.57 www 7644: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 7645: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 7646: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 7647: return '';
7648: }
7649: }
7650: }
1.29 www 7651: }
1.52 www 7652: }
7653:
7654: #
7655: # Rest of the restrictions depend on selected course
7656: #
7657:
1.620 albertel 7658: unless ($env{'request.course.id'}) {
1.766 albertel 7659: if ($thisallowed eq 'A') {
7660: return 'A';
1.814 raeburn 7661: } elsif ($thisallowed eq 'B') {
7662: return 'B';
1.766 albertel 7663: } else {
7664: return '1';
7665: }
1.52 www 7666: }
1.29 www 7667:
1.52 www 7668: #
7669: # Now user is definitely in a course
7670: #
1.53 www 7671:
7672:
7673: # Course preferences
7674:
7675: if ($thisallowed=~/C/) {
1.620 albertel 7676: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7677: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7678: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 7679: =~/\Q$rolecode\E/) {
1.1304 raeburn 7680: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7681: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7682: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7683: $env{'request.course.id'});
7684: }
1.237 www 7685: return '';
7686: }
7687:
1.620 albertel 7688: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 7689: =~/\Q$unamedom\E/) {
1.1304 raeburn 7690: if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689 albertel 7691: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7692: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7693: $env{'request.course.id'});
7694: }
1.54 www 7695: return '';
7696: }
1.53 www 7697: }
7698:
7699: # Resource preferences
7700:
7701: if ($thisallowed=~/R/) {
1.620 albertel 7702: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 7703: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 7704: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 7705: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7706: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7707: }
7708: return '';
1.54 www 7709: }
1.53 www 7710: }
1.30 www 7711:
1.246 www 7712: # Restricted by state or randomout?
1.30 www 7713:
1.52 www 7714: if ($thisallowed=~/X/) {
1.620 albertel 7715: if ($env{'acc.randomout'}) {
1.579 albertel 7716: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7717: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7718: return '';
7719: }
1.247 www 7720: }
7721: if (&condval($statecond)) {
1.52 www 7722: return '2';
7723: } else {
7724: return '';
7725: }
7726: }
1.30 www 7727:
1.766 albertel 7728: if ($thisallowed eq 'A') {
7729: return 'A';
1.814 raeburn 7730: } elsif ($thisallowed eq 'B') {
7731: return 'B';
1.766 albertel 7732: }
1.52 www 7733: return 'F';
1.232 www 7734: }
1.1162 raeburn 7735:
1.1192 raeburn 7736: # ------------------------------------------- Check construction space access
7737:
7738: sub constructaccess {
7739: my ($url,$setpriv)=@_;
7740:
7741: # We do not allow editing of previous versions of files
7742: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7743:
7744: # Get username and domain from URL
7745: my ($ownername,$ownerdomain,$ownerhome);
7746:
7747: ($ownerdomain,$ownername) =
1.1325 raeburn 7748: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192 raeburn 7749:
7750: # The URL does not really point to any authorspace, forget it
7751: unless (($ownername) && ($ownerdomain)) { return ''; }
7752:
7753: # Now we need to see if the user has access to the authorspace of
7754: # $ownername at $ownerdomain
7755:
7756: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7757: # Real author for this?
7758: $ownerhome = $env{'user.home'};
7759: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7760: return ($ownername,$ownerdomain,$ownerhome);
7761: }
7762: } else {
7763: # Co-author for this?
7764: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7765: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7766: $ownerhome = &homeserver($ownername,$ownerdomain);
7767: return ($ownername,$ownerdomain,$ownerhome);
7768: }
1.1312 raeburn 7769: if ($env{'request.course.id'}) {
7770: if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
7771: ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
7772: if (&allowed('mdc',$env{'request.course.id'})) {
7773: $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
7774: return ($ownername,$ownerdomain,$ownerhome);
7775: }
7776: }
7777: }
1.1192 raeburn 7778: }
7779:
7780: # We don't have any access right now. If we are not possibly going to do anything about this,
7781: # we might as well leave
7782: unless ($setpriv) { return ''; }
7783:
7784: # Backdoor access?
7785: my $allowed=&allowed('eco',$ownerdomain);
7786: # Nope
7787: unless ($allowed) { return ''; }
7788: # Looks like we may have access, but could be locked by the owner of the construction space
7789: if ($allowed eq 'U') {
7790: my %blocked=&get('environment',['domcoord.author'],
7791: $ownerdomain,$ownername);
7792: # Is blocked by owner
7793: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7794: }
7795: if (($allowed eq 'F') || ($allowed eq 'U')) {
7796: # Grant temporary access
7797: my $then=$env{'user.login.time'};
1.1209 raeburn 7798: my $update=$env{'user.update.time'};
1.1192 raeburn 7799: if (!$update) { $update = $then; }
7800: my $refresh=$env{'user.refresh.time'};
7801: if (!$refresh) { $refresh = $update; }
7802: my $now = time;
7803: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7804: $now,'ca','constructaccess');
7805: $ownerhome = &homeserver($ownername,$ownerdomain);
7806: return($ownername,$ownerdomain,$ownerhome);
7807: }
7808: # No business here
7809: return '';
7810: }
7811:
1.1282 raeburn 7812: # ----------------------------------------------------------- Content Blocking
7813:
7814: {
7815: # Caches for faster Course Contents display where content blocking
7816: # is in operation (i.e., interval param set) for timed quiz.
7817: #
7818: # User for whom data are being temporarily cached.
7819: my $cacheduser='';
7820: # Cached blockers for this user (a hash of blocking items).
7821: my %cachedblockers=();
7822: # When the data were last cached.
7823: my $cachedlast='';
7824:
7825: sub load_all_blockers {
7826: my ($uname,$udom,$blocks)=@_;
7827: if (($uname ne '') && ($udom ne '')) {
7828: if (($cacheduser eq $uname.':'.$udom) &&
7829: (abs($cachedlast-time)<5)) {
7830: return;
7831: }
7832: }
7833: $cachedlast=time;
7834: $cacheduser=$uname.':'.$udom;
7835: %cachedblockers = &get_commblock_resources($blocks);
7836: }
7837:
1.1162 raeburn 7838: sub get_comm_blocks {
7839: my ($cdom,$cnum) = @_;
7840: if ($cdom eq '' || $cnum eq '') {
7841: return unless ($env{'request.course.id'});
7842: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7843: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7844: }
7845: my %commblocks;
7846: my $hashid=$cdom.'_'.$cnum;
7847: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7848: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7849: %commblocks = %{$blocksref};
7850: } else {
7851: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7852: my $cachetime = 600;
7853: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7854: }
7855: return %commblocks;
7856: }
7857:
1.1282 raeburn 7858: sub get_commblock_resources {
7859: my ($blocks) = @_;
7860: my %blockers = ();
7861: return %blockers unless ($env{'request.course.id'});
7862: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162 raeburn 7863: my %commblocks;
7864: if (ref($blocks) eq 'HASH') {
7865: %commblocks = %{$blocks};
7866: } else {
7867: %commblocks = &get_comm_blocks();
7868: }
1.1282 raeburn 7869: return %blockers unless (keys(%commblocks) > 0);
7870: my $navmap = Apache::lonnavmaps::navmap->new();
7871: return %blockers unless (ref($navmap));
1.1162 raeburn 7872: my $now = time;
7873: foreach my $block (keys(%commblocks)) {
7874: if ($block =~ /^(\d+)____(\d+)$/) {
7875: my ($start,$end) = ($1,$2);
7876: if ($start <= $now && $end >= $now) {
7877: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7878: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7879: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282 raeburn 7880: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7881: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162 raeburn 7882: }
7883: }
7884: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282 raeburn 7885: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7886: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162 raeburn 7887: }
7888: }
7889: }
7890: }
7891: }
7892: } elsif ($block =~ /^firstaccess____(.+)$/) {
7893: my $item = $1;
1.1163 raeburn 7894: my @to_test;
1.1162 raeburn 7895: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7896: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282 raeburn 7897: my @interval;
7898: my $type = 'map';
7899: if ($item eq 'course') {
7900: $type = 'course';
7901: @interval=&EXT("resource.0.interval");
7902: } else {
7903: if ($item =~ /___\d+___/) {
7904: $type = 'resource';
7905: @interval=&EXT("resource.0.interval",$item);
7906: if (ref($navmap)) {
7907: my $res = $navmap->getBySymb($item);
7908: push(@to_test,$res);
7909: }
1.1162 raeburn 7910: } else {
1.1282 raeburn 7911: my $mapsymb = &symbread($item,1);
7912: if ($mapsymb) {
7913: if (ref($navmap)) {
7914: my $mapres = $navmap->getBySymb($mapsymb);
7915: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
7916: foreach my $res (@to_test) {
7917: my $symb = $res->symb();
7918: next if ($symb eq $mapsymb);
7919: if ($symb ne '') {
7920: @interval=&EXT("resource.0.interval",$symb);
7921: if ($interval[1] eq 'map') {
7922: last;
1.1162 raeburn 7923: }
7924: }
7925: }
7926: }
7927: }
7928: }
1.1282 raeburn 7929: }
1.1310 raeburn 7930: if ($interval[0] =~ /^(\d+)/) {
1.1308 raeburn 7931: my $timelimit = $1;
1.1282 raeburn 7932: my $first_access;
7933: if ($type eq 'resource') {
7934: $first_access=&get_first_access($interval[1],$item);
7935: } elsif ($type eq 'map') {
7936: $first_access=&get_first_access($interval[1],undef,$item);
7937: } else {
7938: $first_access=&get_first_access($interval[1]);
7939: }
7940: if ($first_access) {
1.1292 raeburn 7941: my $timesup = $first_access+$timelimit;
1.1282 raeburn 7942: if ($timesup > $now) {
7943: my $activeblock;
7944: foreach my $res (@to_test) {
1.1283 raeburn 7945: if ($res->answerable()) {
1.1282 raeburn 7946: $activeblock = 1;
7947: last;
7948: }
7949: }
7950: if ($activeblock) {
7951: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7952: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
7953: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
7954: }
7955: }
7956: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7957: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
7958: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163 raeburn 7959: }
1.1162 raeburn 7960: }
7961: }
7962: }
7963: }
7964: }
7965: }
7966: }
7967: }
7968: }
1.1282 raeburn 7969: return %blockers;
1.1162 raeburn 7970: }
7971:
1.1282 raeburn 7972: sub has_comm_blocking {
7973: my ($priv,$symb,$uri,$blocks) = @_;
7974: my @blockers;
7975: return unless ($env{'request.course.id'});
7976: return unless ($priv eq 'bre');
7977: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7978: return if ($env{'request.state'} eq 'construct');
7979: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
7980: return unless (keys(%cachedblockers) > 0);
7981: my (%possibles,@symbs);
7982: if (!$symb) {
7983: $symb = &symbread($uri,1,1,1,\%possibles);
1.1162 raeburn 7984: }
1.1282 raeburn 7985: if ($symb) {
7986: @symbs = ($symb);
7987: } elsif (keys(%possibles)) {
7988: @symbs = keys(%possibles);
7989: }
7990: my $noblock;
7991: foreach my $symb (@symbs) {
7992: last if ($noblock);
7993: my ($map,$resid,$resurl)=&decode_symb($symb);
7994: foreach my $block (keys(%cachedblockers)) {
7995: if ($block =~ /^firstaccess____(.+)$/) {
7996: my $item = $1;
7997: if (($item eq $map) || ($item eq $symb)) {
7998: $noblock = 1;
7999: last;
8000: }
8001: }
8002: if (ref($cachedblockers{$block}) eq 'HASH') {
8003: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
8004: if ($cachedblockers{$block}{'resources'}{$symb}) {
8005: unless (grep(/^\Q$block\E$/,@blockers)) {
8006: push(@blockers,$block);
8007: }
8008: }
8009: }
1.1162 raeburn 8010: }
1.1282 raeburn 8011: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
8012: if ($cachedblockers{$block}{'maps'}{$map}) {
8013: unless (grep(/^\Q$block\E$/,@blockers)) {
8014: push(@blockers,$block);
8015: }
8016: }
1.1162 raeburn 8017: }
8018: }
8019: }
1.1282 raeburn 8020: return if ($noblock);
8021: return @blockers;
8022: }
1.1162 raeburn 8023: }
8024:
1.1282 raeburn 8025: # -------------------------------- Deversion and split uri into path an filename
8026:
1.1133 foxr 8027: #
1.1282 raeburn 8028: # Removes the version from a URI and
1.1133 foxr 8029: # splits it in to its filename and path to the filename.
8030: # Seems like File::Basename could have done this more clearly.
8031: # Parameters:
8032: # $uri - input URI
8033: # Returns:
8034: # Two element list consisting of
8035: # $pathname - the URI up to and excluding the trailing /
8036: # $filename - The part of the URI following the last /
8037: # NOTE:
8038: # Another realization of this is simply:
8039: # use File::Basename;
8040: # ...
8041: # $uri = shift;
8042: # $filename = basename($uri);
8043: # $path = dirname($uri);
8044: # return ($filename, $path);
8045: #
8046: # The implementation below is probably faster however.
8047: #
1.710 albertel 8048: sub split_uri_for_cond {
8049: my $uri=&deversion(&declutter(shift));
8050: my @uriparts=split(/\//,$uri);
8051: my $filename=pop(@uriparts);
8052: my $pathname=join('/',@uriparts);
8053: return ($pathname,$filename);
8054: }
1.232 www 8055: # --------------------------------------------------- Is a resource on the map?
8056:
8057: sub is_on_map {
1.710 albertel 8058: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 8059: #Trying to find the conditional for the file
1.620 albertel 8060: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 8061: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 8062: if ($match) {
1.289 bowersj2 8063: return (1,$1);
8064: } else {
1.434 www 8065: return (0,0);
1.289 bowersj2 8066: }
1.12 www 8067: }
8068:
1.427 www 8069: # --------------------------------------------------------- Get symb from alias
8070:
8071: sub get_symb_from_alias {
8072: my $symb=shift;
8073: my ($map,$resid,$url)=&decode_symb($symb);
8074: # Already is a symb
8075: if ($url) { return $symb; }
8076: # Must be an alias
8077: my $aliassymb='';
8078: my %bighash;
1.620 albertel 8079: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 8080: &GDBM_READER(),0640)) {
8081: my $rid=$bighash{'mapalias_'.$symb};
8082: if ($rid) {
8083: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 8084: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8085: $resid,$bighash{'src_'.$rid});
1.427 www 8086: }
8087: untie %bighash;
8088: }
8089: return $aliassymb;
8090: }
8091:
1.12 www 8092: # ----------------------------------------------------------------- Define Role
8093:
8094: sub definerole {
8095: if (allowed('mcr','/')) {
1.1326 raeburn 8096: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800 albertel 8097: foreach my $role (split(':',$sysrole)) {
8098: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8099: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8100: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8101: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8102: return "refused:s:$crole&$cqual";
8103: }
8104: }
1.191 harris41 8105: }
1.800 albertel 8106: foreach my $role (split(':',$domrole)) {
8107: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8108: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8109: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8110: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 8111: return "refused:d:$crole&$cqual";
8112: }
8113: }
1.191 harris41 8114: }
1.800 albertel 8115: foreach my $role (split(':',$courole)) {
8116: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 8117: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8118: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8119: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 8120: return "refused:c:$crole&$cqual";
8121: }
8122: }
1.191 harris41 8123: }
1.1326 raeburn 8124: my $uhome;
8125: if (($uname ne '') && ($udom ne '')) {
8126: $uhome = &homeserver($uname,$udom);
8127: return $uhome if ($uhome eq 'no_host');
8128: } else {
8129: $uname = $env{'user.name'};
8130: $udom = $env{'user.domain'};
8131: $uhome = $env{'user.home'};
8132: }
1.620 albertel 8133: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326 raeburn 8134: "$udom:$uname:rolesdef_$rolename=".
1.21 www 8135: escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326 raeburn 8136: return reply($command,$uhome);
1.12 www 8137: } else {
8138: return 'refused';
8139: }
1.105 harris41 8140: }
8141:
8142: # ---------------- Make a metadata query against the network of library servers
8143:
8144: sub metadata_query {
1.1237 raeburn 8145: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 8146: my %rhash;
1.845 albertel 8147: my %libserv = &all_library();
1.244 matthew 8148: my @server_list = (defined($server_array) ? @$server_array
8149: : keys(%libserv) );
8150: for my $server (@server_list) {
1.1237 raeburn 8151: my $domains = '';
8152: if (ref($domains_hash) eq 'HASH') {
8153: $domains = $domains_hash->{$server};
8154: }
1.118 harris41 8155: unless ($custom or $customshow) {
1.1237 raeburn 8156: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 8157: $rhash{$server}=$reply;
8158: }
8159: else {
8160: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 8161: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 8162: $server);
8163: $rhash{$server}=$reply;
8164: }
1.112 harris41 8165: }
1.118 harris41 8166: return \%rhash;
1.240 www 8167: }
8168:
8169: # ----------------------------------------- Send log queries and wait for reply
8170:
8171: sub log_query {
8172: my ($uname,$udom,$query,%filters)=@_;
8173: my $uhome=&homeserver($uname,$udom);
8174: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 8175: my $uhost=&hostname($uhome);
1.800 albertel 8176: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 8177: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8178: $uhome);
1.479 albertel 8179: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 8180: return get_query_reply($queryid);
8181: }
8182:
1.818 raeburn 8183: # -------------------------- Update MySQL table for portfolio file
8184:
8185: sub update_portfolio_table {
1.821 raeburn 8186: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 8187: if ($group ne '') {
8188: $file_name =~s /^\Q$group\E//;
8189: }
1.818 raeburn 8190: my $homeserver = &homeserver($uname,$udom);
8191: my $queryid=
1.821 raeburn 8192: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8193: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 8194: my $reply = &get_query_reply($queryid);
8195: return $reply;
8196: }
8197:
1.899 raeburn 8198: # -------------------------- Update MySQL allusers table
8199:
8200: sub update_allusers_table {
8201: my ($uname,$udom,$names) = @_;
8202: my $homeserver = &homeserver($uname,$udom);
8203: my $queryid=
8204: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8205: 'lastname='.&escape($names->{'lastname'}).'%%'.
8206: 'firstname='.&escape($names->{'firstname'}).'%%'.
8207: 'middlename='.&escape($names->{'middlename'}).'%%'.
8208: 'generation='.&escape($names->{'generation'}).'%%'.
8209: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8210: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 8211: return;
1.899 raeburn 8212: }
8213:
1.508 raeburn 8214: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 8215:
8216: sub fetch_enrollment_query {
1.511 raeburn 8217: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317 raeburn 8218: my ($homeserver,$sleep,$loopmax);
1.547 raeburn 8219: my $maxtries = 1;
1.508 raeburn 8220: if ($context eq 'automated') {
8221: $homeserver = $perlvar{'lonHostID'};
1.1317 raeburn 8222: $sleep = 2;
8223: $loopmax = 100;
1.547 raeburn 8224: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 8225: } else {
8226: $homeserver = &homeserver($cnum,$dom);
8227: }
1.838 albertel 8228: my $host=&hostname($homeserver);
1.506 raeburn 8229: my $cmd = '';
1.1000 raeburn 8230: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 8231: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 8232: }
8233: $cmd =~ s/%%$//;
8234: $cmd = &escape($cmd);
8235: my $query = 'fetchenrollment';
1.620 albertel 8236: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 8237: unless ($queryid=~/^\Q$host\E\_/) {
8238: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8239: return 'error: '.$queryid;
8240: }
1.1317 raeburn 8241: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8242: my $tries = 1;
8243: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317 raeburn 8244: $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547 raeburn 8245: $tries ++;
8246: }
1.526 raeburn 8247: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 8248: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 8249: } else {
1.901 albertel 8250: my @responses = split(/:/,$reply);
1.1322 raeburn 8251: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
1.800 albertel 8252: foreach my $line (@responses) {
8253: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 8254: $$replyref{$key} = $value;
8255: }
8256: } else {
1.1117 foxr 8257: my $pathname = LONCAPA::tempdir();
1.800 albertel 8258: foreach my $line (@responses) {
8259: my ($key,$value) = split(/=/,$line);
1.506 raeburn 8260: $$replyref{$key} = $value;
8261: if ($value > 0) {
1.800 albertel 8262: foreach my $item (@{$$affiliatesref{$key}}) {
8263: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 8264: my $destname = $pathname.'/'.$filename;
8265: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 8266: if ($xml_classlist =~ /^error/) {
8267: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8268: } else {
1.506 raeburn 8269: if ( open(FILE,">$destname") ) {
8270: print FILE &unescape($xml_classlist);
8271: close(FILE);
1.526 raeburn 8272: } else {
8273: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 8274: }
8275: }
8276: }
8277: }
8278: }
8279: }
8280: return 'ok';
8281: }
8282: return 'error';
8283: }
8284:
1.242 www 8285: sub get_query_reply {
1.1317 raeburn 8286: my ($queryid,$sleep,$loopmax) = @_;;
8287: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8288: $sleep = 0.2;
8289: }
8290: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8291: $loopmax = 100;
8292: }
1.1117 foxr 8293: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 8294: my $reply='';
1.1317 raeburn 8295: for (1..$loopmax) {
8296: sleep($sleep);
1.240 www 8297: if (-e $replyfile.'.end') {
1.448 albertel 8298: if (open(my $fh,$replyfile)) {
1.904 albertel 8299: $reply = join('',<$fh>);
8300: close($fh);
1.240 www 8301: } else { return 'error: reply_file_error'; }
1.242 www 8302: return &unescape($reply);
8303: }
1.240 www 8304: }
1.242 www 8305: return 'timeout:'.$queryid;
1.240 www 8306: }
8307:
8308: sub courselog_query {
1.241 www 8309: #
8310: # possible filters:
8311: # url: url or symb
8312: # username
8313: # domain
8314: # action: view, submit, grade
8315: # start: timestamp
8316: # end: timestamp
8317: #
1.240 www 8318: my (%filters)=@_;
1.620 albertel 8319: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 8320: if ($filters{'url'}) {
8321: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8322: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8323: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8324: }
1.620 albertel 8325: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8326: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 8327: return &log_query($cname,$cdom,'courselog',%filters);
8328: }
8329:
8330: sub userlog_query {
1.858 raeburn 8331: #
8332: # possible filters:
8333: # action: log check role
8334: # start: timestamp
8335: # end: timestamp
8336: #
1.240 www 8337: my ($uname,$udom,%filters)=@_;
8338: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 8339: }
8340:
1.506 raeburn 8341: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8342:
8343: sub auto_run {
1.508 raeburn 8344: my ($cnum,$cdom) = @_;
1.876 raeburn 8345: my $response = 0;
8346: my $settings;
8347: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8348: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8349: $settings = $domconfig{'autoenroll'};
8350: if ($settings->{'run'} eq '1') {
8351: $response = 1;
8352: }
8353: } else {
1.934 raeburn 8354: my $homeserver;
8355: if (&is_course($cdom,$cnum)) {
8356: $homeserver = &homeserver($cnum,$cdom);
8357: } else {
8358: $homeserver = &domain($cdom,'primary');
8359: }
8360: if ($homeserver ne 'no_host') {
8361: $response = &reply('autorun:'.$cdom,$homeserver);
8362: }
1.876 raeburn 8363: }
1.506 raeburn 8364: return $response;
8365: }
1.776 albertel 8366:
1.506 raeburn 8367: sub auto_get_sections {
1.508 raeburn 8368: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 8369: my $homeserver;
8370: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8371: $homeserver = &homeserver($cnum,$cdom);
8372: }
8373: if (!defined($homeserver)) {
8374: if ($cdom =~ /^$match_domain$/) {
8375: $homeserver = &domain($cdom,'primary');
8376: }
8377: }
8378: my @secs;
8379: if (defined($homeserver)) {
8380: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8381: unless ($response eq 'refused') {
8382: @secs = split(/:/,$response);
8383: }
1.506 raeburn 8384: }
8385: return @secs;
8386: }
1.776 albertel 8387:
1.506 raeburn 8388: sub auto_new_course {
1.1099 raeburn 8389: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 8390: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 8391: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 8392: return $response;
8393: }
1.776 albertel 8394:
1.506 raeburn 8395: sub auto_validate_courseID {
1.508 raeburn 8396: my ($cnum,$cdom,$inst_course_id) = @_;
8397: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 8398: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 8399: return $response;
8400: }
1.776 albertel 8401:
1.1007 raeburn 8402: sub auto_validate_instcode {
1.1020 raeburn 8403: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 8404: my ($homeserver,$response);
8405: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8406: $homeserver = &homeserver($cnum,$cdom);
8407: }
8408: if (!defined($homeserver)) {
8409: if ($cdom =~ /^$match_domain$/) {
8410: $homeserver = &domain($cdom,'primary');
8411: }
8412: }
1.1065 raeburn 8413: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8414: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 8415: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
8416: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 8417: }
8418:
1.506 raeburn 8419: sub auto_create_password {
1.873 raeburn 8420: my ($cnum,$cdom,$authparam,$udom) = @_;
8421: my ($homeserver,$response);
1.506 raeburn 8422: my $create_passwd = 0;
8423: my $authchk = '';
1.873 raeburn 8424: if ($udom =~ /^$match_domain$/) {
8425: $homeserver = &domain($udom,'primary');
8426: }
8427: if ($homeserver eq '') {
8428: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8429: $homeserver = &homeserver($cnum,$cdom);
8430: }
8431: }
8432: if ($homeserver eq '') {
8433: $authchk = 'nodomain';
1.506 raeburn 8434: } else {
1.873 raeburn 8435: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8436: if ($response eq 'refused') {
8437: $authchk = 'refused';
8438: } else {
1.901 albertel 8439: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 8440: }
1.506 raeburn 8441: }
8442: return ($authparam,$create_passwd,$authchk);
8443: }
8444:
1.706 raeburn 8445: sub auto_photo_permission {
8446: my ($cnum,$cdom,$students) = @_;
8447: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 8448: my ($outcome,$perm_reqd,$conditions) =
8449: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 8450: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8451: return (undef,undef);
8452: }
1.706 raeburn 8453: return ($outcome,$perm_reqd,$conditions);
8454: }
8455:
8456: sub auto_checkphotos {
8457: my ($uname,$udom,$pid) = @_;
8458: my $homeserver = &homeserver($uname,$udom);
8459: my ($result,$resulttype);
8460: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 8461: &escape($uname).':'.&escape($pid),
8462: $homeserver));
1.709 albertel 8463: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8464: return (undef,undef);
8465: }
1.706 raeburn 8466: if ($outcome) {
8467: ($result,$resulttype) = split(/:/,$outcome);
8468: }
8469: return ($result,$resulttype);
8470: }
8471:
8472: sub auto_photochoice {
8473: my ($cnum,$cdom) = @_;
8474: my $homeserver = &homeserver($cnum,$cdom);
8475: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 8476: &escape($cdom),
8477: $homeserver)));
1.709 albertel 8478: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8479: return (undef,undef);
8480: }
1.706 raeburn 8481: return ($update,$comment);
8482: }
8483:
8484: sub auto_photoupdate {
8485: my ($affiliatesref,$dom,$cnum,$photo) = @_;
8486: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 8487: my $host=&hostname($homeserver);
1.706 raeburn 8488: my $cmd = '';
8489: my $maxtries = 1;
1.800 albertel 8490: foreach my $affiliate (keys(%{$affiliatesref})) {
8491: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 8492: }
8493: $cmd =~ s/%%$//;
8494: $cmd = &escape($cmd);
8495: my $query = 'institutionalphotos';
8496: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
8497: unless ($queryid=~/^\Q$host\E\_/) {
8498: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
8499: return 'error: '.$queryid;
8500: }
8501: my $reply = &get_query_reply($queryid);
8502: my $tries = 1;
8503: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8504: $reply = &get_query_reply($queryid);
8505: $tries ++;
8506: }
8507: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8508: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8509: } else {
8510: my @responses = split(/:/,$reply);
8511: my $outcome = shift(@responses);
8512: foreach my $item (@responses) {
8513: my ($key,$value) = split(/=/,$item);
8514: $$photo{$key} = $value;
8515: }
8516: return $outcome;
8517: }
8518: return 'error';
8519: }
8520:
1.521 raeburn 8521: sub auto_instcode_format {
1.793 albertel 8522: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
8523: $cat_order) = @_;
1.521 raeburn 8524: my $courses = '';
1.772 raeburn 8525: my @homeservers;
1.521 raeburn 8526: if ($caller eq 'global') {
1.841 albertel 8527: my %servers = &get_servers($codedom,'library');
8528: foreach my $tryserver (keys(%servers)) {
8529: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8530: push(@homeservers,$tryserver);
8531: }
1.584 raeburn 8532: }
1.1022 raeburn 8533: } elsif ($caller eq 'requests') {
8534: if ($codedom =~ /^$match_domain$/) {
8535: my $chome = &domain($codedom,'primary');
8536: unless ($chome eq 'no_host') {
8537: push(@homeservers,$chome);
8538: }
8539: }
1.521 raeburn 8540: } else {
1.772 raeburn 8541: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 8542: }
1.793 albertel 8543: foreach my $code (keys(%{$instcodes})) {
8544: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 8545: }
8546: chop($courses);
1.772 raeburn 8547: my $ok_response = 0;
8548: my $response;
8549: while (@homeservers > 0 && $ok_response == 0) {
8550: my $server = shift(@homeservers);
8551: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
8552: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
8553: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 8554: split(/:/,$response);
1.772 raeburn 8555: %{$codes} = (%{$codes},&str2hash($codes_str));
8556: push(@{$codetitles},&str2array($codetitles_str));
8557: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
8558: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
8559: $ok_response = 1;
8560: }
8561: }
8562: if ($ok_response) {
1.521 raeburn 8563: return 'ok';
1.772 raeburn 8564: } else {
8565: return $response;
1.521 raeburn 8566: }
8567: }
8568:
1.792 raeburn 8569: sub auto_instcode_defaults {
8570: my ($domain,$returnhash,$code_order) = @_;
8571: my @homeservers;
1.841 albertel 8572:
8573: my %servers = &get_servers($domain,'library');
8574: foreach my $tryserver (keys(%servers)) {
8575: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8576: push(@homeservers,$tryserver);
8577: }
1.792 raeburn 8578: }
1.841 albertel 8579:
1.792 raeburn 8580: my $response;
1.841 albertel 8581: foreach my $server (@homeservers) {
1.792 raeburn 8582: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 8583: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
8584:
8585: foreach my $pair (split(/\&/,$response)) {
8586: my ($name,$value)=split(/\=/,$pair);
8587: if ($name eq 'code_order') {
8588: @{$code_order} = split(/\&/,&unescape($value));
8589: } else {
8590: $returnhash->{&unescape($name)}=&unescape($value);
8591: }
8592: }
8593: return 'ok';
1.792 raeburn 8594: }
1.841 albertel 8595:
8596: return $response;
1.1003 raeburn 8597: }
8598:
8599: sub auto_possible_instcodes {
1.1007 raeburn 8600: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
8601: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
8602: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8603: return;
8604: }
1.1003 raeburn 8605: my (@homeservers,$uhome);
8606: if (defined(&domain($domain,'primary'))) {
8607: $uhome=&domain($domain,'primary');
8608: push(@homeservers,&domain($domain,'primary'));
8609: } else {
8610: my %servers = &get_servers($domain,'library');
8611: foreach my $tryserver (keys(%servers)) {
8612: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
8613: push(@homeservers,$tryserver);
8614: }
8615: }
8616: }
8617: my $response;
8618: foreach my $server (@homeservers) {
8619: $response=&reply('autopossibleinstcodes:'.$domain,$server);
8620: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 8621: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
8622: split(':',$response);
8623: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
8624: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 8625: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 8626: my ($name,$value)=split('=',$item);
8627: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8628: }
8629: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 8630: my ($name,$value)=split('=',$item);
8631: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 8632: }
8633: return 'ok';
8634: }
8635: return $response;
8636: }
1.792 raeburn 8637:
1.1010 raeburn 8638: sub auto_courserequest_checks {
8639: my ($dom) = @_;
1.1020 raeburn 8640: my ($homeserver,%validations);
8641: if ($dom =~ /^$match_domain$/) {
8642: $homeserver = &domain($dom,'primary');
8643: }
8644: unless ($homeserver eq 'no_host') {
8645: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
8646: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8647: my @items = split(/&/,$response);
8648: foreach my $item (@items) {
8649: my ($key,$value) = split('=',$item);
8650: $validations{&unescape($key)} = &thaw_unescape($value);
8651: }
8652: }
8653: }
1.1010 raeburn 8654: return %validations;
8655: }
8656:
1.1020 raeburn 8657: sub auto_courserequest_validation {
1.1255 raeburn 8658: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 8659: my ($homeserver,$response);
8660: if ($dom =~ /^$match_domain$/) {
8661: $homeserver = &domain($dom,'primary');
8662: }
1.1255 raeburn 8663: unless ($homeserver eq 'no_host') {
8664: my $customdata;
8665: if (ref($custominfo) eq 'HASH') {
8666: $customdata = &freeze_escape($custominfo);
8667: }
1.1020 raeburn 8668: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 8669: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 8670: ':'.&escape($instcode).':'.&escape($instseclist).':'.
8671: $customdata,$homeserver));
1.1020 raeburn 8672: }
8673: return $response;
8674: }
8675:
1.777 albertel 8676: sub auto_validate_class_sec {
1.918 raeburn 8677: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 8678: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 8679: my $ownerlist;
8680: if (ref($owners) eq 'ARRAY') {
8681: $ownerlist = join(',',@{$owners});
8682: } else {
8683: $ownerlist = $owners;
8684: }
1.773 raeburn 8685: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 8686: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 8687: return $response;
8688: }
8689:
1.1248 raeburn 8690: sub auto_crsreq_update {
8691: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 raeburn 8692: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 8693: my ($homeserver,%crsreqresponse);
8694: if ($cdom =~ /^$match_domain$/) {
8695: $homeserver = &domain($cdom,'primary');
8696: }
8697: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8698: my $info;
8699: if (ref($inbound) eq 'HASH') {
8700: $info = &freeze_escape($inbound);
8701: }
8702: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
8703: ':'.&escape($action).':'.&escape($ownername).':'.
8704: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 raeburn 8705: &escape($title).':'.&escape($code).':'.
8706: &escape($accessstart).':'.&escape($accessend).':'.$info,
8707: $homeserver);
1.1248 raeburn 8708: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8709: my @items = split(/&/,$response);
8710: foreach my $item (@items) {
8711: my ($key,$value) = split('=',$item);
8712: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8713: }
8714: }
8715: }
8716: return \%crsreqresponse;
8717: }
8718:
1.1305 raeburn 8719: sub auto_export_grades {
1.1309 raeburn 8720: my ($cdom,$cnum,$inforef,$gradesref) = @_;
8721: my ($homeserver,%exportresponse);
8722: if ($cdom =~ /^$match_domain$/) {
8723: $homeserver = &domain($cdom,'primary');
8724: }
8725: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
8726: my $info;
8727: if (ref($inforef) eq 'HASH') {
8728: $info = &freeze_escape($inforef);
8729: }
8730: if (ref($gradesref) eq 'HASH') {
8731: my $grades = &freeze_escape($gradesref);
8732: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
8733: $info.':'.$grades,$homeserver);
8734: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
8735: my @items = split(/&/,$response);
8736: foreach my $item (@items) {
8737: my ($key,$value) = split('=',$item);
8738: $exportresponse{&unescape($key)} = &thaw_unescape($value);
8739: }
8740: }
8741: }
8742: }
8743: return \%exportresponse;
1.1305 raeburn 8744: }
8745:
1.1287 raeburn 8746: sub check_instcode_cloning {
8747: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
8748: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
8749: return;
8750: }
8751: my $canclone;
8752: if (@{$code_order} > 0) {
8753: my $instcoderegexp ='^';
8754: my @clonecodes = split(/\&/,$cloner);
8755: foreach my $item (@{$code_order}) {
8756: if (grep(/^\Q$item\E=/,@clonecodes)) {
8757: foreach my $pair (@clonecodes) {
8758: my ($key,$val) = split(/\=/,$pair,2);
8759: $val = &unescape($val);
8760: if ($key eq $item) {
8761: $instcoderegexp .= '('.$val.')';
8762: last;
8763: }
8764: }
8765: } else {
8766: $instcoderegexp .= $codedefaults->{$item};
8767: }
8768: }
8769: $instcoderegexp .= '$';
8770: my (@from,@to);
8771: eval {
8772: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8773: (@to) = ($clonetocode =~ /$instcoderegexp/);
8774: };
8775: if ((@from > 0) && (@to > 0)) {
8776: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8777: if (!@diffs) {
8778: $canclone = 1;
8779: }
8780: }
8781: }
8782: return $canclone;
8783: }
8784:
8785: sub default_instcode_cloning {
8786: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
8787: my (%codedefaults,@code_order,$canclone);
8788: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
8789: %codedefaults = %{$codedefaultsref};
8790: @code_order = @{$codeorderref};
8791: } elsif ($clonedom) {
8792: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
8793: }
8794: if (($domdefclone) && (@code_order)) {
8795: my @clonecodes = split(/\+/,$domdefclone);
8796: my $instcoderegexp ='^';
8797: foreach my $item (@code_order) {
8798: if (grep(/^\Q$item\E$/,@clonecodes)) {
8799: $instcoderegexp .= '('.$codedefaults{$item}.')';
8800: } else {
8801: $instcoderegexp .= $codedefaults{$item};
8802: }
8803: }
8804: $instcoderegexp .= '$';
8805: my (@from,@to);
8806: eval {
8807: (@from) = ($clonefromcode =~ /$instcoderegexp/);
8808: (@to) = ($clonetocode =~ /$instcoderegexp/);
8809: };
8810: if ((@from > 0) && (@to > 0)) {
8811: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
8812: if (!@diffs) {
8813: $canclone = 1;
8814: }
8815: }
8816: }
8817: return $canclone;
8818: }
8819:
1.679 raeburn 8820: # ------------------------------------------------------- Course Group routines
8821:
8822: sub get_coursegroups {
1.809 raeburn 8823: my ($cdom,$cnum,$group,$namespace) = @_;
8824: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 8825: }
8826:
1.679 raeburn 8827: sub modify_coursegroup {
8828: my ($cdom,$cnum,$groupsettings) = @_;
8829: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8830: }
8831:
1.809 raeburn 8832: sub toggle_coursegroup_status {
8833: my ($cdom,$cnum,$group,$action) = @_;
8834: my ($from_namespace,$to_namespace);
8835: if ($action eq 'delete') {
8836: $from_namespace = 'coursegroups';
8837: $to_namespace = 'deleted_groups';
8838: } else {
8839: $from_namespace = 'deleted_groups';
8840: $to_namespace = 'coursegroups';
8841: }
8842: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 8843: if (my $tmp = &error(%curr_group)) {
8844: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8845: return ('read error',$tmp);
8846: } else {
8847: my %savedsettings = %curr_group;
1.809 raeburn 8848: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 8849: my $deloutcome;
8850: if ($result eq 'ok') {
1.809 raeburn 8851: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 8852: } else {
8853: return ('write error',$result);
8854: }
8855: if ($deloutcome eq 'ok') {
8856: return 'ok';
8857: } else {
8858: return ('delete error',$deloutcome);
8859: }
8860: }
8861: }
8862:
1.679 raeburn 8863: sub modify_group_roles {
1.957 raeburn 8864: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 8865: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8866: my $role = 'gr/'.&escape($userprivs);
8867: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 8868: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 8869: if ($result eq 'ok') {
8870: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8871: }
1.679 raeburn 8872: return $result;
8873: }
8874:
8875: sub modify_coursegroup_membership {
8876: my ($cdom,$cnum,$membership) = @_;
8877: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8878: return $result;
8879: }
8880:
1.682 raeburn 8881: sub get_active_groups {
8882: my ($udom,$uname,$cdom,$cnum) = @_;
8883: my $now = time;
8884: my %groups = ();
8885: foreach my $key (keys(%env)) {
1.811 albertel 8886: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 8887: my ($start,$end) = split(/\./,$env{$key});
8888: if (($end!=0) && ($end<$now)) { next; }
8889: if (($start!=0) && ($start>$now)) { next; }
8890: if ($1 eq $cdom && $2 eq $cnum) {
8891: $groups{$3} = $env{$key} ;
8892: }
8893: }
8894: }
8895: return %groups;
8896: }
8897:
1.683 raeburn 8898: sub get_group_membership {
8899: my ($cdom,$cnum,$group) = @_;
8900: return(&dump('groupmembership',$cdom,$cnum,$group));
8901: }
8902:
8903: sub get_users_groups {
8904: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8905: my @usersgroups;
1.683 raeburn 8906: my $cachetime=1800;
8907:
8908: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8909: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8910: if (defined($cached)) {
1.734 albertel 8911: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8912: } else {
8913: $grouplist = '';
1.816 raeburn 8914: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8915: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8916: my $access_end = $env{'course.'.$courseid.
8917: '.default_enrollment_end_date'};
8918: my $now = time;
8919: foreach my $key (keys(%roleshash)) {
8920: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8921: my $group = $1;
8922: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8923: my $start = $2;
8924: my $end = $1;
8925: if ($start == -1) { next; } # deleted from group
8926: if (($start!=0) && ($start>$now)) { next; }
8927: if (($end!=0) && ($end<$now)) {
8928: if ($access_end && $access_end < $now) {
8929: if ($access_end - $end < 86400) {
8930: push(@usersgroups,$group);
1.733 raeburn 8931: }
8932: }
1.817 raeburn 8933: next;
1.733 raeburn 8934: }
1.817 raeburn 8935: push(@usersgroups,$group);
1.683 raeburn 8936: }
8937: }
8938: }
1.817 raeburn 8939: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8940: $grouplist = join(':',@usersgroups);
8941: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8942: }
1.733 raeburn 8943: return @usersgroups;
1.683 raeburn 8944: }
8945:
8946: sub devalidate_getgroups_cache {
8947: my ($udom,$uname,$cdom,$cnum)=@_;
8948: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8949:
1.683 raeburn 8950: my $hashid="$udom:$uname:$courseid";
8951: &devalidate_cache_new('getgroups',$hashid);
8952: }
8953:
1.12 www 8954: # ------------------------------------------------------------------ Plain Text
8955:
8956: sub plaintext {
1.988 raeburn 8957: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8958: if ($short =~ m{^cr/}) {
1.758 albertel 8959: return (split('/',$short))[-1];
8960: }
1.742 raeburn 8961: if (!defined($cid)) {
8962: $cid = $env{'request.course.id'};
8963: }
8964: my %rolenames = (
1.1008 raeburn 8965: Course => 'std',
8966: Community => 'alt1',
1.1305 raeburn 8967: Placement => 'std',
1.742 raeburn 8968: );
1.1037 raeburn 8969: if ($cid ne '') {
8970: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8971: unless ($forcedefault) {
8972: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8973: &Apache::lonlocal::mt_escape(\$roletext);
8974: return &Apache::lonlocal::mt($roletext);
8975: }
8976: }
8977: }
8978: if ((defined($type)) && (defined($rolenames{$type})) &&
8979: (defined($rolenames{$type})) &&
8980: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8981: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8982: } elsif ($cid ne '') {
8983: my $crstype = $env{'course.'.$cid.'.type'};
8984: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8985: (defined($prp{$short}{$rolenames{$crstype}}))) {
8986: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8987: }
1.742 raeburn 8988: }
1.1037 raeburn 8989: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8990: }
8991:
8992: # ----------------------------------------------------------------- Assign Role
8993:
8994: sub assignrole {
1.957 raeburn 8995: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8996: $context)=@_;
1.21 www 8997: my $mrole;
8998: if ($role =~ /^cr\//) {
1.393 www 8999: my $cwosec=$url;
1.811 albertel 9000: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 9001: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 9002: my $refused = 1;
9003: if ($context eq 'requestcourses') {
9004: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9005: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9006: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9007: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9008: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9009: if ($crsenv{'internal.courseowner'} eq
9010: $env{'user.name'}.':'.$env{'user.domain'}) {
9011: $refused = '';
9012: }
9013: }
9014: }
9015: }
9016: }
9017: if ($refused) {
9018: &logthis('Refused custom assignrole: '.
9019: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9020: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9021: return 'refused';
9022: }
1.104 www 9023: }
1.21 www 9024: $mrole='cr';
1.678 raeburn 9025: } elsif ($role =~ /^gr\//) {
9026: my $cwogrp=$url;
1.811 albertel 9027: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 9028: unless (&allowed('mdg',$cwogrp)) {
9029: &logthis('Refused group assignrole: '.
9030: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9031: $env{'user.name'}.' at '.$env{'user.domain'});
9032: return 'refused';
9033: }
9034: $mrole='gr';
1.21 www 9035: } else {
1.82 www 9036: my $cwosec=$url;
1.811 albertel 9037: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 9038: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9039: my $refused;
9040: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9041: if (!(&allowed('c'.$role,$url))) {
9042: $refused = 1;
9043: }
9044: } else {
9045: $refused = 1;
9046: }
1.947 raeburn 9047: if ($refused) {
1.1045 raeburn 9048: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9049: if (!$selfenroll && $context eq 'course') {
9050: my %crsenv;
9051: if ($role eq 'cc' || $role eq 'co') {
9052: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9053: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9054: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9055: if ($crsenv{'internal.courseowner'} eq
9056: $env{'user.name'}.':'.$env{'user.domain'}) {
9057: $refused = '';
9058: }
9059: }
9060: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9061: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9062: if ($crsenv{'internal.courseowner'} eq
9063: $env{'user.name'}.':'.$env{'user.domain'}) {
9064: $refused = '';
9065: }
9066: }
9067: }
9068: }
9069: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 9070: $refused = '';
1.1017 raeburn 9071: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 9072: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 9073: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 9074: my $wrongcc;
9075: if ($cnum =~ /^$match_community$/) {
9076: $wrongcc = 1 if ($role eq 'cc');
9077: } else {
9078: $wrongcc = 1 if ($role eq 'co');
9079: }
9080: unless ($wrongcc) {
9081: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9082: if ($crsenv{'internal.courseowner'} eq
9083: $env{'user.name'}.':'.$env{'user.domain'}) {
9084: $refused = '';
9085: }
1.1017 raeburn 9086: }
9087: }
1.1183 raeburn 9088: } elsif ($context eq 'requestauthor') {
9089: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9090: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9091: if ($env{'environment.requestauthor'} eq 'automatic') {
9092: $refused = '';
9093: } else {
9094: my %domdefaults = &get_domain_defaults($udom);
9095: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9096: my $checkbystatus;
9097: if ($env{'user.adv'}) {
9098: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9099: if ($disposition eq 'automatic') {
9100: $refused = '';
9101: } elsif ($disposition eq '') {
9102: $checkbystatus = 1;
9103: }
9104: } else {
9105: $checkbystatus = 1;
9106: }
9107: if ($checkbystatus) {
9108: if ($env{'environment.inststatus'}) {
9109: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9110: foreach my $type (@inststatuses) {
9111: if (($type ne '') &&
9112: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9113: $refused = '';
9114: }
9115: }
9116: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9117: $refused = '';
9118: }
9119: }
9120: }
9121: }
9122: }
1.1017 raeburn 9123: }
9124: if ($refused) {
1.947 raeburn 9125: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9126: ' '.$role.' '.$end.' '.$start.' by '.
9127: $env{'user.name'}.' at '.$env{'user.domain'});
9128: return 'refused';
9129: }
1.932 raeburn 9130: }
1.1131 raeburn 9131: } elsif ($role eq 'au') {
9132: if ($url ne '/'.$udom.'/') {
9133: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9134: ' to assign author role for '.$uname.':'.$udom.
9135: ' in domain: '.$url.' refused (wrong domain).');
9136: return 'refused';
9137: }
1.104 www 9138: }
1.21 www 9139: $mrole=$role;
9140: }
1.620 albertel 9141: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 9142: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 9143: if ($end) { $command.='_'.$end; }
1.21 www 9144: if ($start) {
9145: if ($end) {
1.81 www 9146: $command.='_'.$start;
1.21 www 9147: } else {
1.81 www 9148: $command.='_0_'.$start;
1.21 www 9149: }
9150: }
1.739 raeburn 9151: my $origstart = $start;
9152: my $origend = $end;
1.957 raeburn 9153: my $delflag;
1.357 www 9154: # actually delete
9155: if ($deleteflag) {
1.373 www 9156: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 9157: # modify command to delete the role
1.620 albertel 9158: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 9159: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 9160: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 9161: # set start and finish to negative values for userrolelog
9162: $start=-1;
9163: $end=-1;
1.957 raeburn 9164: $delflag = 1;
1.357 www 9165: }
9166: }
9167: # send command
1.349 www 9168: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 9169: # log new user role if status is ok
1.349 www 9170: if ($answer eq 'ok') {
1.663 raeburn 9171: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 9172: if (($role eq 'cc') || ($role eq 'in') ||
9173: ($role eq 'ep') || ($role eq 'ad') ||
9174: ($role eq 'ta') || ($role eq 'st') ||
9175: ($role=~/^cr/) || ($role eq 'gr') ||
9176: ($role eq 'co')) {
1.1200 raeburn 9177: # for course roles, perform group memberships changes triggered by role change.
9178: unless ($role =~ /^gr/) {
9179: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9180: $origstart,$selfenroll,$context);
9181: }
1.1184 raeburn 9182: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9183: $selfenroll,$context);
9184: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334 raeburn 9185: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9186: ($role eq 'da')) {
1.1184 raeburn 9187: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9188: $context);
9189: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9190: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9191: $context);
9192: }
1.1053 raeburn 9193: if ($role eq 'cc') {
9194: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9195: }
1.349 www 9196: }
9197: return $answer;
1.169 harris41 9198: }
9199:
1.1053 raeburn 9200: sub autoupdate_coowners {
9201: my ($url,$end,$start,$uname,$udom) = @_;
9202: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9203: if (($cdom ne '') && ($cnum ne '')) {
9204: my $now = time;
9205: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9206: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9207: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9208: my $instcode = $coursehash{'internal.coursecode'};
9209: if ($instcode ne '') {
1.1056 raeburn 9210: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9211: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 9212: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 9213: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9214: if ($result eq 'valid') {
9215: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 9216: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9217: push(@newcoowners,$coowner);
9218: }
9219: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9220: push(@newcoowners,$uname.':'.$udom);
9221: }
9222: @newcoowners = sort(@newcoowners);
9223: } else {
9224: push(@newcoowners,$uname.':'.$udom);
9225: }
9226: } else {
9227: if ($coursehash{'internal.co-owners'}) {
9228: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9229: unless ($coowner eq $uname.':'.$udom) {
9230: push(@newcoowners,$coowner);
9231: }
9232: }
9233: unless (@newcoowners > 0) {
9234: $delcoowners = 1;
9235: $coowners = '';
9236: }
9237: }
9238: }
9239: if (@newcoowners || $delcoowners) {
9240: &store_coowners($cdom,$cnum,$coursehash{'home'},
9241: $delcoowners,@newcoowners);
9242: }
9243: }
9244: }
9245: }
9246: }
9247: }
9248: }
9249:
9250: sub store_coowners {
9251: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9252: my $cid = $cdom.'_'.$cnum;
9253: my ($coowners,$delresult,$putresult);
9254: if (@newcoowners) {
9255: $coowners = join(',',@newcoowners);
9256: my %coownershash = (
9257: 'internal.co-owners' => $coowners,
9258: );
9259: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9260: if ($putresult eq 'ok') {
9261: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9262: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9263: }
9264: }
9265: }
9266: if ($delcoowners) {
9267: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9268: if ($delresult eq 'ok') {
9269: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9270: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9271: }
9272: }
9273: }
9274: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9275: my %crsinfo =
9276: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9277: if (ref($crsinfo{$cid}) eq 'HASH') {
9278: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9279: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9280: }
9281: }
9282: }
9283:
1.169 harris41 9284: # -------------------------------------------------- Modify user authentication
1.197 www 9285: # Overrides without validation
9286:
1.169 harris41 9287: sub modifyuserauth {
9288: my ($udom,$uname,$umode,$upass)=@_;
9289: my $uhome=&homeserver($uname,$udom);
1.197 www 9290: unless (&allowed('mau',$udom)) { return 'refused'; }
9291: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 9292: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9293: ' in domain '.$env{'request.role.domain'});
1.169 harris41 9294: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9295: &escape($upass),$uhome);
1.620 albertel 9296: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 9297: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9298: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9299: &log($udom,,$uname,$uhome,
1.620 albertel 9300: 'Authentication changed by '.$env{'user.domain'}.', '.
9301: $env{'user.name'}.', '.$umode.
1.197 www 9302: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 9303: unless ($reply eq 'ok') {
1.197 www 9304: &logthis('Authentication mode error: '.$reply);
1.169 harris41 9305: return 'error: '.$reply;
9306: }
1.170 harris41 9307: return 'ok';
1.80 www 9308: }
9309:
1.81 www 9310: # --------------------------------------------------------------- Modify a user
1.80 www 9311:
1.81 www 9312: sub modifyuser {
1.206 matthew 9313: my ($udom, $uname, $uid,
9314: $umode, $upass, $first,
9315: $middle, $last, $gene,
1.1058 raeburn 9316: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 9317: $udom= &LONCAPA::clean_domain($udom);
9318: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 9319: my $showcandelete = 'none';
9320: if (ref($candelete) eq 'ARRAY') {
9321: if (@{$candelete} > 0) {
9322: $showcandelete = join(', ',@{$candelete});
9323: }
9324: }
1.81 www 9325: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 9326: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 9327: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 9328: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9329: ' desiredhome not specified').
1.620 albertel 9330: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9331: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 9332: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 9333: my $newuser;
9334: if ($uhome eq 'no_host') {
9335: $newuser = 1;
9336: }
1.80 www 9337: # ----------------------------------------------------------------- Create User
1.406 albertel 9338: if (($uhome eq 'no_host') &&
9339: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 9340: my $unhome='';
1.844 albertel 9341: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 9342: $unhome = $desiredhome;
1.620 albertel 9343: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9344: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 9345: } else { # load balancing routine for determining $unhome
1.81 www 9346: my $loadm=10000000;
1.841 albertel 9347: my %servers = &get_servers($udom,'library');
9348: foreach my $tryserver (keys(%servers)) {
9349: my $answer=reply('load',$tryserver);
9350: if (($answer=~/\d+/) && ($answer<$loadm)) {
9351: $loadm=$answer;
9352: $unhome=$tryserver;
9353: }
1.80 www 9354: }
9355: }
9356: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 9357: return 'error: unable to find a home server for '.$uname.
9358: ' in domain '.$udom;
1.80 www 9359: }
9360: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9361: &escape($upass),$unhome);
9362: unless ($reply eq 'ok') {
9363: return 'error: '.$reply;
9364: }
1.230 stredwic 9365: $uhome=&homeserver($uname,$udom,'true');
1.80 www 9366: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 9367: return 'error: unable verify users home machine.';
1.80 www 9368: }
1.209 matthew 9369: } # End of creation of new user
1.80 www 9370: # ---------------------------------------------------------------------- Add ID
9371: if ($uid) {
9372: $uid=~tr/A-Z/a-z/;
9373: my %uidhash=&idrget($udom,$uname);
1.196 www 9374: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
9375: && (!$forceid)) {
1.80 www 9376: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 9377: return 'error: user id "'.$uid.'" does not match '.
9378: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 9379: }
9380: } else {
1.1300 raeburn 9381: &idput($udom,{$uname => $uid},$uhome,'ids');
1.80 www 9382: }
9383: }
9384: # -------------------------------------------------------------- Add names, etc
1.313 matthew 9385: my @tmp=&get('environment',
1.899 raeburn 9386: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 9387: 'permanentemail','inststatus'],
1.134 albertel 9388: $udom,$uname);
1.1075 raeburn 9389: my (%names,%oldnames);
1.313 matthew 9390: if ($tmp[0] =~ m/^error:.*/) {
9391: %names=();
9392: } else {
9393: %names = @tmp;
1.1075 raeburn 9394: %oldnames = %names;
1.313 matthew 9395: }
1.388 www 9396: #
1.1058 raeburn 9397: # If name, email and/or uid are blank (e.g., because an uploaded file
9398: # of users did not contain them), do not overwrite existing values
9399: # unless field is in $candelete array ref.
9400: #
9401:
9402: my @fields = ('firstname','middlename','lastname','generation',
9403: 'permanentemail','id');
9404: my %newvalues;
9405: if (ref($candelete) eq 'ARRAY') {
9406: foreach my $field (@fields) {
9407: if (grep(/^\Q$field\E$/,@{$candelete})) {
9408: if ($field eq 'firstname') {
9409: $names{$field} = $first;
9410: } elsif ($field eq 'middlename') {
9411: $names{$field} = $middle;
9412: } elsif ($field eq 'lastname') {
9413: $names{$field} = $last;
9414: } elsif ($field eq 'generation') {
9415: $names{$field} = $gene;
9416: } elsif ($field eq 'permanentemail') {
9417: $names{$field} = $email;
9418: } elsif ($field eq 'id') {
9419: $names{$field} = $uid;
9420: }
9421: }
9422: }
9423: }
1.388 www 9424: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 9425: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 9426: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 9427: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 9428: if ($email) {
9429: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 9430: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 9431: }
1.899 raeburn 9432: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 9433: if (defined($inststatus)) {
9434: $names{'inststatus'} = '';
9435: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
9436: if (ref($usertypes) eq 'HASH') {
9437: my @okstatuses;
9438: foreach my $item (split(/:/,$inststatus)) {
9439: if (defined($usertypes->{$item})) {
9440: push(@okstatuses,$item);
9441: }
9442: }
9443: if (@okstatuses) {
9444: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
9445: }
9446: }
9447: }
1.1075 raeburn 9448: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 9449: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 9450: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 9451: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
9452: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
9453: } else {
9454: $logmsg .= ' during self creation';
9455: }
1.1075 raeburn 9456: my $changed;
9457: if ($newuser) {
9458: $changed = 1;
9459: } else {
9460: foreach my $field (@fields) {
9461: if ($names{$field} ne $oldnames{$field}) {
9462: $changed = 1;
9463: last;
9464: }
9465: }
9466: }
9467: unless ($changed) {
9468: $logmsg = 'No changes in user information needed for: '.$logmsg;
9469: &logthis($logmsg);
9470: return 'ok';
9471: }
9472: my $reply = &put('environment', \%names, $udom,$uname);
9473: if ($reply ne 'ok') {
9474: return 'error: '.$reply;
9475: }
1.1087 raeburn 9476: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
9477: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
9478: }
1.1075 raeburn 9479: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
9480: &devalidate_cache_new('namescache',$uname.':'.$udom);
9481: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 9482: &logthis($logmsg);
1.134 albertel 9483: return 'ok';
1.80 www 9484: }
9485:
1.81 www 9486: # -------------------------------------------------------------- Modify student
1.80 www 9487:
1.81 www 9488: sub modifystudent {
9489: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 9490: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314 raeburn 9491: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455 albertel 9492: if (!$cid) {
1.620 albertel 9493: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9494: return 'not_in_class';
9495: }
1.80 www 9496: }
9497: # --------------------------------------------------------------- Make the user
1.81 www 9498: my $reply=&modifyuser
1.209 matthew 9499: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 9500: $desiredhome,$email,$inststatus);
1.80 www 9501: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 9502: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 9503: # student's environment
1.297 matthew 9504: $uid = undef if (!$forceid);
1.455 albertel 9505: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 9506: $gene,$usec,$end,$start,$type,$locktype,
1.1314 raeburn 9507: $cid,$selfenroll,$context,$credits,$instsec);
1.297 matthew 9508: return $reply;
9509: }
9510:
9511: sub modify_student_enrollment {
1.1216 raeburn 9512: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314 raeburn 9513: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455 albertel 9514: my ($cdom,$cnum,$chome);
9515: if (!$cid) {
1.620 albertel 9516: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 9517: return 'not_in_class';
9518: }
1.620 albertel 9519: $cdom=$env{'course.'.$cid.'.domain'};
9520: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 9521: } else {
9522: ($cdom,$cnum)=split(/_/,$cid);
9523: }
1.620 albertel 9524: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 9525: if (!$chome) {
1.457 raeburn 9526: $chome=&homeserver($cnum,$cdom);
1.297 matthew 9527: }
1.455 albertel 9528: if (!$chome) { return 'unknown_course'; }
1.297 matthew 9529: # Make sure the user exists
1.81 www 9530: my $uhome=&homeserver($uname,$udom);
9531: if (($uhome eq '') || ($uhome eq 'no_host')) {
9532: return 'error: no such user';
9533: }
1.297 matthew 9534: # Get student data if we were not given enough information
9535: if (!defined($first) || $first eq '' ||
9536: !defined($last) || $last eq '' ||
9537: !defined($uid) || $uid eq '' ||
9538: !defined($middle) || $middle eq '' ||
9539: !defined($gene) || $gene eq '') {
1.294 matthew 9540: # They did not supply us with enough data to enroll the student, so
9541: # we need to pick up more information.
1.297 matthew 9542: my %tmp = &get('environment',
1.294 matthew 9543: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 9544: ,$udom,$uname);
9545:
1.800 albertel 9546: #foreach my $key (keys(%tmp)) {
9547: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 9548: #}
1.294 matthew 9549: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
9550: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
9551: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 9552: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 9553: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
9554: }
1.556 albertel 9555: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 9556: my $user = "$uname:$udom";
9557: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 9558: my $reply=cput('classlist',
1.1148 raeburn 9559: {$user =>
1.1314 raeburn 9560: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487 albertel 9561: $cdom,$cnum);
1.1148 raeburn 9562: if (($reply eq 'ok') || ($reply eq 'delayed')) {
9563: &devalidate_getsection_cache($udom,$uname,$cid);
9564: } else {
1.81 www 9565: return 'error: '.$reply;
9566: }
1.297 matthew 9567: # Add student role to user
1.83 www 9568: my $uurl='/'.$cid;
1.81 www 9569: $uurl=~s/\_/\//g;
9570: if ($usec) {
9571: $uurl.='/'.$usec;
9572: }
1.1148 raeburn 9573: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
9574: $selfenroll,$context);
9575: if ($result ne 'ok') {
9576: if ($old_entry{$user} ne '') {
9577: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
9578: } else {
9579: $reply = &del('classlist',[$user],$cdom,$cnum);
9580: }
9581: }
9582: return $result;
1.21 www 9583: }
9584:
1.556 albertel 9585: sub format_name {
9586: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
9587: my $name;
9588: if ($first ne 'lastname') {
9589: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
9590: } else {
9591: if ($lastname=~/\S/) {
9592: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
9593: $name=~s/\s+,/,/;
9594: } else {
9595: $name.= $firstname.' '.$middlename.' '.$generation;
9596: }
9597: }
9598: $name=~s/^\s+//;
9599: $name=~s/\s+$//;
9600: $name=~s/\s+/ /g;
9601: return $name;
9602: }
9603:
1.84 www 9604: # ------------------------------------------------- Write to course preferences
9605:
9606: sub writecoursepref {
9607: my ($courseid,%prefs)=@_;
9608: $courseid=~s/^\///;
9609: $courseid=~s/\_/\//g;
9610: my ($cdomain,$cnum)=split(/\//,$courseid);
9611: my $chome=homeserver($cnum,$cdomain);
9612: if (($chome eq '') || ($chome eq 'no_host')) {
9613: return 'error: no such course';
9614: }
9615: my $cstring='';
1.800 albertel 9616: foreach my $pref (keys(%prefs)) {
9617: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 9618: }
1.84 www 9619: $cstring=~s/\&$//;
9620: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
9621: }
9622:
9623: # ---------------------------------------------------------- Make/modify course
9624:
9625: sub createcourse {
1.741 raeburn 9626: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 9627: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 9628: $url=&declutter($url);
9629: my $cid='';
1.1028 raeburn 9630: if ($context eq 'requestcourses') {
9631: my $can_create = 0;
9632: my ($ownername,$ownerdom) = split(':',$course_owner);
9633: if ($udom eq $ownerdom) {
9634: if (&usertools_access($ownername,$ownerdom,$category,undef,
9635: $context)) {
9636: $can_create = 1;
9637: }
9638: } else {
9639: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
9640: $category);
9641: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
9642: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
9643: if (@curr > 0) {
9644: my @options = qw(approval validate autolimit);
9645: my $optregex = join('|',@options);
9646: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
9647: $can_create = 1;
9648: }
9649: }
9650: }
9651: }
9652: if ($can_create) {
9653: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
9654: unless (&allowed('ccc',$udom)) {
9655: return 'refused';
9656: }
1.1017 raeburn 9657: }
9658: } else {
9659: return 'refused';
9660: }
1.1028 raeburn 9661: } elsif (!&allowed('ccc',$udom)) {
9662: return 'refused';
1.84 www 9663: }
1.1011 raeburn 9664: # --------------------------------------------------------------- Get Unique ID
9665: my $uname;
9666: if ($cnum =~ /^$match_courseid$/) {
9667: my $chome=&homeserver($cnum,$udom,'true');
9668: if (($chome eq '') || ($chome eq 'no_host')) {
9669: $uname = $cnum;
9670: } else {
1.1038 raeburn 9671: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9672: }
9673: } else {
1.1038 raeburn 9674: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 9675: }
9676: return $uname if ($uname =~ /^error/);
9677: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 9678: if (!defined($course_server)) {
9679: if (defined(&domain($udom,'primary'))) {
9680: $course_server = &domain($udom,'primary');
9681: } else {
9682: $course_server = $env{'user.home'};
9683: }
9684: }
9685: my %host_servers =
9686: &Apache::lonnet::get_servers($udom,'library');
9687: unless ($host_servers{$course_server}) {
9688: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 9689: }
1.84 www 9690: # ------------------------------------------------------------- Make the course
9691: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 9692: $course_server);
1.84 www 9693: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 9694: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 9695: if (($uhome eq '') || ($uhome eq 'no_host')) {
9696: return 'error: no such course';
9697: }
1.271 www 9698: # ----------------------------------------------------------------- Course made
1.516 raeburn 9699: # log existence
1.1029 raeburn 9700: my $now = time;
1.918 raeburn 9701: my $newcourse = {
9702: $udom.'_'.$uname => {
1.921 raeburn 9703: description => $description,
9704: inst_code => $inst_code,
9705: owner => $course_owner,
9706: type => $crstype,
1.1029 raeburn 9707: creator => $env{'user.name'}.':'.
9708: $env{'user.domain'},
9709: created => $now,
9710: context => $context,
1.918 raeburn 9711: },
9712: };
1.921 raeburn 9713: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 9714: # set toplevel url
1.271 www 9715: my $topurl=$url;
9716: unless ($nonstandard) {
9717: # ------------------------------------------ For standard courses, make top url
9718: my $mapurl=&clutter($url);
1.278 www 9719: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 9720: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 9721: <map>
9722: <resource id="1" type="start"></resource>
9723: <resource id="2" src="$mapurl"></resource>
9724: <resource id="3" type="finish"></resource>
9725: <link index="1" from="1" to="2"></link>
9726: <link index="2" from="2" to="3"></link>
9727: </map>
9728: ENDINITMAP
9729: $topurl=&declutter(
1.638 albertel 9730: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 9731: );
9732: }
9733: # ----------------------------------------------------------- Write preferences
1.84 www 9734: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 9735: ('description' => $description,
9736: 'url' => $topurl,
9737: 'internal.creator' => $env{'user.name'}.':'.
9738: $env{'user.domain'},
9739: 'internal.created' => $now,
9740: 'internal.creationcontext' => $context)
9741: );
1.84 www 9742: return '/'.$udom.'/'.$uname;
9743: }
9744:
1.1011 raeburn 9745: # ------------------------------------------------------------------- Create ID
9746: sub generate_coursenum {
1.1038 raeburn 9747: my ($udom,$crstype) = @_;
1.1011 raeburn 9748: my $domdesc = &domain($udom);
9749: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 9750: my $first;
9751: if ($crstype eq 'Community') {
9752: $first = '0';
9753: } else {
9754: $first = int(1+rand(9));
9755: }
9756: my $uname=$first.
1.1011 raeburn 9757: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9758: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9759: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9760: # ----------------------------------------------- Make sure that does not exist
9761: my $uhome=&homeserver($uname,$udom,'true');
9762: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 9763: if ($crstype eq 'Community') {
9764: $first = '0';
9765: } else {
9766: $first = int(1+rand(9));
9767: }
9768: $uname=$first.
1.1011 raeburn 9769: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
9770: substr($$.time,0,5).unpack("H8",pack("I32",time)).
9771: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
9772: $uhome=&homeserver($uname,$udom,'true');
9773: unless (($uhome eq '') || ($uhome eq 'no_host')) {
9774: return 'error: unable to generate unique course-ID';
9775: }
9776: }
9777: return $uname;
9778: }
9779:
1.813 albertel 9780: sub is_course {
1.1167 droeschl 9781: my ($cdom, $cnum) = scalar(@_) == 1 ?
9782: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
9783:
9784: return unless $cdom and $cnum;
9785:
9786: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
9787: '.');
9788:
1.1219 raeburn 9789: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 9790: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 9791: }
9792:
1.1015 raeburn 9793: sub store_userdata {
9794: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 9795: my $result;
1.1016 raeburn 9796: if ($datakey ne '') {
1.1013 raeburn 9797: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 9798: if ($udom eq '' || $uname eq '') {
9799: $udom = $env{'user.domain'};
9800: $uname = $env{'user.name'};
9801: }
9802: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 9803: if (($uhome eq '') || ($uhome eq 'no_host')) {
9804: $result = 'error: no_host';
9805: } else {
9806: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
9807: $storehash->{'host'} = $perlvar{'lonHostID'};
9808:
9809: my $namevalue='';
9810: foreach my $key (keys(%{$storehash})) {
9811: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9812: }
9813: $namevalue=~s/\&$//;
1.1224 raeburn 9814: unless ($namespace eq 'courserequests') {
9815: $datakey = &escape($datakey);
9816: }
1.1105 raeburn 9817: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9818: $namevalue,$uhome);
1.1013 raeburn 9819: }
9820: } else {
9821: $result = 'error: data to store was not a hash reference';
9822: }
9823: } else {
9824: $result= 'error: invalid requestkey';
9825: }
9826: return $result;
9827: }
9828:
1.21 www 9829: # ---------------------------------------------------------- Assign Custom Role
9830:
9831: sub assigncustomrole {
1.957 raeburn 9832: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9833: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 9834: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 9835: }
9836:
9837: # ----------------------------------------------------------------- Revoke Role
9838:
9839: sub revokerole {
1.957 raeburn 9840: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9841: my $now=time;
1.965 raeburn 9842: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 9843: }
9844:
9845: # ---------------------------------------------------------- Revoke Custom Role
9846:
9847: sub revokecustomrole {
1.957 raeburn 9848: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 9849: my $now=time;
1.357 www 9850: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 9851: $deleteflag,$selfenroll,$context);
1.17 www 9852: }
9853:
1.533 banghart 9854: # ------------------------------------------------------------ Disk usage
1.535 albertel 9855: sub diskusage {
1.955 raeburn 9856: my ($udom,$uname,$directorypath,$getpropath)=@_;
9857: $directorypath =~ s/\/$//;
9858: my $listing=&reply('du2:'.&escape($directorypath).':'
9859: .&escape($getpropath).':'.&escape($uname).':'
9860: .&escape($udom),homeserver($uname,$udom));
9861: if ($listing eq 'unknown_cmd') {
9862: if ($getpropath) {
9863: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9864: }
9865: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9866: }
1.514 albertel 9867: return $listing;
1.512 banghart 9868: }
9869:
1.566 banghart 9870: sub is_locked {
1.1096 raeburn 9871: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 9872: my @check;
9873: my $is_locked;
1.1093 raeburn 9874: push (@check,$file_name);
1.613 albertel 9875: my %locked = &get('file_permissions',\@check,
1.620 albertel 9876: $env{'user.domain'},$env{'user.name'});
1.615 albertel 9877: my ($tmp)=keys(%locked);
9878: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 9879:
1.566 banghart 9880: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 9881: $is_locked = 'false';
9882: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 9883: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 9884: $is_locked = 'true';
1.1096 raeburn 9885: if (ref($which) eq 'ARRAY') {
9886: push(@{$which},$entry);
9887: } else {
9888: last;
9889: }
1.745 raeburn 9890: }
9891: }
1.566 banghart 9892: } else {
9893: $is_locked = 'false';
9894: }
1.1093 raeburn 9895: return $is_locked;
1.566 banghart 9896: }
9897:
1.759 albertel 9898: sub declutter_portfile {
9899: my ($file) = @_;
1.833 albertel 9900: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9901: return $file;
9902: }
9903:
1.559 banghart 9904: # ------------------------------------------------------------- Mark as Read Only
9905:
9906: sub mark_as_readonly {
9907: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9908: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9909: my ($tmp)=keys(%current_permissions);
9910: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9911: foreach my $file (@{$files}) {
1.759 albertel 9912: $file = &declutter_portfile($file);
1.561 banghart 9913: push(@{$current_permissions{$file}},$what);
1.559 banghart 9914: }
1.613 albertel 9915: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9916: return;
9917: }
9918:
1.572 banghart 9919: # ------------------------------------------------------------Save Selected Files
9920:
9921: sub save_selected_files {
9922: my ($user, $path, @files) = @_;
9923: my $filename = $user."savedfiles";
1.573 banghart 9924: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9925: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9926: foreach my $file (@files) {
1.620 albertel 9927: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9928: }
9929: foreach my $file (@other_files) {
1.574 banghart 9930: print (OUT $file."\n");
1.572 banghart 9931: }
1.574 banghart 9932: close (OUT);
1.572 banghart 9933: return 'ok';
9934: }
9935:
1.574 banghart 9936: sub clear_selected_files {
9937: my ($user) = @_;
9938: my $filename = $user."savedfiles";
1.1117 foxr 9939: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9940: print (OUT undef);
9941: close (OUT);
9942: return ("ok");
9943: }
9944:
1.572 banghart 9945: sub files_in_path {
9946: my ($user, $path) = @_;
9947: my $filename = $user."savedfiles";
9948: my %return_files;
1.1117 foxr 9949: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9950: while (my $line_in = <IN>) {
1.574 banghart 9951: chomp ($line_in);
9952: my @paths_and_file = split (m!/!, $line_in);
9953: my $file_part = pop (@paths_and_file);
9954: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9955: $path_part.='/';
9956: my $path_and_file = $path_part.$file_part;
9957: if ($path_part eq $path) {
9958: $return_files{$file_part}= 'selected';
9959: }
9960: }
1.574 banghart 9961: close (IN);
9962: return (\%return_files);
1.572 banghart 9963: }
9964:
9965: # called in portfolio select mode, to show files selected NOT in current directory
9966: sub files_not_in_path {
9967: my ($user, $path) = @_;
9968: my $filename = $user."savedfiles";
9969: my @return_files;
9970: my $path_part;
1.1117 foxr 9971: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9972: while (my $line = <IN>) {
1.572 banghart 9973: #ok, I know it's clunky, but I want it to work
1.800 albertel 9974: my @paths_and_file = split(m|/|, $line);
9975: my $file_part = pop(@paths_and_file);
9976: chomp($file_part);
9977: my $path_part = join('/', @paths_and_file);
1.572 banghart 9978: $path_part .= '/';
9979: my $path_and_file = $path_part.$file_part;
9980: if ($path_part ne $path) {
1.800 albertel 9981: push(@return_files, ($path_and_file));
1.572 banghart 9982: }
9983: }
1.800 albertel 9984: close(OUT);
1.574 banghart 9985: return (@return_files);
1.572 banghart 9986: }
9987:
1.1273 raeburn 9988: #------------------------------Submitted/Handedback Portfolio Files Versioning
9989:
9990: sub portfiles_versioning {
9991: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
9992: my $portfolio_root = '/userfiles/portfolio';
9993: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
9994: foreach my $file (@{$portfiles}) {
9995: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
9996: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
9997: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
9998: my $getpropath = 1;
9999: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10000: $stu_name,$getpropath);
10001: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10002: my $new_answer =
10003: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10004: if ($new_answer ne 'problem getting file') {
10005: push(@{$versioned_portfiles}, $directory.$new_answer);
10006: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10007: [$symb,$env{'request.course.id'},'graded']);
10008: }
10009: }
10010: }
10011:
10012: sub get_next_version {
10013: my ($answer_name, $answer_ext, $dir_list) = @_;
10014: my $version;
10015: if (ref($dir_list) eq 'ARRAY') {
10016: foreach my $row (@{$dir_list}) {
10017: my ($file) = split(/\&/,$row,2);
10018: my ($file_name,$file_version,$file_ext) =
10019: &file_name_version_ext($file);
10020: if (($file_name eq $answer_name) &&
10021: ($file_ext eq $answer_ext)) {
10022: # gets here if filename and extension match,
10023: # regardless of version
10024: if ($file_version ne '') {
10025: # a versioned file is found so save it for later
10026: if ($file_version > $version) {
10027: $version = $file_version;
10028: }
10029: }
10030: }
10031: }
10032: }
10033: $version ++;
10034: return($version);
10035: }
10036:
10037: sub version_selected_portfile {
10038: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10039: my ($answer_name,$answer_ver,$answer_ext) =
10040: &file_name_version_ext($file_name);
10041: my $new_answer;
10042: $env{'form.copy'} =
10043: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10044: if($env{'form.copy'} eq '-1') {
10045: $new_answer = 'problem getting file';
10046: } else {
10047: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10048: my $copy_result =
10049: &finishuserfileupload($stu_name,$domain,'copy',
10050: '/portfolio'.$directory.$new_answer);
10051: }
10052: undef($env{'form.copy'});
10053: return ($new_answer);
10054: }
10055:
10056: sub file_name_version_ext {
10057: my ($file)=@_;
10058: my @file_parts = split(/\./, $file);
10059: my ($name,$version,$ext);
10060: if (@file_parts > 1) {
10061: $ext=pop(@file_parts);
10062: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10063: $version=pop(@file_parts);
10064: }
10065: $name=join('.',@file_parts);
10066: } else {
10067: $name=join('.',@file_parts);
10068: }
10069: return($name,$version,$ext);
10070: }
10071:
1.745 raeburn 10072: #----------------------------------------------Get portfolio file permissions
1.629 banghart 10073:
1.745 raeburn 10074: sub get_portfile_permissions {
10075: my ($domain,$user) = @_;
1.613 albertel 10076: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 10077: my ($tmp)=keys(%current_permissions);
10078: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10079: return \%current_permissions;
10080: }
10081:
10082: #---------------------------------------------Get portfolio file access controls
10083:
1.749 raeburn 10084: sub get_access_controls {
1.745 raeburn 10085: my ($current_permissions,$group,$file) = @_;
1.769 albertel 10086: my %access;
10087: my $real_file = $file;
10088: $file =~ s/\.meta$//;
1.745 raeburn 10089: if (defined($file)) {
1.749 raeburn 10090: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10091: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 10092: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 10093: }
10094: }
1.745 raeburn 10095: } else {
1.749 raeburn 10096: foreach my $key (keys(%{$current_permissions})) {
10097: if ($key =~ /\0accesscontrol$/) {
10098: if (defined($group)) {
10099: if ($key !~ m-^\Q$group\E/-) {
10100: next;
10101: }
10102: }
10103: my ($fullpath) = split(/\0/,$key);
10104: if (ref($$current_permissions{$key}) eq 'HASH') {
10105: foreach my $control (keys(%{$$current_permissions{$key}})) {
10106: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10107: }
10108: }
10109: }
10110: }
10111: }
10112: return %access;
10113: }
10114:
10115: sub modify_access_controls {
10116: my ($file_name,$changes,$domain,$user)=@_;
10117: my ($outcome,$deloutcome);
10118: my %store_permissions;
10119: my %new_values;
10120: my %new_control;
10121: my %translation;
10122: my @deletions = ();
10123: my $now = time;
10124: if (exists($$changes{'activate'})) {
10125: if (ref($$changes{'activate'}) eq 'HASH') {
10126: my @newitems = sort(keys(%{$$changes{'activate'}}));
10127: my $numnew = scalar(@newitems);
10128: for (my $i=0; $i<$numnew; $i++) {
10129: my $newkey = $newitems[$i];
10130: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 10131: if ($newkey =~ /^\d+:/) {
10132: $newkey =~ s/^(\d+)/$newid/;
10133: $translation{$1} = $newid;
10134: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10135: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10136: $translation{$1} = $newid;
10137: }
1.749 raeburn 10138: $new_values{$file_name."\0".$newkey} =
10139: $$changes{'activate'}{$newitems[$i]};
10140: $new_control{$newkey} = $now;
10141: }
10142: }
10143: }
10144: my %todelete;
10145: my %changed_items;
10146: foreach my $action ('delete','update') {
10147: if (exists($$changes{$action})) {
10148: if (ref($$changes{$action}) eq 'HASH') {
10149: foreach my $key (keys(%{$$changes{$action}})) {
10150: my ($itemnum) = ($key =~ /^([^:]+):/);
10151: if ($action eq 'delete') {
10152: $todelete{$itemnum} = 1;
10153: } else {
10154: $changed_items{$itemnum} = $key;
10155: }
10156: }
1.745 raeburn 10157: }
10158: }
1.749 raeburn 10159: }
10160: # get lock on access controls for file.
10161: my $lockhash = {
10162: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10163: ':'.$env{'user.domain'},
10164: };
10165: my $tries = 0;
10166: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10167:
1.1288 damieng 10168: while (($gotlock ne 'ok') && $tries < 10) {
1.749 raeburn 10169: $tries ++;
1.1289 damieng 10170: sleep(0.1);
1.749 raeburn 10171: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10172: }
10173: if ($gotlock eq 'ok') {
10174: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10175: my ($tmp)=keys(%curr_permissions);
10176: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10177: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10178: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10179: if (ref($curr_controls) eq 'HASH') {
10180: foreach my $control_item (keys(%{$curr_controls})) {
10181: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10182: if (defined($todelete{$itemnum})) {
10183: push(@deletions,$file_name."\0".$control_item);
10184: } else {
10185: if (defined($changed_items{$itemnum})) {
10186: $new_control{$changed_items{$itemnum}} = $now;
10187: push(@deletions,$file_name."\0".$control_item);
10188: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10189: } else {
10190: $new_control{$control_item} = $$curr_controls{$control_item};
10191: }
10192: }
1.745 raeburn 10193: }
10194: }
10195: }
1.970 raeburn 10196: my ($group);
10197: if (&is_course($domain,$user)) {
10198: ($group,my $file) = split(/\//,$file_name,2);
10199: }
1.749 raeburn 10200: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10201: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10202: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10203: # remove lock
10204: my @del_lock = ($file_name."\0".'locked_access_records');
10205: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 10206: my $sqlresult =
1.970 raeburn 10207: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 10208: $group);
1.749 raeburn 10209: } else {
10210: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 10211: }
1.749 raeburn 10212: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 10213: }
10214:
1.827 raeburn 10215: sub make_public_indefinitely {
1.1271 raeburn 10216: my (@requrl) = @_;
10217: return &automated_portfile_access('public',\@requrl);
10218: }
10219:
10220: sub automated_portfile_access {
10221: my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273 raeburn 10222: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10223: return 'invalid';
10224: }
1.1271 raeburn 10225: my %urls;
10226: if (ref($addsref) eq 'ARRAY') {
10227: foreach my $requrl (@{$addsref}) {
10228: if (&is_portfolio_url($requrl)) {
10229: unless (exists($urls{$requrl})) {
10230: $urls{$requrl} = 'add';
10231: }
10232: }
10233: }
10234: }
10235: if (ref($delsref) eq 'ARRAY') {
10236: foreach my $requrl (@{$delsref}) {
10237: if (&is_portfolio_url($requrl)) {
10238: unless (exists($urls{$requrl})) {
10239: $urls{$requrl} = 'delete';
10240: }
10241: }
10242: }
10243: }
10244: unless (keys(%urls)) {
10245: return 'invalid';
10246: }
10247: my $ip;
10248: if ($accesstype eq 'ip') {
10249: if (ref($info) eq 'HASH') {
10250: if ($info->{'ip'} ne '') {
10251: $ip = $info->{'ip'};
10252: }
10253: }
10254: if ($ip eq '') {
10255: return 'invalid';
10256: }
10257: }
10258: my $errors;
1.827 raeburn 10259: my $now = time;
1.1271 raeburn 10260: my %current_perms;
10261: foreach my $requrl (sort(keys(%urls))) {
10262: my $action;
10263: if ($urls{$requrl} eq 'add') {
10264: $action = 'activate';
10265: } else {
10266: $action = 'none';
10267: }
10268: my $aclnum = 0;
1.827 raeburn 10269: my (undef,$udom,$unum,$file_name,$group) =
10270: &parse_portfolio_url($requrl);
1.1271 raeburn 10271: unless (exists($current_perms{$unum.':'.$udom})) {
10272: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10273: }
10274: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827 raeburn 10275: $group,$file_name);
10276: foreach my $key (keys(%{$access_controls{$file_name}})) {
10277: my ($num,$scope,$end,$start) =
10278: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271 raeburn 10279: if ($scope eq $accesstype) {
10280: if (($start <= $now) && ($end == 0)) {
10281: if ($accesstype eq 'ip') {
10282: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10283: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10284: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10285: if ($urls{$requrl} eq 'add') {
10286: $action = 'none';
10287: last;
10288: } else {
10289: $action = 'delete';
10290: $aclnum = $num;
10291: last;
10292: }
10293: }
10294: }
10295: }
10296: } elsif ($accesstype eq 'public') {
10297: if ($urls{$requrl} eq 'add') {
10298: $action = 'none';
10299: last;
10300: } else {
10301: $action = 'delete';
10302: $aclnum = $num;
10303: last;
10304: }
10305: }
10306: } elsif ($accesstype eq 'public') {
1.827 raeburn 10307: $action = 'update';
10308: $aclnum = $num;
1.1271 raeburn 10309: last;
1.827 raeburn 10310: }
10311: }
10312: }
10313: if ($action eq 'none') {
1.1271 raeburn 10314: next;
1.827 raeburn 10315: } else {
10316: my %changes;
10317: my $newend = 0;
10318: my $newstart = $now;
1.1271 raeburn 10319: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827 raeburn 10320: $changes{$action}{$newkey} = {
1.1271 raeburn 10321: type => $accesstype,
1.827 raeburn 10322: time => {
10323: start => $newstart,
10324: end => $newend,
10325: },
10326: };
1.1271 raeburn 10327: if ($accesstype eq 'ip') {
10328: $changes{$action}{$newkey}{'ip'} = [$ip];
10329: }
1.827 raeburn 10330: my ($outcome,$deloutcome,$new_values,$translation) =
10331: &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271 raeburn 10332: unless ($outcome eq 'ok') {
10333: $errors .= $outcome.' ';
10334: }
1.827 raeburn 10335: }
1.1271 raeburn 10336: }
10337: if ($errors) {
10338: $errors =~ s/\s$//;
10339: return $errors;
1.827 raeburn 10340: } else {
1.1271 raeburn 10341: return 'ok';
1.827 raeburn 10342: }
10343: }
10344:
1.745 raeburn 10345: #------------------------------------------------------Get Marked as Read Only
10346:
10347: sub get_marked_as_readonly {
10348: my ($domain,$user,$what,$group) = @_;
10349: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 10350: my @readonly_files;
1.629 banghart 10351: my $cmp1=$what;
10352: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 10353: while (my ($file_name,$value) = each(%{$current_permissions})) {
10354: if (defined($group)) {
10355: if ($file_name !~ m-^\Q$group\E/-) {
10356: next;
10357: }
10358: }
1.561 banghart 10359: if (ref($value) eq "ARRAY"){
10360: foreach my $stored_what (@{$value}) {
1.629 banghart 10361: my $cmp2=$stored_what;
1.759 albertel 10362: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 10363: $cmp2=join('',@{$stored_what});
1.745 raeburn 10364: }
1.629 banghart 10365: if ($cmp1 eq $cmp2) {
1.561 banghart 10366: push(@readonly_files, $file_name);
1.745 raeburn 10367: last;
1.563 banghart 10368: } elsif (!defined($what)) {
10369: push(@readonly_files, $file_name);
1.745 raeburn 10370: last;
1.561 banghart 10371: }
10372: }
1.745 raeburn 10373: }
1.561 banghart 10374: }
10375: return @readonly_files;
10376: }
1.577 banghart 10377: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 10378:
1.577 banghart 10379: sub get_marked_as_readonly_hash {
1.745 raeburn 10380: my ($current_permissions,$group,$what) = @_;
1.577 banghart 10381: my %readonly_files;
1.745 raeburn 10382: while (my ($file_name,$value) = each(%{$current_permissions})) {
10383: if (defined($group)) {
10384: if ($file_name !~ m-^\Q$group\E/-) {
10385: next;
10386: }
10387: }
1.577 banghart 10388: if (ref($value) eq "ARRAY"){
10389: foreach my $stored_what (@{$value}) {
1.745 raeburn 10390: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 10391: foreach my $lock_descriptor(@{$stored_what}) {
10392: if ($lock_descriptor eq 'graded') {
10393: $readonly_files{$file_name} = 'graded';
10394: } elsif ($lock_descriptor eq 'handback') {
10395: $readonly_files{$file_name} = 'handback';
10396: } else {
10397: if (!exists($readonly_files{$file_name})) {
10398: $readonly_files{$file_name} = 'locked';
10399: }
10400: }
1.745 raeburn 10401: }
1.750 banghart 10402: }
1.577 banghart 10403: }
10404: }
10405: }
10406: return %readonly_files;
10407: }
1.559 banghart 10408: # ------------------------------------------------------------ Unmark as Read Only
10409:
10410: sub unmark_as_readonly {
1.629 banghart 10411: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10412: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 10413: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 10414: $file_name = &declutter_portfile($file_name);
1.634 albertel 10415: my $symb_crs = $what;
10416: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 10417: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 10418: my ($tmp)=keys(%current_permissions);
10419: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 10420: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 10421: foreach my $file (@readonly_files) {
1.759 albertel 10422: my $clean_file = &declutter_portfile($file);
10423: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 10424: my $current_locks = $current_permissions{$file};
1.563 banghart 10425: my @new_locks;
10426: my @del_keys;
10427: if (ref($current_locks) eq "ARRAY"){
10428: foreach my $locker (@{$current_locks}) {
1.632 albertel 10429: my $compare=$locker;
1.749 raeburn 10430: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 10431: $compare=join('',@{$locker});
1.746 raeburn 10432: if ($compare ne $symb_crs) {
10433: push(@new_locks, $locker);
10434: }
1.563 banghart 10435: }
10436: }
1.650 albertel 10437: if (scalar(@new_locks) > 0) {
1.563 banghart 10438: $current_permissions{$file} = \@new_locks;
10439: } else {
10440: push(@del_keys, $file);
1.613 albertel 10441: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 10442: delete($current_permissions{$file});
1.563 banghart 10443: }
10444: }
1.561 banghart 10445: }
1.613 albertel 10446: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 10447: return;
10448: }
1.512 banghart 10449:
1.17 www 10450: # ------------------------------------------------------------ Directory lister
10451:
10452: sub dirlist {
1.955 raeburn 10453: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 10454: $uri=~s/^\///;
10455: $uri=~s/\/$//;
1.253 stredwic 10456: my ($udom, $uname);
1.955 raeburn 10457: if ($getuserdir) {
1.253 stredwic 10458: $udom = $userdomain;
10459: $uname = $username;
1.955 raeburn 10460: } else {
10461: (undef,$udom,$uname)=split(/\//,$uri);
10462: if(defined($userdomain)) {
10463: $udom = $userdomain;
10464: }
10465: if(defined($username)) {
10466: $uname = $username;
10467: }
1.253 stredwic 10468: }
1.955 raeburn 10469: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 10470:
1.955 raeburn 10471: $dirRoot = $perlvar{'lonDocRoot'};
10472: if (defined($getpropath)) {
10473: $dirRoot = &propath($udom,$uname);
1.253 stredwic 10474: $dirRoot =~ s/\/$//;
1.955 raeburn 10475: } elsif (defined($getuserdir)) {
10476: my $subdir=$uname.'__';
10477: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10478: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10479: ."/$udom/$subdir/$uname";
10480: } elsif (defined($alternateRoot)) {
10481: $dirRoot = $alternateRoot;
1.751 banghart 10482: }
1.253 stredwic 10483:
10484: if($udom) {
10485: if($uname) {
1.1135 raeburn 10486: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 10487: if ($uhome eq 'no_host') {
10488: return ([],'no_host');
10489: }
1.955 raeburn 10490: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 10491: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 10492: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 10493: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10494: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 10495: } else {
10496: @listing_results = map { &unescape($_); } split(/:/,$listing);
10497: }
1.605 matthew 10498: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 10499: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 10500: @listing_results = split(/:/,$listing);
10501: } else {
10502: @listing_results = map { &unescape($_); } split(/:/,$listing);
10503: }
1.1135 raeburn 10504: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 10505: ($listing eq 'rejected') || ($listing eq 'refused') ||
10506: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10507: return ([],$listing);
10508: } else {
10509: return (\@listing_results);
1.1135 raeburn 10510: }
1.955 raeburn 10511: } elsif(!$alternateRoot) {
1.1136 raeburn 10512: my (%allusers,%listerror);
1.841 albertel 10513: my %servers = &get_servers($udom,'library');
1.955 raeburn 10514: foreach my $tryserver (keys(%servers)) {
10515: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10516: &escape($udom),$tryserver);
10517: if ($listing eq 'unknown_cmd') {
10518: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10519: $udom, $tryserver);
10520: } else {
10521: @listing_results = map { &unescape($_); } split(/:/,$listing);
10522: }
1.841 albertel 10523: if ($listing eq 'unknown_cmd') {
10524: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10525: $udom, $tryserver);
10526: @listing_results = split(/:/,$listing);
10527: } else {
10528: @listing_results =
10529: map { &unescape($_); } split(/:/,$listing);
10530: }
1.1136 raeburn 10531: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10532: ($listing eq 'rejected') || ($listing eq 'refused') ||
10533: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10534: $listerror{$tryserver} = $listing;
10535: } else {
1.841 albertel 10536: foreach my $line (@listing_results) {
10537: my ($entry) = split(/&/,$line,2);
10538: $allusers{$entry} = 1;
10539: }
10540: }
1.253 stredwic 10541: }
1.1136 raeburn 10542: my @alluserslist=();
1.800 albertel 10543: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 10544: push(@alluserslist,$user.'&user');
1.253 stredwic 10545: }
1.1318 droeschl 10546:
10547: if (!%listerror) {
10548: # no errors
10549: return (\@alluserslist);
10550: } elsif (scalar(keys(%servers)) == 1) {
10551: # one library server, one error
10552: my ($key) = keys(%listerror);
10553: return (\@alluserslist, $listerror{$key});
10554: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10555: # con_lost indicates that we might miss data from at least one
10556: # library server
10557: return (\@alluserslist, 'con_lost');
10558: } else {
10559: # multiple library servers and no con_lost -> data should be
10560: # complete.
10561: return (\@alluserslist);
10562: }
10563:
1.253 stredwic 10564: } else {
1.1136 raeburn 10565: return ([],'missing username');
1.253 stredwic 10566: }
1.955 raeburn 10567: } elsif(!defined($getpropath)) {
1.1136 raeburn 10568: my $path = $perlvar{'lonDocRoot'}.'/res/';
10569: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10570: return (\@all_domains);
1.955 raeburn 10571: } else {
1.1136 raeburn 10572: return ([],'missing domain');
1.275 stredwic 10573: }
10574: }
10575:
10576: # --------------------------------------------- GetFileTimestamp
10577: # This function utilizes dirlist and returns the date stamp for
10578: # when it was last modified. It will also return an error of -1
10579: # if an error occurs
10580:
10581: sub GetFileTimestamp {
1.955 raeburn 10582: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 10583: $studentDomain = &LONCAPA::clean_domain($studentDomain);
10584: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 10585: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10586: undef,$getuserdir);
10587: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10588: return -1;
10589: }
10590: if (ref($fileref) eq 'ARRAY') {
10591: my @stats = split('&',$fileref->[0]);
1.375 matthew 10592: # @stats contains first the filename, then the stat output
10593: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 10594: } else {
10595: return -1;
1.253 stredwic 10596: }
1.26 www 10597: }
10598:
1.712 albertel 10599: sub stat_file {
10600: my ($uri) = @_;
1.787 albertel 10601: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 10602:
1.955 raeburn 10603: my ($udom,$uname,$file);
1.712 albertel 10604: if ($uri =~ m-^/(uploaded|editupload)/-) {
10605: ($udom,$uname,$file) =
1.811 albertel 10606: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 10607: $file = 'userfiles/'.$file;
10608: }
10609: if ($uri =~ m-^/res/-) {
10610: ($udom,$uname) =
1.807 albertel 10611: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 10612: $file = $uri;
10613: }
10614:
10615: if (!$udom || !$uname || !$file) {
10616: # unable to handle the uri
10617: return ();
10618: }
1.956 raeburn 10619: my $getpropath;
10620: if ($file =~ /^userfiles\//) {
10621: $getpropath = 1;
10622: }
1.1136 raeburn 10623: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10624: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10625: return ();
10626: } else {
10627: if (ref($listref) eq 'ARRAY') {
10628: my @stats = split('&',$listref->[0]);
10629: shift(@stats); #filename is first
10630: return @stats;
10631: }
1.712 albertel 10632: }
10633: return ();
10634: }
10635:
1.1313 raeburn 10636: # --------------------------------------------------------- recursedirs
10637: # Recursive function to traverse either a specific user's Authoring Space
10638: # or corresponding Published Resource Space, and populate the hash ref:
10639: # $dirhashref with URLs of all directories, and if $filehashref hash
10640: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
10641: # or .rights files in resource space, and .meta, .save, .log, and .bak
10642: # files in Authoring Space.
10643: #
10644: # Inputs:
10645: #
10646: # $is_home - true if current server is home server for user's space
10647: # $context - either: priv, or res respectively for Authoring or Resource Space.
10648: # $docroot - Document root (i.e., /home/httpd/html
10649: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
10650: # $relpath - Current path (relative to top level).
10651: # $dirhashref - reference to hash to populate with URLs of directories (Required)
10652: # $filehashref - reference to hash to populate with URLs of files (Optional)
10653: #
10654: # Returns: nothing
10655: #
10656: # Side Effects: populates $dirhashref, and $filehashref (if provided).
10657: #
10658: # Currently used by interface/londocs.pm to create linked select boxes for
10659: # directory and filename to import a Course "Author" resource into a course, and
10660: # also to create linked select boxes for Authoring Space and Directory to choose
10661: # save location for creation of a new "standard" problem from the Course Editor.
10662: #
10663:
10664: sub recursedirs {
10665: my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
10666: return unless (ref($dirhashref) eq 'HASH');
10667: my $currpath = $docroot.$toppath;
10668: if ($relpath) {
10669: $currpath .= "/$relpath";
10670: }
10671: my $savefile;
10672: if (ref($filehashref)) {
10673: $savefile = 1;
10674: }
10675: if ($is_home) {
10676: if (opendir(my $dirh,$currpath)) {
10677: foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
10678: next if ($item eq '');
10679: if (-d "$currpath/$item") {
10680: my $newpath;
10681: if ($relpath) {
10682: $newpath = "$relpath/$item";
10683: } else {
10684: $newpath = $item;
10685: }
10686: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10687: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10688: } elsif ($savefile) {
10689: if ($context eq 'priv') {
10690: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10691: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10692: }
10693: } else {
10694: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
10695: $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10696: }
10697: }
10698: }
10699: }
10700: closedir($dirh);
10701: }
10702: } else {
10703: my ($dirlistref,$listerror) =
10704: &dirlist($toppath.$relpath);
10705: my @dir_lines;
10706: my $dirptr=16384;
10707: if (ref($dirlistref) eq 'ARRAY') {
10708: foreach my $dir_line (sort
10709: {
10710: my ($afile)=split('&',$a,2);
10711: my ($bfile)=split('&',$b,2);
10712: return (lc($afile) cmp lc($bfile));
10713: } (@{$dirlistref})) {
10714: my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
10715: split(/\&/,$dir_line,16);
10716: $item =~ s/\s+$//;
10717: next if (($item =~ /^\.\.?$/) || ($obs));
10718: if ($dirptr&$testdir) {
10719: my $newpath;
10720: if ($relpath) {
10721: $newpath = "$relpath/$item";
10722: } else {
10723: $relpath = '/';
10724: $newpath = $item;
10725: }
10726: $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10727: &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10728: } elsif ($savefile) {
10729: if ($context eq 'priv') {
10730: unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10731: $filehashref->{$relpath}{$item} = 1;
10732: }
10733: } else {
10734: unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
10735: $filehashref->{$relpath}{$item} = 1;
10736: }
10737: }
10738: }
10739: }
10740: }
10741: }
10742: return;
10743: }
10744:
1.26 www 10745: # -------------------------------------------------------- Value of a Condition
10746:
1.713 albertel 10747: # gets the value of a specific preevaluated condition
10748: # stored in the string $env{user.state.<cid>}
10749: # or looks up a condition reference in the bighash and if if hasn't
10750: # already been evaluated recurses into docondval to get the value of
10751: # the condition, then memoizing it to
10752: # $env{user.state.<cid>.<condition>}
1.40 www 10753: sub directcondval {
10754: my $number=shift;
1.620 albertel 10755: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 10756: &Apache::lonuserstate::evalstate();
10757: }
1.713 albertel 10758: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10759: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10760: } elsif ($number =~ /^_/) {
10761: my $sub_condition;
10762: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10763: &GDBM_READER(),0640)) {
10764: $sub_condition=$bighash{'conditions'.$number};
10765: untie(%bighash);
10766: }
10767: my $value = &docondval($sub_condition);
1.949 raeburn 10768: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 10769: return $value;
10770: }
1.620 albertel 10771: if ($env{'user.state.'.$env{'request.course.id'}}) {
10772: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 10773: } else {
10774: return 2;
10775: }
10776: }
10777:
1.713 albertel 10778: # get the collection of conditions for this resource
1.26 www 10779: sub condval {
10780: my $condidx=shift;
1.54 www 10781: my $allpathcond='';
1.713 albertel 10782: foreach my $cond (split(/\|/,$condidx)) {
10783: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10784: $allpathcond.=
10785: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10786: }
1.191 harris41 10787: }
1.54 www 10788: $allpathcond=~s/\|$//;
1.713 albertel 10789: return &docondval($allpathcond);
10790: }
10791:
10792: #evaluates an expression of conditions
10793: sub docondval {
10794: my ($allpathcond) = @_;
10795: my $result=0;
10796: if ($env{'request.course.id'}
10797: && defined($allpathcond)) {
10798: my $operand='|';
10799: my @stack;
10800: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10801: if ($chunk eq '(') {
10802: push @stack,($operand,$result);
10803: } elsif ($chunk eq ')') {
10804: my $before=pop @stack;
10805: if (pop @stack eq '&') {
10806: $result=$result>$before?$before:$result;
10807: } else {
10808: $result=$result>$before?$result:$before;
10809: }
10810: } elsif (($chunk eq '&') || ($chunk eq '|')) {
10811: $operand=$chunk;
10812: } else {
10813: my $new=directcondval($chunk);
10814: if ($operand eq '&') {
10815: $result=$result>$new?$new:$result;
10816: } else {
10817: $result=$result>$new?$result:$new;
10818: }
10819: }
10820: }
1.26 www 10821: }
10822: return $result;
1.421 albertel 10823: }
10824:
10825: # ---------------------------------------------------- Devalidate courseresdata
10826:
10827: sub devalidatecourseresdata {
10828: my ($coursenum,$coursedomain)=@_;
10829: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10830: &devalidate_cache_new('courseres',$hashid);
1.28 www 10831: }
10832:
1.763 www 10833:
1.200 www 10834: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 10835: #
10836: # Parameters:
10837: # $coursenum - Number of the course.
10838: # $coursedomain - Domain at which the course was created.
10839: # Returns:
10840: # A hash of the course parameters along (I think) with timestamps
10841: # and version info.
1.877 foxr 10842:
1.624 albertel 10843: sub get_courseresdata {
10844: my ($coursenum,$coursedomain)=@_;
1.200 www 10845: my $coursehom=&homeserver($coursenum,$coursedomain);
10846: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 10847: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 10848: my %dumpreply;
1.417 albertel 10849: unless (defined($cached)) {
1.624 albertel 10850: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 10851: $result=\%dumpreply;
1.251 albertel 10852: my ($tmp) = keys(%dumpreply);
10853: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 10854: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 10855: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10856: return $tmp;
1.416 albertel 10857: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 10858: $result=undef;
1.599 albertel 10859: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 10860: }
10861: }
1.624 albertel 10862: return $result;
10863: }
10864:
1.633 albertel 10865: sub devalidateuserresdata {
10866: my ($uname,$udom)=@_;
10867: my $hashid="$udom:$uname";
10868: &devalidate_cache_new('userres',$hashid);
10869: }
10870:
1.624 albertel 10871: sub get_userresdata {
10872: my ($uname,$udom)=@_;
10873: #most student don\'t have any data set, check if there is some data
10874: if (&EXT_cache_status($udom,$uname)) { return undef; }
10875:
10876: my $hashid="$udom:$uname";
10877: my ($result,$cached)=&is_cached_new('userres',$hashid);
10878: if (!defined($cached)) {
10879: my %resourcedata=&dump('resourcedata',$udom,$uname);
10880: $result=\%resourcedata;
10881: &do_cache_new('userres',$hashid,$result,600);
10882: }
10883: my ($tmp)=keys(%$result);
10884: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10885: return $result;
10886: }
10887: #error 2 occurs when the .db doesn't exist
10888: if ($tmp!~/error: 2 /) {
1.1294 raeburn 10889: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10890: &logthis("<font color=\"blue\">WARNING:".
10891: " Trying to get resource data for ".
10892: $uname." at ".$udom.": ".
10893: $tmp."</font>");
10894: }
1.624 albertel 10895: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 10896: #&EXT_cache_set($udom,$uname);
10897: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 10898: undef($tmp); # not really an error so don't send it back
1.624 albertel 10899: }
10900: return $tmp;
10901: }
1.879 foxr 10902: #----------------------------------------------- resdata - return resource data
10903: # Purpose:
10904: # Return resource data for either users or for a course.
10905: # Parameters:
10906: # $name - Course/user name.
10907: # $domain - Name of the domain the user/course is registered on.
1.1311 raeburn 10908: # $type - Type of thing $name is (must be 'course' or 'user')
1.1301 raeburn 10909: # $mapp - decluttered URL of enclosing map
10910: # $recursed - Ref to scalar -- set to 1, if nested maps have been recursed.
10911: # $recurseup - Ref to array of map URLs, starting with map containing
10912: # $mapp up through hierarchy of nested maps to top level map.
10913: # $courseid - CourseID (first part of param identifier).
10914: # $modifier - Middle part of param identifier.
10915: # $what - Last part of param identifier.
1.879 foxr 10916: # @which - Array of names of resources desired.
10917: # Returns:
10918: # The value of the first reasource in @which that is found in the
10919: # resource hash.
10920: # Exceptional Conditions:
10921: # If the $type passed in is not valid (not the string 'course' or
10922: # 'user', an undefined reference is returned.
10923: # If none of the resources are found, an undef is returned
1.624 albertel 10924: sub resdata {
1.1301 raeburn 10925: my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
10926: $modifier,$what,@which)=@_;
1.624 albertel 10927: my $result;
10928: if ($type eq 'course') {
10929: $result=&get_courseresdata($name,$domain);
10930: } elsif ($type eq 'user') {
10931: $result=&get_userresdata($name,$domain);
10932: }
10933: if (!ref($result)) { return $result; }
1.251 albertel 10934: foreach my $item (@which) {
1.1301 raeburn 10935: if ($item->[1] eq 'course') {
10936: if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
10937: unless ($$recursed) {
1.1302 raeburn 10938: @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301 raeburn 10939: $$recursed = 1;
10940: }
10941: foreach my $item (@${recurseup}) {
10942: my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
10943: last if (defined($result->{$norecursechk}));
10944: my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
10945: if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
10946: }
10947: }
10948: }
10949: if (defined($result->{$item->[0]})) {
1.927 albertel 10950: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 10951: }
1.250 albertel 10952: }
1.291 albertel 10953: return undef;
1.200 www 10954: }
10955:
1.1298 raeburn 10956: sub get_domain_ltitools {
10957: my ($cdom) = @_;
10958: my %ltitools;
10959: my ($result,$cached)=&is_cached_new('ltitools',$cdom);
10960: if (defined($cached)) {
10961: if (ref($result) eq 'HASH') {
10962: %ltitools = %{$result};
10963: }
10964: } else {
10965: my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
10966: if (ref($domconfig{'ltitools'}) eq 'HASH') {
10967: %ltitools = %{$domconfig{'ltitools'}};
1.1344 ! raeburn 10968: my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
! 10969: if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
! 10970: foreach my $id (keys(%ltitools)) {
! 10971: if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
! 10972: foreach my $item ('key','secret') {
! 10973: $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
! 10974: }
! 10975: }
! 10976: }
! 10977: }
1.1298 raeburn 10978: }
10979: my $cachetime = 24*60*60;
10980: &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
10981: }
10982: return %ltitools;
10983: }
10984:
1.1236 raeburn 10985: sub get_numsuppfiles {
10986: my ($cnum,$cdom,$ignorecache)=@_;
10987: my $hashid=$cnum.':'.$cdom;
10988: my ($suppcount,$cached);
10989: unless ($ignorecache) {
10990: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10991: }
10992: unless (defined($cached)) {
10993: my $chome=&homeserver($cnum,$cdom);
10994: unless ($chome eq 'no_host') {
10995: ($suppcount,my $errors) = (0,0);
10996: my $suppmap = 'supplemental.sequence';
10997: ($suppcount,$errors) =
10998: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10999: }
11000: &do_cache_new('suppcount',$hashid,$suppcount,600);
11001: }
11002: return $suppcount;
11003: }
11004:
1.379 matthew 11005: #
11006: # EXT resource caching routines
11007: #
11008:
1.1302 raeburn 11009: {
11010: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11011: #
11012: # The course for which we cache
11013: my $cachedmapkey='';
11014: # The cached recursive maps for this course
11015: my %cachedmaps=();
11016: # When this was last done
11017: my $cachedmaptime='';
11018:
1.379 matthew 11019: sub clear_EXT_cache_status {
1.383 albertel 11020: &delenv('cache.EXT.');
1.379 matthew 11021: }
11022:
11023: sub EXT_cache_status {
11024: my ($target_domain,$target_user) = @_;
1.383 albertel 11025: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 11026: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 11027: # We know already the user has no data
11028: return 1;
11029: } else {
11030: return 0;
11031: }
11032: }
11033:
11034: sub EXT_cache_set {
11035: my ($target_domain,$target_user) = @_;
1.383 albertel 11036: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 11037: #&appenv({$cachename => time});
1.379 matthew 11038: }
11039:
1.28 www 11040: # --------------------------------------------------------- Value of a Variable
1.58 www 11041: sub EXT {
1.715 albertel 11042:
1.1228 raeburn 11043: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 11044: unless ($varname) { return ''; }
1.218 albertel 11045: #get real user name/domain, courseid and symb
11046: my $courseid;
1.359 albertel 11047: my $publicuser;
1.427 www 11048: if ($symbparm) {
11049: $symbparm=&get_symb_from_alias($symbparm);
11050: }
1.218 albertel 11051: if (!($uname && $udom)) {
1.790 albertel 11052: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 11053: if (!$symbparm) { $symbparm=$cursymb; }
11054: } else {
1.620 albertel 11055: $courseid=$env{'request.course.id'};
1.218 albertel 11056: }
1.48 www 11057: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11058: my $rest;
1.320 albertel 11059: if (defined($therest[0])) {
1.48 www 11060: $rest=join('.',@therest);
11061: } else {
11062: $rest='';
11063: }
1.320 albertel 11064:
1.57 www 11065: my $qualifierrest=$qualifier;
11066: if ($rest) { $qualifierrest.='.'.$rest; }
11067: my $spacequalifierrest=$space;
11068: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 11069: if ($realm eq 'user') {
1.48 www 11070: # --------------------------------------------------------------- user.resource
11071: if ($space eq 'resource') {
1.651 albertel 11072: if ( (defined($Apache::lonhomework::parsing_a_problem)
11073: || defined($Apache::lonhomework::parsing_a_task))
11074: &&
1.744 albertel 11075: ($symbparm eq &symbread()) ) {
11076: # if we are in the middle of processing the resource the
11077: # get the value we are planning on committing
11078: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11079: return $Apache::lonhomework::results{$qualifierrest};
11080: } else {
11081: return $Apache::lonhomework::history{$qualifierrest};
11082: }
1.335 albertel 11083: } else {
1.359 albertel 11084: my %restored;
1.620 albertel 11085: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 11086: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11087: } else {
11088: %restored=&restore($symbparm,$courseid,$udom,$uname);
11089: }
1.335 albertel 11090: return $restored{$qualifierrest};
11091: }
1.48 www 11092: # ----------------------------------------------------------------- user.access
11093: } elsif ($space eq 'access') {
1.218 albertel 11094: # FIXME - not supporting calls for a specific user
1.48 www 11095: return &allowed($qualifier,$rest);
11096: # ------------------------------------------ user.preferences, user.environment
11097: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 11098: if (($uname eq $env{'user.name'}) &&
11099: ($udom eq $env{'user.domain'})) {
11100: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 11101: } else {
1.359 albertel 11102: my %returnhash;
11103: if (!$publicuser) {
11104: %returnhash=&userenvironment($udom,$uname,
11105: $qualifierrest);
11106: }
1.218 albertel 11107: return $returnhash{$qualifierrest};
11108: }
1.48 www 11109: # ----------------------------------------------------------------- user.course
11110: } elsif ($space eq 'course') {
1.218 albertel 11111: # FIXME - not supporting calls for a specific user
1.620 albertel 11112: return $env{join('.',('request.course',$qualifier))};
1.48 www 11113: # ------------------------------------------------------------------- user.role
11114: } elsif ($space eq 'role') {
1.218 albertel 11115: # FIXME - not supporting calls for a specific user
1.620 albertel 11116: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 11117: if ($qualifier eq 'value') {
11118: return $role;
11119: } elsif ($qualifier eq 'extent') {
11120: return $where;
11121: }
11122: # ----------------------------------------------------------------- user.domain
11123: } elsif ($space eq 'domain') {
1.218 albertel 11124: return $udom;
1.48 www 11125: # ------------------------------------------------------------------- user.name
11126: } elsif ($space eq 'name') {
1.218 albertel 11127: return $uname;
1.48 www 11128: # ---------------------------------------------------- Any other user namespace
1.29 www 11129: } else {
1.359 albertel 11130: my %reply;
11131: if (!$publicuser) {
11132: %reply=&get($space,[$qualifierrest],$udom,$uname);
11133: }
11134: return $reply{$qualifierrest};
1.48 www 11135: }
1.236 www 11136: } elsif ($realm eq 'query') {
11137: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 11138: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11139: [$spacequalifierrest]);
1.620 albertel 11140: return $env{'form.'.$spacequalifierrest};
1.236 www 11141: } elsif ($realm eq 'request') {
1.48 www 11142: # ------------------------------------------------------------- request.browser
11143: if ($space eq 'browser') {
1.1145 bisitz 11144: return $env{'browser.'.$qualifier};
1.57 www 11145: # ------------------------------------------------------------ request.filename
11146: } else {
1.620 albertel 11147: return $env{'request.'.$spacequalifierrest};
1.29 www 11148: }
1.28 www 11149: } elsif ($realm eq 'course') {
1.48 www 11150: # ---------------------------------------------------------- course.description
1.620 albertel 11151: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 11152: } elsif ($realm eq 'resource') {
1.165 www 11153:
1.620 albertel 11154: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 11155: if (!$symbparm) { $symbparm=&symbread(); }
11156: }
1.693 albertel 11157:
1.1232 raeburn 11158: if ($qualifier eq '') {
11159: if ($space eq 'title') {
11160: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11161: return &gettitle($symbparm);
11162: }
1.693 albertel 11163:
1.1232 raeburn 11164: if ($space eq 'map') {
11165: my ($map) = &decode_symb($symbparm);
11166: return &symbread($map);
11167: }
11168: if ($space eq 'maptitle') {
11169: my ($map) = &decode_symb($symbparm);
11170: return &gettitle($map);
11171: }
11172: if ($space eq 'filename') {
11173: if ($symbparm) {
11174: return &clutter((&decode_symb($symbparm))[2]);
11175: }
11176: return &hreflocation('',$env{'request.filename'});
1.905 albertel 11177: }
1.1232 raeburn 11178:
1.1233 raeburn 11179: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11180: if ($space eq 'visibleparts') {
11181: my $navmap = Apache::lonnavmaps::navmap->new();
11182: my $item;
11183: if (ref($navmap)) {
11184: my $res = $navmap->getBySymb($symbparm);
11185: my $parts = $res->parts();
11186: if (ref($parts) eq 'ARRAY') {
11187: $item = join(',',@{$parts});
11188: }
11189: undef($navmap);
1.1232 raeburn 11190: }
1.1233 raeburn 11191: return $item;
1.1232 raeburn 11192: }
11193: }
11194: }
1.693 albertel 11195:
1.1301 raeburn 11196: my ($section, $group, @groups, @recurseup, $recursed);
11197: my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228 raeburn 11198: if (($courseid eq '') && ($cid)) {
11199: $courseid = $cid;
11200: }
11201: if (($symbparm && $courseid) &&
11202: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 11203:
1.218 albertel 11204: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 11205:
1.60 www 11206: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 11207: my $symbp=$symbparm;
1.1301 raeburn 11208: $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 11209: my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301 raeburn 11210: my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218 albertel 11211: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620 albertel 11212: if (($env{'user.name'} eq $uname) &&
11213: ($env{'user.domain'} eq $udom)) {
11214: $section=$env{'request.course.sec'};
1.733 raeburn 11215: @groups = split(/:/,$env{'request.course.groups'});
11216: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 11217: } else {
1.539 albertel 11218: if (! defined($usection)) {
1.551 albertel 11219: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 11220: } else {
11221: $section = $usection;
11222: }
1.733 raeburn 11223: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 11224: }
11225:
11226: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11227: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301 raeburn 11228: my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218 albertel 11229: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11230:
1.593 albertel 11231: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 11232: my $courselevelr=$courseid.'.'.$symbparm;
1.1301 raeburn 11233: $courseleveli=$courseid.'.'.$recurseparm;
1.593 albertel 11234: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 11235:
1.60 www 11236: # ----------------------------------------------------------- first, check user
1.624 albertel 11237:
1.1301 raeburn 11238: my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11239: \@recurseup,$courseid,'.',$spacequalifierrest,
1.927 albertel 11240: ([$courselevelr,'resource'],
11241: [$courselevelm,'map' ],
1.1301 raeburn 11242: [$courseleveli,'map' ],
1.927 albertel 11243: [$courselevel, 'course' ]));
1.931 albertel 11244: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 11245:
1.594 albertel 11246: # ------------------------------------------------ second, check some of course
1.684 raeburn 11247: my $coursereply;
1.691 raeburn 11248: if (@groups > 0) {
11249: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301 raeburn 11250: $recurseparm,$mapparm,$spacequalifierrest,
11251: $mapp,\$recursed,\@recurseup);
11252: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 11253: }
1.96 www 11254:
1.684 raeburn 11255: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 11256: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 11257: 'course',$mapp,\$recursed,\@recurseup,
11258: $courseid,'.['.$section.'].',$spacequalifierrest,
1.927 albertel 11259: ([$seclevelr, 'resource'],
11260: [$seclevelm, 'map' ],
1.1301 raeburn 11261: [$secleveli, 'map' ],
1.927 albertel 11262: [$seclevel, 'course' ],
11263: [$courselevelr,'resource']));
11264: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 11265:
1.60 www 11266: # ------------------------------------------------------ third, check map parms
1.218 albertel 11267: my %parmhash=();
11268: my $thisparm='';
11269: if (tie(%parmhash,'GDBM_File',
1.620 albertel 11270: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 11271: &GDBM_READER(),0640)) {
1.218 albertel 11272: $thisparm=$parmhash{$symbparm};
11273: untie(%parmhash);
11274: }
1.927 albertel 11275: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 11276: }
1.594 albertel 11277: # ------------------------------------------ fourth, look in resource metadata
1.1301 raeburn 11278:
11279: my $what = $spacequalifierrest;
11280: $what=~s/\./\_/;
1.282 albertel 11281: my $filename;
11282: if (!$symbparm) { $symbparm=&symbread(); }
11283: if ($symbparm) {
1.409 www 11284: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 11285: } else {
1.620 albertel 11286: $filename=$env{'request.filename'};
1.282 albertel 11287: }
1.1301 raeburn 11288: my $metadata=&metadata($filename,$what);
1.927 albertel 11289: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301 raeburn 11290: $metadata=&metadata($filename,'parameter_'.$what);
1.927 albertel 11291: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 11292:
1.1301 raeburn 11293: # ----------------------------------------------- fifth, look in rest of course
1.593 albertel 11294: if ($symbparm && defined($courseid) &&
1.620 albertel 11295: $courseid eq $env{'request.course.id'}) {
1.624 albertel 11296: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11297: $env{'course.'.$courseid.'.domain'},
1.1301 raeburn 11298: 'course',$mapp,\$recursed,\@recurseup,
11299: $courseid,'.',$spacequalifierrest,
1.927 albertel 11300: ([$courselevelm,'map' ],
1.1301 raeburn 11301: [$courseleveli,'map' ],
1.927 albertel 11302: [$courselevel, 'course']));
11303: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 11304: }
1.145 www 11305: # ------------------------------------------------------------------ Cascade up
1.218 albertel 11306: unless ($space eq '0') {
1.336 albertel 11307: my @parts=split(/_/,$space);
11308: my $id=pop(@parts);
11309: my $part=join('_',@parts);
11310: if ($part eq '') { $part='0'; }
1.927 albertel 11311: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 11312: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 11313: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 11314: }
1.395 albertel 11315: if ($recurse) { return undef; }
11316: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 11317: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 11318: # ---------------------------------------------------- Any other user namespace
11319: } elsif ($realm eq 'environment') {
11320: # ----------------------------------------------------------------- environment
1.620 albertel 11321: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11322: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 11323: } else {
1.770 albertel 11324: if ($uname eq 'anonymous' && $udom eq '') {
11325: return '';
11326: }
1.219 albertel 11327: my %returnhash=&userenvironment($udom,$uname,
11328: $spacequalifierrest);
11329: return $returnhash{$spacequalifierrest};
11330: }
1.28 www 11331: } elsif ($realm eq 'system') {
1.48 www 11332: # ----------------------------------------------------------------- system.time
11333: if ($space eq 'time') {
11334: return time;
11335: }
1.696 albertel 11336: } elsif ($realm eq 'server') {
11337: # ----------------------------------------------------------------- system.time
11338: if ($space eq 'name') {
11339: return $ENV{'SERVER_NAME'};
11340: }
1.28 www 11341: }
1.48 www 11342: return '';
1.61 www 11343: }
11344:
1.927 albertel 11345: sub get_reply {
11346: my ($reply_value) = @_;
1.940 raeburn 11347: if (ref($reply_value) eq 'ARRAY') {
11348: if (wantarray) {
11349: return @$reply_value;
11350: }
11351: return $reply_value->[0];
11352: } else {
11353: return $reply_value;
1.927 albertel 11354: }
11355: }
11356:
1.691 raeburn 11357: sub check_group_parms {
1.1301 raeburn 11358: my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11359: $recursed,$recurseupref) = @_;
11360: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11361: [$what,'course']);
11362: my $coursereply;
1.691 raeburn 11363: foreach my $group (@{$groups}) {
1.1301 raeburn 11364: my @groupitems = ();
1.691 raeburn 11365: foreach my $level (@levels) {
1.927 albertel 11366: my $item = $courseid.'.['.$group.'].'.$level->[0];
11367: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 11368: }
1.1301 raeburn 11369: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11370: $env{'course.'.$courseid.'.domain'},
11371: 'course',$mapp,$recursed,$recurseupref,
11372: $courseid,'.['.$group.'].',$what,
11373: @groupitems);
11374: last if (defined($coursereply));
1.691 raeburn 11375: }
11376: return $coursereply;
11377: }
11378:
1.1301 raeburn 11379: sub get_map_hierarchy {
1.1302 raeburn 11380: my ($mapname,$courseid) = @_;
11381: my @recurseup = ();
1.1301 raeburn 11382: if ($mapname) {
1.1302 raeburn 11383: if (($cachedmapkey eq $courseid) &&
11384: (abs($cachedmaptime-time)<5)) {
11385: if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11386: return @{$cachedmaps{$mapname}};
11387: }
11388: }
1.1301 raeburn 11389: my $navmap = Apache::lonnavmaps::navmap->new();
11390: if (ref($navmap)) {
11391: @recurseup = $navmap->recurseup_maps($mapname);
11392: undef($navmap);
1.1302 raeburn 11393: $cachedmaps{$mapname} = \@recurseup;
11394: $cachedmaptime=time;
11395: $cachedmapkey=$courseid;
1.1301 raeburn 11396: }
11397: }
11398: return @recurseup;
11399: }
11400:
1.1302 raeburn 11401: }
11402:
1.691 raeburn 11403: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 11404: my ($courseid,@groups) = @_;
11405: @groups = sort(@groups);
1.691 raeburn 11406: return @groups;
11407: }
11408:
1.395 albertel 11409: sub packages_tab_default {
11410: my ($uri,$varname)=@_;
11411: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 11412:
11413: my (@extension,@specifics,$do_default);
11414: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 11415: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 11416: if ($pack_type eq 'default') {
11417: $do_default=1;
11418: } elsif ($pack_type eq 'extension') {
11419: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 11420: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 11421: # only look at packages defaults for packages that this id is
1.738 albertel 11422: push(@specifics,[$package,$pack_type,$pack_part]);
11423: }
11424: }
11425: # first look for a package that matches the requested part id
11426: foreach my $package (@specifics) {
11427: my (undef,$pack_type,$pack_part)=@{$package};
11428: next if ($pack_part ne $part);
11429: if (defined($packagetab{"$pack_type&$name&default"})) {
11430: return $packagetab{"$pack_type&$name&default"};
11431: }
11432: }
11433: # look for any possible matching non extension_ package
11434: foreach my $package (@specifics) {
11435: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 11436: if (defined($packagetab{"$pack_type&$name&default"})) {
11437: return $packagetab{"$pack_type&$name&default"};
11438: }
1.585 albertel 11439: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 11440: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11441: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 11442: }
11443: }
1.738 albertel 11444: # look for any posible extension_ match
11445: foreach my $package (@extension) {
11446: my ($package,$pack_type)=@{$package};
11447: if (defined($packagetab{"$pack_type&$name&default"})) {
11448: return $packagetab{"$pack_type&$name&default"};
11449: }
11450: if (defined($packagetab{$package."&$name&default"})) {
11451: return $packagetab{$package."&$name&default"};
11452: }
11453: }
11454: # look for a global default setting
11455: if ($do_default && defined($packagetab{"default&$name&default"})) {
11456: return $packagetab{"default&$name&default"};
11457: }
1.395 albertel 11458: return undef;
11459: }
11460:
1.334 albertel 11461: sub add_prefix_and_part {
11462: my ($prefix,$part)=@_;
11463: my $keyroot;
11464: if (defined($prefix) && $prefix !~ /^__/) {
11465: # prefix that has a part already
11466: $keyroot=$prefix;
11467: } elsif (defined($prefix)) {
11468: # prefix that is missing a part
11469: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11470: } else {
11471: # no prefix at all
11472: if (defined($part)) { $keyroot='_'.$part; }
11473: }
11474: return $keyroot;
11475: }
11476:
1.71 www 11477: # ---------------------------------------------------------------- Get metadata
11478:
1.599 albertel 11479: my %metaentry;
1.1070 www 11480: my %importedpartids;
1.71 www 11481: sub metadata {
1.176 www 11482: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 11483: $uri=&declutter($uri);
1.288 albertel 11484: # if it is a non metadata possible uri return quickly
1.529 albertel 11485: if (($uri eq '') ||
11486: (($uri =~ m|^/*adm/|) &&
1.1343 raeburn 11487: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108 raeburn 11488: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 11489: return undef;
11490: }
1.1261 raeburn 11491: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
1.924 albertel 11492: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 11493: return undef;
1.288 albertel 11494: }
1.73 www 11495: my $filename=$uri;
11496: $uri=~s/\.meta$//;
1.172 www 11497: #
11498: # Is the metadata already cached?
1.177 www 11499: # Look at timestamp of caching
1.172 www 11500: # Everything is cached by the main uri, libraries are never directly cached
11501: #
1.428 albertel 11502: if (!defined($liburi)) {
1.599 albertel 11503: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 11504: if (defined($cached)) { return $result->{':'.$what}; }
11505: }
11506: {
1.1069 www 11507: # Imported parts would go here
1.1070 www 11508: my %importedids=();
11509: my @origfileimportpartids=();
1.1069 www 11510: my $importedparts=0;
1.172 www 11511: #
11512: # Is this a recursive call for a library?
11513: #
1.599 albertel 11514: # if (! exists($metacache{$uri})) {
11515: # $metacache{$uri}={};
11516: # }
1.924 albertel 11517: my $cachetime = 60*60;
1.171 www 11518: if ($liburi) {
11519: $liburi=&declutter($liburi);
11520: $filename=$liburi;
1.401 bowersj2 11521: } else {
1.599 albertel 11522: &devalidate_cache_new('meta',$uri);
11523: undef(%metaentry);
1.401 bowersj2 11524: }
1.140 www 11525: my %metathesekeys=();
1.73 www 11526: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 11527: my $metastring;
1.1140 www 11528: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 11529: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 11530: $metastring =
1.929 albertel 11531: &Apache::lonnet::ssi_body($which,
1.924 albertel 11532: ('grade_target' => 'meta'));
11533: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 11534: } elsif (($uri !~ m -^(editupload)/-) &&
11535: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 11536: my $file=&filelocation('',&clutter($filename));
1.599 albertel 11537: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 11538: $metastring=&getfile($file);
1.489 albertel 11539: }
1.208 albertel 11540: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 11541: my $token;
1.140 www 11542: undef %metathesekeys;
1.71 www 11543: while ($token=$parser->get_token) {
1.339 albertel 11544: if ($token->[0] eq 'S') {
11545: if (defined($token->[2]->{'package'})) {
1.172 www 11546: #
11547: # This is a package - get package info
11548: #
1.339 albertel 11549: my $package=$token->[2]->{'package'};
11550: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11551: if (defined($token->[2]->{'id'})) {
11552: $keyroot.='_'.$token->[2]->{'id'};
11553: }
1.599 albertel 11554: if ($metaentry{':packages'}) {
11555: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 11556: } else {
1.599 albertel 11557: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 11558: }
1.736 albertel 11559: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 11560: my $part=$keyroot;
11561: $part=~s/^\_//;
1.736 albertel 11562: if ($pack_entry=~/^\Q$package\E\&/ ||
11563: $pack_entry=~/^\Q$package\E_0\&/) {
11564: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 11565: # ignore package.tab specified default values
11566: # here &package_tab_default() will fetch those
11567: if ($subp eq 'default') { next; }
1.736 albertel 11568: my $value=$packagetab{$pack_entry};
1.432 albertel 11569: my $unikey;
11570: if ($pack =~ /_0$/) {
11571: $unikey='parameter_0_'.$name;
11572: $part=0;
11573: } else {
11574: $unikey='parameter'.$keyroot.'_'.$name;
11575: }
1.339 albertel 11576: if ($subp eq 'display') {
11577: $value.=' [Part: '.$part.']';
11578: }
1.599 albertel 11579: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 11580: $metathesekeys{$unikey}=1;
1.599 albertel 11581: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11582: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 11583: }
1.599 albertel 11584: if (defined($metaentry{':'.$unikey.'.default'})) {
11585: $metaentry{':'.$unikey}=
11586: $metaentry{':'.$unikey.'.default'};
1.356 albertel 11587: }
1.339 albertel 11588: }
11589: }
11590: } else {
1.172 www 11591: #
11592: # This is not a package - some other kind of start tag
1.339 albertel 11593: #
11594: my $entry=$token->[1];
1.1068 www 11595: my $unikey='';
1.175 www 11596:
1.339 albertel 11597: if ($entry eq 'import') {
1.175 www 11598: #
11599: # Importing a library here
1.339 albertel 11600: #
1.1067 www 11601: my $location=$parser->get_text('/import');
11602: my $dir=$filename;
11603: $dir=~s|[^/]*$||;
11604: $location=&filelocation($dir,$location);
1.1069 www 11605:
1.1068 www 11606: my $importmode=$token->[2]->{'importmode'};
11607: if ($importmode eq 'problem') {
1.1069 www 11608: # Import as problem/response
1.1068 www 11609: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11610: } elsif ($importmode eq 'part') {
11611: # Import as part(s)
1.1069 www 11612: $importedparts=1;
11613: # We need to get the original file and the imported file to get the part order correct
11614: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11615: # Load and inspect original file
1.1070 www 11616: if ($#origfileimportpartids<0) {
11617: undef(%importedpartids);
11618: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11619: my $origfile=&getfile($origfilelocation);
11620: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11621: }
11622:
1.1069 www 11623: # Load and inspect imported file
11624: my $impfile=&getfile($location);
11625: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11626: if ($#impfilepartids>=0) {
11627: # This problem had parts
1.1070 www 11628: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 11629: } else {
11630: # Importing by turning a single problem into a problem part
11631: # It gets the import-tags ID as part-ID
11632: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 11633: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 11634: }
1.1068 www 11635: } else {
11636: # Normal import
11637: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11638: if (defined($token->[2]->{'id'})) {
11639: $unikey.='_'.$token->[2]->{'id'};
11640: }
1.1067 www 11641: }
11642:
1.339 albertel 11643: if ($depthcount<20) {
1.736 albertel 11644: my $metadata =
11645: &metadata($uri,'keys', $location,$unikey,
11646: $depthcount+1);
11647: foreach my $meta (split(',',$metadata)) {
11648: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11649: $metathesekeys{$meta}=1;
1.339 albertel 11650: }
1.1068 www 11651:
11652: }
1.1067 www 11653: } else {
11654: #
11655: # Not importing, some other kind of non-package, non-library start tag
11656: #
11657: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11658: if (defined($token->[2]->{'id'})) {
11659: $unikey.='_'.$token->[2]->{'id'};
11660: }
1.339 albertel 11661: if (defined($token->[2]->{'name'})) {
11662: $unikey.='_'.$token->[2]->{'name'};
11663: }
11664: $metathesekeys{$unikey}=1;
1.736 albertel 11665: foreach my $param (@{$token->[3]}) {
11666: $metaentry{':'.$unikey.'.'.$param} =
11667: $token->[2]->{$param};
1.339 albertel 11668: }
11669: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 11670: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 11671: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11672: # only ws inside the tag, and not in default, so use default
11673: # as value
1.599 albertel 11674: $metaentry{':'.$unikey}=$default;
1.908 albertel 11675: } elsif ( $internaltext =~ /\S/ ) {
11676: # something interesting inside the tag
11677: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 11678: } else {
1.908 albertel 11679: # no interesting values, don't set a default
1.339 albertel 11680: }
1.172 www 11681: # end of not-a-package not-a-library import
1.339 albertel 11682: }
1.172 www 11683: # end of not-a-package start tag
1.339 albertel 11684: }
1.172 www 11685: # the next is the end of "start tag"
1.339 albertel 11686: }
11687: }
1.483 albertel 11688: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 11689: $extension = lc($extension);
11690: if ($extension eq 'htm') { $extension='html'; }
11691:
1.737 albertel 11692: foreach my $key (keys(%packagetab)) {
1.483 albertel 11693: #no specific packages #how's our extension
11694: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 11695: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 11696: \%metathesekeys);
11697: }
1.883 albertel 11698:
11699: if (!exists($metaentry{':packages'})
11700: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 11701: foreach my $key (keys(%packagetab)) {
1.483 albertel 11702: #no specific packages well let's get default then
11703: if ($key!~/^default&/) { next; }
1.488 albertel 11704: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 11705: \%metathesekeys);
11706: }
11707: }
1.338 www 11708: # are there custom rights to evaluate
1.599 albertel 11709: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 11710:
1.338 www 11711: #
11712: # Importing a rights file here
1.339 albertel 11713: #
11714: unless ($depthcount) {
1.599 albertel 11715: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 11716: my $dir=$filename;
11717: $dir=~s|[^/]*$||;
11718: $location=&filelocation($dir,$location);
1.736 albertel 11719: my $rights_metadata =
11720: &metadata($uri,'keys',$location,'_rights',
11721: $depthcount+1);
11722: foreach my $rights (split(',',$rights_metadata)) {
11723: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11724: $metathesekeys{$rights}=1;
1.339 albertel 11725: }
11726: }
11727: }
1.737 albertel 11728: # uniqifiy package listing
11729: my %seen;
11730: my @uniq_packages =
11731: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11732: $metaentry{':packages'} = join(',',@uniq_packages);
11733:
1.1070 www 11734: if ($importedparts) {
11735: # We had imported parts and need to rebuild partorder
11736: $metaentry{':partorder'}='';
11737: $metathesekeys{'partorder'}=1;
11738: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11739: if ($origfileimportpartids[$index] eq 'part') {
11740: # original part, part of the problem
11741: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11742: } else {
11743: # we have imported parts at this position
11744: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11745: }
11746: }
11747: $metaentry{':partorder'}=~s/^\,//;
11748: }
11749:
1.737 albertel 11750: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 11751: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274 raeburn 11752: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924 albertel 11753: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 11754: # this is the end of "was not already recently cached
1.71 www 11755: }
1.599 albertel 11756: return $metaentry{':'.$what};
1.261 albertel 11757: }
11758:
1.488 albertel 11759: sub metadata_create_package_def {
1.483 albertel 11760: my ($uri,$key,$package,$metathesekeys)=@_;
11761: my ($pack,$name,$subp)=split(/\&/,$key);
11762: if ($subp eq 'default') { next; }
11763:
1.599 albertel 11764: if (defined($metaentry{':packages'})) {
11765: $metaentry{':packages'}.=','.$package;
1.483 albertel 11766: } else {
1.599 albertel 11767: $metaentry{':packages'}=$package;
1.483 albertel 11768: }
11769: my $value=$packagetab{$key};
11770: my $unikey;
11771: $unikey='parameter_0_'.$name;
1.599 albertel 11772: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 11773: $$metathesekeys{$unikey}=1;
1.599 albertel 11774: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11775: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 11776: }
1.599 albertel 11777: if (defined($metaentry{':'.$unikey.'.default'})) {
11778: $metaentry{':'.$unikey}=
11779: $metaentry{':'.$unikey.'.default'};
1.483 albertel 11780: }
11781: }
11782:
1.261 albertel 11783: sub metadata_generate_part0 {
11784: my ($metadata,$metacache,$uri) = @_;
11785: my %allnames;
1.737 albertel 11786: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 11787: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 11788: my $part=$$metacache{':'.$metakey.'.part'};
11789: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 11790: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 11791: $allnames{$name}=$part;
11792: }
11793: }
11794: }
11795: foreach my $name (keys(%allnames)) {
11796: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 11797: my $key=":parameter_0_$name";
1.261 albertel 11798: $$metacache{"$key.part"}='0';
11799: $$metacache{"$key.name"}=$name;
1.428 albertel 11800: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 11801: $allnames{$name}.'_'.$name.
11802: '.type'};
1.428 albertel 11803: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 11804: '.display'};
1.644 www 11805: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 11806: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 11807: $$metacache{"$key.display"}=$olddis;
11808: }
1.71 www 11809: }
11810:
1.764 albertel 11811: # ------------------------------------------------------ Devalidate title cache
11812:
11813: sub devalidate_title_cache {
11814: my ($url)=@_;
11815: if (!$env{'request.course.id'}) { return; }
11816: my $symb=&symbread($url);
11817: if (!$symb) { return; }
11818: my $key=$env{'request.course.id'}."\0".$symb;
11819: &devalidate_cache_new('title',$key);
11820: }
11821:
1.1014 droeschl 11822: # ------------------------------------------------- Get the title of a course
11823:
11824: sub current_course_title {
11825: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11826: }
1.301 www 11827: # ------------------------------------------------- Get the title of a resource
11828:
11829: sub gettitle {
11830: my $urlsymb=shift;
11831: my $symb=&symbread($urlsymb);
1.534 albertel 11832: if ($symb) {
1.620 albertel 11833: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 11834: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 11835: if (defined($cached)) {
11836: return $result;
11837: }
1.534 albertel 11838: my ($map,$resid,$url)=&decode_symb($symb);
11839: my $title='';
1.907 albertel 11840: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11841: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11842: } else {
11843: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11844: &GDBM_READER(),0640)) {
11845: my $mapid=$bighash{'map_pc_'.&clutter($map)};
11846: $title=$bighash{'title_'.$mapid.'.'.$resid};
11847: untie(%bighash);
11848: }
1.534 albertel 11849: }
11850: $title=~s/\&colon\;/\:/gs;
11851: if ($title) {
1.1159 www 11852: # Remember both $symb and $title for dynamic metadata
11853: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 11854: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 11855: # Cache this title and then return it
1.599 albertel 11856: return &do_cache_new('title',$key,$title,600);
1.534 albertel 11857: }
11858: $urlsymb=$url;
11859: }
11860: my $title=&metadata($urlsymb,'title');
11861: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
11862: return $title;
1.301 www 11863: }
1.613 albertel 11864:
1.614 albertel 11865: sub get_slot {
11866: my ($which,$cnum,$cdom)=@_;
11867: if (!$cnum || !$cdom) {
1.790 albertel 11868: (undef,my $courseid)=&whichuser();
1.620 albertel 11869: $cdom=$env{'course.'.$courseid.'.domain'};
11870: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 11871: }
1.703 albertel 11872: my $key=join("\0",'slots',$cdom,$cnum,$which);
11873: my %slotinfo;
11874: if (exists($remembered{$key})) {
11875: $slotinfo{$which} = $remembered{$key};
11876: } else {
11877: %slotinfo=&get('slots',[$which],$cdom,$cnum);
11878: &Apache::lonhomework::showhash(%slotinfo);
11879: my ($tmp)=keys(%slotinfo);
11880: if ($tmp=~/^error:/) { return (); }
11881: $remembered{$key} = $slotinfo{$which};
11882: }
1.616 albertel 11883: if (ref($slotinfo{$which}) eq 'HASH') {
11884: return %{$slotinfo{$which}};
11885: }
11886: return $slotinfo{$which};
1.614 albertel 11887: }
1.1150 raeburn 11888:
11889: sub get_reservable_slots {
11890: my ($cnum,$cdom,$uname,$udom) = @_;
11891: my $now = time;
11892: my $reservable_info;
11893: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11894: if (exists($remembered{$key})) {
11895: $reservable_info = $remembered{$key};
11896: } else {
11897: my %resv;
11898: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11899: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11900: $reservable_info = \%resv;
11901: $remembered{$key} = $reservable_info;
11902: }
11903: return $reservable_info;
11904: }
11905:
11906: sub get_course_slots {
11907: my ($cnum,$cdom) = @_;
11908: my $hashid=$cnum.':'.$cdom;
11909: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11910: if (defined($cached)) {
11911: if (ref($result) eq 'HASH') {
11912: return %{$result};
11913: }
11914: } else {
11915: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11916: my ($tmp) = keys(%slots);
11917: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 11918: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 11919: return %slots;
11920: }
11921: }
11922: return;
11923: }
11924:
11925: sub devalidate_slots_cache {
11926: my ($cnum,$cdom)=@_;
11927: my $hashid=$cnum.':'.$cdom;
11928: &devalidate_cache_new('allslots',$hashid);
11929: }
11930:
1.1181 raeburn 11931: sub get_coursechange {
11932: my ($cdom,$cnum) = @_;
11933: if ($cdom eq '' || $cnum eq '') {
11934: return unless ($env{'request.course.id'});
11935: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11936: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11937: }
11938: my $hashid=$cdom.'_'.$cnum;
11939: my ($change,$cached)=&is_cached_new('crschange',$hashid);
11940: if ((defined($cached)) && ($change ne '')) {
11941: return $change;
11942: } else {
11943: my %crshash;
11944: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11945: if ($crshash{'internal.contentchange'} eq '') {
11946: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11947: if ($change eq '') {
11948: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11949: $change = $crshash{'internal.created'};
11950: }
11951: } else {
11952: $change = $crshash{'internal.contentchange'};
11953: }
11954: my $cachetime = 600;
11955: &do_cache_new('crschange',$hashid,$change,$cachetime);
11956: }
11957: return $change;
11958: }
11959:
11960: sub devalidate_coursechange_cache {
11961: my ($cnum,$cdom)=@_;
11962: my $hashid=$cnum.':'.$cdom;
11963: &devalidate_cache_new('crschange',$hashid);
11964: }
11965:
1.31 www 11966: # ------------------------------------------------- Update symbolic store links
11967:
11968: sub symblist {
11969: my ($mapname,%newhash)=@_;
1.438 www 11970: $mapname=&deversion(&declutter($mapname));
1.31 www 11971: my %hash;
1.620 albertel 11972: if (($env{'request.course.fn'}) && (%newhash)) {
11973: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 11974: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 11975: foreach my $url (keys(%newhash)) {
1.711 albertel 11976: next if ($url eq 'last_known'
11977: && $env{'form.no_update_last_known'});
11978: $hash{declutter($url)}=&encode_symb($mapname,
11979: $newhash{$url}->[1],
11980: $newhash{$url}->[0]);
1.191 harris41 11981: }
1.31 www 11982: if (untie(%hash)) {
11983: return 'ok';
11984: }
11985: }
11986: }
11987: return 'error';
1.212 www 11988: }
11989:
11990: # --------------------------------------------------------------- Verify a symb
11991:
11992: sub symbverify {
1.1190 raeburn 11993: my ($symb,$thisurl,$encstate)=@_;
1.510 www 11994: my $thisfn=$thisurl;
1.439 www 11995: $thisfn=&declutter($thisfn);
1.215 www 11996: # direct jump to resource in page or to a sequence - will construct own symbs
11997: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11998: # check URL part
1.409 www 11999: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 12000:
1.431 www 12001: unless ($url eq $thisfn) { return 0; }
1.213 www 12002:
1.216 www 12003: $symb=&symbclean($symb);
1.510 www 12004: $thisurl=&deversion($thisurl);
1.439 www 12005: $thisfn=&deversion($thisfn);
1.213 www 12006:
12007: my %bighash;
12008: my $okay=0;
1.431 www 12009:
1.620 albertel 12010: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12011: &GDBM_READER(),0640)) {
1.1204 raeburn 12012: my $noclutter;
1.1032 raeburn 12013: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12014: $thisurl =~ s/\?.+$//;
1.1204 raeburn 12015: if ($map =~ m{^uploaded/.+\.page$}) {
12016: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12017: $thisurl =~ s{^\Qhttp://https://\E}{https://};
12018: $noclutter = 1;
12019: }
12020: }
12021: my $ids;
12022: if ($noclutter) {
12023: $ids=$bighash{'ids_'.$thisurl};
12024: } else {
12025: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 12026: }
1.1102 raeburn 12027: unless ($ids) {
12028: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
12029: $ids=$bighash{$idkey};
1.216 www 12030: }
12031: if ($ids) {
12032: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 12033: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 12034: $symb =~ s/\?.+$//;
1.1202 raeburn 12035: }
1.800 albertel 12036: foreach my $id (split(/\,/,$ids)) {
12037: my ($mapid,$resid)=split(/\./,$id);
1.216 www 12038: if (
12039: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 12040: eq $symb) {
12041: if (ref($encstate)) {
12042: $$encstate = $bighash{'encrypted_'.$id};
12043: }
1.620 albertel 12044: if (($env{'request.role.adv'}) ||
1.1101 raeburn 12045: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12046: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 12047: $okay=1;
1.1202 raeburn 12048: last;
1.582 albertel 12049: }
12050: }
1.216 www 12051: }
12052: }
1.213 www 12053: untie(%bighash);
12054: }
12055: return $okay;
1.31 www 12056: }
12057:
1.210 www 12058: # --------------------------------------------------------------- Clean-up symb
12059:
12060: sub symbclean {
12061: my $symb=shift;
1.568 albertel 12062: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 12063: # remove version from map
12064: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 12065:
1.210 www 12066: # remove version from URL
12067: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 12068:
1.507 www 12069: # remove wrapper
12070:
1.510 www 12071: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 12072: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 12073: return $symb;
1.409 www 12074: }
12075:
12076: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 12077:
12078: sub encode_symb {
12079: my ($map,$resid,$url)=@_;
12080: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12081: }
1.409 www 12082:
12083: sub decode_symb {
1.568 albertel 12084: my $symb=shift;
12085: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12086: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 12087: return (&fixversion($map),$resid,&fixversion($url));
12088: }
12089:
12090: sub fixversion {
12091: my $fn=shift;
1.609 banghart 12092: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 12093: my %bighash;
12094: my $uri=&clutter($fn);
1.620 albertel 12095: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 12096: # is this cached?
1.599 albertel 12097: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 12098: if (defined($cached)) { return $result; }
12099: # unfortunately not cached, or expired
1.620 albertel 12100: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 12101: &GDBM_READER(),0640)) {
12102: if ($bighash{'version_'.$uri}) {
12103: my $version=$bighash{'version_'.$uri};
1.444 www 12104: unless (($version eq 'mostrecent') ||
12105: ($version==&getversion($uri))) {
1.440 www 12106: $uri=~s/\.(\w+)$/\.$version\.$1/;
12107: }
12108: }
12109: untie %bighash;
1.413 www 12110: }
1.599 albertel 12111: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 12112: }
12113:
12114: sub deversion {
12115: my $url=shift;
12116: $url=~s/\.\d+\.(\w+)$/\.$1/;
12117: return $url;
1.210 www 12118: }
12119:
1.31 www 12120: # ------------------------------------------------------ Return symb list entry
12121:
12122: sub symbread {
1.1282 raeburn 12123: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265 raeburn 12124: my $cache_str='request.symbread.cached.'.$thisfn;
1.1282 raeburn 12125: if (defined($env{$cache_str})) {
12126: if ($ignorecachednull) {
12127: return $env{$cache_str} unless ($env{$cache_str} eq '');
12128: } else {
12129: return $env{$cache_str};
12130: }
12131: }
1.242 www 12132: # no filename provided? try from environment
1.1265 raeburn 12133: unless ($thisfn) {
1.620 albertel 12134: if ($env{'request.symb'}) {
12135: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 12136: }
1.620 albertel 12137: $thisfn=$env{'request.filename'};
1.44 www 12138: }
1.569 albertel 12139: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 12140: # is that filename actually a symb? Verify, clean, and return
12141: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 12142: if (&symbverify($thisfn,$1)) {
1.620 albertel 12143: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 12144: }
1.242 www 12145: }
1.44 www 12146: $thisfn=declutter($thisfn);
1.31 www 12147: my %hash;
1.37 www 12148: my %bighash;
12149: my $syval='';
1.620 albertel 12150: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 12151: my $targetfn = $thisfn;
1.609 banghart 12152: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 12153: $targetfn = 'adm/wrapper/'.$thisfn;
12154: }
1.687 albertel 12155: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12156: $targetfn=$1;
12157: }
1.620 albertel 12158: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 12159: &GDBM_READER(),0640)) {
1.481 raeburn 12160: $syval=$hash{$targetfn};
1.37 www 12161: untie(%hash);
12162: }
12163: # ---------------------------------------------------------- There was an entry
12164: if ($syval) {
1.601 albertel 12165: #unless ($syval=~/\_\d+$/) {
1.620 albertel 12166: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 12167: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12168: #return $env{$cache_str}='';
1.601 albertel 12169: #}
12170: #$syval.=$1;
12171: #}
1.37 www 12172: } else {
12173: # ------------------------------------------------------- Was not in symb table
1.620 albertel 12174: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 12175: &GDBM_READER(),0640)) {
1.37 www 12176: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 12177: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 12178: unless ($ids) {
12179: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 12180: }
12181: unless ($ids) {
12182: # alias?
12183: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 12184: }
1.37 www 12185: if ($ids) {
12186: # ------------------------------------------------------------------- Has ID(s)
12187: my @possibilities=split(/\,/,$ids);
1.39 www 12188: if ($#possibilities==0) {
12189: # ----------------------------------------------- There is only one possibility
1.37 www 12190: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 12191: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12192: $resid,$thisfn);
1.1282 raeburn 12193: if (ref($possibles) eq 'HASH') {
12194: $possibles->{$syval} = 1;
12195: }
12196: if ($checkforblock) {
12197: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12198: if (@blockers) {
12199: $syval = '';
12200: return;
12201: }
12202: }
12203: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39 www 12204: # ------------------------------------------ There is more than one possibility
12205: my $realpossible=0;
1.800 albertel 12206: foreach my $id (@possibilities) {
12207: my $file=$bighash{'src_'.$id};
1.1282 raeburn 12208: my $canaccess;
12209: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12210: $canaccess = 1;
12211: } else {
12212: $canaccess = &allowed('bre',$file);
12213: }
12214: if ($canaccess) {
12215: my ($mapid,$resid)=split(/\./,$id);
12216: if ($bighash{'map_type_'.$mapid} ne 'page') {
12217: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12218: $resid,$thisfn);
12219: if (ref($possibles) eq 'HASH') {
12220: $possibles->{$syval} = 1;
12221: }
12222: if ($checkforblock) {
12223: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12224: unless (@blockers > 0) {
12225: $syval = $poss_syval;
12226: $realpossible++;
12227: }
12228: } else {
12229: $syval = $poss_syval;
12230: $realpossible++;
12231: }
12232: }
1.39 www 12233: }
1.191 harris41 12234: }
1.39 www 12235: if ($realpossible!=1) { $syval=''; }
1.249 www 12236: } else {
12237: $syval='';
1.37 www 12238: }
12239: }
1.1282 raeburn 12240: untie(%bighash);
1.481 raeburn 12241: }
1.31 www 12242: }
1.62 www 12243: if ($syval) {
1.620 albertel 12244: return $env{$cache_str}=$syval;
1.62 www 12245: }
1.31 www 12246: }
1.949 raeburn 12247: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 12248: return $env{$cache_str}='';
1.31 www 12249: }
12250:
12251: # ---------------------------------------------------------- Return random seed
12252:
1.32 www 12253: sub numval {
12254: my $txt=shift;
12255: $txt=~tr/A-J/0-9/;
12256: $txt=~tr/a-j/0-9/;
12257: $txt=~tr/K-T/0-9/;
12258: $txt=~tr/k-t/0-9/;
12259: $txt=~tr/U-Z/0-5/;
12260: $txt=~tr/u-z/0-5/;
12261: $txt=~s/\D//g;
1.564 albertel 12262: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 12263: return int($txt);
1.368 albertel 12264: }
12265:
1.484 albertel 12266: sub numval2 {
12267: my $txt=shift;
12268: $txt=~tr/A-J/0-9/;
12269: $txt=~tr/a-j/0-9/;
12270: $txt=~tr/K-T/0-9/;
12271: $txt=~tr/k-t/0-9/;
12272: $txt=~tr/U-Z/0-5/;
12273: $txt=~tr/u-z/0-5/;
12274: $txt=~s/\D//g;
12275: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12276: my $total;
12277: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 12278: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 12279: return int($total);
12280: }
12281:
1.575 albertel 12282: sub numval3 {
12283: use integer;
12284: my $txt=shift;
12285: $txt=~tr/A-J/0-9/;
12286: $txt=~tr/a-j/0-9/;
12287: $txt=~tr/K-T/0-9/;
12288: $txt=~tr/k-t/0-9/;
12289: $txt=~tr/U-Z/0-5/;
12290: $txt=~tr/u-z/0-5/;
12291: $txt=~s/\D//g;
12292: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12293: my $total;
12294: foreach my $val (@txts) { $total+=$val; }
12295: if ($_64bit) { $total=(($total<<32)>>32); }
12296: return $total;
12297: }
12298:
1.675 albertel 12299: sub digest {
12300: my ($data)=@_;
12301: my $digest=&Digest::MD5::md5($data);
12302: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12303: my ($e,$f);
12304: {
12305: use integer;
12306: $e=($a+$b);
12307: $f=($c+$d);
12308: if ($_64bit) {
12309: $e=(($e<<32)>>32);
12310: $f=(($f<<32)>>32);
12311: }
12312: }
12313: if (wantarray) {
12314: return ($e,$f);
12315: } else {
12316: my $g;
12317: {
12318: use integer;
12319: $g=($e+$f);
12320: if ($_64bit) {
12321: $g=(($g<<32)>>32);
12322: }
12323: }
12324: return $g;
12325: }
12326: }
12327:
1.368 albertel 12328: sub latest_rnd_algorithm_id {
1.675 albertel 12329: return '64bit5';
1.366 albertel 12330: }
1.32 www 12331:
1.503 albertel 12332: sub get_rand_alg {
12333: my ($courseid)=@_;
1.790 albertel 12334: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 12335: if ($courseid) {
1.620 albertel 12336: return $env{"course.$courseid.rndseed"};
1.503 albertel 12337: }
12338: return &latest_rnd_algorithm_id();
12339: }
12340:
1.562 albertel 12341: sub validCODE {
12342: my ($CODE)=@_;
12343: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12344: return 0;
12345: }
12346:
1.491 albertel 12347: sub getCODE {
1.620 albertel 12348: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 12349: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12350: defined($Apache::lonhomework::parsing_a_task) ) &&
12351: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 12352: return $Apache::lonhomework::history{'resource.CODE'};
12353: }
12354: return undef;
12355: }
1.1133 foxr 12356: #
12357: # Determines the random seed for a specific context:
12358: #
12359: # parameters:
12360: # symb - in course context the symb for the seed.
12361: # course_id - The course id of the form domain_coursenum.
12362: # domain - Domain for the user.
12363: # course - Course for the user.
12364: # cenv - environment of the course.
12365: #
12366: # NOTE:
12367: # All parameters are picked out of the environment if missing
12368: # or not defined.
12369: # If a symb cannot be determined the current time is used instead.
12370: #
12371: # For a given well defined symb, courside, domain, username,
12372: # and course environment, the seed is reproducible.
12373: #
1.31 www 12374: sub rndseed {
1.1133 foxr 12375: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 12376: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 12377: if (!defined($symb)) {
1.366 albertel 12378: unless ($symb=$wsymb) { return time; }
12379: }
1.1146 foxr 12380: if (!defined $courseid) {
12381: $courseid=$wcourseid;
12382: }
12383: if (!defined $domain) { $domain=$wdomain; }
12384: if (!defined $username) { $username=$wusername }
1.1133 foxr 12385:
12386: my $which;
12387: if (defined($cenv->{'rndseed'})) {
12388: $which = $cenv->{'rndseed'};
12389: } else {
12390: $which =&get_rand_alg($courseid);
12391: }
1.491 albertel 12392: if (defined(&getCODE())) {
1.1133 foxr 12393:
1.675 albertel 12394: if ($which eq '64bit5') {
12395: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12396: } elsif ($which eq '64bit4') {
1.575 albertel 12397: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12398: } else {
12399: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12400: }
1.675 albertel 12401: } elsif ($which eq '64bit5') {
12402: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 12403: } elsif ($which eq '64bit4') {
12404: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 12405: } elsif ($which eq '64bit3') {
12406: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 12407: } elsif ($which eq '64bit2') {
12408: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 12409: } elsif ($which eq '64bit') {
12410: return &rndseed_64bit($symb,$courseid,$domain,$username);
12411: }
12412: return &rndseed_32bit($symb,$courseid,$domain,$username);
12413: }
12414:
12415: sub rndseed_32bit {
12416: my ($symb,$courseid,$domain,$username)=@_;
12417: {
12418: use integer;
12419: my $symbchck=unpack("%32C*",$symb) << 27;
12420: my $symbseed=numval($symb) << 22;
12421: my $namechck=unpack("%32C*",$username) << 17;
12422: my $nameseed=numval($username) << 12;
12423: my $domainseed=unpack("%32C*",$domain) << 7;
12424: my $courseseed=unpack("%32C*",$courseid);
12425: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 12426: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12427: #&logthis("rndseed :$num:$symb");
1.564 albertel 12428: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 12429: return $num;
12430: }
12431: }
12432:
12433: sub rndseed_64bit {
12434: my ($symb,$courseid,$domain,$username)=@_;
12435: {
12436: use integer;
12437: my $symbchck=unpack("%32S*",$symb) << 21;
12438: my $symbseed=numval($symb) << 10;
12439: my $namechck=unpack("%32S*",$username);
12440:
12441: my $nameseed=numval($username) << 21;
12442: my $domainseed=unpack("%32S*",$domain) << 10;
12443: my $courseseed=unpack("%32S*",$courseid);
12444:
12445: my $num1=$symbchck+$symbseed+$namechck;
12446: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12447: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12448: #&logthis("rndseed :$num:$symb");
1.564 albertel 12449: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 12450: return "$num1,$num2";
1.155 albertel 12451: }
1.366 albertel 12452: }
12453:
1.443 albertel 12454: sub rndseed_64bit2 {
12455: my ($symb,$courseid,$domain,$username)=@_;
12456: {
12457: use integer;
12458: # strings need to be an even # of cahracters long, it it is odd the
12459: # last characters gets thrown away
12460: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12461: my $symbseed=numval($symb) << 10;
12462: my $namechck=unpack("%32S*",$username.' ');
12463:
12464: my $nameseed=numval($username) << 21;
1.501 albertel 12465: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12466: my $courseseed=unpack("%32S*",$courseid.' ');
12467:
12468: my $num1=$symbchck+$symbseed+$namechck;
12469: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12470: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12471: #&logthis("rndseed :$num:$symb");
1.803 albertel 12472: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 12473: return "$num1,$num2";
12474: }
12475: }
12476:
12477: sub rndseed_64bit3 {
12478: my ($symb,$courseid,$domain,$username)=@_;
12479: {
12480: use integer;
12481: # strings need to be an even # of cahracters long, it it is odd the
12482: # last characters gets thrown away
12483: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12484: my $symbseed=numval2($symb) << 10;
12485: my $namechck=unpack("%32S*",$username.' ');
12486:
12487: my $nameseed=numval2($username) << 21;
1.443 albertel 12488: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12489: my $courseseed=unpack("%32S*",$courseid.' ');
12490:
12491: my $num1=$symbchck+$symbseed+$namechck;
12492: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12493: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12494: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 12495: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12496:
1.503 albertel 12497: return "$num1:$num2";
1.443 albertel 12498: }
12499: }
12500:
1.575 albertel 12501: sub rndseed_64bit4 {
12502: my ($symb,$courseid,$domain,$username)=@_;
12503: {
12504: use integer;
12505: # strings need to be an even # of cahracters long, it it is odd the
12506: # last characters gets thrown away
12507: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12508: my $symbseed=numval3($symb) << 10;
12509: my $namechck=unpack("%32S*",$username.' ');
12510:
12511: my $nameseed=numval3($username) << 21;
12512: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12513: my $courseseed=unpack("%32S*",$courseid.' ');
12514:
12515: my $num1=$symbchck+$symbseed+$namechck;
12516: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 12517: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12518: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 12519: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 12520:
1.575 albertel 12521: return "$num1:$num2";
12522: }
12523: }
12524:
1.675 albertel 12525: sub rndseed_64bit5 {
12526: my ($symb,$courseid,$domain,$username)=@_;
12527: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12528: return "$num1:$num2";
12529: }
12530:
1.366 albertel 12531: sub rndseed_CODE_64bit {
12532: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 12533: {
1.366 albertel 12534: use integer;
1.443 albertel 12535: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 12536: my $symbseed=numval2($symb);
1.491 albertel 12537: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12538: my $CODEseed=numval(&getCODE());
1.443 albertel 12539: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 12540: my $num1=$symbseed+$CODEchck;
12541: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12542: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12543: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 12544: if ($_64bit) { $num1=(($num1<<32)>>32); }
12545: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 12546: return "$num1:$num2";
1.366 albertel 12547: }
12548: }
12549:
1.575 albertel 12550: sub rndseed_CODE_64bit4 {
12551: my ($symb,$courseid,$domain,$username)=@_;
12552: {
12553: use integer;
12554: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12555: my $symbseed=numval3($symb);
12556: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12557: my $CODEseed=numval3(&getCODE());
12558: my $courseseed=unpack("%32S*",$courseid.' ');
12559: my $num1=$symbseed+$CODEchck;
12560: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 12561: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12562: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 12563: if ($_64bit) { $num1=(($num1<<32)>>32); }
12564: if ($_64bit) { $num2=(($num2<<32)>>32); }
12565: return "$num1:$num2";
12566: }
12567: }
12568:
1.675 albertel 12569: sub rndseed_CODE_64bit5 {
12570: my ($symb,$courseid,$domain,$username)=@_;
12571: my $code = &getCODE();
12572: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12573: return "$num1:$num2";
12574: }
12575:
1.366 albertel 12576: sub setup_random_from_rndseed {
12577: my ($rndseed)=@_;
1.503 albertel 12578: if ($rndseed =~/([,:])/) {
1.1262 raeburn 12579: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12580: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12581: &Math::Random::random_set_seed_from_phrase($rndseed);
12582: } else {
12583: &Math::Random::random_set_seed($num1,$num2);
12584: }
1.366 albertel 12585: } else {
12586: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 12587: }
1.36 albertel 12588: }
12589:
1.474 albertel 12590: sub latest_receipt_algorithm_id {
1.835 albertel 12591: return 'receipt3';
1.474 albertel 12592: }
12593:
1.480 www 12594: sub recunique {
12595: my $fucourseid=shift;
12596: my $unique;
1.835 albertel 12597: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12598: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12599: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 12600: } else {
12601: $unique=$perlvar{'lonReceipt'};
12602: }
12603: return unpack("%32C*",$unique);
12604: }
12605:
12606: sub recprefix {
12607: my $fucourseid=shift;
12608: my $prefix;
1.835 albertel 12609: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12610: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 12611: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 12612: } else {
12613: $prefix=$perlvar{'lonHostID'};
12614: }
12615: return unpack("%32C*",$prefix);
12616: }
12617:
1.76 www 12618: sub ireceipt {
1.474 albertel 12619: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 12620:
12621: my $return =&recprefix($fucourseid).'-';
12622:
12623: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12624: $env{'request.state'} eq 'construct') {
12625: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12626: return $return;
12627: }
12628:
1.76 www 12629: my $cuname=unpack("%32C*",$funame);
12630: my $cudom=unpack("%32C*",$fudom);
12631: my $cucourseid=unpack("%32C*",$fucourseid);
12632: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 12633: my $cunique=&recunique($fucourseid);
1.474 albertel 12634: my $cpart=unpack("%32S*",$part);
1.835 albertel 12635: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12636:
1.790 albertel 12637: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 12638:
12639: $return.= ($cunique%$cuname+
12640: $cunique%$cudom+
12641: $cusymb%$cuname+
12642: $cusymb%$cudom+
12643: $cucourseid%$cuname+
12644: $cucourseid%$cudom+
12645: $cpart%$cuname+
12646: $cpart%$cudom);
12647: } else {
12648: $return.= ($cunique%$cuname+
12649: $cunique%$cudom+
12650: $cusymb%$cuname+
12651: $cusymb%$cudom+
12652: $cucourseid%$cuname+
12653: $cucourseid%$cudom);
12654: }
12655: return $return;
1.76 www 12656: }
12657:
12658: sub receipt {
1.474 albertel 12659: my ($part)=@_;
1.790 albertel 12660: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 12661: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 12662: }
1.260 ng 12663:
1.790 albertel 12664: sub whichuser {
12665: my ($passedsymb)=@_;
12666: my ($symb,$courseid,$domain,$name,$publicuser);
12667: if (defined($env{'form.grade_symb'})) {
12668: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12669: my $allowed=&allowed('vgr',$tmp_courseid);
12670: if (!$allowed &&
12671: exists($env{'request.course.sec'}) &&
12672: $env{'request.course.sec'} !~ /^\s*$/) {
12673: $allowed=&allowed('vgr',$tmp_courseid.
12674: '/'.$env{'request.course.sec'});
12675: }
12676: if ($allowed) {
12677: ($symb)=&get_env_multiple('form.grade_symb');
12678: $courseid=$tmp_courseid;
12679: ($domain)=&get_env_multiple('form.grade_domain');
12680: ($name)=&get_env_multiple('form.grade_username');
12681: return ($symb,$courseid,$domain,$name,$publicuser);
12682: }
12683: }
12684: if (!$passedsymb) {
12685: $symb=&symbread();
12686: } else {
12687: $symb=$passedsymb;
12688: }
12689: $courseid=$env{'request.course.id'};
12690: $domain=$env{'user.domain'};
12691: $name=$env{'user.name'};
12692: if ($name eq 'public' && $domain eq 'public') {
12693: if (!defined($env{'form.username'})) {
12694: $env{'form.username'}.=time.rand(10000000);
12695: }
12696: $name.=$env{'form.username'};
12697: }
12698: return ($symb,$courseid,$domain,$name,$publicuser);
12699:
12700: }
12701:
1.36 albertel 12702: # ------------------------------------------------------------ Serves up a file
1.472 albertel 12703: # returns either the contents of the file or
12704: # -1 if the file doesn't exist
1.481 raeburn 12705: #
12706: # if the target is a file that was uploaded via DOCS,
12707: # a check will be made to see if a current copy exists on the local server,
12708: # if it does this will be served, otherwise a copy will be retrieved from
12709: # the home server for the course and stored in /home/httpd/html/userfiles on
12710: # the local server.
1.472 albertel 12711:
1.36 albertel 12712: sub getfile {
1.538 albertel 12713: my ($file) = @_;
1.609 banghart 12714: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 12715: &repcopy($file);
12716: return &readfile($file);
12717: }
12718:
12719: sub repcopy_userfile {
12720: my ($file)=@_;
1.1142 raeburn 12721: my $londocroot = $perlvar{'lonDocRoot'};
12722: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 12723: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 12724: my ($cdom,$cnum,$filename) =
1.811 albertel 12725: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 12726: my $uri="/uploaded/$cdom/$cnum/$filename";
12727: if (-e "$file") {
1.828 www 12728: # we already have a local copy, check it out
1.538 albertel 12729: my @fileinfo = stat($file);
1.828 www 12730: my $rtncode;
12731: my $info;
1.538 albertel 12732: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 12733: if ($lwpresp ne 'ok') {
1.828 www 12734: # there is no such file anymore, even though we had a local copy
1.482 albertel 12735: if ($rtncode eq '404') {
1.538 albertel 12736: unlink($file);
1.482 albertel 12737: }
12738: return -1;
12739: }
12740: if ($info < $fileinfo[9]) {
1.828 www 12741: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 12742: return 'ok';
1.828 www 12743: } else {
12744: # the file is outdated, get rid of it
12745: unlink($file);
1.482 albertel 12746: }
1.828 www 12747: }
12748: # one way or the other, at this point, we don't have the file
12749: # construct the correct path for the file
12750: my @parts = ($cdom,$cnum);
12751: if ($filename =~ m|^(.+)/[^/]+$|) {
12752: push @parts, split(/\//,$1);
12753: }
12754: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12755: foreach my $part (@parts) {
12756: $path .= '/'.$part;
12757: if (!-e $path) {
12758: mkdir($path,0770);
1.482 albertel 12759: }
12760: }
1.828 www 12761: # now the path exists for sure
12762: # get a user agent
12763: my $ua=new LWP::UserAgent;
12764: my $transferfile=$file.'.in.transfer';
12765: # FIXME: this should flock
12766: if (-e $transferfile) { return 'ok'; }
12767: my $request;
12768: $uri=~s/^\///;
1.980 raeburn 12769: my $homeserver = &homeserver($cnum,$cdom);
12770: my $protocol = $protocol{$homeserver};
12771: $protocol = 'http' if ($protocol ne 'https');
12772: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 12773: my $response=$ua->request($request,$transferfile);
12774: # did it work?
12775: if ($response->is_error()) {
12776: unlink($transferfile);
12777: &logthis("Userfile repcopy failed for $uri");
12778: return -1;
12779: }
12780: # worked, rename the transfer file
12781: rename($transferfile,$file);
1.607 raeburn 12782: return 'ok';
1.481 raeburn 12783: }
12784:
1.517 albertel 12785: sub tokenwrapper {
12786: my $uri=shift;
1.980 raeburn 12787: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 12788: $uri=~s|^/||;
1.620 albertel 12789: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 12790: my $token=$1;
1.552 albertel 12791: my (undef,$udom,$uname,$file)=split('/',$uri,4);
12792: if ($udom && $uname && $file) {
12793: $file=~s|(\?\.*)*$||;
1.949 raeburn 12794: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 12795: my $homeserver = &homeserver($uname,$udom);
12796: my $protocol = $protocol{$homeserver};
12797: $protocol = 'http' if ($protocol ne 'https');
12798: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 12799: (($uri=~/\?/)?'&':'?').'token='.$token.
12800: '&tokenissued='.$perlvar{'lonHostID'};
12801: } else {
12802: return '/adm/notfound.html';
12803: }
12804: }
12805:
1.828 www 12806: # call with reqtype HEAD: get last modification time
12807: # call with reqtype GET: get the file contents
12808: # Do not call this with reqtype GET for large files! It loads everything into memory
12809: #
1.481 raeburn 12810: sub getuploaded {
12811: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12812: $uri=~s/^\///;
1.980 raeburn 12813: my $homeserver = &homeserver($cnum,$cdom);
12814: my $protocol = $protocol{$homeserver};
12815: $protocol = 'http' if ($protocol ne 'https');
12816: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 12817: my $ua=new LWP::UserAgent;
12818: my $request=new HTTP::Request($reqtype,$uri);
12819: my $response=$ua->request($request);
12820: $$rtncode = $response->code;
1.482 albertel 12821: if (! $response->is_success()) {
12822: return 'failed';
12823: }
12824: if ($reqtype eq 'HEAD') {
1.486 www 12825: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 12826: } elsif ($reqtype eq 'GET') {
12827: $$info = $response->content;
1.472 albertel 12828: }
1.482 albertel 12829: return 'ok';
1.36 albertel 12830: }
12831:
1.481 raeburn 12832: sub readfile {
12833: my $file = shift;
12834: if ( (! -e $file ) || ($file eq '') ) { return -1; };
12835: my $fh;
12836: open($fh,"<$file");
12837: my $a='';
1.800 albertel 12838: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 12839: return $a;
12840: }
12841:
1.36 albertel 12842: sub filelocation {
1.590 banghart 12843: my ($dir,$file) = @_;
12844: my $location;
12845: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 12846:
12847: if ($file =~ m-^/adm/-) {
12848: $file=~s-^/adm/wrapper/-/-;
12849: $file=~s-^/adm/coursedocs/showdoc/-/-;
12850: }
1.882 albertel 12851:
1.1139 www 12852: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 12853: $location = $file;
1.609 banghart 12854: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 12855: my ($udom,$uname,$filename)=
1.811 albertel 12856: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 12857: my $home=&homeserver($uname,$udom);
12858: my $is_me=0;
12859: my @ids=¤t_machine_ids();
12860: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12861: if ($is_me) {
1.1117 foxr 12862: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 12863: } else {
12864: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12865: $udom.'/'.$uname.'/'.$filename;
12866: }
1.882 albertel 12867: } elsif ($file =~ m-^/adm/-) {
12868: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 12869: } else {
12870: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 12871: $file=~s:^/(res|priv)/:/:;
12872: my $space=$1;
1.590 banghart 12873: if ( !( $file =~ m:^/:) ) {
12874: $location = $dir. '/'.$file;
12875: } else {
1.1142 raeburn 12876: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 12877: }
1.59 albertel 12878: }
1.590 banghart 12879: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 12880: while ($location=~m{/\.\./}) {
12881: if ($location =~ m{/[^/]+/\.\./}) {
12882: $location=~ s{/[^/]+/\.\./}{/}g;
12883: } else {
12884: $location=~ s{/\.\./}{/}g;
12885: }
12886: } #remove dir/..
1.590 banghart 12887: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12888: return $location;
1.46 www 12889: }
1.36 albertel 12890:
1.46 www 12891: sub hreflocation {
12892: my ($dir,$file)=@_;
1.980 raeburn 12893: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 12894: $file=filelocation($dir,$file);
1.700 albertel 12895: } elsif ($file=~m-^/adm/-) {
12896: $file=~s-^/adm/wrapper/-/-;
12897: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 12898: }
12899: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12900: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12901: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 12902: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12903: {/uploaded/$1/$2/}x;
1.46 www 12904: }
1.913 albertel 12905: if ($file=~ m{^/userfiles/}) {
12906: $file =~ s{^/userfiles/}{/uploaded/};
12907: }
1.462 albertel 12908: return $file;
1.465 albertel 12909: }
12910:
1.1139 www 12911:
12912:
12913:
12914:
1.465 albertel 12915: sub current_machine_domains {
1.853 albertel 12916: return &machine_domains(&hostname($perlvar{'lonHostID'}));
12917: }
12918:
12919: sub machine_domains {
12920: my ($hostname) = @_;
1.465 albertel 12921: my @domains;
1.838 albertel 12922: my %hostname = &all_hostnames();
1.465 albertel 12923: while( my($id, $name) = each(%hostname)) {
1.467 matthew 12924: # &logthis("-$id-$name-$hostname-");
1.465 albertel 12925: if ($hostname eq $name) {
1.844 albertel 12926: push(@domains,&host_domain($id));
1.465 albertel 12927: }
12928: }
12929: return @domains;
12930: }
12931:
12932: sub current_machine_ids {
1.853 albertel 12933: return &machine_ids(&hostname($perlvar{'lonHostID'}));
12934: }
12935:
12936: sub machine_ids {
12937: my ($hostname) = @_;
12938: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 12939: my @ids;
1.888 albertel 12940: my %name_to_host = &all_names();
1.889 albertel 12941: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12942: return @{ $name_to_host{$hostname} };
12943: }
12944: return;
1.31 www 12945: }
12946:
1.824 raeburn 12947: sub additional_machine_domains {
12948: my @domains;
12949: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12950: while( my $line = <$fh>) {
12951: $line =~ s/\s//g;
12952: push(@domains,$line);
12953: }
12954: return @domains;
12955: }
12956:
12957: sub default_login_domain {
12958: my $domain = $perlvar{'lonDefDomain'};
12959: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12960: foreach my $posdom (¤t_machine_domains(),
12961: &additional_machine_domains()) {
12962: if (lc($posdom) eq lc($testdomain)) {
12963: $domain=$posdom;
12964: last;
12965: }
12966: }
12967: return $domain;
12968: }
12969:
1.31 www 12970: # ------------------------------------------------------------- Declutters URLs
12971:
12972: sub declutter {
12973: my $thisfn=shift;
1.569 albertel 12974: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261 raeburn 12975: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12976: $thisfn=~s{^/home/httpd/html}{};
12977: }
1.31 www 12978: $thisfn=~s/^\///;
1.697 albertel 12979: $thisfn=~s|^adm/wrapper/||;
12980: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 12981: $thisfn=~s/^res\///;
1.1172 bisitz 12982: $thisfn=~s/^priv\///;
1.1032 raeburn 12983: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12984: $thisfn=~s/\?.+$//;
12985: }
1.268 www 12986: return $thisfn;
12987: }
12988:
12989: # ------------------------------------------------------------- Clutter up URLs
12990:
12991: sub clutter {
12992: my $thisfn='/'.&declutter(shift);
1.887 albertel 12993: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 12994: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 12995: $thisfn='/res'.$thisfn;
12996: }
1.1031 raeburn 12997: if ($thisfn !~m|^/adm|) {
12998: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 12999: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 13000: } else {
13001: my ($ext) = ($thisfn =~ /\.(\w+)$/);
13002: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 13003: if ($embstyle eq 'ssi'
13004: || ($embstyle eq 'hdn')
13005: || ($embstyle eq 'rat')
13006: || ($embstyle eq 'prv')
13007: || ($embstyle eq 'ign')) {
13008: #do nothing with these
13009: } elsif (($embstyle eq 'img')
1.695 albertel 13010: || ($embstyle eq 'emb')
13011: || ($embstyle eq 'wrp')) {
13012: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 13013: } elsif ($embstyle eq 'unk'
13014: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 13015: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 13016: } else {
1.718 www 13017: # &logthis("Got a blank emb style");
1.695 albertel 13018: }
1.694 albertel 13019: }
1.1343 raeburn 13020: } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298 raeburn 13021: $thisfn='/adm/wrapper'.$thisfn;
1.694 albertel 13022: }
1.31 www 13023: return $thisfn;
1.12 www 13024: }
13025:
1.787 albertel 13026: sub clutter_with_no_wrapper {
13027: my $uri = &clutter(shift);
13028: if ($uri =~ m-^/adm/-) {
13029: $uri =~ s-^/adm/wrapper/-/-;
13030: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
13031: }
13032: return $uri;
13033: }
13034:
1.557 albertel 13035: sub freeze_escape {
13036: my ($value)=@_;
13037: if (ref($value)) {
13038: $value=&nfreeze($value);
13039: return '__FROZEN__'.&escape($value);
13040: }
13041: return &escape($value);
13042: }
13043:
1.11 www 13044:
1.557 albertel 13045: sub thaw_unescape {
13046: my ($value)=@_;
13047: if ($value =~ /^__FROZEN__/) {
13048: substr($value,0,10,undef);
13049: $value=&unescape($value);
13050: return &thaw($value);
13051: }
13052: return &unescape($value);
13053: }
13054:
1.436 albertel 13055: sub correct_line_ends {
13056: my ($result)=@_;
13057: $$result =~s/\r\n/\n/mg;
13058: $$result =~s/\r/\n/mg;
1.415 albertel 13059: }
1.1 albertel 13060: # ================================================================ Main Program
13061:
1.184 www 13062: sub goodbye {
1.204 albertel 13063: &logthis("Starting Shut down");
1.443 albertel 13064: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 13065: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 13066: #converted
1.599 albertel 13067: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 13068: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13069: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13070: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 13071: #1.1 only
1.870 albertel 13072: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13073: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13074: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13075: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13076: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 13077: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13078: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 13079: &flushcourselogs();
13080: &logthis("Shutting down");
13081: }
13082:
1.852 albertel 13083: sub get_dns {
1.1210 raeburn 13084: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 13085: if (!$ignore_cache) {
13086: my ($content,$cached)=
13087: &Apache::lonnet::is_cached_new('dns',$url);
13088: if ($cached) {
1.1210 raeburn 13089: &$func($content,$hashref);
1.869 albertel 13090: return;
13091: }
13092: }
13093:
13094: my %alldns;
1.852 albertel 13095: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13096: foreach my $dns (<$config>) {
13097: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 13098: my $line = $1;
13099: my ($host,$protocol) = split(/:/,$line);
13100: if ($protocol ne 'https') {
13101: $protocol = 'http';
13102: }
13103: $alldns{$host} = $protocol;
1.869 albertel 13104: }
13105: while (%alldns) {
1.1263 raeburn 13106: my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852 albertel 13107: my $ua=new LWP::UserAgent;
1.1134 raeburn 13108: $ua->timeout(30);
1.979 raeburn 13109: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 13110: my $response=$ua->request($request);
1.979 raeburn 13111: delete($alldns{$dns});
1.852 albertel 13112: next if ($response->is_error());
13113: my @content = split("\n",$response->content);
1.1210 raeburn 13114: unless ($nocache) {
1.1219 raeburn 13115: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 13116: }
13117: &$func(\@content,$hashref);
1.869 albertel 13118: return;
1.852 albertel 13119: }
13120: close($config);
1.871 albertel 13121: my $which = (split('/',$url))[3];
13122: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13123: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 13124: my @content = <$config>;
1.1210 raeburn 13125: &$func(\@content,$hashref);
13126: return;
13127: }
13128:
13129: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 13130: sub parse_dns_checksums_tab {
1.1210 raeburn 13131: my ($lines,$hashref) = @_;
1.1264 raeburn 13132: my $lonhost = $perlvar{'lonHostID'};
13133: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210 raeburn 13134: my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264 raeburn 13135: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13136: my $webconfdir = '/etc/httpd/conf';
13137: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13138: $webconfdir = '/etc/apache2';
13139: } elsif ($distro =~ /^sles(\d+)$/) {
13140: if ($1 >= 10) {
13141: $webconfdir = '/etc/apache2';
13142: }
13143: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13144: if ($1 >= 10.0) {
13145: $webconfdir = '/etc/apache2';
13146: }
13147: }
1.1210 raeburn 13148: my ($release,$timestamp) = split(/\-/,$loncaparev);
13149: my (%chksum,%revnum);
13150: if (ref($lines) eq 'ARRAY') {
13151: chomp(@{$lines});
1.1238 raeburn 13152: my $version = shift(@{$lines});
13153: if ($version eq $release) {
1.1210 raeburn 13154: foreach my $line (@{$lines}) {
1.1238 raeburn 13155: my ($file,$version,$shasum) = split(/,/,$line);
1.1264 raeburn 13156: if ($file =~ m{^/etc/httpd/conf}) {
13157: if ($webconfdir eq '/etc/apache2') {
13158: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13159: }
13160: }
1.1238 raeburn 13161: $chksum{$file} = $shasum;
13162: $revnum{$file} = $version;
1.1210 raeburn 13163: }
13164: if (ref($hashref) eq 'HASH') {
13165: %{$hashref} = (
13166: sums => \%chksum,
13167: versions => \%revnum,
13168: );
13169: }
13170: }
13171: }
1.869 albertel 13172: return;
1.852 albertel 13173: }
1.1210 raeburn 13174:
13175: sub fetch_dns_checksums {
1.1238 raeburn 13176: my %checksums;
13177: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260 raeburn 13178: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238 raeburn 13179: my ($release,$timestamp) = split(/\-/,$loncaparev);
13180: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 13181: \%checksums);
1.1210 raeburn 13182: return \%checksums;
13183: }
13184:
1.327 albertel 13185: # ------------------------------------------------------------ Read domain file
13186: {
1.852 albertel 13187: my $loaded;
1.846 albertel 13188: my %domain;
13189:
1.852 albertel 13190: sub parse_domain_tab {
13191: my ($lines) = @_;
13192: foreach my $line (@$lines) {
13193: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 13194:
1.846 albertel 13195: chomp($line);
1.852 albertel 13196: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 13197: my %this_domain;
13198: foreach my $field ('description', 'auth_def', 'auth_arg_def',
13199: 'lang_def', 'city', 'longi', 'lati',
13200: 'primary') {
13201: $this_domain{$field} = shift(@elements);
13202: }
13203: $domain{$name} = \%this_domain;
1.852 albertel 13204: }
13205: }
1.864 albertel 13206:
13207: sub reset_domain_info {
13208: undef($loaded);
13209: undef(%domain);
13210: }
13211:
1.852 albertel 13212: sub load_domain_tab {
1.1293 raeburn 13213: my ($ignore_cache,$nocache) = @_;
13214: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852 albertel 13215: my $fh;
13216: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
13217: my @lines = <$fh>;
13218: &parse_domain_tab(\@lines);
1.448 albertel 13219: }
1.852 albertel 13220: close($fh);
13221: $loaded = 1;
1.327 albertel 13222: }
1.846 albertel 13223:
13224: sub domain {
1.852 albertel 13225: &load_domain_tab() if (!$loaded);
13226:
1.846 albertel 13227: my ($name,$what) = @_;
13228: return if ( !exists($domain{$name}) );
13229:
13230: if (!$what) {
13231: return $domain{$name}{'description'};
13232: }
13233: return $domain{$name}{$what};
13234: }
1.974 raeburn 13235:
13236: sub domain_info {
13237: &load_domain_tab() if (!$loaded);
13238: return %domain;
13239: }
13240:
1.327 albertel 13241: }
13242:
13243:
1.1 albertel 13244: # ------------------------------------------------------------- Read hosts file
13245: {
1.838 albertel 13246: my %hostname;
1.844 albertel 13247: my %hostdom;
1.845 albertel 13248: my %libserv;
1.852 albertel 13249: my $loaded;
1.888 albertel 13250: my %name_to_host;
1.1074 raeburn 13251: my %internetdom;
1.1107 raeburn 13252: my %LC_dns_serv;
1.852 albertel 13253:
13254: sub parse_hosts_tab {
13255: my ($file) = @_;
13256: foreach my $configline (@$file) {
13257: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 13258: chomp($configline);
13259: if ($configline =~ /^\^/) {
13260: if ($configline =~ /^\^([\w.\-]+)/) {
13261: $LC_dns_serv{$1} = 1;
13262: }
13263: next;
13264: }
1.1074 raeburn 13265: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 13266: $name=~s/\s//g;
13267: if ($id && $domain && $role && $name) {
13268: $hostname{$id}=$name;
1.888 albertel 13269: push(@{$name_to_host{$name}}, $id);
1.852 albertel 13270: $hostdom{$id}=$domain;
13271: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 13272: if (defined($protocol)) {
13273: if ($protocol eq 'https') {
13274: $protocol{$id} = $protocol;
13275: } else {
13276: $protocol{$id} = 'http';
13277: }
1.968 raeburn 13278: } else {
1.969 raeburn 13279: $protocol{$id} = 'http';
1.968 raeburn 13280: }
1.1074 raeburn 13281: if (defined($intdom)) {
13282: $internetdom{$id} = $intdom;
13283: }
1.852 albertel 13284: }
13285: }
13286: }
1.864 albertel 13287:
13288: sub reset_hosts_info {
1.897 albertel 13289: &purge_remembered();
1.864 albertel 13290: &reset_domain_info();
13291: &reset_hosts_ip_info();
1.1339 raeburn 13292: undef(%internetdom);
1.892 albertel 13293: undef(%name_to_host);
1.864 albertel 13294: undef(%hostname);
13295: undef(%hostdom);
13296: undef(%libserv);
13297: undef($loaded);
13298: }
1.1 albertel 13299:
1.852 albertel 13300: sub load_hosts_tab {
1.1293 raeburn 13301: my ($ignore_cache,$nocache) = @_;
13302: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852 albertel 13303: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13304: my @config = <$config>;
13305: &parse_hosts_tab(\@config);
13306: close($config);
13307: $loaded=1;
1.1 albertel 13308: }
1.852 albertel 13309:
1.838 albertel 13310: sub hostname {
1.852 albertel 13311: &load_hosts_tab() if (!$loaded);
13312:
1.838 albertel 13313: my ($lonid) = @_;
13314: return $hostname{$lonid};
13315: }
1.845 albertel 13316:
1.838 albertel 13317: sub all_hostnames {
1.852 albertel 13318: &load_hosts_tab() if (!$loaded);
13319:
1.838 albertel 13320: return %hostname;
13321: }
1.845 albertel 13322:
1.888 albertel 13323: sub all_names {
1.1293 raeburn 13324: my ($ignore_cache,$nocache) = @_;
13325: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888 albertel 13326:
13327: return %name_to_host;
13328: }
13329:
1.974 raeburn 13330: sub all_host_domain {
13331: &load_hosts_tab() if (!$loaded);
13332: return %hostdom;
13333: }
13334:
1.1339 raeburn 13335: sub all_host_intdom {
13336: &load_hosts_tab() if (!$loaded);
13337: return %internetdom;
13338: }
13339:
1.845 albertel 13340: sub is_library {
1.852 albertel 13341: &load_hosts_tab() if (!$loaded);
13342:
1.845 albertel 13343: return exists($libserv{$_[0]});
13344: }
13345:
13346: sub all_library {
1.852 albertel 13347: &load_hosts_tab() if (!$loaded);
13348:
1.845 albertel 13349: return %libserv;
13350: }
13351:
1.1062 droeschl 13352: sub unique_library {
13353: #2x reverse removes all hostnames that appear more than once
13354: my %unique = reverse &all_library();
13355: return reverse %unique;
13356: }
13357:
1.841 albertel 13358: sub get_servers {
1.852 albertel 13359: &load_hosts_tab() if (!$loaded);
13360:
1.841 albertel 13361: my ($domain,$type) = @_;
13362: my %possible_hosts = ($type eq 'library') ? %libserv
13363: : %hostname;
13364: my %result;
1.842 albertel 13365: if (ref($domain) eq 'ARRAY') {
13366: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 13367: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 13368: $result{$host} = $hostname;
13369: }
13370: }
13371: } else {
13372: while ( my ($host,$hostname) = each(%possible_hosts)) {
13373: if ($hostdom{$host} eq $domain) {
13374: $result{$host} = $hostname;
13375: }
1.841 albertel 13376: }
13377: }
13378: return %result;
13379: }
1.845 albertel 13380:
1.1062 droeschl 13381: sub get_unique_servers {
13382: my %unique = reverse &get_servers(@_);
13383: return reverse %unique;
13384: }
13385:
1.844 albertel 13386: sub host_domain {
1.852 albertel 13387: &load_hosts_tab() if (!$loaded);
13388:
1.844 albertel 13389: my ($lonid) = @_;
13390: return $hostdom{$lonid};
13391: }
13392:
1.841 albertel 13393: sub all_domains {
1.852 albertel 13394: &load_hosts_tab() if (!$loaded);
13395:
1.841 albertel 13396: my %seen;
13397: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13398: return @uniq;
13399: }
1.1074 raeburn 13400:
13401: sub internet_dom {
13402: &load_hosts_tab() if (!$loaded);
13403:
13404: my ($lonid) = @_;
13405: return $internetdom{$lonid};
13406: }
1.1107 raeburn 13407:
13408: sub is_LC_dns {
13409: &load_hosts_tab() if (!$loaded);
13410:
13411: my ($hostname) = @_;
13412: return exists($LC_dns_serv{$hostname});
13413: }
13414:
1.1 albertel 13415: }
13416:
1.847 albertel 13417: {
13418: my %iphost;
1.856 albertel 13419: my %name_to_ip;
13420: my %lonid_to_ip;
1.869 albertel 13421:
1.847 albertel 13422: sub get_hosts_from_ip {
13423: my ($ip) = @_;
13424: my %iphosts = &get_iphost();
13425: if (ref($iphosts{$ip})) {
13426: return @{$iphosts{$ip}};
13427: }
13428: return;
1.839 albertel 13429: }
1.864 albertel 13430:
13431: sub reset_hosts_ip_info {
13432: undef(%iphost);
13433: undef(%name_to_ip);
13434: undef(%lonid_to_ip);
13435: }
1.856 albertel 13436:
13437: sub get_host_ip {
13438: my ($lonid) = @_;
13439: if (exists($lonid_to_ip{$lonid})) {
13440: return $lonid_to_ip{$lonid};
13441: }
13442: my $name=&hostname($lonid);
13443: my $ip = gethostbyname($name);
13444: return if (!$ip || length($ip) ne 4);
13445: $ip=inet_ntoa($ip);
13446: $name_to_ip{$name} = $ip;
13447: $lonid_to_ip{$lonid} = $ip;
13448: return $ip;
13449: }
1.847 albertel 13450:
13451: sub get_iphost {
1.1293 raeburn 13452: my ($ignore_cache,$nocache) = @_;
1.894 albertel 13453:
1.869 albertel 13454: if (!$ignore_cache) {
13455: if (%iphost) {
13456: return %iphost;
13457: }
13458: my ($ip_info,$cached)=
13459: &Apache::lonnet::is_cached_new('iphost','iphost');
13460: if ($cached) {
13461: %iphost = %{$ip_info->[0]};
13462: %name_to_ip = %{$ip_info->[1]};
13463: %lonid_to_ip = %{$ip_info->[2]};
13464: return %iphost;
13465: }
13466: }
1.894 albertel 13467:
13468: # get yesterday's info for fallback
13469: my %old_name_to_ip;
13470: my ($ip_info,$cached)=
13471: &Apache::lonnet::is_cached_new('iphost','iphost');
13472: if ($cached) {
13473: %old_name_to_ip = %{$ip_info->[1]};
13474: }
13475:
1.1293 raeburn 13476: my %name_to_host = &all_names($ignore_cache,$nocache);
1.888 albertel 13477: foreach my $name (keys(%name_to_host)) {
1.847 albertel 13478: my $ip;
13479: if (!exists($name_to_ip{$name})) {
13480: $ip = gethostbyname($name);
13481: if (!$ip || length($ip) ne 4) {
1.894 albertel 13482: if (defined($old_name_to_ip{$name})) {
13483: $ip = $old_name_to_ip{$name};
13484: &logthis("Can't find $name defaulting to old $ip");
13485: } else {
13486: &logthis("Name $name no IP found");
13487: next;
13488: }
13489: } else {
13490: $ip=inet_ntoa($ip);
1.847 albertel 13491: }
13492: $name_to_ip{$name} = $ip;
13493: } else {
13494: $ip = $name_to_ip{$name};
1.653 albertel 13495: }
1.888 albertel 13496: foreach my $id (@{ $name_to_host{$name} }) {
13497: $lonid_to_ip{$id} = $ip;
13498: }
13499: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 13500: }
1.1293 raeburn 13501: unless ($nocache) {
13502: &do_cache_new('iphost','iphost',
13503: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13504: 48*60*60);
13505: }
1.869 albertel 13506:
1.847 albertel 13507: return %iphost;
1.598 albertel 13508: }
13509:
1.992 raeburn 13510: #
13511: # Given a DNS returns the loncapa host name for that DNS
13512: #
13513: sub host_from_dns {
13514: my ($dns) = @_;
13515: my @hosts;
13516: my $ip;
13517:
1.993 raeburn 13518: if (exists($name_to_ip{$dns})) {
1.992 raeburn 13519: $ip = $name_to_ip{$dns};
13520: }
13521: if (!$ip) {
13522: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13523: if (length($ip) == 4) {
13524: $ip = &IO::Socket::inet_ntoa($ip);
13525: }
13526: }
13527: if ($ip) {
13528: @hosts = get_hosts_from_ip($ip);
13529: return $hosts[0];
13530: }
13531: return undef;
1.986 foxr 13532: }
1.992 raeburn 13533:
1.1074 raeburn 13534: sub get_internet_names {
13535: my ($lonid) = @_;
13536: return if ($lonid eq '');
13537: my ($idnref,$cached)=
13538: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13539: if ($cached) {
13540: return $idnref;
13541: }
13542: my $ip = &get_host_ip($lonid);
13543: my @hosts = &get_hosts_from_ip($ip);
13544: my %iphost = &get_iphost();
13545: my (@idns,%seen);
13546: foreach my $id (@hosts) {
13547: my $dom = &host_domain($id);
13548: my $prim_id = &domain($dom,'primary');
13549: my $prim_ip = &get_host_ip($prim_id);
13550: next if ($seen{$prim_ip});
13551: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13552: foreach my $id (@{$iphost{$prim_ip}}) {
13553: my $intdom = &internet_dom($id);
13554: unless (grep(/^\Q$intdom\E$/,@idns)) {
13555: push(@idns,$intdom);
13556: }
13557: }
13558: }
13559: $seen{$prim_ip} = 1;
13560: }
1.1219 raeburn 13561: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 13562: }
13563:
1.986 foxr 13564: }
13565:
1.1079 raeburn 13566: sub all_loncaparevs {
1.1249 raeburn 13567: 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 13568: }
13569:
1.1227 raeburn 13570: # ---------------------------------------------------------- Read loncaparev table
13571: {
13572: sub load_loncaparevs {
13573: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13574: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13575: while (my $configline=<$config>) {
13576: chomp($configline);
13577: my ($hostid,$loncaparev)=split(/:/,$configline);
13578: $loncaparevs{$hostid}=$loncaparev;
13579: }
13580: close($config);
13581: }
13582: }
13583: }
13584: }
13585:
13586: # ---------------------------------------------------------- Read serverhostID table
13587: {
13588: sub load_serverhomeIDs {
13589: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13590: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13591: while (my $configline=<$config>) {
13592: chomp($configline);
13593: my ($name,$id)=split(/:/,$configline);
13594: $serverhomeIDs{$name}=$id;
13595: }
13596: close($config);
13597: }
13598: }
13599: }
13600: }
13601:
13602:
1.862 albertel 13603: BEGIN {
13604:
13605: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13606: unless ($readit) {
13607: {
13608: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13609: %perlvar = (%perlvar,%{$configvars});
13610: }
13611:
13612:
1.1 albertel 13613: # ------------------------------------------------------ Read spare server file
13614: {
1.448 albertel 13615: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 13616:
13617: while (my $configline=<$config>) {
13618: chomp($configline);
1.284 matthew 13619: if ($configline) {
1.784 albertel 13620: my ($host,$type) = split(':',$configline,2);
1.785 albertel 13621: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 13622: push(@{ $spareid{$type} }, $host);
1.1 albertel 13623: }
13624: }
1.448 albertel 13625: close($config);
1.1 albertel 13626: }
1.11 www 13627: # ------------------------------------------------------------ Read permissions
13628: {
1.448 albertel 13629: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 13630:
13631: while (my $configline=<$config>) {
1.448 albertel 13632: chomp($configline);
13633: if ($configline) {
13634: my ($role,$perm)=split(/ /,$configline);
13635: if ($perm ne '') { $pr{$role}=$perm; }
13636: }
1.11 www 13637: }
1.448 albertel 13638: close($config);
1.11 www 13639: }
13640:
13641: # -------------------------------------------- Read plain texts for permissions
13642: {
1.448 albertel 13643: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 13644:
13645: while (my $configline=<$config>) {
1.448 albertel 13646: chomp($configline);
13647: if ($configline) {
1.742 raeburn 13648: my ($short,@plain)=split(/:/,$configline);
13649: %{$prp{$short}} = ();
13650: if (@plain > 0) {
13651: $prp{$short}{'std'} = $plain[0];
13652: for (my $i=1; $i<@plain; $i++) {
13653: $prp{$short}{'alt'.$i} = $plain[$i];
13654: }
13655: }
1.448 albertel 13656: }
1.135 www 13657: }
1.448 albertel 13658: close($config);
1.135 www 13659: }
13660:
13661: # ---------------------------------------------------------- Read package table
13662: {
1.448 albertel 13663: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 13664:
13665: while (my $configline=<$config>) {
1.483 albertel 13666: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 13667: chomp($configline);
13668: my ($short,$plain)=split(/:/,$configline);
13669: my ($pack,$name)=split(/\&/,$short);
13670: if ($plain ne '') {
13671: $packagetab{$pack.'&'.$name.'&name'}=$name;
13672: $packagetab{$short}=$plain;
13673: }
1.11 www 13674: }
1.448 albertel 13675: close($config);
1.329 matthew 13676: }
13677:
1.1073 raeburn 13678: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 13679:
13680: &load_loncaparevs();
1.1073 raeburn 13681:
1.1074 raeburn 13682: # ---------------------------------------------------------- Read serverhostID table
13683:
1.1227 raeburn 13684: &load_serverhomeIDs();
13685:
13686: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 13687: {
13688: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13689: if (-e $file) {
13690: my $parser = HTML::LCParser->new($file);
13691: while (my $token = $parser->get_token()) {
13692: if ($token->[0] eq 'S') {
13693: my $item = $token->[1];
13694: my $name = $token->[2]{'name'};
13695: my $value = $token->[2]{'value'};
1.1285 raeburn 13696: my $valuematch = $token->[2]{'valuematch'};
1.1303 raeburn 13697: my $namematch = $token->[2]{'namematch'};
13698: if ($item eq 'parameter') {
13699: if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
13700: my $release = $parser->get_text();
13701: $release =~ s/(^\s*|\s*$ )//gx;
13702: $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
13703: }
13704: } elsif ($item ne '' && $name ne '') {
1.1079 raeburn 13705: my $release = $parser->get_text();
13706: $release =~ s/(^\s*|\s*$ )//gx;
1.1303 raeburn 13707: $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079 raeburn 13708: }
13709: }
13710: }
13711: }
1.1073 raeburn 13712: }
13713:
1.1138 raeburn 13714: # ---------------------------------------------------------- Read managers table
13715: {
13716: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13717: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
13718: while (my $configline=<$config>) {
13719: chomp($configline);
13720: next if ($configline =~ /^\#/);
13721: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13722: $managerstab{$configline} = 1;
13723: }
13724: }
13725: close($config);
13726: }
13727: }
13728: }
13729:
1.329 matthew 13730: # ------------- set up temporary directory
13731: {
1.1117 foxr 13732: $tmpdir = LONCAPA::tempdir();
1.329 matthew 13733:
1.11 www 13734: }
13735:
1.794 albertel 13736: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
13737: 'compress_threshold'=> 20_000,
13738: });
1.185 www 13739:
1.281 www 13740: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 13741: $dumpcount=0;
1.958 www 13742: $locknum=0;
1.22 www 13743:
1.163 harris41 13744: &logtouch();
1.672 albertel 13745: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 13746: $readit=1;
1.564 albertel 13747: {
13748: use integer;
13749: my $test=(2**32)+1;
1.568 albertel 13750: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 13751: &logthis(" Detected 64bit platform ($_64bit)");
13752: }
1.195 www 13753: }
1.1 albertel 13754: }
1.179 www 13755:
1.1 albertel 13756: 1;
1.191 harris41 13757: __END__
13758:
1.243 albertel 13759: =pod
13760:
1.191 harris41 13761: =head1 NAME
13762:
1.243 albertel 13763: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 13764:
13765: =head1 SYNOPSIS
13766:
1.243 albertel 13767: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 13768:
13769: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13770:
1.243 albertel 13771: Common parameters:
13772:
13773: =over 4
13774:
13775: =item *
13776:
13777: $uname : an internal username (if $cname expecting a course Id specifically)
13778:
13779: =item *
13780:
13781: $udom : a domain (if $cdom expecting a course's domain specifically)
13782:
13783: =item *
13784:
13785: $symb : a resource instance identifier
13786:
13787: =item *
13788:
13789: $namespace : the name of a .db file that contains the data needed or
13790: being set.
13791:
13792: =back
13793:
1.394 bowersj2 13794: =head1 OVERVIEW
1.191 harris41 13795:
1.394 bowersj2 13796: lonnet provides subroutines which interact with the
13797: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13798: about classes, users, and resources.
1.243 albertel 13799:
13800: For many of these objects you can also use this to store data about
13801: them or modify them in various ways.
1.191 harris41 13802:
1.394 bowersj2 13803: =head2 Symbs
1.191 harris41 13804:
1.394 bowersj2 13805: To identify a specific instance of a resource, LON-CAPA uses symbols
13806: or "symbs"X<symb>. These identifiers are built from the URL of the
13807: map, the resource number of the resource in the map, and the URL of
13808: the resource itself. The latter is somewhat redundant, but might help
13809: if maps change.
13810:
13811: An example is
13812:
13813: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13814:
13815: The respective map entry is
13816:
13817: <resource id="19" src="/res/msu/korte/tests/part12.problem"
13818: title="Problem 2">
13819: </resource>
13820:
13821: Symbs are used by the random number generator, as well as to store and
13822: restore data specific to a certain instance of for example a problem.
13823:
13824: =head2 Storing And Retrieving Data
13825:
13826: X<store()>X<cstore()>X<restore()>Three of the most important functions
13827: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13828: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13829: is is the non-critical message twin of cstore. These functions are for
13830: handlers to store a perl hash to a user's permanent data space in an
13831: easy manner, and to retrieve it again on another call. It is expected
13832: that a handler would use this once at the beginning to retrieve data,
13833: and then again once at the end to send only the new data back.
13834:
13835: The data is stored in the user's data directory on the user's
13836: homeserver under the ID of the course.
13837:
13838: The hash that is returned by restore will have all of the previous
13839: value for all of the elements of the hash.
13840:
13841: Example:
13842:
13843: #creating a hash
13844: my %hash;
13845: $hash{'foo'}='bar';
13846:
13847: #storing it
13848: &Apache::lonnet::cstore(\%hash);
13849:
13850: #changing a value
13851: $hash{'foo'}='notbar';
13852:
13853: #adding a new value
13854: $hash{'bar'}='foo';
13855: &Apache::lonnet::cstore(\%hash);
13856:
13857: #retrieving the hash
13858: my %history=&Apache::lonnet::restore();
13859:
13860: #print the hash
13861: foreach my $key (sort(keys(%history))) {
13862: print("\%history{$key} = $history{$key}");
13863: }
13864:
13865: Will print out:
1.191 harris41 13866:
1.394 bowersj2 13867: %history{1:foo} = bar
13868: %history{1:keys} = foo:timestamp
13869: %history{1:timestamp} = 990455579
13870: %history{2:bar} = foo
13871: %history{2:foo} = notbar
13872: %history{2:keys} = foo:bar:timestamp
13873: %history{2:timestamp} = 990455580
13874: %history{bar} = foo
13875: %history{foo} = notbar
13876: %history{timestamp} = 990455580
13877: %history{version} = 2
13878:
13879: Note that the special hash entries C<keys>, C<version> and
13880: C<timestamp> were added to the hash. C<version> will be equal to the
13881: total number of versions of the data that have been stored. The
13882: C<timestamp> attribute will be the UNIX time the hash was
13883: stored. C<keys> is available in every historical section to list which
13884: keys were added or changed at a specific historical revision of a
13885: hash.
13886:
13887: B<Warning>: do not store the hash that restore returns directly. This
13888: will cause a mess since it will restore the historical keys as if the
13889: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 13890:
1.394 bowersj2 13891: Calling convention:
1.191 harris41 13892:
1.1225 raeburn 13893: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269 raeburn 13894: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191 harris41 13895:
1.394 bowersj2 13896: For more detailed information, see lonnet specific documentation.
1.191 harris41 13897:
1.394 bowersj2 13898: =head1 RETURN MESSAGES
1.191 harris41 13899:
1.394 bowersj2 13900: =over 4
1.191 harris41 13901:
1.394 bowersj2 13902: =item * B<con_lost>: unable to contact remote host
1.191 harris41 13903:
1.394 bowersj2 13904: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13905: when the connection is brought back up
1.191 harris41 13906:
1.394 bowersj2 13907: =item * B<con_failed>: unable to contact remote host and unable to save message
13908: for later delivery
1.191 harris41 13909:
1.967 bisitz 13910: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 13911:
1.394 bowersj2 13912: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 13913: that was requested
1.191 harris41 13914:
1.243 albertel 13915: =back
1.191 harris41 13916:
1.243 albertel 13917: =head1 PUBLIC SUBROUTINES
1.191 harris41 13918:
1.243 albertel 13919: =head2 Session Environment Functions
1.191 harris41 13920:
1.243 albertel 13921: =over 4
1.191 harris41 13922:
1.394 bowersj2 13923: =item *
13924: X<appenv()>
1.949 raeburn 13925: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 13926: the user envirnoment file, and will be restored for each access this
1.620 albertel 13927: user makes during this session, also modifies the %env for the current
1.949 raeburn 13928: process. Optional rolesarrayref - if defined contains a reference to an array
13929: of roles which are exempt from the restriction on modifying user.role entries
13930: in the user's environment.db and in %env.
1.191 harris41 13931:
13932: =item *
1.394 bowersj2 13933: X<delenv()>
1.987 raeburn 13934: B<delenv($delthis,$regexp)>: removes all items from the session
13935: environment file that begin with $delthis. If the
13936: optional second arg - $regexp - is true, $delthis is treated as a
13937: regular expression, otherwise \Q$delthis\E is used.
13938: The values are also deleted from the current processes %env.
1.191 harris41 13939:
1.795 albertel 13940: =item * get_env_multiple($name)
13941:
13942: gets $name from the %env hash, it seemlessly handles the cases where multiple
13943: values may be defined and end up as an array ref.
13944:
13945: returns an array of values
13946:
1.243 albertel 13947: =back
13948:
13949: =head2 User Information
1.191 harris41 13950:
1.243 albertel 13951: =over 4
1.191 harris41 13952:
13953: =item *
1.394 bowersj2 13954: X<queryauthenticate()>
13955: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 13956: authentication scheme
13957:
13958: =item *
1.394 bowersj2 13959: X<authenticate()>
1.1073 raeburn 13960: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 13961: authenticate user from domain's lib servers (first use the current
13962: one). C<$upass> should be the users password.
1.1073 raeburn 13963: $checkdefauth is optional (value is 1 if a check should be made to
13964: authenticate user using default authentication method, and allow
13965: account creation if username does not have account in the domain).
13966: $clientcancheckhost is optional (value is 1 if checking whether the
13967: server can host will occur on the client side in lonauth.pm).
1.191 harris41 13968:
13969: =item *
1.394 bowersj2 13970: X<homeserver()>
13971: B<homeserver($uname,$udom)>: find the server which has
13972: the user's directory and files (there must be only one), this caches
13973: the answer, and also caches if there is a borken connection.
1.191 harris41 13974:
13975: =item *
1.394 bowersj2 13976: X<idget()>
1.1300 raeburn 13977: B<idget($udom,$idsref,$namespace)>: find the usernames behind either
13978: a list of student/employee IDs or clicker IDs
13979: (student/employee IDs are a unique resource in a domain, there must be
13980: only 1 ID per username, and only 1 username per ID in a specific domain).
13981: clickerIDs are not necessarily unique, as students might share clickers.
13982: (returns hash: id=>name,id=>name)
1.191 harris41 13983:
13984: =item *
1.394 bowersj2 13985: X<idrget()>
13986: B<idrget($udom,@unames)>: find the IDs behind a list of
13987: usernames (returns hash: name=>id,name=>id)
1.191 harris41 13988:
13989: =item *
1.394 bowersj2 13990: X<idput()>
1.1300 raeburn 13991: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of
13992: names and associated student/employee IDs or clicker IDs.
13993:
13994: =item *
13995: X<iddel()>
13996: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted
13997: student/employee ID or clicker ID username look-ups from domain.
13998: The homeserver ($uhome) and namespace ($namespace) are optional.
13999: If no $uhome is provided, it will be determined usig &homeserver()
14000: for each user. If no $namespace is provided, the default is ids.
14001:
14002: =item *
14003: X<updateclickers()>
14004: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update
14005: clicker ID-to-username look-ups in clickers.db on library server.
14006: Permitted actions are add or del (i.e., add or delete). The
14007: clickers.db contains clickerID as keys (escaped), and each corresponding
14008: value is an escaped comma-separated list of usernames (for whom the
14009: library server is the homeserver), who registered that particular ID.
14010: If $critical is true, the update will be sent via &critical, otherwise
14011: &reply() will be used.
1.191 harris41 14012:
14013: =item *
1.394 bowersj2 14014: X<rolesinit()>
1.1169 droeschl 14015: B<rolesinit($udom,$username)>: get user privileges.
14016: returns user role, first access and timer interval hashes
1.243 albertel 14017:
14018: =item *
1.1171 droeschl 14019: X<privileged()>
14020: B<privileged($username,$domain)>: returns a true if user has a
14021: privileged and active role (i.e. su or dc), false otherwise.
14022:
14023: =item *
1.551 albertel 14024: X<getsection()>
14025: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 14026: course $cname, return section name/number or '' for "not in course"
14027: and '-1' for "no section"
14028:
14029: =item *
1.394 bowersj2 14030: X<userenvironment()>
14031: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 14032: passed in @what from the requested user's environment, returns a hash
14033:
1.858 raeburn 14034: =item *
14035: X<userlog_query()>
1.859 albertel 14036: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14037: activity.log file. %filters defines filters applied when parsing the
14038: log file. These can be start or end timestamps, or the type of action
14039: - log to look for Login or Logout events, check for Checkin or
14040: Checkout, role for role selection. The response is in the form
14041: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
14042: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 14043:
1.243 albertel 14044: =back
14045:
14046: =head2 User Roles
14047:
14048: =over 4
14049:
14050: =item *
14051:
1.1284 raeburn 14052: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14053: returns codes for allowed actions.
14054:
14055: The first argument is required, all others are optional.
14056:
14057: $priv is the privilege being checked.
14058: $uri contains additional information about what is being checked for access (e.g.,
14059: URL, course ID etc.).
14060: $symb is the unique resource instance identifier in a course; if needed,
14061: but not provided, it will be retrieved via a call to &symbread().
14062: $role is the role for which a priv is being checked (only used if priv is evb).
14063: $clientip is the user's IP address (only used when checking for access to portfolio
14064: files).
14065: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14066: prevents recursive calls to &allowed.
14067:
1.243 albertel 14068: F: full access
14069: U,I,K: authentication modes (cxx only)
14070: '': forbidden
14071: 1: user needs to choose course
14072: 2: browse allowed
1.766 albertel 14073: A: passphrase authentication needed
1.1284 raeburn 14074: B: access temporarily blocked because of a blocking event in a course.
1.243 albertel 14075:
14076: =item *
14077:
1.1192 raeburn 14078: constructaccess($url,$setpriv) : check for access to construction space URL
14079:
14080: See if the owner domain and name in the URL match those in the
14081: expected environment. If so, return three element list
14082: ($ownername,$ownerdomain,$ownerhome).
14083:
14084: Otherwise return the null string.
14085:
14086: If second argument 'setpriv' is true, it assigns the privileges,
14087: and returns the same three element list, unless the owner has
14088: blocked "ad hoc" Domain Coordinator access to the Author Space,
14089: in which case the null string is returned.
14090:
14091: =item *
14092:
1.1326 raeburn 14093: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14094: define a custom role rolename set privileges in format of lonTabs/roles.tab
14095: for system, domain, and course level. $uname and $udom are optional (current
14096: user's username and domain will be used when either of $uname or $udom are absent.
1.243 albertel 14097:
14098: =item *
14099:
1.988 raeburn 14100: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
14101: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 14102: $type is Course (default) or Community.
1.988 raeburn 14103: If $forcedefault evaluates to true, text returned will be default
14104: text for $type. Otherwise, if this is a course, the text returned
14105: will be a custom name for the role (if defined in the course's
14106: environment). If no custom name is defined the default is returned.
14107:
1.832 raeburn 14108: =item *
14109:
1.1219 raeburn 14110: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 14111: All arguments are optional. Returns a hash of a roles, either for
14112: co-author/assistant author roles for a user's Construction Space
1.906 albertel 14113: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 14114: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14115: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14116: For each key, value is set to colon-separated start and end times for
14117: the role. If no username and domain are specified, will default to
1.934 raeburn 14118: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 14119: of role statuses (active, future or previous), roles
14120: (e.g., cc,in, st etc.) and domains of the roles which can be used
14121: to restrict the list of roles reported. If no array ref is
14122: provided for types, will default to return only active roles.
1.834 albertel 14123:
1.1195 raeburn 14124: =item *
14125:
14126: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 14127: user: $uname:$udom has a role in the course: $cdom_$cnum.
14128:
14129: Additional optional arguments are: $type (if role checking is to be restricted
14130: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 14131: available roles) or future (roles available in the future), and
14132: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 14133: have active Domain Coordinator role in course's domain or in additional
14134: domains (specified in 'Domains to check for privileged users' in course
14135: environment -- set via: Course Settings -> Classlists and staff listing).
14136:
14137: =item *
14138:
14139: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14140: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14141: $possdomains and $possroles are optional array refs -- to domains to check and
14142: roles to check. If $possdomains is not specified, a dump will be done of the
14143: users' roles.db to check for a dc or su role in any domain. This can be
14144: time consuming if &privileged is called repeatedly (e.g., when displaying a
14145: classlist), so in such cases, supplying a $possdomains array is preferred, as
14146: this then allows &privileged_by_domain() to be used, which caches the identity
14147: of privileged users, eliminating the need for repeated calls to &dump().
14148:
14149: =item *
14150:
14151: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14152: where the outer hash keys are domains specified in the $possdomains array ref,
14153: next inner hash keys are privileged roles specified in the $roles array ref,
14154: and the innermost hash contains key = value pairs for username:domain = end:start
14155: for active or future "privileged" users with that role in that domain. To avoid
14156: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14157: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 14158:
1.243 albertel 14159: =back
14160:
14161: =head2 User Modification
14162:
14163: =over 4
14164:
14165: =item *
14166:
1.957 raeburn 14167: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 14168: user for the level given by URL. Optional start and end dates (leave empty
14169: string or zero for "no date")
1.191 harris41 14170:
14171: =item *
14172:
1.243 albertel 14173: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14174: change a users, password, possible return values are: ok,
14175: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14176: refused
1.191 harris41 14177:
14178: =item *
14179:
1.243 albertel 14180: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 14181:
14182: =item *
14183:
1.1058 raeburn 14184: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14185: $forceid,$desiredhome,$email,$inststatus,$candelete) :
14186:
14187: will update user information (firstname,middlename,lastname,generation,
14188: permanentemail), and if forceid is true, student/employee ID also.
14189: A user's institutional affiliation(s) can also be updated.
14190: User information fields will not be overwritten with empty entries
14191: unless the field is included in the $candelete array reference.
14192: This array is included when a single user is modified via "Manage Users",
14193: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 14194:
14195: =item *
14196:
1.286 matthew 14197: modifystudent
14198:
1.957 raeburn 14199: modify a student's enrollment and identification information.
1.1235 raeburn 14200: The course id is resolved based on the current user's environment.
14201: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 14202: associated with a course.
14203:
1.297 matthew 14204: This call is essentially a wrapper for lonnet::modifyuser and
14205: lonnet::modify_student_enrollment
1.286 matthew 14206:
14207: Inputs:
14208:
14209: =over 4
14210:
1.957 raeburn 14211: =item B<$udom> Student's loncapa domain
1.286 matthew 14212:
1.957 raeburn 14213: =item B<$uname> Student's loncapa login name
1.286 matthew 14214:
1.964 bisitz 14215: =item B<$uid> Student/Employee ID
1.286 matthew 14216:
1.957 raeburn 14217: =item B<$umode> Student's authentication mode
1.286 matthew 14218:
1.957 raeburn 14219: =item B<$upass> Student's password
1.286 matthew 14220:
1.957 raeburn 14221: =item B<$first> Student's first name
1.286 matthew 14222:
1.957 raeburn 14223: =item B<$middle> Student's middle name
1.286 matthew 14224:
1.957 raeburn 14225: =item B<$last> Student's last name
1.286 matthew 14226:
1.957 raeburn 14227: =item B<$gene> Student's generation
1.286 matthew 14228:
1.957 raeburn 14229: =item B<$usec> Student's section in course
1.286 matthew 14230:
14231: =item B<$end> Unix time of the roles expiration
14232:
14233: =item B<$start> Unix time of the roles start date
14234:
14235: =item B<$forceid> If defined, allow $uid to be changed
14236:
14237: =item B<$desiredhome> server to use as home server for student
14238:
1.957 raeburn 14239: =item B<$email> Student's permanent e-mail address
14240:
14241: =item B<$type> Type of enrollment (auto or manual)
14242:
1.963 raeburn 14243: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
14244:
14245: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 14246:
1.963 raeburn 14247: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 14248:
1.963 raeburn 14249: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 14250:
1.1216 raeburn 14251: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14252:
14253: =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 14254:
1.286 matthew 14255: =back
1.297 matthew 14256:
14257: =item *
14258:
14259: modify_student_enrollment
14260:
1.1235 raeburn 14261: Change a student's enrollment status in a class. The environment variable
1.297 matthew 14262: 'role.request.course' must be defined for this function to proceed.
14263:
14264: Inputs:
14265:
14266: =over 4
14267:
1.1235 raeburn 14268: =item $udom, student's domain
1.297 matthew 14269:
1.1235 raeburn 14270: =item $uname, student's name
1.297 matthew 14271:
1.1235 raeburn 14272: =item $uid, student's user id
1.297 matthew 14273:
1.1235 raeburn 14274: =item $first, student's first name
1.297 matthew 14275:
14276: =item $middle
14277:
14278: =item $last
14279:
14280: =item $gene
14281:
14282: =item $usec
14283:
14284: =item $end
14285:
14286: =item $start
14287:
1.957 raeburn 14288: =item $type
14289:
14290: =item $locktype
14291:
14292: =item $cid
14293:
14294: =item $selfenroll
14295:
14296: =item $context
14297:
1.1216 raeburn 14298: =item $credits, number of credits student will earn from this class
14299:
1.1314 raeburn 14300: =item $instsec, institutional course section code for student
14301:
1.297 matthew 14302: =back
14303:
1.191 harris41 14304:
14305: =item *
14306:
1.243 albertel 14307: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14308: custom role; give a custom role to a user for the level given by URL. Specify
14309: name and domain of role author, and role name
1.191 harris41 14310:
14311: =item *
14312:
1.243 albertel 14313: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 14314:
14315: =item *
14316:
1.243 albertel 14317: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14318:
14319: =back
14320:
14321: =head2 Course Infomation
14322:
14323: =over 4
1.191 harris41 14324:
14325: =item *
14326:
1.1118 foxr 14327: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 14328: specified course id, including all environment settings for the
14329: course, the description of the course will be in the hash under the
14330: key 'description'
1.191 harris41 14331:
1.1118 foxr 14332: $options is an optional parameter that if supplied is a hash reference that controls
14333: what how this function works. It has the following key/values:
14334:
14335: =over 4
14336:
14337: =item freshen_cache
14338:
14339: If defined, and the environment cache for the course is valid, it is
14340: returned in the returned hash.
14341:
14342: =item one_time
14343:
14344: If defined, the last cache time is set to _now_
14345:
14346: =item user
14347:
14348: If defined, the supplied username is used instead of the current user.
14349:
14350:
14351: =back
14352:
1.191 harris41 14353: =item *
14354:
1.624 albertel 14355: resdata($name,$domain,$type,@which) : request for current parameter
14356: setting for a specific $type, where $type is either 'course' or 'user',
14357: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 14358: answers for 10 minutes.
1.243 albertel 14359:
1.877 foxr 14360: =item *
14361:
14362: get_courseresdata($courseid, $domain) : dump the entire course resource
14363: data base, returning a hash that is keyed by the resource name and has
14364: values that are the resource value. I believe that the timestamps and
14365: versions are also returned.
14366:
1.1236 raeburn 14367: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14368: supplemental content area. This routine caches the number of files for
14369: 10 minutes.
14370:
1.243 albertel 14371: =back
14372:
14373: =head2 Course Modification
14374:
14375: =over 4
1.191 harris41 14376:
14377: =item *
14378:
1.243 albertel 14379: writecoursepref($courseid,%prefs) : write preferences (environment
14380: database) for a course
1.191 harris41 14381:
14382: =item *
14383:
1.1011 raeburn 14384: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14385:
14386: =item *
14387:
1.1038 raeburn 14388: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 14389:
1.1167 droeschl 14390: =item *
14391:
14392: is_course($courseid), is_course($cdom, $cnum)
14393:
14394: Accepts either a combined $courseid (in the form of domain_courseid) or the
14395: two component version $cdom, $cnum. It checks if the specified course exists.
14396:
14397: Returns:
14398: undef if the course doesn't exist, otherwise
14399: in scalar context the combined courseid.
14400: in list context the two components of the course identifier, domain and
14401: courseid.
14402:
1.243 albertel 14403: =back
14404:
14405: =head2 Resource Subroutines
14406:
14407: =over 4
1.191 harris41 14408:
14409: =item *
14410:
1.243 albertel 14411: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 14412:
14413: =item *
14414:
1.243 albertel 14415: repcopy($filename) : subscribes to the requested file, and attempts to
14416: replicate from the owning library server, Might return
1.607 raeburn 14417: 'unavailable', 'not_found', 'forbidden', 'ok', or
14418: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 14419: resource. Expects the local filesystem pathname
14420: (/home/httpd/html/res/....)
14421:
14422: =back
14423:
14424: =head2 Resource Information
14425:
14426: =over 4
1.191 harris41 14427:
14428: =item *
14429:
1.1228 raeburn 14430: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
14431: and returns the value of a variety of different possible values,
14432: $varname should be a request string, and the other parameters can be
14433: used to specify who and what one is asking about. Ordinarily, $cid
14434: does not need to be specified, as it is retrived from
14435: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14436: within lonuserstate::loadmap() when initializing a course, before
14437: $env{'request.course.id'} has been set, so it needs to be provided
14438: in that one case.
1.243 albertel 14439:
14440: Possible values for $varname are environment.lastname (or other item
14441: from the envirnment hash), user.name (or someother aspect about the
14442: user), resource.0.maxtries (or some other part and parameter of a
14443: resource)
1.204 albertel 14444:
14445: =item *
14446:
1.243 albertel 14447: directcondval($number) : get current value of a condition; reads from a state
14448: string
1.204 albertel 14449:
14450: =item *
14451:
1.243 albertel 14452: condval($condidx) : value of condition index based on state
1.204 albertel 14453:
14454: =item *
14455:
1.243 albertel 14456: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14457: resource's metadata, $what should be either a specific key, or either
14458: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14459: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14460:
14461: this function automatically caches all requests
1.191 harris41 14462:
14463: =item *
14464:
1.243 albertel 14465: metadata_query($query,$custom,$customshow) : make a metadata query against the
14466: network of library servers; returns file handle of where SQL and regex results
14467: will be stored for query
1.191 harris41 14468:
14469: =item *
14470:
1.1282 raeburn 14471: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14472: return symbolic list entry (all arguments optional).
14473:
14474: Args: filename is the filename (including path) for the file for which a symb
14475: is required; donotrecurse, if true will prevent calls to allowed() being made
14476: to check access status if more than one resource was found in the bighash
14477: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14478: a randompick); ignorecachednull, if true will prevent a symb of '' being
14479: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14480: cause possible symbs to be checked to determine if they are subject to content
14481: blocking, if so they will not be included as possible symbs; possibles is a
14482: ref to a hash, which, as a side effect, will be populated with all possible
14483: symbs (content blocking not tested).
14484:
1.243 albertel 14485: returns the data handle
1.191 harris41 14486:
14487: =item *
14488:
1.1190 raeburn 14489: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
14490: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 14491: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 14492: on failure, user must be in a course, as it assumes the existence of
14493: the course initial hash, and uses $env('request.course.id'}. The third
14494: arg is an optional reference to a scalar. If this arg is passed in the
14495: call to symbverify, it will be set to 1 if the symb has been set to be
14496: encrypted; otherwise it will be null.
1.191 harris41 14497:
14498: =item *
14499:
1.243 albertel 14500: symbclean($symb) : removes versions numbers from a symb, returns the
14501: cleaned symb
1.191 harris41 14502:
14503: =item *
14504:
1.243 albertel 14505: is_on_map($uri) : checks if the $uri is somewhere on the current
14506: course map, user must be in a course for it to work.
1.191 harris41 14507:
14508: =item *
14509:
1.243 albertel 14510: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 14511:
14512: =item *
14513:
1.243 albertel 14514: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14515: a random seed, all arguments are optional, if they aren't sent it uses the
14516: environment to derive them. Note: if symb isn't sent and it can't get one
14517: from &symbread it will use the current time as its return value
1.191 harris41 14518:
14519: =item *
14520:
1.243 albertel 14521: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14522: unfakeable, receipt
1.191 harris41 14523:
14524: =item *
14525:
1.620 albertel 14526: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 14527:
14528: =item *
14529:
1.243 albertel 14530: countacc($url) : count the number of accesses to a given URL
1.191 harris41 14531:
14532: =item *
14533:
1.243 albertel 14534: 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 14535:
14536: =item *
14537:
1.243 albertel 14538: 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 14539:
14540: =item *
14541:
1.243 albertel 14542: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 14543:
14544: =item *
14545:
1.243 albertel 14546: devalidate($symb) : devalidate temporary spreadsheet calculations,
14547: forcing spreadsheet to reevaluate the resource scores next time.
14548:
1.1195 raeburn 14549: =item *
14550:
1.1196 raeburn 14551: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14552: when viewing in course context.
1.1195 raeburn 14553:
1.1196 raeburn 14554: input: six args -- filename (decluttered), course number, course domain,
14555: url, symb (if registered) and group (if this is a
14556: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 14557:
1.1196 raeburn 14558: output: array of five scalars --
1.1195 raeburn 14559: $cfile -- url for file editing if editable on current server
14560: $home -- homeserver of resource (i.e., for author if published,
14561: or course if uploaded.).
14562: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 14563: $forceedit -- 1 if icon/link should be to go to edit mode
14564: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 14565:
14566: =item *
14567:
14568: is_course_upload($file,$cnum,$cdom)
14569:
14570: Used in course context to determine if current file was uploaded to
14571: the course (i.e., would be found in /userfiles/docs on the course's
14572: homeserver.
14573:
14574: input: 3 args -- filename (decluttered), course number and course domain.
14575: output: boolean -- 1 if file was uploaded.
14576:
1.243 albertel 14577: =back
14578:
14579: =head2 Storing/Retreiving Data
14580:
14581: =over 4
1.191 harris41 14582:
14583: =item *
14584:
1.1269 raeburn 14585: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14586: permanently for this url; hashref needs to be given and should be a \%hashname;
14587: the remaining args aren't required and if they aren't passed or are '' they will
14588: be derived from the env (with the exception of $laststore, which is an
14589: optional arg used when a user's submission is stored in grading).
14590: $laststore is $version=$timestamp, where $version is the most recent version
14591: number retrieved for the corresponding $symb in the $namespace db file, and
14592: $timestamp is the timestamp for that transaction (UNIX time).
14593: $laststore is currently only passed when cstore() is called by
14594: structuretags::finalize_storage().
1.191 harris41 14595:
14596: =item *
14597:
1.1269 raeburn 14598: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14599: but uses critical subroutine
1.191 harris41 14600:
14601: =item *
14602:
1.243 albertel 14603: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14604: all args are optional
1.191 harris41 14605:
14606: =item *
14607:
1.717 albertel 14608: dumpstore($namespace,$udom,$uname,$regexp,$range) :
14609: dumps the complete (or key matching regexp) namespace into a hash
14610: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14611: normally &store()ed into
14612:
14613: $range should be either an integer '100' (give me the first 100
14614: matching records)
14615: or be two integers sperated by a - with no spaces
14616: '30-50' (give me the 30th through the 50th matching
14617: records)
14618:
14619:
14620: =item *
14621:
1.1269 raeburn 14622: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717 albertel 14623: replaces a &store() version of data with a replacement set of data
14624: for a particular resource in a namespace passed in the $storehash hash
1.1269 raeburn 14625: reference. If $tolog is true, the transaction is logged in the courselog
14626: with an action=PUTSTORE.
1.717 albertel 14627:
14628: =item *
14629:
1.243 albertel 14630: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14631: works very similar to store/cstore, but all data is stored in a
14632: temporary location and can be reset using tmpreset, $storehash should
14633: be a hash reference, returns nothing on success
1.191 harris41 14634:
14635: =item *
14636:
1.243 albertel 14637: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14638: similar to restore, but all data is stored in a temporary location and
14639: can be reset using tmpreset. Returns a hash of values on success,
14640: error string otherwise.
1.191 harris41 14641:
14642: =item *
14643:
1.243 albertel 14644: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14645: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 14646:
14647: =item *
14648:
1.243 albertel 14649: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14650: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 14651:
14652: =item *
14653:
1.243 albertel 14654: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14655: namesp ($udom and $uname are optional)
1.191 harris41 14656:
14657: =item *
14658:
1.702 albertel 14659: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 14660: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 14661: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 14662:
1.702 albertel 14663: $range should be either an integer '100' (give me the first 100
14664: matching records)
14665: or be two integers sperated by a - with no spaces
14666: '30-50' (give me the 30th through the 50th matching
14667: records)
1.449 matthew 14668: =item *
14669:
14670: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14671: $store can be a scalar, an array reference, or if the amount to be
14672: incremented is > 1, a hash reference.
14673:
14674: ($udom and $uname are optional)
1.191 harris41 14675:
14676: =item *
14677:
1.243 albertel 14678: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14679: ($udom and $uname are optional)
1.191 harris41 14680:
14681: =item *
14682:
1.243 albertel 14683: cput($namespace,$storehash,$udom,$uname) : critical put
14684: ($udom and $uname are optional)
1.191 harris41 14685:
14686: =item *
14687:
1.748 albertel 14688: newput($namespace,$storehash,$udom,$uname) :
14689:
14690: Attempts to store the items in the $storehash, but only if they don't
14691: currently exist, if this succeeds you can be certain that you have
14692: successfully created a new key value pair in the $namespace db.
14693:
14694:
14695: Args:
14696: $namespace: name of database to store values to
14697: $storehash: hashref to store to the db
14698: $udom: (optional) domain of user containing the db
14699: $uname: (optional) name of user caontaining the db
14700:
14701: Returns:
14702: 'ok' -> succeeded in storing all keys of $storehash
14703: 'key_exists: <key>' -> failed to anything out of $storehash, as at
14704: least <key> already existed in the db (other
14705: requested keys may also already exist)
1.967 bisitz 14706: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 14707: 'con_lost' -> unable to contact request server
14708: 'refused' -> action was not allowed by remote machine
14709:
14710:
14711: =item *
14712:
1.243 albertel 14713: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14714: reference filled in from namesp (encrypts the return communication)
14715: ($udom and $uname are optional)
1.191 harris41 14716:
14717: =item *
14718:
1.243 albertel 14719: log($udom,$name,$home,$message) : write to permanent log for user; use
14720: critical subroutine
14721:
1.806 raeburn 14722: =item *
14723:
1.860 raeburn 14724: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14725: array reference filled in from namespace found in domain level on either
14726: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 14727:
14728: =item *
14729:
1.860 raeburn 14730: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
14731: domain level either on specified domain server ($uhome) or primary domain
14732: server ($udom and $uhome are optional)
1.806 raeburn 14733:
1.943 raeburn 14734: =item *
14735:
1.1240 raeburn 14736: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
14737: for: authentication, language, quotas, timezone, date locale, and portal URL in
14738: the target domain.
14739:
14740: May also include additional key => value pairs for the following groups:
14741:
14742: =over
14743:
14744: =item
14745: disk quotas (MB allocated by default to portfolios and authoring spaces).
14746:
14747: =over
14748:
14749: =item defaultquota, authorquota
14750:
14751: =back
14752:
14753: =item
14754: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14755: portfolio for users).
14756:
14757: =over
14758:
14759: =item
14760: aboutme, blog, webdav, portfolio
14761:
14762: =back
14763:
14764: =item
14765: requestcourses: ability to request courses, and how requests are processed.
14766:
14767: =over
14768:
14769: =item
1.1305 raeburn 14770: official, unofficial, community, textbook, placement
1.1240 raeburn 14771:
14772: =back
14773:
14774: =item
14775: inststatus: types of institutional affiliation, and order in which they are displayed.
14776:
14777: =over
14778:
14779: =item
1.1256 raeburn 14780: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 14781:
14782: =back
14783:
14784: =item
14785: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14786: for course's uploaded content.
14787:
14788: =over
14789:
14790: =item
1.1246 raeburn 14791: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
1.1305 raeburn 14792: communityquota, textbookquota, placementquota
1.1240 raeburn 14793:
14794: =back
14795:
14796: =item
14797: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
14798: on your servers.
14799:
14800: =over
14801:
14802: =item
14803: remotesessions, hostedsessions
14804:
14805: =back
14806:
14807: =back
14808:
14809: In cases where a domain coordinator has never used the "Set Domain Configuration"
14810: utility to create a configuration.db file on a domain's primary library server
14811: only the following domain defaults: auth_def, auth_arg_def, lang_def
14812: -- corresponding values are authentication type (internal, krb4, krb5,
14813: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
14814: will be available. Values are retrieved from cache (if current), unless the
14815: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14816: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14817:
14818: Typical usage:
1.943 raeburn 14819:
1.1240 raeburn 14820: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 14821:
1.243 albertel 14822: =back
14823:
14824: =head2 Network Status Functions
14825:
14826: =over 4
1.191 harris41 14827:
14828: =item *
14829:
1.1137 raeburn 14830: dirlist() : return directory list based on URI (first arg).
14831:
14832: Inputs: 1 required, 5 optional.
14833:
14834: =over
14835:
14836: =item
14837: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14838:
14839: =item
14840: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
14841:
14842: =item
14843: $username - username of user/course to be listed. Extracted from $uri if absent.
14844:
14845: =item
14846: $getpropath - boolean: 1 if prepend path using &propath().
14847:
14848: =item
14849: $getuserdir - boolean: 1 if prepend path for "userfiles".
14850:
14851: =item
14852: $alternateRoot - path to prepend in place of path from $uri.
14853:
14854: =back
14855:
14856: Returns: Array of up to two items.
14857:
14858: =over
14859:
14860: a reference to an array of files/subdirectories
14861:
14862: =over
14863:
14864: Each element in the array of files/subdirectories is a & separated list of
14865: item name and the result of running stat on the item. If dirlist was requested
14866: for a file instead of a directory, the item name will be ''. For a directory
14867: listing, if the item is a metadata file, the element will end &N&M
14868: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14869: default copyright set (1).
14870:
14871: =back
14872:
14873: a scalar containing error condition (if encountered).
14874:
14875: =over
14876:
14877: =item
14878: no_host (no homeserver identified for $username:$domain).
14879:
14880: =item
14881: no_such_host (server contacted for listing not identified as valid host).
14882:
14883: =item
14884: con_lost (connection to remote server failed).
14885:
14886: =item
14887: refused (invalid $username:$domain received on lond side).
14888:
14889: =item
14890: no_such_dir (directory at specified path on lond side does not exist).
14891:
14892: =item
14893: empty (directory at specified path on lond side is empty).
14894:
14895: =over
14896:
14897: This is currently not encountered because the &ls3, &ls2,
14898: &ls (_handler) routines on the lond side do not filter out
14899: . and .. from a directory listing.
14900:
14901: =back
14902:
14903: =back
14904:
14905: =back
1.191 harris41 14906:
14907: =item *
14908:
1.243 albertel 14909: spareserver() : find server with least workload from spare.tab
14910:
1.986 foxr 14911:
14912: =item *
14913:
14914: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14915: if there is no corresponding loncapa host.
14916:
1.243 albertel 14917: =back
14918:
1.986 foxr 14919:
1.243 albertel 14920: =head2 Apache Request
14921:
14922: =over 4
1.191 harris41 14923:
14924: =item *
14925:
1.243 albertel 14926: ssi($url,%hash) : server side include, does a complete request cycle on url to
14927: localhost, posts hash
14928:
14929: =back
14930:
14931: =head2 Data to String to Data
14932:
14933: =over 4
1.191 harris41 14934:
14935: =item *
14936:
1.243 albertel 14937: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14938: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 14939:
14940: =item *
14941:
1.243 albertel 14942: hashref2str($hashref) : convert a hashref into a string complete with
14943: escaping and '=' and '&' separators, supports elements that are
14944: arrayrefs and hashrefs
1.191 harris41 14945:
14946: =item *
14947:
1.243 albertel 14948: arrayref2str($arrayref) : convert an arrayref into a string complete
14949: with escaping and '&' separators, supports elements that are arrayrefs
14950: and hashrefs
1.191 harris41 14951:
14952: =item *
14953:
1.243 albertel 14954: str2hash($string) : convert string to hash using unescaping and
14955: splitting on '=' and '&', supports elements that are arrayrefs and
14956: hashrefs
1.191 harris41 14957:
14958: =item *
14959:
1.243 albertel 14960: str2array($string) : convert string to hash using unescaping and
14961: splitting on '&', supports elements that are arrayrefs and hashrefs
14962:
14963: =back
14964:
14965: =head2 Logging Routines
14966:
14967:
14968: These routines allow one to make log messages in the lonnet.log and
14969: lonnet.perm logfiles.
1.191 harris41 14970:
1.1119 foxr 14971: =over 4
14972:
1.191 harris41 14973: =item *
14974:
1.243 albertel 14975: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 14976:
14977: =item *
14978:
1.243 albertel 14979: logthis() : append message to the normal lonnet.log file, it gets
14980: preiodically rolled over and deleted.
1.191 harris41 14981:
14982: =item *
14983:
1.243 albertel 14984: logperm() : append a permanent message to lonnet.perm.log, this log
14985: file never gets deleted by any automated portion of the system, only
14986: messages of critical importance should go in here.
14987:
1.1119 foxr 14988:
1.243 albertel 14989: =back
14990:
14991: =head2 General File Helper Routines
14992:
14993: =over 4
1.191 harris41 14994:
14995: =item *
14996:
1.481 raeburn 14997: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14998: (a) files in /uploaded
14999: (i) If a local copy of the file exists -
15000: compares modification date of local copy with last-modified date for
15001: definitive version stored on home server for course. If local copy is
15002: stale, requests a new version from the home server and stores it.
15003: If the original has been removed from the home server, then local copy
15004: is unlinked.
15005: (ii) If local copy does not exist -
15006: requests the file from the home server and stores it.
15007:
15008: If $caller is 'uploadrep':
15009: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15010: for request for files originally uploaded via DOCS.
15011: - returns 'ok' if fresh local copy now available, -1 otherwise.
15012:
15013: Otherwise:
15014: This indicates a call from the content generation phase of the request.
15015: - returns the entire contents of the file or -1.
15016:
15017: (b) files in /res
15018: - returns the entire contents of a file or -1;
15019: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 15020:
1.712 albertel 15021:
15022: =item *
15023:
15024: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15025: reference
15026:
15027: returns either a stat() list of data about the file or an empty list
15028: if the file doesn't exist or couldn't find out about it (connection
15029: problems or user unknown)
15030:
1.191 harris41 15031: =item *
15032:
1.243 albertel 15033: filelocation($dir,$file) : returns file system location of a file
15034: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15035: directory that relative $file lookups are to looked in ($dir of /a/dir
15036: and a file of ../bob will become /a/bob)
1.191 harris41 15037:
15038: =item *
15039:
15040: hreflocation($dir,$file) : returns file system location or a URL; same as
15041: filelocation except for hrefs
15042:
15043: =item *
15044:
1.1261 raeburn 15045: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15046: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191 harris41 15047:
1.243 albertel 15048: =back
15049:
1.608 albertel 15050: =head2 Usererfile file routines (/uploaded*)
15051:
15052: =over 4
15053:
15054: =item *
15055:
15056: userfileupload(): main rotine for putting a file in a user or course's
15057: filespace, arguments are,
15058:
1.620 albertel 15059: formname - required - this is the name of the element in $env where the
1.608 albertel 15060: filename, and the contents of the file to create/modifed exist
1.620 albertel 15061: the filename is in $env{'form.'.$formname.'.filename'} and the
15062: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 15063: context - if coursedoc, store the file in the course of the active role
15064: of the current user;
15065: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15066: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 15067: subdir - required - subdirectory to put the file in under ../userfiles/
15068: if undefined, it will be placed in "unknown"
15069:
15070: (This routine calls clean_filename() to remove any dangerous
15071: characters from the filename, and then calls finuserfileupload() to
15072: complete the transaction)
15073:
15074: returns either the url of the uploaded file (/uploaded/....) if successful
15075: and /adm/notfound.html if unsuccessful
15076:
15077: =item *
15078:
15079: clean_filename(): routine for cleaing a filename up for storage in
15080: userfile space, argument is:
15081:
15082: filename - proposed filename
15083:
15084: returns: the new clean filename
15085:
15086: =item *
15087:
1.1090 raeburn 15088: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 15089: userspace, probably shouldn't be called directly
15090:
15091: docuname: username or courseid of destination for the file
15092: docudom: domain of user/course of destination for the file
15093: formname: same as for userfileupload()
1.1090 raeburn 15094: fname: filename (including subdirectories) for the file
15095: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15096: allfiles: reference to hash used to store objects found by parser
15097: codebase: reference to hash used for codebases of java objects found by parser
15098: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15099: thumbheight: height (pixels) of thumbnail to be created for uploaded image
15100: resizewidth: width to be used to resize image using resizeImage from ImageMagick
15101: resizeheight: height to be used to resize image using resizeImage from ImageMagick
15102: context: if 'overwrite', will move the uploaded file from its temporary location to
15103: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 15104: mimetype: reference to scalar to accommodate mime type determined
15105: from File::MMagic if $parser = parse.
1.608 albertel 15106:
15107: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 15108: and /adm/notfound.html if unsuccessful (or an error message if context
15109: was 'overwrite').
15110:
1.608 albertel 15111:
15112: =item *
15113:
15114: renameuserfile(): renames an existing userfile to a new name
15115:
15116: Args:
15117: docuname: username or courseid of destination for the file
15118: docudom: domain of user/course of destination for the file
15119: old: current file name (including any subdirs under userfiles)
15120: new: desired file name (including any subdirs under userfiles)
15121:
15122: =item *
15123:
15124: mkdiruserfile(): creates a directory is a userfiles dir
15125:
15126: Args:
15127: docuname: username or courseid of destination for the file
15128: docudom: domain of user/course of destination for the file
15129: dir: dir to create (including any subdirs under userfiles)
15130:
15131: =item *
15132:
15133: removeuserfile(): removes a file that exists in userfiles
15134:
15135: Args:
15136: docuname: username or courseid of destination for the file
15137: docudom: domain of user/course of destination for the file
15138: fname: filname to delete (including any subdirs under userfiles)
15139:
15140: =item *
15141:
15142: removeuploadedurl(): convience function for removeuserfile()
15143:
15144: Args:
15145: url: a full /uploaded/... url to delete
15146:
1.747 albertel 15147: =item *
15148:
15149: get_portfile_permissions():
15150: Args:
15151: domain: domain of user or course contain the portfolio files
15152: user: name of user or num of course contain the portfolio files
15153: Returns:
15154: hashref of a dump of the proper file_permissions.db
15155:
15156:
15157: =item *
15158:
15159: get_access_controls():
15160:
15161: Args:
15162: current_permissions: the hash ref returned from get_portfile_permissions()
15163: group: (optional) the group you want the files associated with
15164: file: (optional) the file you want access info on
15165:
15166: Returns:
1.749 raeburn 15167: a hash (keys are file names) of hashes containing
15168: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15169: values are XML containing access control settings (see below)
1.747 albertel 15170:
15171: Internal notes:
15172:
1.749 raeburn 15173: access controls are stored in file_permissions.db as key=value pairs.
15174: key -> path to file/file_name\0uniqueID:scope_end_start
15175: where scope -> public,guest,course,group,domains or users.
15176: end -> UNIX time for end of access (0 -> no end date)
15177: start -> UNIX time for start of access
15178:
15179: value -> XML description of access control
15180: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15181: <start></start>
15182: <end></end>
15183:
15184: <password></password> for scope type = guest
15185:
15186: <domain></domain> for scope type = course or group
15187: <number></number>
15188: <roles id="">
15189: <role></role>
15190: <access></access>
15191: <section></section>
15192: <group></group>
15193: </roles>
15194:
15195: <dom></dom> for scope type = domains
15196:
15197: <users> for scope type = users
15198: <user>
15199: <uname></uname>
15200: <udom></udom>
15201: </user>
15202: </users>
15203: </scope>
15204:
15205: Access data is also aggregated for each file in an additional key=value pair:
15206: key -> path to file/file_name\0accesscontrol
15207: value -> reference to hash
15208: hash contains key = value pairs
15209: where key = uniqueID:scope_end_start
15210: value = UNIX time record was last updated
15211:
15212: Used to improve speed of look-ups of access controls for each file.
15213:
15214: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15215:
1.1198 raeburn 15216: =item *
15217:
1.749 raeburn 15218: modify_access_controls():
15219:
15220: Modifies access controls for a portfolio file
15221: Args
15222: 1. file name
15223: 2. reference to hash of required changes,
15224: 3. domain
15225: 4. username
15226: where domain,username are the domain of the portfolio owner
15227: (either a user or a course)
15228:
15229: Returns:
15230: 1. result of additions or updates ('ok' or 'error', with error message).
15231: 2. result of deletions ('ok' or 'error', with error message).
15232: 3. reference to hash of any new or updated access controls.
15233: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15234: key = integer (inbound ID)
1.1198 raeburn 15235: value = uniqueID
15236:
15237: =item *
15238:
15239: get_timebased_id():
15240:
15241: Attempts to get a unique timestamp-based suffix for use with items added to a
15242: course via the Course Editor (e.g., folders, composite pages,
15243: group bulletin boards).
15244:
15245: Args: (first three required; six others optional)
15246:
15247: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15248: docssequence, or name of group
15249:
15250: 2. keyid (alphanumeric): name of temporary locking key in hash,
15251: e.g., num, boardids
15252:
15253: 3. namespace: name of gdbm file used to store suffixes already assigned;
15254: file will be named nohist_namespace.db
15255:
15256: 4. cdom: domain of course; default is current course domain from %env
15257:
15258: 5. cnum: course number; default is current course number from %env
15259:
15260: 6. idtype: set to concat if an additional digit is to be appended to the
15261: unix timestamp to form the suffix, if the plain timestamp is already
15262: in use. Default is to not do this, but simply increment the unix
15263: timestamp by 1 until a unique key is obtained.
15264:
15265: 7. who: holder of locking key; defaults to user:domain for user.
15266:
15267: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15268: retrying); default is 3.
15269:
15270: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15271:
15272: Returns:
15273:
15274: 1. suffix obtained (numeric)
15275:
15276: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15277:
15278: 3. error: contains (localized) error message if an error occurred.
15279:
1.747 albertel 15280:
1.608 albertel 15281: =back
15282:
1.243 albertel 15283: =head2 HTTP Helper Routines
15284:
15285: =over 4
15286:
1.191 harris41 15287: =item *
15288:
15289: escape() : unpack non-word characters into CGI-compatible hex codes
15290:
15291: =item *
15292:
15293: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15294:
1.243 albertel 15295: =back
15296:
15297: =head1 PRIVATE SUBROUTINES
15298:
15299: =head2 Underlying communication routines (Shouldn't call)
15300:
15301: =over 4
15302:
15303: =item *
15304:
15305: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15306:
15307: =item *
15308:
15309: reply() : uses subreply to send a message to remote machine, logs all failures
15310:
15311: =item *
15312:
15313: critical() : passes a critical message to another server; if cannot
15314: get through then place message in connection buffer directory and
15315: returns con_delayed, if incapable of saving message, returns
15316: con_failed
15317:
15318: =item *
15319:
15320: reconlonc() : tries to reconnect lonc client processes.
15321:
15322: =back
15323:
15324: =head2 Resource Access Logging
15325:
15326: =over 4
15327:
15328: =item *
15329:
15330: flushcourselogs() : flush (save) buffer logs and access logs
15331:
15332: =item *
15333:
15334: courselog($what) : save message for course in hash
15335:
15336: =item *
15337:
15338: courseacclog($what) : save message for course using &courselog(). Perform
15339: special processing for specific resource types (problems, exams, quizzes, etc).
15340:
1.191 harris41 15341: =item *
15342:
15343: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15344: as a PerlChildExitHandler
1.243 albertel 15345:
15346: =back
15347:
15348: =head2 Other
15349:
15350: =over 4
15351:
15352: =item *
15353:
15354: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 15355:
15356: =back
15357:
15358: =cut
1.877 foxr 15359:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>