Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1244
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1244 ! raeburn 4: # $Id: lonnet.pm,v 1.1243 2013/10/14 17:14:48 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.1213 raeburn 81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $apache
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.539 albertel 95: use Time::HiRes qw( 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.550 foxr 108: my $max_connection_retries = 10; # 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.993 raeburn 232: sub get_server_loncaparev {
1.1073 raeburn 233: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 234: if (defined($lonhost)) {
235: if (!defined(&hostname($lonhost))) {
236: undef($lonhost);
237: }
238: }
239: if (!defined($lonhost)) {
240: if (defined(&domain($dom,'primary'))) {
241: $lonhost=&domain($dom,'primary');
242: if ($lonhost eq 'no_host') {
243: undef($lonhost);
244: }
245: }
246: }
247: if (defined($lonhost)) {
1.1073 raeburn 248: my $cachetime = 12*3600;
249: if (!$ignore_cache) {
250: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
251: if (defined($cached)) {
252: return $loncaparev;
253: }
254: }
255: my ($answer,$loncaparev);
256: my @ids=¤t_machine_ids();
257: if (grep(/^\Q$lonhost\E$/,@ids)) {
258: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 259: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 260: $loncaparev = $1;
261: }
262: } else {
263: $answer = &reply('serverloncaparev',$lonhost);
264: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
265: if ($caller eq 'loncron') {
266: my $ua=new LWP::UserAgent;
1.1082 raeburn 267: $ua->timeout(4);
1.1073 raeburn 268: my $protocol = $protocol{$lonhost};
269: $protocol = 'http' if ($protocol ne 'https');
270: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
271: my $request=new HTTP::Request('GET',$url);
272: my $response=$ua->request($request);
273: unless ($response->is_error()) {
274: my $content = $response->content;
1.1081 raeburn 275: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 276: $loncaparev = $1;
277: }
278: }
279: } else {
280: $loncaparev = $loncaparevs{$lonhost};
281: }
1.1081 raeburn 282: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 283: $loncaparev = $1;
284: }
1.993 raeburn 285: }
1.1073 raeburn 286: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 287: }
288: }
289:
1.1074 raeburn 290: sub get_server_homeID {
291: my ($hostname,$ignore_cache,$caller) = @_;
292: unless ($ignore_cache) {
293: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
294: if (defined($cached)) {
295: return $serverhomeID;
296: }
297: }
298: my $cachetime = 12*3600;
299: my $serverhomeID;
300: if ($caller eq 'loncron') {
301: my @machine_ids = &machine_ids($hostname);
302: foreach my $id (@machine_ids) {
303: my $response = &reply('serverhomeID',$id);
304: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
305: $serverhomeID = $response;
306: last;
307: }
308: }
309: if ($serverhomeID eq '') {
310: $serverhomeID = $machine_ids[-1];
311: }
312: } else {
313: $serverhomeID = $serverhomeIDs{$hostname};
314: }
315: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
316: }
317:
1.1121 raeburn 318: sub get_remote_globals {
319: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 320: my ($result,%returnhash,%whatneeded);
321: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 322: foreach my $what (sort(keys(%{$whathash}))) {
323: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 324: my ($response,$cached);
1.1121 raeburn 325: unless ($ignore_cache) {
1.1125 raeburn 326: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 327: }
328: if (defined($cached)) {
1.1125 raeburn 329: $returnhash{$what} = $response;
1.1121 raeburn 330: } else {
1.1125 raeburn 331: $whatneeded{$what} = 1;
1.1121 raeburn 332: }
333: }
1.1125 raeburn 334: if (keys(%whatneeded) == 0) {
335: $result = 'ok';
336: } else {
1.1121 raeburn 337: my $requested = &freeze_escape(\%whatneeded);
338: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 339: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
340: ($rep eq 'unknown_cmd')) {
341: $result = $rep;
342: } else {
343: $result = 'ok';
1.1121 raeburn 344: my @pairs=split(/\&/,$rep);
1.1125 raeburn 345: foreach my $item (@pairs) {
346: my ($key,$value)=split(/=/,$item,2);
347: my $what = &unescape($key);
348: my $hashid = $lonhost.'-'.$what;
349: $returnhash{$what}=&thaw_unescape($value);
350: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 351: }
352: }
353: }
354: }
1.1125 raeburn 355: return ($result,\%returnhash);
1.1121 raeburn 356: }
357:
1.1124 raeburn 358: sub remote_devalidate_cache {
1.1241 raeburn 359: my ($lonhost,$cachekeys) = @_;
360: my $items;
361: return unless (ref($cachekeys) eq 'ARRAY');
362: my $cachestr = join('&',@{$cachekeys});
363: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124 raeburn 364: return $response;
365: }
366:
1.1 albertel 367: # -------------------------------------------------- Non-critical communication
368: sub subreply {
369: my ($cmd,$server)=@_;
1.838 albertel 370: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 371: #
372: # With loncnew process trimming, there's a timing hole between lonc server
373: # process exit and the master server picking up the listen on the AF_UNIX
374: # socket. In that time interval, a lock file will exist:
375:
376: my $lockfile=$peerfile.".lock";
377: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
378: sleep(1);
379: }
380: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 381: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 382: #
1.550 foxr 383: # We'll give the connection a few tries before abandoning it. If
384: # connection is not possible, we'll con_lost back to the client.
385: #
386: my $client;
387: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
388: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
389: Type => SOCK_STREAM,
390: Timeout => 10);
1.869 albertel 391: if ($client) {
1.550 foxr 392: last; # Connected!
1.850 albertel 393: } else {
1.853 albertel 394: &create_connection(&hostname($server),$server);
1.550 foxr 395: }
1.850 albertel 396: sleep(1); # Try again later if failed connection.
1.550 foxr 397: }
398: my $answer;
399: if ($client) {
1.704 albertel 400: print $client "sethost:$server:$cmd\n";
1.550 foxr 401: $answer=<$client>;
402: if (!$answer) { $answer="con_lost"; }
403: chomp($answer);
404: } else {
405: $answer = 'con_lost'; # Failed connection.
406: }
1.1 albertel 407: return $answer;
408: }
409:
410: sub reply {
411: my ($cmd,$server)=@_;
1.838 albertel 412: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 413: my $answer=subreply($cmd,$server);
1.65 www 414: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 415: &logthis("<font color=\"blue\">WARNING:".
1.12 www 416: " $cmd to $server returned $answer</font>");
417: }
1.1 albertel 418: return $answer;
419: }
420:
421: # ----------------------------------------------------------- Send USR1 to lonc
422:
423: sub reconlonc {
1.891 albertel 424: my ($lonid) = @_;
425: my $hostname = &hostname($lonid);
426: if ($lonid) {
427: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
428: if ($hostname && -e $peerfile) {
429: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
430: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
431: Type => SOCK_STREAM,
432: Timeout => 10);
433: if ($client) {
434: print $client ("reset_retries\n");
435: my $answer=<$client>;
436: #reset just this one.
437: }
438: }
439: return;
440: }
441:
1.836 www 442: &logthis("Trying to reconnect lonc");
1.1 albertel 443: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 444: if (open(my $fh,"<$loncfile")) {
1.1 albertel 445: my $loncpid=<$fh>;
446: chomp($loncpid);
447: if (kill 0 => $loncpid) {
448: &logthis("lonc at pid $loncpid responding, sending USR1");
449: kill USR1 => $loncpid;
450: sleep 1;
1.836 www 451: } else {
1.12 www 452: &logthis(
1.672 albertel 453: "<font color=\"blue\">WARNING:".
1.12 www 454: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 455: }
456: } else {
1.836 www 457: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 458: }
459: }
460:
461: # ------------------------------------------------------ Critical communication
1.12 www 462:
1.1 albertel 463: sub critical {
464: my ($cmd,$server)=@_;
1.838 albertel 465: unless (&hostname($server)) {
1.672 albertel 466: &logthis("<font color=\"blue\">WARNING:".
1.89 www 467: " Critical message to unknown server ($server)</font>");
468: return 'no_such_host';
469: }
1.1 albertel 470: my $answer=reply($cmd,$server);
471: if ($answer eq 'con_lost') {
472: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 473: my $answer=reply($cmd,$server);
1.1 albertel 474: if ($answer eq 'con_lost') {
475: my $now=time;
476: my $middlename=$cmd;
1.5 www 477: $middlename=substr($middlename,0,16);
1.1 albertel 478: $middlename=~s/\W//g;
479: my $dfilename=
1.305 www 480: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
481: $dumpcount++;
1.1 albertel 482: {
1.448 albertel 483: my $dfh;
484: if (open($dfh,">$dfilename")) {
485: print $dfh "$cmd\n";
486: close($dfh);
487: }
1.1 albertel 488: }
489: sleep 2;
490: my $wcmd='';
491: {
1.448 albertel 492: my $dfh;
493: if (open($dfh,"<$dfilename")) {
494: $wcmd=<$dfh>;
495: close($dfh);
496: }
1.1 albertel 497: }
498: chomp($wcmd);
1.7 www 499: if ($wcmd eq $cmd) {
1.672 albertel 500: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 501: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 502: &logperm("D:$server:$cmd");
503: return 'con_delayed';
504: } else {
1.672 albertel 505: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 506: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 507: &logperm("F:$server:$cmd");
508: return 'con_failed';
509: }
510: }
511: }
512: return $answer;
1.405 albertel 513: }
514:
1.755 albertel 515: # ------------------------------------------- check if return value is an error
516:
517: sub error {
518: my ($result) = @_;
1.756 albertel 519: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 520: if ($2 == 2) { return undef; }
521: return $1;
522: }
523: return undef;
524: }
525:
1.783 albertel 526: sub convert_and_load_session_env {
527: my ($lonidsdir,$handle)=@_;
528: my @profile;
529: {
1.917 albertel 530: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
531: if (!$opened) {
1.915 albertel 532: return 0;
533: }
1.783 albertel 534: flock($idf,LOCK_SH);
535: @profile=<$idf>;
536: close($idf);
537: }
538: my %temp_env;
539: foreach my $line (@profile) {
1.786 albertel 540: if ($line !~ m/=/) {
541: return 0;
542: }
1.783 albertel 543: chomp($line);
544: my ($envname,$envvalue)=split(/=/,$line,2);
545: $temp_env{&unescape($envname)} = &unescape($envvalue);
546: }
547: unlink("$lonidsdir/$handle.id");
548: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
549: 0640)) {
550: %disk_env = %temp_env;
551: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
552: untie(%disk_env);
553: }
1.786 albertel 554: return 1;
1.783 albertel 555: }
556:
1.374 www 557: # ------------------------------------------- Transfer profile into environment
1.780 albertel 558: my $env_loaded;
559: sub transfer_profile_to_env {
1.788 albertel 560: my ($lonidsdir,$handle,$force_transfer) = @_;
561: if (!$force_transfer && $env_loaded) { return; }
1.374 www 562:
1.720 albertel 563: if (!defined($lonidsdir)) {
564: $lonidsdir = $perlvar{'lonIDsDir'};
565: }
566: if (!defined($handle)) {
567: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
568: }
569:
1.786 albertel 570: my $convert;
571: {
1.917 albertel 572: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
573: if (!$opened) {
1.915 albertel 574: return;
575: }
1.786 albertel 576: flock($idf,LOCK_SH);
577: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
578: &GDBM_READER(),0640)) {
579: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
580: untie(%disk_env);
581: } else {
582: $convert = 1;
583: }
584: }
585: if ($convert) {
586: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
587: &logthis("Failed to load session, or convert session.");
588: }
1.374 www 589: }
1.783 albertel 590:
1.786 albertel 591: my %remove;
1.783 albertel 592: while ( my $envname = each(%env) ) {
1.433 matthew 593: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
594: if ($time < time-300) {
1.783 albertel 595: $remove{$key}++;
1.433 matthew 596: }
597: }
598: }
1.783 albertel 599:
1.619 albertel 600: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 601: $env_loaded=1;
1.783 albertel 602: foreach my $expired_key (keys(%remove)) {
1.433 matthew 603: &delenv($expired_key);
1.374 www 604: }
1.1 albertel 605: }
606:
1.916 albertel 607: # ---------------------------------------------------- Check for valid session
608: sub check_for_valid_session {
1.1244 ! raeburn 609: my ($r,$name,$userref) = @_;
1.916 albertel 610: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 611: if ($name eq '') {
612: $name = 'lonID';
613: }
614: my $lonid=$cookies{$name};
1.916 albertel 615: return undef if (!$lonid);
616:
617: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 618: my $lonidsdir;
619: if ($name eq 'lonDAV') {
620: $lonidsdir=$r->dir_config('lonDAVsessDir');
621: } else {
622: $lonidsdir=$r->dir_config('lonIDsDir');
623: }
1.916 albertel 624: return undef if (!-e "$lonidsdir/$handle.id");
625:
1.917 albertel 626: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
627: return undef if (!$opened);
1.916 albertel 628:
629: flock($idf,LOCK_SH);
630: my %disk_env;
631: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
632: &GDBM_READER(),0640)) {
633: return undef;
634: }
635:
636: if (!defined($disk_env{'user.name'})
637: || !defined($disk_env{'user.domain'})) {
638: return undef;
639: }
1.1244 ! raeburn 640: if ($apache >= 2.4) {
! 641: if ($r->user() eq '') {
! 642: if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
! 643: $r->user($disk_env{'user.name'});
! 644: } else {
! 645: $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
! 646: }
! 647: }
! 648: if (($r->user() ne '') && (ref($userref))) {
! 649: $$userref = $r->user();
1.1212 raeburn 650: }
651: }
1.916 albertel 652: return $handle;
653: }
654:
1.830 albertel 655: sub timed_flock {
656: my ($file,$lock_type) = @_;
657: my $failed=0;
658: eval {
659: local $SIG{__DIE__}='DEFAULT';
660: local $SIG{ALRM}=sub {
661: $failed=1;
662: die("failed lock");
663: };
664: alarm(13);
665: flock($file,$lock_type);
666: alarm(0);
667: };
668: if ($failed) {
669: return undef;
670: } else {
671: return 1;
672: }
673: }
674:
1.5 www 675: # ---------------------------------------------------------- Append Environment
676:
677: sub appenv {
1.949 raeburn 678: my ($newenv,$roles) = @_;
679: if (ref($newenv) eq 'HASH') {
680: foreach my $key (keys(%{$newenv})) {
681: my $refused = 0;
682: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
683: $refused = 1;
684: if (ref($roles) eq 'ARRAY') {
685: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
686: if (grep(/^\Q$role\E$/,@{$roles})) {
687: $refused = 0;
688: }
689: }
690: }
691: if ($refused) {
692: &logthis("<font color=\"blue\">WARNING: ".
693: "Attempt to modify environment ".$key." to ".$newenv->{$key}
694: .'</font>');
695: delete($newenv->{$key});
696: } else {
697: $env{$key}=$newenv->{$key};
698: }
699: }
700: my $opened = open(my $env_file,'+<',$env{'user.environment'});
701: if ($opened
702: && &timed_flock($env_file,LOCK_EX)
703: &&
704: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
705: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
706: while (my ($key,$value) = each(%{$newenv})) {
707: $disk_env{$key} = $value;
708: }
709: untie(%disk_env);
1.35 www 710: }
1.191 harris41 711: }
1.56 www 712: return 'ok';
713: }
714: # ----------------------------------------------------- Delete from Environment
715:
716: sub delenv {
1.1104 raeburn 717: my ($delthis,$regexp,$roles) = @_;
718: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
719: my $refused = 1;
720: if (ref($roles) eq 'ARRAY') {
721: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
722: if (grep(/^\Q$role\E$/,@{$roles})) {
723: $refused = 0;
724: }
725: }
726: if ($refused) {
727: &logthis("<font color=\"blue\">WARNING: ".
728: "Attempt to delete from environment ".$delthis);
729: return 'error';
730: }
1.56 www 731: }
1.917 albertel 732: my $opened = open(my $env_file,'+<',$env{'user.environment'});
733: if ($opened
1.915 albertel 734: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 735: &&
736: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
737: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 738: foreach my $key (keys(%disk_env)) {
1.987 raeburn 739: if ($regexp) {
740: if ($key=~/^$delthis/) {
741: delete($env{$key});
742: delete($disk_env{$key});
743: }
744: } else {
745: if ($key=~/^\Q$delthis\E/) {
746: delete($env{$key});
747: delete($disk_env{$key});
748: }
749: }
1.448 albertel 750: }
1.783 albertel 751: untie(%disk_env);
1.5 www 752: }
753: return 'ok';
1.369 albertel 754: }
755:
1.790 albertel 756: sub get_env_multiple {
757: my ($name) = @_;
758: my @values;
759: if (defined($env{$name})) {
760: # exists is it an array
761: if (ref($env{$name})) {
762: @values=@{ $env{$name} };
763: } else {
764: $values[0]=$env{$name};
765: }
766: }
767: return(@values);
768: }
769:
1.958 www 770: # ------------------------------------------------------------------- Locking
771:
772: sub set_lock {
773: my ($text)=@_;
774: $locknum++;
775: my $id=$$.'-'.$locknum;
776: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
777: 'session.lock.'.$id => $text});
778: return $id;
779: }
780:
781: sub get_locks {
782: my $num=0;
783: my %texts=();
784: foreach my $lock (split(/\,/,$env{'session.locks'})) {
785: if ($lock=~/\w/) {
786: $num++;
787: $texts{$lock}=$env{'session.lock.'.$lock};
788: }
789: }
790: return ($num,%texts);
791: }
792:
793: sub remove_lock {
794: my ($id)=@_;
795: my $newlocks='';
796: foreach my $lock (split(/\,/,$env{'session.locks'})) {
797: if (($lock=~/\w/) && ($lock ne $id)) {
798: $newlocks.=','.$lock;
799: }
800: }
801: &appenv({'session.locks' => $newlocks});
802: &delenv('session.lock.'.$id);
803: }
804:
805: sub remove_all_locks {
806: my $activelocks=$env{'session.locks'};
807: foreach my $lock (split(/\,/,$env{'session.locks'})) {
808: if ($lock=~/\w/) {
809: &remove_lock($lock);
810: }
811: }
812: }
813:
814:
1.369 albertel 815: # ------------------------------------------ Find out current server userload
816: sub userload {
817: my $numusers=0;
818: {
819: opendir(LONIDS,$perlvar{'lonIDsDir'});
820: my $filename;
821: my $curtime=time;
822: while ($filename=readdir(LONIDS)) {
1.925 albertel 823: next if ($filename eq '.' || $filename eq '..');
824: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 825: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 826: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 827: }
828: closedir(LONIDS);
829: }
830: my $userloadpercent=0;
831: my $maxuserload=$perlvar{'lonUserLoadLim'};
832: if ($maxuserload) {
1.371 albertel 833: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 834: }
1.372 albertel 835: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 836: return $userloadpercent;
1.283 www 837: }
838:
1.1 albertel 839: # ------------------------------ Find server with least workload from spare.tab
1.11 www 840:
1.1 albertel 841: sub spareserver {
1.1083 raeburn 842: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 843: my $spare_server;
1.370 albertel 844: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 845: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
846: : $userloadpercent;
1.1083 raeburn 847: my ($uint_dom,$remotesessions);
848: if (($udom ne '') && (&domain($udom) ne '')) {
849: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
850: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
851: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
852: $remotesessions = $udomdefaults{'remotesessions'};
853: }
1.1123 raeburn 854: my $spareshash = &this_host_spares($udom);
855: if (ref($spareshash) eq 'HASH') {
856: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
857: foreach my $try_server (@{ $spareshash->{'primary'} }) {
858: if ($uint_dom) {
859: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
860: $try_server));
861: }
862: ($spare_server, $lowest_load) =
863: &compare_server_load($try_server, $spare_server, $lowest_load);
864: }
1.1083 raeburn 865: }
1.784 albertel 866:
1.1123 raeburn 867: my $found_server = ($spare_server ne '' && $lowest_load < 100);
868:
869: if (!$found_server) {
870: if (ref($spareshash->{'default'}) eq 'ARRAY') {
871: foreach my $try_server (@{ $spareshash->{'default'} }) {
872: if ($uint_dom) {
873: next unless (&spare_can_host($udom,$uint_dom,
874: $remotesessions,$try_server));
875: }
876: ($spare_server, $lowest_load) =
877: &compare_server_load($try_server, $spare_server, $lowest_load);
878: }
879: }
880: }
1.784 albertel 881: }
882:
883: if (!$want_server_name) {
1.968 raeburn 884: my $protocol = 'http';
885: if ($protocol{$spare_server} eq 'https') {
886: $protocol = $protocol{$spare_server};
887: }
1.1001 raeburn 888: if (defined($spare_server)) {
889: my $hostname = &hostname($spare_server);
1.1083 raeburn 890: if (defined($hostname)) {
1.1001 raeburn 891: $spare_server = $protocol.'://'.$hostname;
892: }
893: }
1.784 albertel 894: }
895: return $spare_server;
896: }
897:
898: sub compare_server_load {
899: my ($try_server, $spare_server, $lowest_load) = @_;
900:
901: my $loadans = &reply('load', $try_server);
902: my $userloadans = &reply('userload',$try_server);
903:
904: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 905: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 906: }
907:
908: my $load;
909: if ($loadans =~ /\d/) {
910: if ($userloadans =~ /\d/) {
911: #both are numbers, pick the bigger one
912: $load = ($loadans > $userloadans) ? $loadans
913: : $userloadans;
1.411 albertel 914: } else {
1.784 albertel 915: $load = $loadans;
1.411 albertel 916: }
1.784 albertel 917: } else {
918: $load = $userloadans;
919: }
920:
921: if (($load =~ /\d/) && ($load < $lowest_load)) {
922: $spare_server = $try_server;
923: $lowest_load = $load;
1.370 albertel 924: }
1.784 albertel 925: return ($spare_server,$lowest_load);
1.202 matthew 926: }
1.914 albertel 927:
928: # --------------------------- ask offload servers if user already has a session
929: sub find_existing_session {
930: my ($udom,$uname) = @_;
1.1123 raeburn 931: my $spareshash = &this_host_spares($udom);
932: if (ref($spareshash) eq 'HASH') {
933: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
934: foreach my $try_server (@{ $spareshash->{'primary'} }) {
935: return $try_server if (&has_user_session($try_server, $udom, $uname));
936: }
937: }
938: if (ref($spareshash->{'default'}) eq 'ARRAY') {
939: foreach my $try_server (@{ $spareshash->{'default'} }) {
940: return $try_server if (&has_user_session($try_server, $udom, $uname));
941: }
942: }
1.914 albertel 943: }
944: return;
945: }
946:
947: # -------------------------------- ask if server already has a session for user
948: sub has_user_session {
949: my ($lonid,$udom,$uname) = @_;
950: my $result = &reply(join(':','userhassession',
951: map {&escape($_)} ($udom,$uname)),$lonid);
952: return 1 if ($result eq 'ok');
953:
954: return 0;
955: }
956:
1.1076 raeburn 957: # --------- determine least loaded server in a user's domain which allows login
958:
959: sub choose_server {
1.1115 raeburn 960: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 961: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 962: my %servers = &get_servers($udom);
1.1076 raeburn 963: my $lowest_load = 30000;
1.1151 raeburn 964: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 965: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 966: my $loginvia;
967: if ($checkloginvia) {
968: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 969: if ($loginvia) {
970: my ($server,$path) = split(/:/,$loginvia);
971: ($login_host, $lowest_load) =
972: &compare_server_load($server, $login_host, $lowest_load);
973: if ($login_host eq $server) {
974: $portal_path = $path;
1.1151 raeburn 975: $isredirect = 1;
1.1116 raeburn 976: }
977: } else {
978: ($login_host, $lowest_load) =
979: &compare_server_load($lonhost, $login_host, $lowest_load);
980: if ($login_host eq $lonhost) {
981: $portal_path = '';
1.1151 raeburn 982: $isredirect = '';
1.1116 raeburn 983: }
984: }
985: } else {
1.1076 raeburn 986: ($login_host, $lowest_load) =
1.1116 raeburn 987: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 988: }
989: }
990: if ($login_host ne '') {
1.1116 raeburn 991: $hostname = &hostname($login_host);
1.1076 raeburn 992: }
1.1151 raeburn 993: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 994: }
995:
1.202 matthew 996: # --------------------------------------------- Try to change a user's password
997:
998: sub changepass {
1.799 raeburn 999: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1000: $currentpass = &escape($currentpass);
1001: $newpass = &escape($newpass);
1.1030 raeburn 1002: my $lonhost = $perlvar{'lonHostID'};
1003: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1004: $server);
1005: if (! $answer) {
1006: &logthis("No reply on password change request to $server ".
1007: "by $uname in domain $udom.");
1008: } elsif ($answer =~ "^ok") {
1009: &logthis("$uname in $udom successfully changed their password ".
1010: "on $server.");
1011: } elsif ($answer =~ "^pwchange_failure") {
1012: &logthis("$uname in $udom was unable to change their password ".
1013: "on $server. The action was blocked by either lcpasswd ".
1014: "or pwchange");
1015: } elsif ($answer =~ "^non_authorized") {
1016: &logthis("$uname in $udom did not get their password correct when ".
1017: "attempting to change it on $server.");
1018: } elsif ($answer =~ "^auth_mode_error") {
1019: &logthis("$uname in $udom attempted to change their password despite ".
1020: "not being locally or internally authenticated on $server.");
1021: } elsif ($answer =~ "^unknown_user") {
1022: &logthis("$uname in $udom attempted to change their password ".
1023: "on $server but were unable to because $server is not ".
1024: "their home server.");
1025: } elsif ($answer =~ "^refused") {
1026: &logthis("$server refused to change $uname in $udom password because ".
1027: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1028: } elsif ($answer =~ "invalid_client") {
1029: &logthis("$server refused to change $uname in $udom password because ".
1030: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1031: }
1032: return $answer;
1.1 albertel 1033: }
1034:
1.169 harris41 1035: # ----------------------- Try to determine user's current authentication scheme
1036:
1037: sub queryauthenticate {
1038: my ($uname,$udom)=@_;
1.456 albertel 1039: my $uhome=&homeserver($uname,$udom);
1040: if (!$uhome) {
1041: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1042: return 'no_host';
1043: }
1044: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1045: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1046: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1047: }
1.456 albertel 1048: return $answer;
1.169 harris41 1049: }
1050:
1.1 albertel 1051: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1052:
1.1 albertel 1053: sub authenticate {
1.1073 raeburn 1054: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1055: $upass=&escape($upass);
1056: $uname= &LONCAPA::clean_username($uname);
1.836 www 1057: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1058: my $newhome;
1.836 www 1059: if ((!$uhome) || ($uhome eq 'no_host')) {
1060: # Maybe the machine was offline and only re-appeared again recently?
1061: &reconlonc();
1062: # One more
1.952 raeburn 1063: $uhome=&homeserver($uname,$udom,1);
1064: if (($uhome eq 'no_host') && $checkdefauth) {
1065: if (defined(&domain($udom,'primary'))) {
1066: $newhome=&domain($udom,'primary');
1067: }
1068: if ($newhome ne '') {
1069: $uhome = $newhome;
1070: }
1071: }
1.836 www 1072: if ((!$uhome) || ($uhome eq 'no_host')) {
1073: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1074: return 'no_host';
1075: }
1.1 albertel 1076: }
1.1073 raeburn 1077: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1078: if ($answer eq 'authorized') {
1.952 raeburn 1079: if ($newhome) {
1080: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1081: return 'no_account_on_host';
1082: } else {
1083: &logthis("User $uname at $udom authorized by $uhome");
1084: return $uhome;
1085: }
1.471 albertel 1086: }
1087: if ($answer eq 'non_authorized') {
1088: &logthis("User $uname at $udom rejected by $uhome");
1089: return 'no_host';
1.9 www 1090: }
1.471 albertel 1091: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1092: return 'no_host';
1093: }
1094:
1.1073 raeburn 1095: sub can_host_session {
1.1074 raeburn 1096: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1097: my $canhost = 1;
1.1074 raeburn 1098: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1099: if (ref($remotesessions) eq 'HASH') {
1100: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1101: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1102: $canhost = 0;
1103: } else {
1104: $canhost = 1;
1105: }
1106: }
1107: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1108: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1109: $canhost = 1;
1110: } else {
1111: $canhost = 0;
1112: }
1113: }
1114: if ($canhost) {
1115: if ($remotesessions->{'version'} ne '') {
1116: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1117: if ($reqmajor ne '' && $reqminor ne '') {
1118: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1119: my $major = $1;
1120: my $minor = $2;
1121: if (($major < $reqmajor ) ||
1122: (($major == $reqmajor) && ($minor < $reqminor))) {
1123: $canhost = 0;
1124: }
1125: } else {
1126: $canhost = 0;
1127: }
1128: }
1129: }
1130: }
1131: }
1132: if ($canhost) {
1133: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1134: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1135: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1136: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1137: if (($uint_dom ne '') &&
1138: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1139: $canhost = 0;
1140: } else {
1141: $canhost = 1;
1142: }
1143: }
1144: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1145: if (($uint_dom ne '') &&
1146: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1147: $canhost = 1;
1148: } else {
1149: $canhost = 0;
1150: }
1151: }
1152: }
1153: }
1154: return $canhost;
1155: }
1156:
1.1083 raeburn 1157: sub spare_can_host {
1158: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1159: my $canhost=1;
1160: my @intdoms;
1161: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1162: if (ref($internet_names) eq 'ARRAY') {
1163: @intdoms = @{$internet_names};
1164: }
1165: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1166: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1167: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1168: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1169: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1170: $canhost = &can_host_session($udom,$try_server,$remoterev,
1171: $remotesessions,
1172: $defdomdefaults{'hostedsessions'});
1173: }
1174: return $canhost;
1175: }
1176:
1.1123 raeburn 1177: sub this_host_spares {
1178: my ($dom) = @_;
1.1126 raeburn 1179: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1180: my @hosts = ¤t_machine_ids();
1181: foreach my $lonhost (@hosts) {
1182: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1183: $dom_in_use = $dom;
1184: $lonhost_in_use = $lonhost;
1.1123 raeburn 1185: last;
1186: }
1187: }
1.1126 raeburn 1188: if ($dom_in_use ne '') {
1189: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1190: }
1191: if (ref($result) ne 'HASH') {
1192: $lonhost_in_use = $perlvar{'lonHostID'};
1193: $dom_in_use = &host_domain($lonhost_in_use);
1194: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1195: if (ref($result) ne 'HASH') {
1196: $result = \%spareid;
1197: }
1198: }
1199: return $result;
1200: }
1201:
1202: sub spares_for_offload {
1203: my ($dom_in_use,$lonhost_in_use) = @_;
1204: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1205: if (defined($cached)) {
1206: return $result;
1207: } else {
1.1126 raeburn 1208: my $cachetime = 60*60*24;
1209: my %domconfig =
1210: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1211: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1212: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1213: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1214: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1215: }
1216: }
1217: }
1218: }
1.1126 raeburn 1219: return;
1.1123 raeburn 1220: }
1221:
1.1129 raeburn 1222: sub get_lonbalancer_config {
1223: my ($servers) = @_;
1224: my ($currbalancer,$currtargets);
1225: if (ref($servers) eq 'HASH') {
1226: foreach my $server (keys(%{$servers})) {
1227: my %what = (
1228: spareid => 1,
1229: perlvar => 1,
1230: );
1231: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1232: if ($result eq 'ok') {
1233: if (ref($returnhash) eq 'HASH') {
1234: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1235: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1236: $currbalancer = $server;
1237: $currtargets = {};
1238: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1239: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1240: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1241: }
1242: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1243: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1244: }
1245: }
1246: last;
1247: }
1248: }
1249: }
1250: }
1251: }
1252: }
1253: return ($currbalancer,$currtargets);
1254: }
1255:
1256: sub check_loadbalancing {
1257: my ($uname,$udom) = @_;
1.1191 raeburn 1258: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1259: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1260: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1261: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1262: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1263: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1264: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1265: my $serverhomedom = &host_domain($lonhost);
1266:
1267: my $cachetime = 60*60*24;
1268:
1269: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1270: $dom_in_use = $udom;
1271: $homeintdom = 1;
1272: } else {
1273: $dom_in_use = $serverhomedom;
1274: }
1275: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1276: unless (defined($cached)) {
1277: my %domconfig =
1278: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1279: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1280: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1281: }
1282: }
1283: if (ref($result) eq 'HASH') {
1.1191 raeburn 1284: ($is_balancer,$currtargets,$currrules) =
1285: &check_balancer_result($result,@hosts);
1.1129 raeburn 1286: if ($is_balancer) {
1287: if (ref($currrules) eq 'HASH') {
1288: if ($homeintdom) {
1289: if ($uname ne '') {
1290: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1291: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1292: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1293: $rule_in_effect = $currrules->{'_LC_author'};
1294: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1295: $rule_in_effect = $currrules->{'_LC_adv'}
1296: }
1297: }
1298: if ($rule_in_effect eq '') {
1299: my %userenv = &userenvironment($udom,$uname,'inststatus');
1300: if ($userenv{'inststatus'} ne '') {
1301: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1302: my ($othertitle,$usertypes,$types) =
1303: &Apache::loncommon::sorted_inst_types($udom);
1304: if (ref($types) eq 'ARRAY') {
1305: foreach my $type (@{$types}) {
1306: if (grep(/^\Q$type\E$/,@statuses)) {
1307: if (exists($currrules->{$type})) {
1308: $rule_in_effect = $currrules->{$type};
1309: }
1310: }
1311: }
1312: }
1313: } else {
1314: if (exists($currrules->{'default'})) {
1315: $rule_in_effect = $currrules->{'default'};
1316: }
1317: }
1318: }
1319: } else {
1320: if (exists($currrules->{'default'})) {
1321: $rule_in_effect = $currrules->{'default'};
1322: }
1323: }
1324: } else {
1325: if ($currrules->{'_LC_external'} ne '') {
1326: $rule_in_effect = $currrules->{'_LC_external'};
1327: }
1328: }
1329: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1330: $uname,$udom);
1331: }
1332: }
1333: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1334: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1335: unless (defined($cached)) {
1336: my %domconfig =
1337: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1338: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1339: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1340: }
1341: }
1342: if (ref($result) eq 'HASH') {
1.1191 raeburn 1343: ($is_balancer,$currtargets,$currrules) =
1344: &check_balancer_result($result,@hosts);
1345: if ($is_balancer) {
1.1129 raeburn 1346: if (ref($currrules) eq 'HASH') {
1347: if ($currrules->{'_LC_internetdom'} ne '') {
1348: $rule_in_effect = $currrules->{'_LC_internetdom'};
1349: }
1350: }
1351: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1352: $uname,$udom);
1353: }
1354: } else {
1355: if ($perlvar{'lonBalancer'} eq 'yes') {
1356: $is_balancer = 1;
1357: $offloadto = &this_host_spares($dom_in_use);
1358: }
1359: }
1360: } else {
1361: if ($perlvar{'lonBalancer'} eq 'yes') {
1362: $is_balancer = 1;
1363: $offloadto = &this_host_spares($dom_in_use);
1364: }
1365: }
1.1176 raeburn 1366: if ($is_balancer) {
1367: my $lowest_load = 30000;
1368: if (ref($offloadto) eq 'HASH') {
1369: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1370: foreach my $try_server (@{$offloadto->{'primary'}}) {
1371: ($otherserver,$lowest_load) =
1372: &compare_server_load($try_server,$otherserver,$lowest_load);
1373: }
1.1129 raeburn 1374: }
1.1176 raeburn 1375: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1376:
1.1176 raeburn 1377: if (!$found_server) {
1378: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1379: foreach my $try_server (@{$offloadto->{'default'}}) {
1380: ($otherserver,$lowest_load) =
1381: &compare_server_load($try_server,$otherserver,$lowest_load);
1382: }
1383: }
1384: }
1385: } elsif (ref($offloadto) eq 'ARRAY') {
1386: if (@{$offloadto} == 1) {
1387: $otherserver = $offloadto->[0];
1388: } elsif (@{$offloadto} > 1) {
1389: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1390: ($otherserver,$lowest_load) =
1391: &compare_server_load($try_server,$otherserver,$lowest_load);
1392: }
1393: }
1394: }
1.1176 raeburn 1395: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1396: $is_balancer = 0;
1397: if ($uname ne '' && $udom ne '') {
1398: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1399:
1400: &appenv({'user.loadbalexempt' => $lonhost,
1401: 'user.loadbalcheck.time' => time});
1402: }
1.1129 raeburn 1403: }
1404: }
1405: }
1406: return ($is_balancer,$otherserver);
1407: }
1408:
1.1191 raeburn 1409: sub check_balancer_result {
1410: my ($result,@hosts) = @_;
1411: my ($is_balancer,$currtargets,$currrules);
1412: if (ref($result) eq 'HASH') {
1413: if ($result->{'lonhost'} ne '') {
1414: my $currbalancer = $result->{'lonhost'};
1415: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1416: $is_balancer = 1;
1417: $currtargets = $result->{'targets'};
1418: $currrules = $result->{'rules'};
1419: }
1420: } else {
1421: foreach my $key (keys(%{$result})) {
1422: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1423: (ref($result->{$key}) eq 'HASH')) {
1424: $is_balancer = 1;
1425: $currrules = $result->{$key}{'rules'};
1426: $currtargets = $result->{$key}{'targets'};
1427: last;
1428: }
1429: }
1430: }
1431: }
1432: return ($is_balancer,$currtargets,$currrules);
1433: }
1434:
1.1129 raeburn 1435: sub get_loadbalancer_targets {
1436: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1437: my $offloadto;
1.1175 raeburn 1438: if ($rule_in_effect eq 'none') {
1439: return [$perlvar{'lonHostID'}];
1440: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1441: $offloadto = $currtargets;
1442: } else {
1443: if ($rule_in_effect eq 'homeserver') {
1444: my $homeserver = &homeserver($uname,$udom);
1445: if ($homeserver ne 'no_host') {
1446: $offloadto = [$homeserver];
1447: }
1448: } elsif ($rule_in_effect eq 'externalbalancer') {
1449: my %domconfig =
1450: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1451: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1452: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1453: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1454: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1455: }
1456: }
1457: } else {
1.1178 raeburn 1458: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1459: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1460: if (&hostname($remotebalancer) ne '') {
1461: $offloadto = [$remotebalancer];
1462: }
1463: }
1464: } elsif (&hostname($rule_in_effect) ne '') {
1465: $offloadto = [$rule_in_effect];
1466: }
1467: }
1468: return $offloadto;
1469: }
1470:
1.1127 raeburn 1471: sub internet_dom_servers {
1472: my ($dom) = @_;
1473: my (%uniqservers,%servers);
1474: my $primaryserver = &hostname(&domain($dom,'primary'));
1475: my @machinedoms = &machine_domains($primaryserver);
1476: foreach my $mdom (@machinedoms) {
1477: my %currservers = %servers;
1478: my %server = &get_servers($mdom);
1479: %servers = (%currservers,%server);
1480: }
1481: my %by_hostname;
1482: foreach my $id (keys(%servers)) {
1483: push(@{$by_hostname{$servers{$id}}},$id);
1484: }
1485: foreach my $hostname (sort(keys(%by_hostname))) {
1486: if (@{$by_hostname{$hostname}} > 1) {
1487: my $match = 0;
1488: foreach my $id (@{$by_hostname{$hostname}}) {
1489: if (&host_domain($id) eq $dom) {
1490: $uniqservers{$id} = $hostname;
1491: $match = 1;
1492: }
1493: }
1494: unless ($match) {
1495: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1496: }
1497: } else {
1498: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1499: }
1500: }
1501: return %uniqservers;
1502: }
1503:
1.1 albertel 1504: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1505:
1.599 albertel 1506: my %homecache;
1.1 albertel 1507: sub homeserver {
1.230 stredwic 1508: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1509: my $index="$uname:$udom";
1.426 albertel 1510:
1.599 albertel 1511: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1512:
1513: my %servers = &get_servers($udom,'library');
1514: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1515: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1516: exists($badServerCache{$tryserver}));
1.841 albertel 1517:
1518: my $answer=reply("home:$udom:$uname",$tryserver);
1519: if ($answer eq 'found') {
1520: delete($badServerCache{$tryserver});
1521: return $homecache{$index}=$tryserver;
1522: } elsif ($answer eq 'no_host') {
1523: $badServerCache{$tryserver}=1;
1524: }
1.1 albertel 1525: }
1526: return 'no_host';
1.70 www 1527: }
1528:
1529: # ------------------------------------- Find the usernames behind a list of IDs
1530:
1531: sub idget {
1532: my ($udom,@ids)=@_;
1533: my %returnhash=();
1534:
1.841 albertel 1535: my %servers = &get_servers($udom,'library');
1536: foreach my $tryserver (keys(%servers)) {
1537: my $idlist=join('&',@ids);
1538: $idlist=~tr/A-Z/a-z/;
1539: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1540: my @answer=();
1541: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1542: @answer=split(/\&/,$reply);
1543: } ;
1544: my $i;
1545: for ($i=0;$i<=$#ids;$i++) {
1546: if ($answer[$i]) {
1547: $returnhash{$ids[$i]}=$answer[$i];
1548: }
1549: }
1550: }
1.70 www 1551: return %returnhash;
1552: }
1553:
1554: # ------------------------------------- Find the IDs behind a list of usernames
1555:
1556: sub idrget {
1557: my ($udom,@unames)=@_;
1558: my %returnhash=();
1.800 albertel 1559: foreach my $uname (@unames) {
1560: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1561: }
1.70 www 1562: return %returnhash;
1563: }
1564:
1565: # ------------------------------- Store away a list of names and associated IDs
1566:
1567: sub idput {
1568: my ($udom,%ids)=@_;
1569: my %servers=();
1.800 albertel 1570: foreach my $uname (keys(%ids)) {
1571: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1572: my $uhom=&homeserver($uname,$udom);
1.70 www 1573: if ($uhom ne 'no_host') {
1.800 albertel 1574: my $id=&escape($ids{$uname});
1.70 www 1575: $id=~tr/A-Z/a-z/;
1.800 albertel 1576: my $esc_unam=&escape($uname);
1.70 www 1577: if ($servers{$uhom}) {
1.800 albertel 1578: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1579: } else {
1.800 albertel 1580: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1581: }
1582: }
1.191 harris41 1583: }
1.800 albertel 1584: foreach my $server (keys(%servers)) {
1585: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1586: }
1.344 www 1587: }
1588:
1.1231 raeburn 1589: # ---------------------------------------- Delete unwanted IDs from ids.db file
1590:
1591: sub iddel {
1592: my ($udom,$idshashref,$uhome)=@_;
1593: my %result=();
1594: unless (ref($idshashref) eq 'HASH') {
1595: return %result;
1596: }
1597: my %servers=();
1598: while (my ($id,$uname) = each(%{$idshashref})) {
1599: my $uhom;
1600: if ($uhome) {
1601: $uhom = $uhome;
1602: } else {
1603: $uhom=&homeserver($uname,$udom);
1604: }
1605: if ($uhom ne 'no_host') {
1606: if ($servers{$uhom}) {
1607: $servers{$uhom}.='&'.&escape($id);
1608: } else {
1609: $servers{$uhom}=&escape($id);
1610: }
1611: }
1612: }
1613: foreach my $server (keys(%servers)) {
1614: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1615: }
1616: return %result;
1617: }
1618:
1.1023 raeburn 1619: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1620: sub dump_dom {
1.1165 droeschl 1621: my ($namespace, $udom, $regexp) = @_;
1622:
1623: $udom ||= $env{'user.domain'};
1624:
1625: return () unless $udom;
1626:
1627: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1628: }
1629:
1.1023 raeburn 1630: # ------------------------------------------ get items from domain db files
1.806 raeburn 1631:
1632: sub get_dom {
1.860 raeburn 1633: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1634: my $items='';
1635: foreach my $item (@$storearr) {
1636: $items.=&escape($item).'&';
1637: }
1638: $items=~s/\&$//;
1.860 raeburn 1639: if (!$udom) {
1640: $udom=$env{'user.domain'};
1641: if (defined(&domain($udom,'primary'))) {
1642: $uhome=&domain($udom,'primary');
1643: } else {
1.874 albertel 1644: undef($uhome);
1.860 raeburn 1645: }
1646: } else {
1647: if (!$uhome) {
1648: if (defined(&domain($udom,'primary'))) {
1649: $uhome=&domain($udom,'primary');
1650: }
1651: }
1652: }
1653: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1654: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1655: my %returnhash;
1.875 albertel 1656: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1657: return %returnhash;
1658: }
1.806 raeburn 1659: my @pairs=split(/\&/,$rep);
1660: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1661: return @pairs;
1662: }
1663: my $i=0;
1664: foreach my $item (@$storearr) {
1665: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1666: $i++;
1667: }
1668: return %returnhash;
1669: } else {
1.880 banghart 1670: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1671: }
1672: }
1673:
1674: # -------------------------------------------- put items in domain db files
1675:
1676: sub put_dom {
1.860 raeburn 1677: my ($namespace,$storehash,$udom,$uhome)=@_;
1678: if (!$udom) {
1679: $udom=$env{'user.domain'};
1680: if (defined(&domain($udom,'primary'))) {
1681: $uhome=&domain($udom,'primary');
1682: } else {
1.874 albertel 1683: undef($uhome);
1.860 raeburn 1684: }
1685: } else {
1686: if (!$uhome) {
1687: if (defined(&domain($udom,'primary'))) {
1688: $uhome=&domain($udom,'primary');
1689: }
1690: }
1691: }
1692: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1693: my $items='';
1694: foreach my $item (keys(%$storehash)) {
1695: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1696: }
1697: $items=~s/\&$//;
1698: return &reply("putdom:$udom:$namespace:$items",$uhome);
1699: } else {
1.860 raeburn 1700: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1701: }
1702: }
1703:
1.1023 raeburn 1704: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1705: sub newput_dom {
1.1023 raeburn 1706: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1707: my $result;
1708: if (!$udom) {
1709: $udom=$env{'user.domain'};
1710: }
1.1023 raeburn 1711: if ($udom) {
1712: my $uname = &get_domainconfiguser($udom);
1713: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1714: }
1715: return $result;
1716: }
1717:
1.1023 raeburn 1718: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1719: sub del_dom {
1.1023 raeburn 1720: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1721: if (ref($storearr) eq 'ARRAY') {
1722: if (!$udom) {
1723: $udom=$env{'user.domain'};
1724: }
1.1023 raeburn 1725: if ($udom) {
1726: my $uname = &get_domainconfiguser($udom);
1727: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1728: }
1729: }
1730: }
1731:
1.1023 raeburn 1732: # ----------------------------------construct domainconfig user for a domain
1733: sub get_domainconfiguser {
1734: my ($udom) = @_;
1735: return $udom.'-domainconfig';
1736: }
1737:
1.837 raeburn 1738: sub retrieve_inst_usertypes {
1739: my ($udom) = @_;
1740: my (%returnhash,@order);
1.989 raeburn 1741: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1742: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1743: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1744: %returnhash = %{$domdefs{'inststatustypes'}};
1745: @order = @{$domdefs{'inststatusorder'}};
1746: } else {
1747: if (defined(&domain($udom,'primary'))) {
1748: my $uhome=&domain($udom,'primary');
1749: my $rep=&reply("inst_usertypes:$udom",$uhome);
1750: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1751: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1752: return (\%returnhash,\@order);
1753: }
1754: my ($hashitems,$orderitems) = split(/:/,$rep);
1755: my @pairs=split(/\&/,$hashitems);
1756: foreach my $item (@pairs) {
1757: my ($key,$value)=split(/=/,$item,2);
1758: $key = &unescape($key);
1759: next if ($key =~ /^error: 2 /);
1760: $returnhash{$key}=&thaw_unescape($value);
1761: }
1762: my @esc_order = split(/\&/,$orderitems);
1763: foreach my $item (@esc_order) {
1764: push(@order,&unescape($item));
1765: }
1766: } else {
1767: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1768: }
1769: }
1770: return (\%returnhash,\@order);
1771: }
1772:
1.868 raeburn 1773: sub is_domainimage {
1774: my ($url) = @_;
1775: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1776: if (&domain($1) ne '') {
1777: return '1';
1778: }
1779: }
1780: return;
1781: }
1782:
1.899 raeburn 1783: sub inst_directory_query {
1784: my ($srch) = @_;
1785: my $udom = $srch->{'srchdomain'};
1786: my %results;
1787: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1788: my $outcome;
1.899 raeburn 1789: if ($homeserver ne '') {
1.904 albertel 1790: my $queryid=&reply("querysend:instdirsearch:".
1791: &escape($srch->{'srchby'}).':'.
1792: &escape($srch->{'srchterm'}).':'.
1793: &escape($srch->{'srchtype'}),$homeserver);
1794: my $host=&hostname($homeserver);
1795: if ($queryid !~/^\Q$host\E\_/) {
1796: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1797: return;
1798: }
1799: my $response = &get_query_reply($queryid);
1800: my $maxtries = 5;
1801: my $tries = 1;
1802: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1803: $response = &get_query_reply($queryid);
1804: $tries ++;
1805: }
1806:
1807: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1808: if ($response eq 'unavailable') {
1809: $outcome = $response;
1810: } else {
1811: $outcome = 'ok';
1812: my @matches = split(/\n/,$response);
1813: foreach my $match (@matches) {
1814: my ($key,$value) = split(/=/,$match);
1815: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1816: }
1.899 raeburn 1817: }
1818: }
1819: }
1.909 raeburn 1820: return ($outcome,%results);
1.899 raeburn 1821: }
1822:
1823: sub usersearch {
1824: my ($srch) = @_;
1825: my $dom = $srch->{'srchdomain'};
1826: my %results;
1827: my %libserv = &all_library();
1828: my $query = 'usersearch';
1829: foreach my $tryserver (keys(%libserv)) {
1830: if (&host_domain($tryserver) eq $dom) {
1831: my $host=&hostname($tryserver);
1832: my $queryid=
1.911 raeburn 1833: &reply("querysend:".&escape($query).':'.
1834: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1835: &escape($srch->{'srchtype'}).':'.
1836: &escape($srch->{'srchterm'}),$tryserver);
1837: if ($queryid !~/^\Q$host\E\_/) {
1838: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1839: next;
1.899 raeburn 1840: }
1841: my $reply = &get_query_reply($queryid);
1842: my $maxtries = 1;
1843: my $tries = 1;
1844: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1845: $reply = &get_query_reply($queryid);
1846: $tries ++;
1847: }
1848: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1849: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1850: } else {
1.911 raeburn 1851: my @matches;
1852: if ($reply =~ /\n/) {
1853: @matches = split(/\n/,$reply);
1854: } else {
1855: @matches = split(/\&/,$reply);
1856: }
1.899 raeburn 1857: foreach my $match (@matches) {
1858: my ($uname,$udom,%userhash);
1.911 raeburn 1859: foreach my $entry (split(/:/,$match)) {
1860: my ($key,$value) =
1861: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1862: $userhash{$key} = $value;
1863: if ($key eq 'username') {
1864: $uname = $value;
1865: } elsif ($key eq 'domain') {
1866: $udom = $value;
1.911 raeburn 1867: }
1.899 raeburn 1868: }
1869: $results{$uname.':'.$udom} = \%userhash;
1870: }
1871: }
1872: }
1873: }
1874: return %results;
1875: }
1876:
1.912 raeburn 1877: sub get_instuser {
1878: my ($udom,$uname,$id) = @_;
1879: my $homeserver = &domain($udom,'primary');
1880: my ($outcome,%results);
1881: if ($homeserver ne '') {
1882: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1883: &escape($id).':'.&escape($udom),$homeserver);
1884: my $host=&hostname($homeserver);
1885: if ($queryid !~/^\Q$host\E\_/) {
1886: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1887: return;
1888: }
1889: my $response = &get_query_reply($queryid);
1890: my $maxtries = 5;
1891: my $tries = 1;
1892: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1893: $response = &get_query_reply($queryid);
1894: $tries ++;
1895: }
1896: if (!&error($response) && $response ne 'refused') {
1897: if ($response eq 'unavailable') {
1898: $outcome = $response;
1899: } else {
1900: $outcome = 'ok';
1901: my @matches = split(/\n/,$response);
1902: foreach my $match (@matches) {
1903: my ($key,$value) = split(/=/,$match);
1904: $results{&unescape($key)} = &thaw_unescape($value);
1905: }
1906: }
1907: }
1908: }
1909: my %userinfo;
1910: if (ref($results{$uname}) eq 'HASH') {
1911: %userinfo = %{$results{$uname}};
1912: }
1913: return ($outcome,%userinfo);
1914: }
1915:
1916: sub inst_rulecheck {
1.923 raeburn 1917: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1918: my %returnhash;
1919: if ($udom ne '') {
1920: if (ref($rules) eq 'ARRAY') {
1921: @{$rules} = map {&escape($_);} (@{$rules});
1922: my $rulestr = join(':',@{$rules});
1923: my $homeserver=&domain($udom,'primary');
1924: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1925: my $response;
1926: if ($item eq 'username') {
1927: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1928: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1929: $homeserver));
1.923 raeburn 1930: } elsif ($item eq 'id') {
1931: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1932: ':'.&escape($id).':'.$rulestr,
1933: $homeserver));
1.945 raeburn 1934: } elsif ($item eq 'selfcreate') {
1935: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1936: &escape($udom).':'.&escape($uname).
1937: ':'.$rulestr,$homeserver));
1.923 raeburn 1938: }
1.912 raeburn 1939: if ($response ne 'refused') {
1940: my @pairs=split(/\&/,$response);
1941: foreach my $item (@pairs) {
1942: my ($key,$value)=split(/=/,$item,2);
1943: $key = &unescape($key);
1944: next if ($key =~ /^error: 2 /);
1945: $returnhash{$key}=&thaw_unescape($value);
1946: }
1947: }
1948: }
1949: }
1950: }
1951: return %returnhash;
1952: }
1953:
1954: sub inst_userrules {
1.923 raeburn 1955: my ($udom,$check) = @_;
1.912 raeburn 1956: my (%ruleshash,@ruleorder);
1957: if ($udom ne '') {
1958: my $homeserver=&domain($udom,'primary');
1959: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1960: my $response;
1961: if ($check eq 'id') {
1962: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1963: $homeserver);
1.943 raeburn 1964: } elsif ($check eq 'email') {
1965: $response=&reply('instemailrules:'.&escape($udom),
1966: $homeserver);
1.923 raeburn 1967: } else {
1968: $response=&reply('instuserrules:'.&escape($udom),
1969: $homeserver);
1970: }
1.912 raeburn 1971: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1972: ($response ne 'unknown_cmd') &&
1.912 raeburn 1973: ($response ne 'no_such_host')) {
1974: my ($hashitems,$orderitems) = split(/:/,$response);
1975: my @pairs=split(/\&/,$hashitems);
1976: foreach my $item (@pairs) {
1977: my ($key,$value)=split(/=/,$item,2);
1978: $key = &unescape($key);
1979: next if ($key =~ /^error: 2 /);
1980: $ruleshash{$key}=&thaw_unescape($value);
1981: }
1982: my @esc_order = split(/\&/,$orderitems);
1983: foreach my $item (@esc_order) {
1984: push(@ruleorder,&unescape($item));
1985: }
1986: }
1987: }
1988: }
1989: return (\%ruleshash,\@ruleorder);
1990: }
1991:
1.976 raeburn 1992: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1993:
1994: sub get_domain_defaults {
1.1240 raeburn 1995: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 1996: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 1997: my $cachetime = 60*60*24;
1.1240 raeburn 1998: unless ($ignore_cache) {
1999: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2000: if (defined($cached)) {
2001: if (ref($result) eq 'HASH') {
2002: return %{$result};
2003: }
1.943 raeburn 2004: }
2005: }
2006: my %domdefaults;
2007: my %domconfig =
1.989 raeburn 2008: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2009: 'requestcourses','inststatus',
1.1183 raeburn 2010: 'coursedefaults','usersessions',
2011: 'requestauthor'],$domain);
1.943 raeburn 2012: if (ref($domconfig{'defaults'}) eq 'HASH') {
2013: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2014: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2015: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2016: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2017: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2018: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2019: } else {
2020: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2021: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2022: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2023: }
1.976 raeburn 2024: if (ref($domconfig{'quotas'}) eq 'HASH') {
2025: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2026: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2027: } else {
2028: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2029: }
1.1177 raeburn 2030: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2031: foreach my $item (@usertools) {
2032: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2033: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2034: }
2035: }
1.1229 raeburn 2036: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2037: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2038: }
1.976 raeburn 2039: }
1.985 raeburn 2040: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 2041: foreach my $item ('official','unofficial','community') {
1.985 raeburn 2042: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2043: }
2044: }
1.1183 raeburn 2045: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2046: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2047: }
1.989 raeburn 2048: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2049: foreach my $item ('inststatustypes','inststatusorder') {
2050: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2051: }
2052: }
1.1047 raeburn 2053: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2054: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1216 raeburn 2055: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2056: $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
2057: $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
2058: }
1.1230 raeburn 2059: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2060: $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
2061: $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
2062: $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};
2063: }
1.1047 raeburn 2064: }
1.1073 raeburn 2065: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2066: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2067: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2068: }
2069: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2070: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2071: }
2072: }
1.1219 raeburn 2073: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2074: return %domdefaults;
2075: }
2076:
1.344 www 2077: # --------------------------------------------------- Assign a key to a student
2078:
2079: sub assign_access_key {
1.364 www 2080: #
2081: # a valid key looks like uname:udom#comments
2082: # comments are being appended
2083: #
1.498 www 2084: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2085: $kdom=
1.620 albertel 2086: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2087: $knum=
1.620 albertel 2088: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2089: $cdom=
1.620 albertel 2090: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2091: $cnum=
1.620 albertel 2092: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2093: $udom=$env{'user.name'} unless (defined($udom));
2094: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2095: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2096: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2097: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2098: # assigned to this person
2099: # - this should not happen,
1.345 www 2100: # unless something went wrong
2101: # the first time around
2102: # ready to assign
1.364 www 2103: $logentry=$1.'; '.$logentry;
1.496 www 2104: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2105: $kdom,$knum) eq 'ok') {
1.345 www 2106: # key now belongs to user
1.346 www 2107: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2108: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2109: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2110: return 'ok';
2111: } else {
2112: return
2113: 'error: Count not permanently assign key, will need to be re-entered later.';
2114: }
2115: } else {
2116: return 'error: Could not assign key, try again later.';
2117: }
1.364 www 2118: } elsif (!$existing{$ckey}) {
1.345 www 2119: # the key does not exist
2120: return 'error: The key does not exist';
2121: } else {
2122: # the key is somebody else's
2123: return 'error: The key is already in use';
2124: }
1.344 www 2125: }
2126:
1.364 www 2127: # ------------------------------------------ put an additional comment on a key
2128:
2129: sub comment_access_key {
2130: #
2131: # a valid key looks like uname:udom#comments
2132: # comments are being appended
2133: #
2134: my ($ckey,$cdom,$cnum,$logentry)=@_;
2135: $cdom=
1.620 albertel 2136: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2137: $cnum=
1.620 albertel 2138: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2139: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2140: if ($existing{$ckey}) {
2141: $existing{$ckey}.='; '.$logentry;
2142: # ready to assign
1.367 www 2143: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2144: $cdom,$cnum) eq 'ok') {
2145: return 'ok';
2146: } else {
2147: return 'error: Count not store comment.';
2148: }
2149: } else {
2150: # the key does not exist
2151: return 'error: The key does not exist';
2152: }
2153: }
2154:
1.344 www 2155: # ------------------------------------------------------ Generate a set of keys
2156:
2157: sub generate_access_keys {
1.364 www 2158: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2159: $cdom=
1.620 albertel 2160: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2161: $cnum=
1.620 albertel 2162: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2163: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2164: unless (($cdom) && ($cnum)) { return 0; }
2165: if ($number>10000) { return 0; }
2166: sleep(2); # make sure don't get same seed twice
2167: srand(time()^($$+($$<<15))); # from "Programming Perl"
2168: my $total=0;
2169: for (my $i=1;$i<=$number;$i++) {
2170: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2171: sprintf("%lx",int(100000*rand)).'-'.
2172: sprintf("%lx",int(100000*rand));
2173: $newkey=~s/1/g/g; # folks mix up 1 and l
2174: $newkey=~s/0/h/g; # and also 0 and O
2175: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2176: if ($existing{$newkey}) {
2177: $i--;
2178: } else {
1.364 www 2179: if (&put('accesskeys',
2180: { $newkey => '# generated '.localtime().
1.620 albertel 2181: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2182: '; '.$logentry },
2183: $cdom,$cnum) eq 'ok') {
1.344 www 2184: $total++;
2185: }
2186: }
2187: }
1.620 albertel 2188: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2189: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2190: return $total;
2191: }
2192:
2193: # ------------------------------------------------------- Validate an accesskey
2194:
2195: sub validate_access_key {
2196: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2197: $cdom=
1.620 albertel 2198: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2199: $cnum=
1.620 albertel 2200: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2201: $udom=$env{'user.domain'} unless (defined($udom));
2202: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2203: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2204: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2205: }
2206:
2207: # ------------------------------------- Find the section of student in a course
1.652 albertel 2208: sub devalidate_getsection_cache {
2209: my ($udom,$unam,$courseid)=@_;
2210: my $hashid="$udom:$unam:$courseid";
2211: &devalidate_cache_new('getsection',$hashid);
2212: }
1.298 matthew 2213:
1.815 albertel 2214: sub courseid_to_courseurl {
2215: my ($courseid) = @_;
2216: #already url style courseid
2217: return $courseid if ($courseid =~ m{^/});
2218:
2219: if (exists($env{'course.'.$courseid.'.num'})) {
2220: my $cnum = $env{'course.'.$courseid.'.num'};
2221: my $cdom = $env{'course.'.$courseid.'.domain'};
2222: return "/$cdom/$cnum";
2223: }
2224:
2225: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2226: if (exists($courseinfo{'num'})) {
2227: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2228: }
2229:
2230: return undef;
2231: }
2232:
1.298 matthew 2233: sub getsection {
2234: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2235: my $cachetime=1800;
1.551 albertel 2236:
2237: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2238: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2239: if (defined($cached)) { return $result; }
2240:
1.298 matthew 2241: my %Pending;
2242: my %Expired;
2243: #
2244: # Each role can either have not started yet (pending), be active,
2245: # or have expired.
2246: #
2247: # If there is an active role, we are done.
2248: #
2249: # If there is more than one role which has not started yet,
2250: # choose the one which will start sooner
2251: # If there is one role which has not started yet, return it.
2252: #
2253: # If there is more than one expired role, choose the one which ended last.
2254: # If there is a role which has expired, return it.
2255: #
1.815 albertel 2256: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2257: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2258: foreach my $key (keys(%roleshash)) {
1.479 albertel 2259: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2260: my $section=$1;
2261: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2262: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2263: my $now=time;
1.548 albertel 2264: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2265: $Expired{$end}=$section;
2266: next;
2267: }
1.548 albertel 2268: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2269: $Pending{$start}=$section;
2270: next;
2271: }
1.599 albertel 2272: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2273: }
2274: #
2275: # Presumedly there will be few matching roles from the above
2276: # loop and the sorting time will be negligible.
2277: if (scalar(keys(%Pending))) {
2278: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2279: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2280: }
2281: if (scalar(keys(%Expired))) {
2282: my @sorted = sort {$a <=> $b} keys(%Expired);
2283: my $time = pop(@sorted);
1.599 albertel 2284: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2285: }
1.599 albertel 2286: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2287: }
1.70 www 2288:
1.599 albertel 2289: sub save_cache {
2290: &purge_remembered();
1.722 albertel 2291: #&Apache::loncommon::validate_page();
1.620 albertel 2292: undef(%env);
1.780 albertel 2293: undef($env_loaded);
1.599 albertel 2294: }
1.452 albertel 2295:
1.599 albertel 2296: my $to_remember=-1;
2297: my %remembered;
2298: my %accessed;
2299: my $kicks=0;
2300: my $hits=0;
1.849 albertel 2301: sub make_key {
2302: my ($name,$id) = @_;
1.872 albertel 2303: if (length($id) > 65
2304: && length(&escape($id)) > 200) {
2305: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2306: }
1.849 albertel 2307: return &escape($name.':'.$id);
2308: }
2309:
1.599 albertel 2310: sub devalidate_cache_new {
2311: my ($name,$id,$debug) = @_;
2312: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2313: $id=&make_key($name,$id);
1.599 albertel 2314: $memcache->delete($id);
2315: delete($remembered{$id});
2316: delete($accessed{$id});
2317: }
2318:
2319: sub is_cached_new {
2320: my ($name,$id,$debug) = @_;
1.849 albertel 2321: $id=&make_key($name,$id);
1.599 albertel 2322: if (exists($remembered{$id})) {
1.1133 foxr 2323: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2324: $accessed{$id}=[&gettimeofday()];
2325: $hits++;
2326: return ($remembered{$id},1);
2327: }
2328: my $value = $memcache->get($id);
2329: if (!(defined($value))) {
2330: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2331: return (undef,undef);
1.416 albertel 2332: }
1.599 albertel 2333: if ($value eq '__undef__') {
2334: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2335: $value=undef;
2336: }
2337: &make_room($id,$value,$debug);
2338: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2339: return ($value,1);
2340: }
2341:
2342: sub do_cache_new {
2343: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2344: $id=&make_key($name,$id);
1.599 albertel 2345: my $setvalue=$value;
2346: if (!defined($setvalue)) {
2347: $setvalue='__undef__';
2348: }
1.623 albertel 2349: if (!defined($time) ) {
2350: $time=600;
2351: }
1.599 albertel 2352: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2353: my $result = $memcache->set($id,$setvalue,$time);
2354: if (! $result) {
1.872 albertel 2355: &logthis("caching of id -> $id failed");
1.910 albertel 2356: $memcache->disconnect_all();
1.872 albertel 2357: }
1.600 albertel 2358: # need to make a copy of $value
1.919 albertel 2359: &make_room($id,$value,$debug);
1.599 albertel 2360: return $value;
2361: }
2362:
2363: sub make_room {
2364: my ($id,$value,$debug)=@_;
1.919 albertel 2365:
2366: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2367: : $value;
1.599 albertel 2368: if ($to_remember<0) { return; }
2369: $accessed{$id}=[&gettimeofday()];
2370: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2371: my $to_kick;
2372: my $max_time=0;
2373: foreach my $other (keys(%accessed)) {
2374: if (&tv_interval($accessed{$other}) > $max_time) {
2375: $to_kick=$other;
2376: $max_time=&tv_interval($accessed{$other});
2377: }
2378: }
2379: delete($remembered{$to_kick});
2380: delete($accessed{$to_kick});
2381: $kicks++;
2382: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2383: return;
2384: }
2385:
1.599 albertel 2386: sub purge_remembered {
1.604 albertel 2387: #&logthis("Tossing ".scalar(keys(%remembered)));
2388: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2389: undef(%remembered);
2390: undef(%accessed);
1.428 albertel 2391: }
1.70 www 2392: # ------------------------------------- Read an entry from a user's environment
2393:
2394: sub userenvironment {
2395: my ($udom,$unam,@what)=@_;
1.976 raeburn 2396: my $items;
2397: foreach my $item (@what) {
2398: $items.=&escape($item).'&';
2399: }
2400: $items=~s/\&$//;
1.70 www 2401: my %returnhash=();
1.1009 raeburn 2402: my $uhome = &homeserver($unam,$udom);
2403: unless ($uhome eq 'no_host') {
2404: my @answer=split(/\&/,
2405: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2406: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2407: return %returnhash;
2408: }
1.1009 raeburn 2409: my $i;
2410: for ($i=0;$i<=$#what;$i++) {
2411: $returnhash{$what[$i]}=&unescape($answer[$i]);
2412: }
1.70 www 2413: }
2414: return %returnhash;
1.1 albertel 2415: }
2416:
1.617 albertel 2417: # ---------------------------------------------------------- Get a studentphoto
2418: sub studentphoto {
2419: my ($udom,$unam,$ext) = @_;
2420: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2421: if (defined($env{'request.course.id'})) {
1.708 raeburn 2422: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2423: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2424: return(&retrievestudentphoto($udom,$unam,$ext));
2425: } else {
2426: my ($result,$perm_reqd)=
1.707 albertel 2427: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2428: if ($result eq 'ok') {
2429: if (!($perm_reqd eq 'yes')) {
2430: return(&retrievestudentphoto($udom,$unam,$ext));
2431: }
2432: }
2433: }
2434: }
2435: } else {
2436: my ($result,$perm_reqd) =
1.707 albertel 2437: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2438: if ($result eq 'ok') {
2439: if (!($perm_reqd eq 'yes')) {
2440: return(&retrievestudentphoto($udom,$unam,$ext));
2441: }
2442: }
2443: }
2444: return '/adm/lonKaputt/lonlogo_broken.gif';
2445: }
2446:
2447: sub retrievestudentphoto {
2448: my ($udom,$unam,$ext,$type) = @_;
2449: my $home=&Apache::lonnet::homeserver($unam,$udom);
2450: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2451: if ($ret eq 'ok') {
2452: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2453: if ($type eq 'thumbnail') {
2454: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2455: }
2456: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2457: return $tokenurl;
2458: } else {
2459: if ($type eq 'thumbnail') {
2460: return '/adm/lonKaputt/genericstudent_tn.gif';
2461: } else {
2462: return '/adm/lonKaputt/lonlogo_broken.gif';
2463: }
1.617 albertel 2464: }
2465: }
2466:
1.263 www 2467: # -------------------------------------------------------------------- New chat
2468:
2469: sub chatsend {
1.724 raeburn 2470: my ($newentry,$anon,$group)=@_;
1.620 albertel 2471: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2472: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2473: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2474: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2475: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2476: &escape($newentry)).':'.$group,$chome);
1.292 www 2477: }
2478:
2479: # ------------------------------------------ Find current version of a resource
2480:
2481: sub getversion {
2482: my $fname=&clutter(shift);
1.1189 raeburn 2483: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2484: return ¤tversion(&filelocation('',$fname));
2485: }
2486:
2487: sub currentversion {
2488: my $fname=shift;
2489: my $author=$fname;
2490: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2491: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2492: my $home=&homeserver($uname,$udom);
1.292 www 2493: if ($home eq 'no_host') {
2494: return -1;
2495: }
1.1112 www 2496: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2497: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2498: return -1;
2499: }
1.1112 www 2500: return $answer;
1.263 www 2501: }
2502:
1.1111 www 2503: #
2504: # Return special version number of resource if set by override, empty otherwise
2505: #
2506: sub usedversion {
2507: my $fname=shift;
2508: unless ($fname) { $fname=$env{'request.uri'}; }
2509: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2510: if ($urlversion) { return $urlversion; }
2511: return '';
2512: }
2513:
1.1 albertel 2514: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2515:
1.1 albertel 2516: sub subscribe {
2517: my $fname=shift;
1.761 raeburn 2518: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2519: $fname=~s/[\n\r]//g;
1.1 albertel 2520: my $author=$fname;
2521: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2522: my ($udom,$uname)=split(/\//,$author);
2523: my $home=homeserver($uname,$udom);
1.335 albertel 2524: if ($home eq 'no_host') {
2525: return 'not_found';
1.1 albertel 2526: }
2527: my $answer=reply("sub:$fname",$home);
1.64 www 2528: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2529: $answer.=' by '.$home;
2530: }
1.1 albertel 2531: return $answer;
2532: }
2533:
1.8 www 2534: # -------------------------------------------------------------- Replicate file
2535:
2536: sub repcopy {
2537: my $filename=shift;
1.23 www 2538: $filename=~s/\/+/\//g;
1.1142 raeburn 2539: my $londocroot = $perlvar{'lonDocRoot'};
2540: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2541: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2542: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2543: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2544: return &repcopy_userfile($filename);
2545: }
1.532 albertel 2546: $filename=~s/[\n\r]//g;
1.8 www 2547: my $transname="$filename.in.transfer";
1.828 www 2548: # FIXME: this should flock
1.607 raeburn 2549: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2550: my $remoteurl=subscribe($filename);
1.64 www 2551: if ($remoteurl =~ /^con_lost by/) {
2552: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2553: return 'unavailable';
1.8 www 2554: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2555: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2556: return 'not_found';
1.64 www 2557: } elsif ($remoteurl =~ /^rejected by/) {
2558: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2559: return 'forbidden';
1.20 www 2560: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2561: return 'ok';
1.8 www 2562: } else {
1.290 www 2563: my $author=$filename;
2564: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2565: my ($udom,$uname)=split(/\//,$author);
2566: my $home=homeserver($uname,$udom);
2567: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2568: my @parts=split(/\//,$filename);
2569: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2570: if ($path ne "$londocroot/res") {
1.8 www 2571: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2572: return 'bad_request';
1.8 www 2573: }
2574: my $count;
2575: for ($count=5;$count<$#parts;$count++) {
2576: $path.="/$parts[$count]";
2577: if ((-e $path)!=1) {
2578: mkdir($path,0777);
2579: }
2580: }
2581: my $ua=new LWP::UserAgent;
2582: my $request=new HTTP::Request('GET',"$remoteurl");
2583: my $response=$ua->request($request,$transname);
2584: if ($response->is_error()) {
2585: unlink($transname);
2586: my $message=$response->status_line;
1.672 albertel 2587: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2588: ." LWP get: $message: $filename</font>");
1.607 raeburn 2589: return 'unavailable';
1.8 www 2590: } else {
1.16 www 2591: if ($remoteurl!~/\.meta$/) {
2592: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2593: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2594: if ($mresponse->is_error()) {
2595: unlink($filename.'.meta');
2596: &logthis(
1.672 albertel 2597: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2598: }
2599: }
1.8 www 2600: rename($transname,$filename);
1.607 raeburn 2601: return 'ok';
1.8 www 2602: }
1.290 www 2603: }
1.8 www 2604: }
1.330 www 2605: }
2606:
2607: # ------------------------------------------------ Get server side include body
2608: sub ssi_body {
1.381 albertel 2609: my ($filelink,%form)=@_;
1.606 matthew 2610: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2611: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2612: }
1.953 www 2613: my $output='';
2614: my $response;
1.980 raeburn 2615: if ($filelink=~/^https?\:/) {
1.954 raeburn 2616: ($output,$response)=&externalssi($filelink);
1.953 www 2617: } else {
1.1004 droeschl 2618: $filelink .= $filelink=~/\?/ ? '&' : '?';
2619: $filelink .= 'inhibitmenu=yes';
1.953 www 2620: ($output,$response)=&ssi($filelink,%form);
2621: }
1.778 albertel 2622: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2623: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2624: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2625: if (wantarray) {
2626: return ($output, $response);
2627: } else {
2628: return $output;
2629: }
1.8 www 2630: }
2631:
1.15 www 2632: # --------------------------------------------------------- Server Side Include
2633:
1.782 albertel 2634: sub absolute_url {
2635: my ($host_name) = @_;
2636: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2637: if ($host_name eq '') {
2638: $host_name = $ENV{'SERVER_NAME'};
2639: }
2640: return $protocol.$host_name;
2641: }
2642:
1.942 foxr 2643: #
2644: # Server side include.
2645: # Parameters:
2646: # fn Possibly encrypted resource name/id.
2647: # form Hash that describes how the rendering should be done
2648: # and other things.
1.944 foxr 2649: # Returns:
1.950 raeburn 2650: # Scalar context: The content of the response.
2651: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2652: #
1.15 www 2653: sub ssi {
2654:
1.944 foxr 2655: my ($fn,%form)=@_;
1.15 www 2656: my $ua=new LWP::UserAgent;
1.23 www 2657: my $request;
1.711 albertel 2658:
2659: $form{'no_update_last_known'}=1;
1.895 albertel 2660: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2661: if (%form) {
1.782 albertel 2662: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2663: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2664: } else {
1.782 albertel 2665: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2666: }
2667:
1.15 www 2668: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2669: my $response= $ua->request($request);
1.1182 foxr 2670: my $content = $response->content;
2671:
2672:
1.944 foxr 2673: if (wantarray) {
1.1173 foxr 2674: return ($content, $response);
1.944 foxr 2675: } else {
1.1173 foxr 2676: return $content;
1.942 foxr 2677: }
1.324 www 2678: }
2679:
2680: sub externalssi {
2681: my ($url)=@_;
2682: my $ua=new LWP::UserAgent;
2683: my $request=new HTTP::Request('GET',$url);
2684: my $response=$ua->request($request);
1.954 raeburn 2685: if (wantarray) {
2686: return ($response->content, $response);
2687: } else {
2688: return $response->content;
2689: }
1.15 www 2690: }
1.254 www 2691:
1.492 albertel 2692: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2693:
2694: sub allowuploaded {
2695: my ($srcurl,$url)=@_;
2696: $url=&clutter(&declutter($url));
2697: my $dir=$url;
2698: $dir=~s/\/[^\/]+$//;
2699: my %httpref=();
2700: my $httpurl=&hreflocation('',$url);
2701: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2702: &Apache::lonnet::appenv(\%httpref);
1.254 www 2703: }
1.477 raeburn 2704:
1.1193 raeburn 2705: #
2706: # Determine if the current user should be able to edit a particular resource,
2707: # when viewing in course context.
2708: # (a) When viewing resource used to determine if "Edit" item is included in
2709: # Functions.
2710: # (b) When displaying folder contents in course editor, used to determine if
2711: # "Edit" link will be displayed alongside resource.
2712: #
1.1196 raeburn 2713: # input: six args -- filename (decluttered), course number, course domain,
2714: # url, symb (if registered) and group (if this is a group
2715: # item -- e.g., bulletin board, group page etc.).
2716: # output: array of five scalars --
1.1193 raeburn 2717: # $cfile -- url for file editing if editable on current server
2718: # $home -- homeserver of resource (i.e., for author if published,
2719: # or course if uploaded.).
2720: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 2721: # $forceedit -- 1 if icon/link should be to go to edit mode
2722: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 2723: #
2724:
2725: sub can_edit_resource {
1.1194 raeburn 2726: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2727: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2728: #
2729: # For aboutme pages user can only edit his/her own.
2730: #
1.1199 raeburn 2731: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 2732: my ($sdom,$sname) = ($1,$2);
2733: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2734: $home = $env{'user.home'};
2735: $cfile = $resurl;
2736: if ($env{'form.forceedit'}) {
2737: $forceview = 1;
2738: } else {
2739: $forceedit = 1;
2740: }
2741: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2742: } else {
2743: return;
2744: }
2745: }
2746:
2747: if ($env{'request.course.id'}) {
2748: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2749: if ($group ne '') {
2750: # if this is a group homepage or group bulletin board, check group privs
2751: my $allowed = 0;
1.1197 raeburn 2752: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2753: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 2754: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 2755: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2756: $allowed = 1;
2757: }
1.1197 raeburn 2758: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2759: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2760: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 2761: $allowed = 1;
2762: }
2763: }
2764: if ($allowed) {
2765: $home=&homeserver($cnum,$cdom);
2766: if ($env{'form.forceedit'}) {
2767: $forceview = 1;
2768: } else {
2769: $forceedit = 1;
2770: }
2771: $cfile = $resurl;
2772: } else {
2773: return;
2774: }
2775: } else {
1.1208 raeburn 2776: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2777: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2778: return;
2779: }
2780: } elsif (!$crsedit) {
1.1194 raeburn 2781: #
2782: # No edit allowed where CC has switched to student role.
2783: #
2784: return;
2785: }
2786: }
2787: }
2788:
1.1193 raeburn 2789: if ($file ne '') {
2790: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 2791: if (&is_course_upload($file,$cnum,$cdom)) {
2792: $uploaded = 1;
2793: $incourse = 1;
1.1193 raeburn 2794: if ($file =~/\.(htm|html|css|js|txt)$/) {
2795: $cfile = &hreflocation('',$file);
1.1201 raeburn 2796: if ($env{'form.forceedit'}) {
2797: $forceview = 1;
2798: } else {
2799: $forceedit = 1;
2800: }
1.1194 raeburn 2801: }
2802: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2803: $incourse = 1;
2804: if ($env{'form.forceedit'}) {
2805: $forceview = 1;
2806: } else {
2807: $forceedit = 1;
2808: }
2809: $cfile = $resurl;
2810: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2811: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2812: $incourse = 1;
2813: if ($env{'form.forceedit'}) {
2814: $forceview = 1;
2815: } else {
2816: $forceedit = 1;
2817: }
2818: $cfile = $resurl;
1.1199 raeburn 2819: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 2820: $incourse = 1;
2821: $cfile = $resurl.'/smpedit';
1.1199 raeburn 2822: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 2823: $incourse = 1;
1.1199 raeburn 2824: if ($env{'form.forceedit'}) {
2825: $forceview = 1;
2826: } else {
2827: $forceedit = 1;
2828: }
2829: $cfile = $resurl;
1.1208 raeburn 2830: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2831: $incourse = 1;
2832: if ($env{'form.forceedit'}) {
2833: $forceview = 1;
2834: } else {
2835: $forceedit = 1;
2836: }
2837: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 2838: }
2839: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2840: my $template = '/res/lib/templates/simpleproblem.problem';
2841: if (&is_on_map($template)) {
2842: $incourse = 1;
2843: $forceview = 1;
2844: $cfile = $template;
1.1193 raeburn 2845: }
1.1199 raeburn 2846: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2847: $incourse = 1;
2848: if ($env{'form.forceedit'}) {
2849: $forceview = 1;
2850: } else {
2851: $forceedit = 1;
2852: }
2853: $cfile = $resurl;
2854: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2855: $incourse = 1;
2856: $forceview = 1;
2857: if ($symb) {
2858: my ($map,$id,$res)=&decode_symb($symb);
2859: $env{'request.symb'} = $symb;
2860: $cfile = &clutter($res);
2861: } else {
2862: $cfile = $env{'form.suppurl'};
2863: $cfile =~ s{^http://}{};
2864: $cfile = '/adm/wrapper/ext/'.$cfile;
2865: }
1.1234 raeburn 2866: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2867: if ($env{'form.forceedit'}) {
2868: $forceview = 1;
2869: } else {
2870: $forceedit = 1;
2871: }
2872: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 2873: }
2874: }
1.1194 raeburn 2875: if ($uploaded || $incourse) {
2876: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 2877: } elsif ($file !~ m{/$}) {
1.1193 raeburn 2878: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2879: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2880: # Check that the user has permission to edit this resource
2881: my $setpriv = 1;
2882: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2883: if (defined($cfudom)) {
2884: $home=&homeserver($cfuname,$cfudom);
2885: $cfile=$file;
2886: }
2887: }
1.1194 raeburn 2888: if (($cfile ne '') && (!$incourse || $uploaded) &&
2889: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 2890: my @ids=¤t_machine_ids();
2891: unless (grep(/^\Q$home\E$/,@ids)) {
2892: $switchserver=1;
2893: }
2894: }
2895: }
1.1194 raeburn 2896: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 2897: }
2898:
2899: sub is_course_upload {
2900: my ($file,$cnum,$cdom) = @_;
2901: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2902: $uploadpath =~ s{^\/}{};
1.1201 raeburn 2903: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2904: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 2905: return 1;
2906: }
2907: return;
2908: }
2909:
1.1194 raeburn 2910: sub in_course {
1.1195 raeburn 2911: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2912: if ($hideprivileged) {
2913: my $skipuser;
1.1219 raeburn 2914: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2915: my @possdoms = ($cdom);
2916: if ($coursehash{'checkforpriv'}) {
2917: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2918: }
2919: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 2920: $skipuser = 1;
2921: if ($coursehash{'nothideprivileged'}) {
2922: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2923: my $user;
2924: if ($item =~ /:/) {
2925: $user = $item;
2926: } else {
2927: $user = join(':',split(/[\@]/,$item));
2928: }
2929: if ($user eq $uname.':'.$udom) {
2930: undef($skipuser);
2931: last;
2932: }
2933: }
2934: }
2935: if ($skipuser) {
2936: return 0;
2937: }
2938: }
2939: }
1.1194 raeburn 2940: $type ||= 'any';
2941: if (!defined($cdom) || !defined($cnum)) {
2942: my $cid = $env{'request.course.id'};
2943: $cdom = $env{'course.'.$cid.'.domain'};
2944: $cnum = $env{'course.'.$cid.'.num'};
2945: }
2946: my $typesref;
1.1195 raeburn 2947: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 2948: $typesref = ['active','previous','future'];
2949: } elsif ($type eq 'previous' || $type eq 'future') {
2950: $typesref = [$type];
2951: }
2952: my %roles = &get_my_roles($uname,$udom,'userroles',
2953: $typesref,undef,[$cdom]);
2954: my ($tmp) = keys(%roles);
2955: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
2956: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
2957: if (@course_roles > 0) {
2958: return 1;
2959: }
2960: return 0;
2961: }
2962:
1.478 albertel 2963: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2964: # input: action, courseID, current domain, intended
1.637 raeburn 2965: # path to file, source of file, instruction to parse file for objects,
2966: # ref to hash for embedded objects,
2967: # ref to hash for codebase of java objects.
1.1095 raeburn 2968: # reference to scalar to accommodate mime type determined
2969: # from File::MMagic if $parser = parse.
1.637 raeburn 2970: #
1.485 raeburn 2971: # output: url to file (if action was uploaddoc),
2972: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2973: #
1.478 albertel 2974: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2975: # course.
1.477 raeburn 2976: #
1.478 albertel 2977: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2978: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2979: # course's home server.
1.477 raeburn 2980: #
1.478 albertel 2981: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2982: # be copied from $source (current location) to
2983: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2984: # and will then be copied to
2985: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2986: # course's home server.
1.485 raeburn 2987: #
1.481 raeburn 2988: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2989: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2990: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2991: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2992: # in course's home server.
1.637 raeburn 2993: #
1.477 raeburn 2994:
2995: sub process_coursefile {
1.1095 raeburn 2996: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2997: $mimetype)=@_;
1.477 raeburn 2998: my $fetchresult;
1.638 albertel 2999: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3000: if ($action eq 'propagate') {
1.638 albertel 3001: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3002: $home);
1.481 raeburn 3003: } else {
1.477 raeburn 3004: my $fpath = '';
3005: my $fname = $file;
1.478 albertel 3006: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3007: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3008: my $filepath = &build_filepath($fpath);
1.481 raeburn 3009: if ($action eq 'copy') {
3010: if ($source eq '') {
3011: $fetchresult = 'no source file';
3012: return $fetchresult;
3013: } else {
3014: my $destination = $filepath.'/'.$fname;
3015: rename($source,$destination);
3016: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3017: $home);
1.481 raeburn 3018: }
3019: } elsif ($action eq 'uploaddoc') {
3020: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3021: print $fh $env{'form.'.$source};
1.481 raeburn 3022: close($fh);
1.637 raeburn 3023: if ($parser eq 'parse') {
1.1024 raeburn 3024: my $mm = new File::MMagic;
1.1095 raeburn 3025: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3026: if ($type eq 'text/html') {
1.1024 raeburn 3027: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3028: unless ($parse_result eq 'ok') {
3029: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3030: }
1.637 raeburn 3031: }
1.1095 raeburn 3032: if (ref($mimetype)) {
3033: $$mimetype = $type;
3034: }
1.637 raeburn 3035: }
1.477 raeburn 3036: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3037: $home);
1.481 raeburn 3038: if ($fetchresult eq 'ok') {
3039: return '/uploaded/'.$fpath.'/'.$fname;
3040: } else {
3041: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3042: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3043: return '/adm/notfound.html';
3044: }
1.477 raeburn 3045: }
3046: }
1.485 raeburn 3047: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3048: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3049: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3050: }
3051: return $fetchresult;
3052: }
3053:
1.637 raeburn 3054: sub build_filepath {
3055: my ($fpath) = @_;
3056: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3057: unless ($fpath eq '') {
3058: my @parts=split('/',$fpath);
3059: foreach my $part (@parts) {
3060: $filepath.= '/'.$part;
3061: if ((-e $filepath)!=1) {
3062: mkdir($filepath,0777);
3063: }
3064: }
3065: }
3066: return $filepath;
3067: }
3068:
3069: sub store_edited_file {
1.638 albertel 3070: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3071: my $file = $primary_url;
3072: $file =~ s#^/uploaded/$docudom/$docuname/##;
3073: my $fpath = '';
3074: my $fname = $file;
3075: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3076: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3077: my $filepath = &build_filepath($fpath);
3078: open(my $fh,'>'.$filepath.'/'.$fname);
3079: print $fh $content;
3080: close($fh);
1.638 albertel 3081: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3082: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3083: $home);
1.637 raeburn 3084: if ($$fetchresult eq 'ok') {
3085: return '/uploaded/'.$fpath.'/'.$fname;
3086: } else {
1.638 albertel 3087: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3088: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3089: return '/adm/notfound.html';
3090: }
3091: }
3092:
1.531 albertel 3093: sub clean_filename {
1.831 albertel 3094: my ($fname,$args)=@_;
1.315 www 3095: # Replace Windows backslashes by forward slashes
1.257 www 3096: $fname=~s/\\/\//g;
1.831 albertel 3097: if (!$args->{'keep_path'}) {
3098: # Get rid of everything but the actual filename
3099: $fname=~s/^.*\/([^\/]+)$/$1/;
3100: }
1.315 www 3101: # Replace spaces by underscores
3102: $fname=~s/\s+/\_/g;
3103: # Replace all other weird characters by nothing
1.831 albertel 3104: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3105: # Replace all .\d. sequences with _\d. so they no longer look like version
3106: # numbers
3107: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3108: return $fname;
3109: }
1.1051 raeburn 3110: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3111: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3112: # image with the same aspect ratio as the original, but with dimensions which do
3113: # not exceed $resizewidth and $resizeheight.
3114:
1.984 neumanie 3115: sub resizeImage {
1.1051 raeburn 3116: my ($img_path,$resizewidth,$resizeheight) = @_;
3117: my $ima = Image::Magick->new;
3118: my $resized;
3119: if (-e $img_path) {
3120: $ima->Read($img_path);
3121: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3122: my $width = $ima->Get('width');
3123: my $height = $ima->Get('height');
3124: if ($width > $resizewidth) {
3125: my $factor = $width/$resizewidth;
3126: my $newheight = $height/$factor;
3127: $ima->Scale(width=>$resizewidth,height=>$newheight);
3128: $resized = 1;
3129: }
3130: }
3131: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3132: my $width = $ima->Get('width');
3133: my $height = $ima->Get('height');
3134: if ($height > $resizeheight) {
3135: my $factor = $height/$resizeheight;
3136: my $newwidth = $width/$factor;
3137: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3138: $resized = 1;
3139: }
3140: }
3141: if ($resized) {
3142: $ima->Write($img_path);
3143: }
3144: }
3145: return;
1.977 amueller 3146: }
3147:
1.608 albertel 3148: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3149: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3150: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3151: # $context - possible values: coursedoc, existingfile, overwrite,
3152: # canceloverwrite, or ''.
3153: # if 'coursedoc': upload to the current course
3154: # if 'existingfile': write file to tmp/overwrites directory
3155: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3156: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3157: # $subdir - directory in userfile to store the file into
1.858 raeburn 3158: # $parser - instruction to parse file for objects ($parser = parse)
3159: # $allfiles - reference to hash for embedded objects
3160: # $codebase - reference to hash for codebase of java objects
3161: # $desuname - username for permanent storage of uploaded file
3162: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3163: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3164: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3165: # $resizewidth - width (pixels) to which to resize uploaded image
3166: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3167: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3168: # from File::MMagic.
1.858 raeburn 3169: #
1.686 albertel 3170: # output: url of file in userspace, or error: <message>
3171: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3172:
1.531 albertel 3173: sub userfileupload {
1.1090 raeburn 3174: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3175: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3176: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3177: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3178: $fname=&clean_filename($fname);
1.1090 raeburn 3179: # See if there is anything left
1.257 www 3180: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3181: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3182: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3183: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3184: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3185: my $now = time;
1.1090 raeburn 3186: my $filepath;
1.1095 raeburn 3187: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3188: $filepath = 'tmp/helprequests/'.$now;
3189: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3190: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3191: '_'.$env{'user.domain'}.'/pending';
3192: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3193: my ($docuname,$docudom);
3194: if ($destudom) {
3195: $docudom = $destudom;
3196: } else {
3197: $docudom = $env{'user.domain'};
3198: }
3199: if ($destuname) {
3200: $docuname = $destuname;
3201: } else {
3202: $docuname = $env{'user.name'};
3203: }
3204: if (exists($env{'form.group'})) {
3205: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3206: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3207: }
3208: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3209: if ($context eq 'canceloverwrite') {
3210: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3211: if (-e $tempfile) {
3212: my @info = stat($tempfile);
3213: if ($info[9] eq $env{'form.timestamp'}) {
3214: unlink($tempfile);
3215: }
3216: }
3217: return;
1.523 raeburn 3218: }
3219: }
1.1090 raeburn 3220: # Create the directory if not present
1.741 raeburn 3221: my @parts=split(/\//,$filepath);
3222: my $fullpath = $perlvar{'lonDaemons'};
3223: for (my $i=0;$i<@parts;$i++) {
3224: $fullpath .= '/'.$parts[$i];
3225: if ((-e $fullpath)!=1) {
3226: mkdir($fullpath,0777);
3227: }
3228: }
3229: open(my $fh,'>'.$fullpath.'/'.$fname);
3230: print $fh $env{'form.'.$formname};
3231: close($fh);
1.1090 raeburn 3232: if ($context eq 'existingfile') {
3233: my @info = stat($fullpath.'/'.$fname);
3234: return ($fullpath.'/'.$fname,$info[9]);
3235: } else {
3236: return $fullpath.'/'.$fname;
3237: }
1.523 raeburn 3238: }
1.995 raeburn 3239: if ($subdir eq 'scantron') {
3240: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3241: } else {
1.995 raeburn 3242: $fname="$subdir/$fname";
3243: }
1.1090 raeburn 3244: if ($context eq 'coursedoc') {
1.638 albertel 3245: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3246: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3247: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3248: return &finishuserfileupload($docuname,$docudom,
3249: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3250: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3251: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3252: } else {
1.1218 raeburn 3253: if ($env{'form.folder'}) {
3254: $fname=$env{'form.folder'}.'/'.$fname;
3255: }
1.638 albertel 3256: return &process_coursefile('uploaddoc',$docuname,$docudom,
3257: $fname,$formname,$parser,
1.1095 raeburn 3258: $allfiles,$codebase,$mimetype);
1.481 raeburn 3259: }
1.719 banghart 3260: } elsif (defined($destuname)) {
3261: my $docuname=$destuname;
3262: my $docudom=$destudom;
1.860 raeburn 3263: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3264: $parser,$allfiles,$codebase,
1.1051 raeburn 3265: $thumbwidth,$thumbheight,
1.1095 raeburn 3266: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3267: } else {
1.638 albertel 3268: my $docuname=$env{'user.name'};
3269: my $docudom=$env{'user.domain'};
1.1220 raeburn 3270: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3271: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3272: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3273: }
1.860 raeburn 3274: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3275: $parser,$allfiles,$codebase,
1.1051 raeburn 3276: $thumbwidth,$thumbheight,
1.1095 raeburn 3277: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3278: }
1.271 www 3279: }
3280:
3281: sub finishuserfileupload {
1.860 raeburn 3282: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3283: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3284: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3285: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3286:
1.860 raeburn 3287: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3288: $file=$fname;
3289: if ($fname=~m|/|) {
3290: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3291: $path.=$fnamepath.'/';
3292: }
1.259 www 3293: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3294: my $count;
3295: for ($count=4;$count<=$#parts;$count++) {
3296: $filepath.="/$parts[$count]";
3297: if ((-e $filepath)!=1) {
3298: mkdir($filepath,0777);
3299: }
3300: }
1.984 neumanie 3301:
1.258 www 3302: # Save the file
3303: {
1.701 albertel 3304: if (!open(FH,'>'.$filepath.'/'.$file)) {
3305: &logthis('Failed to create '.$filepath.'/'.$file);
3306: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3307: return '/adm/notfound.html';
3308: }
1.1090 raeburn 3309: if ($context eq 'overwrite') {
1.1117 foxr 3310: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3311: my $target = $filepath.'/'.$file;
3312: if (-e $source) {
3313: my @info = stat($source);
3314: if ($info[9] eq $env{'form.timestamp'}) {
3315: unless (&File::Copy::move($source,$target)) {
3316: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3317: return "Moving from $source failed";
3318: }
3319: } else {
3320: return "Temporary file: $source had unexpected date/time for last modification";
3321: }
3322: } else {
3323: return "Temporary file: $source missing";
3324: }
3325: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3326: &logthis('Failed to write to '.$filepath.'/'.$file);
3327: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3328: return '/adm/notfound.html';
3329: }
1.570 albertel 3330: close(FH);
1.1051 raeburn 3331: if ($resizewidth && $resizeheight) {
3332: my $mm = new File::MMagic;
3333: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3334: if ($mime_type =~ m{^image/}) {
3335: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3336: }
1.977 amueller 3337: }
1.258 www 3338: }
1.1152 raeburn 3339: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3340: if (ref($mimetype)) {
3341: if ($$mimetype eq '') {
3342: my $mm = new File::MMagic;
3343: my $type = $mm->checktype_filename($filepath.'/'.$file);
3344: $$mimetype = $type;
3345: }
3346: }
3347: }
1.637 raeburn 3348: if ($parser eq 'parse') {
1.1152 raeburn 3349: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3350: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3351: $allfiles,$codebase);
3352: unless ($parse_result eq 'ok') {
3353: &logthis('Failed to parse '.$filepath.$file.
3354: ' for embedded media: '.$parse_result);
3355: }
1.637 raeburn 3356: }
3357: }
1.860 raeburn 3358: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3359: my $input = $filepath.'/'.$file;
3360: my $output = $filepath.'/'.'tn-'.$file;
3361: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3362: system("convert -sample $thumbsize $input $output");
3363: if (-e $filepath.'/'.'tn-'.$file) {
3364: $fetchthumb = 1;
3365: }
3366: }
1.858 raeburn 3367:
1.259 www 3368: # Notify homeserver to grep it
3369: #
1.984 neumanie 3370: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3371: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3372: if ($fetchresult eq 'ok') {
1.860 raeburn 3373: if ($fetchthumb) {
3374: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3375: if ($thumbresult ne 'ok') {
3376: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3377: $docuhome.': '.$thumbresult);
3378: }
3379: }
1.259 www 3380: #
1.258 www 3381: # Return the URL to it
1.494 albertel 3382: return '/uploaded/'.$path.$file;
1.263 www 3383: } else {
1.494 albertel 3384: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3385: ': '.$fetchresult);
1.263 www 3386: return '/adm/notfound.html';
1.858 raeburn 3387: }
1.493 albertel 3388: }
3389:
1.637 raeburn 3390: sub extract_embedded_items {
1.961 raeburn 3391: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3392: my @state = ();
1.1164 raeburn 3393: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3394: my %javafiles = (
3395: codebase => '',
3396: code => '',
3397: archive => ''
3398: );
3399: my %mediafiles = (
3400: src => '',
3401: movie => '',
3402: );
1.648 raeburn 3403: my $p;
3404: if ($content) {
3405: $p = HTML::LCParser->new($content);
3406: } else {
1.961 raeburn 3407: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3408: }
1.641 albertel 3409: while (my $t=$p->get_token()) {
1.640 albertel 3410: if ($t->[0] eq 'S') {
3411: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3412: push(@state, $tagname);
1.648 raeburn 3413: if (lc($tagname) eq 'allow') {
3414: &add_filetype($allfiles,$attr->{'src'},'src');
3415: }
1.640 albertel 3416: if (lc($tagname) eq 'img') {
3417: &add_filetype($allfiles,$attr->{'src'},'src');
3418: }
1.886 albertel 3419: if (lc($tagname) eq 'a') {
1.1222 raeburn 3420: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3421: &add_filetype($allfiles,$attr->{'href'},'href');
3422: }
1.886 albertel 3423: }
1.645 raeburn 3424: if (lc($tagname) eq 'script') {
1.1164 raeburn 3425: my $src;
1.645 raeburn 3426: if ($attr->{'archive'} =~ /\.jar$/i) {
3427: &add_filetype($allfiles,$attr->{'archive'},'archive');
3428: } else {
1.1164 raeburn 3429: if ($attr->{'src'} ne '') {
3430: $src = $attr->{'src'};
3431: &add_filetype($allfiles,$src,'src');
3432: }
3433: }
3434: my $text = $p->get_trimmed_text();
3435: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3436: my @swfargs = split(/,/,$1);
3437: foreach my $item (@swfargs) {
3438: $item =~ s/["']//g;
3439: $item =~ s/^\s+//;
3440: $item =~ s/\s+$//;
3441: }
3442: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3443: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3444: push(@{$related{$swfargs[0]}},$swfargs[2]);
3445: } else {
3446: $related{$swfargs[0]} = [$swfargs[2]];
3447: }
3448: }
1.645 raeburn 3449: }
3450: }
3451: if (lc($tagname) eq 'link') {
3452: if (lc($attr->{'rel'}) eq 'stylesheet') {
3453: &add_filetype($allfiles,$attr->{'href'},'href');
3454: }
3455: }
1.640 albertel 3456: if (lc($tagname) eq 'object' ||
3457: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3458: foreach my $item (keys(%javafiles)) {
3459: $javafiles{$item} = '';
3460: }
1.1164 raeburn 3461: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3462: $lastids{lc($tagname)} = $attr->{'id'};
3463: }
1.640 albertel 3464: }
3465: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3466: my $name = lc($attr->{'name'});
3467: foreach my $item (keys(%javafiles)) {
3468: if ($name eq $item) {
3469: $javafiles{$item} = $attr->{'value'};
3470: last;
3471: }
3472: }
1.1164 raeburn 3473: my $pathfrom;
1.640 albertel 3474: foreach my $item (keys(%mediafiles)) {
3475: if ($name eq $item) {
1.1164 raeburn 3476: $pathfrom = $attr->{'value'};
3477: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3478: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3479: last;
3480: }
3481: }
1.1164 raeburn 3482: if ($name eq 'flashvars') {
3483: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3484: }
3485: if ($pathfrom ne '') {
3486: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3487: $pathfrom);
3488: }
1.640 albertel 3489: }
3490: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3491: foreach my $item (keys(%javafiles)) {
3492: if ($attr->{$item}) {
3493: $javafiles{$item} = $attr->{$item};
3494: last;
3495: }
3496: }
3497: foreach my $item (keys(%mediafiles)) {
3498: if ($attr->{$item}) {
3499: &add_filetype($allfiles,$attr->{$item},$item);
3500: last;
3501: }
3502: }
1.1164 raeburn 3503: if (lc($tagname) eq 'embed') {
3504: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3505: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3506: $attr->{'src'});
3507: }
3508: }
1.640 albertel 3509: }
1.1243 raeburn 3510: if (lc($tagname) eq 'iframe') {
3511: my $src = $attr->{'src'} ;
3512: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3513: &add_filetype($allfiles,$src,'src');
3514: } elsif ($src =~ m{^/}) {
3515: if ($env{'request.course.id'}) {
3516: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3517: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3518: my $url = &hreflocation('',$fullpath);
3519: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3520: my $relpath = $1;
3521: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3522: &add_filetype($allfiles,$1,'src');
3523: }
3524: }
3525: }
3526: }
3527: }
1.1164 raeburn 3528: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3529: pop(@state);
1.1164 raeburn 3530: }
1.640 albertel 3531: } elsif ($t->[0] eq 'E') {
3532: my ($tagname) = ($t->[1]);
3533: if ($javafiles{'codebase'} ne '') {
3534: $javafiles{'codebase'} .= '/';
3535: }
3536: if (lc($tagname) eq 'applet' ||
3537: lc($tagname) eq 'object' ||
3538: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3539: ) {
3540: foreach my $item (keys(%javafiles)) {
3541: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3542: my $file=$javafiles{'codebase'}.$javafiles{$item};
3543: &add_filetype($allfiles,$file,$item);
3544: }
3545: }
3546: }
3547: pop @state;
3548: }
3549: }
1.1164 raeburn 3550: foreach my $id (sort(keys(%flashvars))) {
3551: if ($shockwave{$id} ne '') {
3552: my @pairs = split(/\&/,$flashvars{$id});
3553: foreach my $pair (@pairs) {
3554: my ($key,$value) = split(/\=/,$pair);
3555: if ($key eq 'thumb') {
3556: &add_filetype($allfiles,$value,$key);
3557: } elsif ($key eq 'content') {
3558: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3559: my ($ext) = ($value =~ /\.([^.]+)$/);
3560: if ($ext ne '') {
3561: &add_filetype($allfiles,$path.$value,$ext);
3562: }
3563: }
3564: }
3565: }
3566: }
1.637 raeburn 3567: return 'ok';
3568: }
3569:
1.639 albertel 3570: sub add_filetype {
3571: my ($allfiles,$file,$type)=@_;
3572: if (exists($allfiles->{$file})) {
3573: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3574: push(@{$allfiles->{$file}}, &escape($type));
3575: }
3576: } else {
3577: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3578: }
3579: }
3580:
1.1164 raeburn 3581: sub embedded_dependency {
3582: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3583: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3584: if (($identifier ne '') &&
3585: (ref($related->{$identifier}) eq 'ARRAY') &&
3586: ($pathfrom ne '')) {
3587: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3588: foreach my $dep (@{$related->{$identifier}}) {
3589: &add_filetype($allfiles,$path.$dep,'object');
3590: }
3591: }
3592: }
3593: return;
3594: }
3595:
1.493 albertel 3596: sub removeuploadedurl {
1.984 neumanie 3597: my ($url)=@_;
3598: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3599: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3600: }
3601:
3602: sub removeuserfile {
3603: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3604: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3605: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3606: if ($result eq 'ok') {
1.798 raeburn 3607: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3608: my $metafile = $fname.'.meta';
3609: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3610: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3611: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3612: my $sqlresult =
1.823 albertel 3613: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3614: 'portfolio_metadata',$group,
3615: 'delete');
1.798 raeburn 3616: }
3617: }
3618: return $result;
1.257 www 3619: }
1.15 www 3620:
1.530 albertel 3621: sub mkdiruserfile {
3622: my ($docuname,$docudom,$dir)=@_;
3623: my $home=&homeserver($docuname,$docudom);
3624: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3625: }
3626:
1.531 albertel 3627: sub renameuserfile {
3628: my ($docuname,$docudom,$old,$new)=@_;
3629: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3630: my $result = &reply("renameuserfile:$docudom:$docuname:".
3631: &escape("$old").':'.&escape("$new"),$home);
3632: if ($result eq 'ok') {
3633: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3634: my $oldmeta = $old.'.meta';
3635: my $newmeta = $new.'.meta';
3636: my $metaresult =
3637: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3638: my $url = "/uploaded/$docudom/$docuname/$old";
3639: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3640: my $sqlresult =
1.823 albertel 3641: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3642: 'portfolio_metadata',$group,
3643: 'delete');
1.798 raeburn 3644: }
3645: }
3646: return $result;
1.531 albertel 3647: }
3648:
1.14 www 3649: # ------------------------------------------------------------------------- Log
3650:
3651: sub log {
3652: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3653: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3654: }
3655:
3656: # ------------------------------------------------------------------ Course Log
1.352 www 3657: #
3658: # This routine flushes several buffers of non-mission-critical nature
3659: #
1.157 www 3660:
3661: sub flushcourselogs {
1.352 www 3662: &logthis('Flushing log buffers');
3663: #
3664: # course logs
3665: # This is a log of all transactions in a course, which can be used
3666: # for data mining purposes
3667: #
3668: # It also collects the courseid database, which lists last transaction
3669: # times and course titles for all courseids
3670: #
3671: my %courseidbuffer=();
1.921 raeburn 3672: foreach my $crsid (keys(%courselogs)) {
1.352 www 3673: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3674: &escape($courselogs{$crsid}),
3675: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3676: delete $courselogs{$crsid};
3677: } else {
3678: &logthis('Failed to flush log buffer for '.$crsid);
3679: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3680: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3681: " exceeded maximum size, deleting.</font>");
3682: delete $courselogs{$crsid};
3683: }
1.352 www 3684: }
1.920 raeburn 3685: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3686: 'description' => $coursedescrbuf{$crsid},
3687: 'inst_code' => $courseinstcodebuf{$crsid},
3688: 'type' => $coursetypebuf{$crsid},
3689: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3690: };
1.191 harris41 3691: }
1.352 www 3692: #
3693: # Write course id database (reverse lookup) to homeserver of courses
3694: # Is used in pickcourse
3695: #
1.840 albertel 3696: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3697: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3698: $courseidbuffer{$crs_home},
3699: $crs_home,'timeonly');
1.352 www 3700: }
3701: #
3702: # File accesses
3703: # Writes to the dynamic metadata of resources to get hit counts, etc.
3704: #
1.449 matthew 3705: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3706: if ($entry =~ /___count$/) {
3707: my ($dom,$name);
1.807 albertel 3708: ($dom,$name,undef)=
1.811 albertel 3709: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3710: if (! defined($dom) || $dom eq '' ||
3711: ! defined($name) || $name eq '') {
1.620 albertel 3712: my $cid = $env{'request.course.id'};
3713: $dom = $env{'request.'.$cid.'.domain'};
3714: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3715: }
1.450 matthew 3716: my $value = $accesshash{$entry};
3717: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3718: my %temphash=($url => $value);
1.449 matthew 3719: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3720: if ($result eq 'ok') {
3721: delete $accesshash{$entry};
3722: }
3723: } else {
1.811 albertel 3724: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3725: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3726: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3727: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3728: delete $accesshash{$entry};
3729: }
1.185 www 3730: }
1.191 harris41 3731: }
1.352 www 3732: #
3733: # Roles
3734: # Reverse lookup of user roles for course faculty/staff and co-authorship
3735: #
1.800 albertel 3736: foreach my $entry (keys(%userrolehash)) {
1.351 www 3737: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3738: split(/\:/,$entry);
3739: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3740: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3741: $rudom,$runame) eq 'ok') {
3742: delete $userrolehash{$entry};
3743: }
3744: }
1.662 raeburn 3745: #
3746: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3747: #
3748: my %domrolebuffer = ();
1.1000 raeburn 3749: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3750: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3751: if ($domrolebuffer{$rudom}) {
3752: $domrolebuffer{$rudom}.='&'.&escape($entry).
3753: '='.&escape($domainrolehash{$entry});
3754: } else {
3755: $domrolebuffer{$rudom}.=&escape($entry).
3756: '='.&escape($domainrolehash{$entry});
3757: }
3758: delete $domainrolehash{$entry};
3759: }
3760: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3761: my %servers = &get_servers($dom,'library');
3762: foreach my $tryserver (keys(%servers)) {
3763: unless (&reply('domroleput:'.$dom.':'.
3764: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3765: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3766: }
1.662 raeburn 3767: }
3768: }
1.186 www 3769: $dumpcount++;
1.157 www 3770: }
3771:
3772: sub courselog {
3773: my $what=shift;
1.158 www 3774: $what=time.':'.$what;
1.620 albertel 3775: unless ($env{'request.course.id'}) { return ''; }
3776: $coursedombuf{$env{'request.course.id'}}=
3777: $env{'course.'.$env{'request.course.id'}.'.domain'};
3778: $coursenumbuf{$env{'request.course.id'}}=
3779: $env{'course.'.$env{'request.course.id'}.'.num'};
3780: $coursehombuf{$env{'request.course.id'}}=
3781: $env{'course.'.$env{'request.course.id'}.'.home'};
3782: $coursedescrbuf{$env{'request.course.id'}}=
3783: $env{'course.'.$env{'request.course.id'}.'.description'};
3784: $courseinstcodebuf{$env{'request.course.id'}}=
3785: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3786: $courseownerbuf{$env{'request.course.id'}}=
3787: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3788: $coursetypebuf{$env{'request.course.id'}}=
3789: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3790: if (defined $courselogs{$env{'request.course.id'}}) {
3791: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3792: } else {
1.620 albertel 3793: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3794: }
1.620 albertel 3795: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3796: &flushcourselogs();
3797: }
1.158 www 3798: }
3799:
3800: sub courseacclog {
3801: my $fnsymb=shift;
1.620 albertel 3802: unless ($env{'request.course.id'}) { return ''; }
3803: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3804: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3805: $what.=':POST';
1.583 matthew 3806: # FIXME: Probably ought to escape things....
1.800 albertel 3807: foreach my $key (keys(%env)) {
3808: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3809: my $formitem = $1;
3810: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3811: $what.=':'.$formitem.'='.$env{$key};
3812: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3813: $what.=':'.$formitem.'='.$env{$key};
3814: }
1.158 www 3815: }
1.191 harris41 3816: }
1.583 matthew 3817: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3818: # FIXME: We should not be depending on a form parameter that someone
3819: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3820: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3821: $what.= ':POST';
3822: # FIXME: Probably ought to escape things....
3823: foreach my $element ('courseexp','crsfulltext','crsrelated',
3824: 'crsdiscuss') {
1.620 albertel 3825: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3826: }
3827: }
1.158 www 3828: }
3829: &courselog($what);
1.149 www 3830: }
3831:
1.185 www 3832: sub countacc {
3833: my $url=&declutter(shift);
1.458 matthew 3834: return if (! defined($url) || $url eq '');
1.620 albertel 3835: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3836: #
3837: # Mark that this url was used in this course
3838: #
1.620 albertel 3839: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3840: #
3841: # Increase the access count for this resource in this child process
3842: #
1.281 www 3843: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3844: $accesshash{$key}++;
1.185 www 3845: }
1.349 www 3846:
1.361 www 3847: sub linklog {
3848: my ($from,$to)=@_;
3849: $from=&declutter($from);
3850: $to=&declutter($to);
3851: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3852: $accesshash{$to.'___'.$from.'___goto'}=1;
3853: }
1.1160 www 3854:
3855: sub statslog {
3856: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3857: if ($users<2) { return; }
3858: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3859: 'course' => $env{'request.course.id'},
3860: 'sections' => '"all"',
3861: 'num_students' => $users,
3862: 'part' => $part,
3863: 'symb' => $symb,
3864: 'mean_tries' => $av_attempts,
3865: 'deg_of_diff' => $degdiff});
3866: foreach my $key (keys(%dynstore)) {
3867: $accesshash{$key}=$dynstore{$key};
3868: }
3869: }
1.361 www 3870:
1.349 www 3871: sub userrolelog {
3872: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3873: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3874: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3875: $userrolehash
3876: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3877: =$tend.':'.$tstart;
1.662 raeburn 3878: }
1.1169 droeschl 3879: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3880: $userrolehash
3881: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3882: =$tend.':'.$tstart;
3883: }
1.1169 droeschl 3884: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3885: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3886: $domainrolehash
3887: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3888: = $tend.':'.$tstart;
3889: }
1.351 www 3890: }
3891:
1.957 raeburn 3892: sub courserolelog {
3893: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 3894: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3895: my $cdom = $1;
3896: my $cnum = $2;
3897: my $sec = $3;
3898: my $namespace = 'rolelog';
3899: my %storehash = (
3900: role => $trole,
3901: start => $tstart,
3902: end => $tend,
3903: selfenroll => $selfenroll,
3904: context => $context,
3905: );
3906: if ($trole eq 'gr') {
3907: $namespace = 'groupslog';
3908: $storehash{'group'} = $sec;
3909: } else {
3910: $storehash{'section'} = $sec;
3911: }
1.1188 raeburn 3912: &write_log('course',$namespace,\%storehash,$delflag,$username,
3913: $domain,$cnum,$cdom);
1.1184 raeburn 3914: if (($trole ne 'st') || ($sec ne '')) {
3915: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3916: }
3917: }
3918: return;
3919: }
3920:
1.1184 raeburn 3921: sub domainrolelog {
3922: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3923: if ($area =~ m{^/($match_domain)/$}) {
3924: my $cdom = $1;
3925: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3926: my $namespace = 'rolelog';
3927: my %storehash = (
3928: role => $trole,
3929: start => $tstart,
3930: end => $tend,
3931: context => $context,
3932: );
1.1188 raeburn 3933: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3934: $domain,$domconfiguser,$cdom);
1.1184 raeburn 3935: }
3936: return;
3937:
3938: }
3939:
3940: sub coauthorrolelog {
3941: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3942: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3943: my $audom = $1;
3944: my $auname = $2;
3945: my $namespace = 'rolelog';
3946: my %storehash = (
3947: role => $trole,
3948: start => $tstart,
3949: end => $tend,
3950: context => $context,
3951: );
1.1188 raeburn 3952: &write_log('author',$namespace,\%storehash,$delflag,$username,
3953: $domain,$auname,$audom);
1.1184 raeburn 3954: }
3955: return;
3956: }
3957:
1.351 www 3958: sub get_course_adv_roles {
1.948 raeburn 3959: my ($cid,$codes) = @_;
1.620 albertel 3960: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3961: my %coursehash=&coursedescription($cid);
1.988 raeburn 3962: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3963: my %nothide=();
1.800 albertel 3964: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3965: if ($user !~ /:/) {
3966: $nothide{join(':',split(/[\@]/,$user))}=1;
3967: } else {
3968: $nothide{$user}=1;
3969: }
1.470 www 3970: }
1.1219 raeburn 3971: my @possdoms = ($coursehash{'domain'});
3972: if ($coursehash{'checkforpriv'}) {
3973: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3974: }
1.351 www 3975: my %returnhash=();
3976: my %dumphash=
3977: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3978: my $now=time;
1.997 raeburn 3979: my %privileged;
1.1000 raeburn 3980: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3981: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3982: if (($tstart) && ($tstart<0)) { next; }
3983: if (($tend) && ($tend<$now)) { next; }
3984: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3985: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3986: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 3987: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 3988: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3989: if ($role eq 'cr') { next; }
1.948 raeburn 3990: if ($codes) {
3991: if ($section) { $role .= ':'.$section; }
3992: if ($returnhash{$role}) {
3993: $returnhash{$role}.=','.$username.':'.$domain;
3994: } else {
3995: $returnhash{$role}=$username.':'.$domain;
3996: }
1.351 www 3997: } else {
1.988 raeburn 3998: my $key=&plaintext($role,$crstype);
1.973 bisitz 3999: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4000: if ($returnhash{$key}) {
4001: $returnhash{$key}.=','.$username.':'.$domain;
4002: } else {
4003: $returnhash{$key}=$username.':'.$domain;
4004: }
1.351 www 4005: }
1.948 raeburn 4006: }
1.400 www 4007: return %returnhash;
4008: }
4009:
4010: sub get_my_roles {
1.937 raeburn 4011: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4012: unless (defined($uname)) { $uname=$env{'user.name'}; }
4013: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4014: my (%dumphash,%nothide);
1.1086 raeburn 4015: if ($context eq 'userroles') {
1.1166 raeburn 4016: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4017: } else {
1.1219 raeburn 4018: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4019: if ($hidepriv) {
4020: my %coursehash=&coursedescription($udom.'_'.$uname);
4021: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4022: if ($user !~ /:/) {
4023: $nothide{join(':',split(/[\@]/,$user))} = 1;
4024: } else {
4025: $nothide{$user} = 1;
4026: }
4027: }
4028: }
1.858 raeburn 4029: }
1.400 www 4030: my %returnhash=();
4031: my $now=time;
1.999 raeburn 4032: my %privileged;
1.800 albertel 4033: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4034: my ($role,$tend,$tstart);
4035: if ($context eq 'userroles') {
1.1149 raeburn 4036: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4037: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4038: } else {
4039: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4040: }
1.400 www 4041: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4042: my $status = 'active';
1.939 raeburn 4043: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4044: $status = 'previous';
4045: }
4046: if (($tstart) && ($now<$tstart)) {
4047: $status = 'future';
4048: }
4049: if (ref($types) eq 'ARRAY') {
4050: if (!grep(/^\Q$status\E$/,@{$types})) {
4051: next;
4052: }
4053: } else {
4054: if ($status ne 'active') {
4055: next;
4056: }
4057: }
1.867 raeburn 4058: my ($rolecode,$username,$domain,$section,$area);
4059: if ($context eq 'userroles') {
1.1186 raeburn 4060: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4061: (undef,$domain,$username,$section) = split(/\//,$area);
4062: } else {
4063: ($role,$username,$domain,$section) = split(/\:/,$entry);
4064: }
1.832 raeburn 4065: if (ref($roledoms) eq 'ARRAY') {
4066: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4067: next;
4068: }
4069: }
4070: if (ref($roles) eq 'ARRAY') {
4071: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4072: if ($role =~ /^cr\//) {
4073: if (!grep(/^cr$/,@{$roles})) {
4074: next;
4075: }
1.1104 raeburn 4076: } elsif ($role =~ /^gr\//) {
4077: if (!grep(/^gr$/,@{$roles})) {
4078: next;
4079: }
1.922 raeburn 4080: } else {
4081: next;
4082: }
1.832 raeburn 4083: }
1.867 raeburn 4084: }
1.937 raeburn 4085: if ($hidepriv) {
1.1219 raeburn 4086: my @privroles = ('dc','su');
1.999 raeburn 4087: if ($context eq 'userroles') {
1.1219 raeburn 4088: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4089: } else {
1.1219 raeburn 4090: my $possdoms = [$domain];
4091: if (ref($roledoms) eq 'ARRAY') {
4092: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4093: }
1.1219 raeburn 4094: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4095: if (!$nothide{$username.':'.$domain}) {
4096: next;
4097: }
4098: }
1.937 raeburn 4099: }
4100: }
1.933 raeburn 4101: if ($withsec) {
4102: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4103: $tstart.':'.$tend;
4104: } else {
4105: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4106: }
1.832 raeburn 4107: }
1.373 www 4108: return %returnhash;
1.399 www 4109: }
4110:
4111: # ----------------------------------------------------- Frontpage Announcements
4112: #
4113: #
4114:
4115: sub postannounce {
4116: my ($server,$text)=@_;
1.844 albertel 4117: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4118: unless ($text=~/\w/) { $text=''; }
4119: return &reply('setannounce:'.&escape($text),$server);
4120: }
4121:
4122: sub getannounce {
1.448 albertel 4123:
4124: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4125: my $announcement='';
1.800 albertel 4126: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4127: close($fh);
1.399 www 4128: if ($announcement=~/\w/) {
4129: return
4130: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4131: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4132: } else {
4133: return '';
4134: }
4135: } else {
4136: return '';
4137: }
1.351 www 4138: }
1.353 www 4139:
4140: # ---------------------------------------------------------- Course ID routines
4141: # Deal with domain's nohist_courseid.db files
4142: #
4143:
4144: sub courseidput {
1.921 raeburn 4145: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4146: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4147: my $outcome;
4148: if ($caller eq 'timeonly') {
4149: my $cids = '';
4150: foreach my $item (keys(%$storehash)) {
4151: $cids.=&escape($item).'&';
4152: }
4153: $cids=~s/\&$//;
4154: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4155: $coursehome);
4156: } else {
4157: my $items = '';
4158: foreach my $item (keys(%$storehash)) {
4159: $items.= &escape($item).'='.
4160: &freeze_escape($$storehash{$item}).'&';
4161: }
4162: $items=~s/\&$//;
4163: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4164: $coursehome);
1.918 raeburn 4165: }
4166: if ($outcome eq 'unknown_cmd') {
4167: my $what;
4168: foreach my $cid (keys(%$storehash)) {
4169: $what .= &escape($cid).'=';
1.921 raeburn 4170: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4171: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4172: }
4173: $what =~ s/\:$/&/;
4174: }
4175: $what =~ s/\&$//;
4176: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4177: } else {
4178: return $outcome;
4179: }
1.353 www 4180: }
4181:
4182: sub courseiddump {
1.921 raeburn 4183: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4184: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4185: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 4186: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 4187: my $as_hash = 1;
4188: my %returnhash;
4189: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4190: my %libserv = &all_library();
4191: foreach my $tryserver (keys(%libserv)) {
4192: if ( ( $hostidflag == 1
4193: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4194: || (!defined($hostidflag)) ) {
4195:
1.918 raeburn 4196: if (($domfilter eq '') ||
4197: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4198: my $rep;
4199: if (grep { $_ eq $tryserver } current_machine_ids()) {
4200: $rep = LONCAPA::Lond::dump_course_id_handler(
4201: join(":", (&host_domain($tryserver), $sincefilter,
4202: &escape($descfilter), &escape($instcodefilter),
4203: &escape($ownerfilter), &escape($coursefilter),
4204: &escape($typefilter), &escape($regexp_ok),
4205: $as_hash, &escape($selfenrollonly),
4206: &escape($catfilter), $showhidden, $caller,
4207: &escape($cloner), &escape($cc_clone), $cloneonly,
4208: &escape($createdbefore), &escape($createdafter),
4209: &escape($creationcontext), $domcloner)));
4210: } else {
4211: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4212: $sincefilter.':'.&escape($descfilter).':'.
4213: &escape($instcodefilter).':'.&escape($ownerfilter).
4214: ':'.&escape($coursefilter).':'.&escape($typefilter).
4215: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4216: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4217: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4218: &escape($cc_clone).':'.$cloneonly.':'.
4219: &escape($createdbefore).':'.&escape($createdafter).':'.
4220: &escape($creationcontext).':'.$domcloner,
4221: $tryserver);
4222: }
4223:
1.918 raeburn 4224: my @pairs=split(/\&/,$rep);
4225: foreach my $item (@pairs) {
4226: my ($key,$value)=split(/\=/,$item,2);
4227: $key = &unescape($key);
4228: next if ($key =~ /^error: 2 /);
4229: my $result = &thaw_unescape($value);
4230: if (ref($result) eq 'HASH') {
4231: $returnhash{$key}=$result;
4232: } else {
1.921 raeburn 4233: my @responses = split(/:/,$value);
4234: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4235: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4236: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4237: }
1.1008 raeburn 4238: }
1.353 www 4239: }
4240: }
4241: }
4242: }
4243: return %returnhash;
4244: }
4245:
1.1055 raeburn 4246: sub courselastaccess {
4247: my ($cdom,$cnum,$hostidref) = @_;
4248: my %returnhash;
4249: if ($cdom && $cnum) {
4250: my $chome = &homeserver($cnum,$cdom);
4251: if ($chome ne 'no_host') {
4252: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4253: &extract_lastaccess(\%returnhash,$rep);
4254: }
4255: } else {
4256: if (!$cdom) { $cdom=''; }
4257: my %libserv = &all_library();
4258: foreach my $tryserver (keys(%libserv)) {
4259: if (ref($hostidref) eq 'ARRAY') {
4260: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4261: }
4262: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4263: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4264: &extract_lastaccess(\%returnhash,$rep);
4265: }
4266: }
4267: }
4268: return %returnhash;
4269: }
4270:
4271: sub extract_lastaccess {
4272: my ($returnhash,$rep) = @_;
4273: if (ref($returnhash) eq 'HASH') {
4274: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4275: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4276: $rep eq '') {
4277: my @pairs=split(/\&/,$rep);
4278: foreach my $item (@pairs) {
4279: my ($key,$value)=split(/\=/,$item,2);
4280: $key = &unescape($key);
4281: next if ($key =~ /^error: 2 /);
4282: $returnhash->{$key} = &thaw_unescape($value);
4283: }
4284: }
4285: }
4286: return;
4287: }
4288:
1.658 raeburn 4289: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4290:
4291: sub dcmailput {
1.685 raeburn 4292: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4293: my $status = &Apache::lonnet::critical(
1.740 www 4294: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4295: &escape($message),$server);
1.662 raeburn 4296: return $status;
4297: }
4298:
1.658 raeburn 4299: sub dcmaildump {
4300: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4301: my %returnhash=();
1.846 albertel 4302:
4303: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4304: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4305: &escape($enddate).':';
4306: my @esc_senders=map { &escape($_)} @$senders;
4307: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4308: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4309: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4310: if (($key) && ($value)) {
4311: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4312: }
4313: }
4314: }
4315: return %returnhash;
4316: }
1.662 raeburn 4317: # ---------------------------------------------------------- Domain roles
4318:
4319: sub get_domain_roles {
4320: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4321: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4322: $startdate = '.';
4323: }
1.1018 raeburn 4324: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4325: $enddate = '.';
4326: }
1.922 raeburn 4327: my $rolelist;
4328: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4329: $rolelist = join('&',@{$roles});
1.922 raeburn 4330: }
1.662 raeburn 4331: my %personnel = ();
1.841 albertel 4332:
4333: my %servers = &get_servers($dom,'library');
4334: foreach my $tryserver (keys(%servers)) {
4335: %{$personnel{$tryserver}}=();
4336: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4337: &escape($startdate).':'.
4338: &escape($enddate).':'.
4339: &escape($rolelist), $tryserver))) {
4340: my ($key,$value) = split(/\=/,$line,2);
4341: if (($key) && ($value)) {
4342: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4343: }
4344: }
1.662 raeburn 4345: }
4346: return %personnel;
4347: }
1.658 raeburn 4348:
1.1057 www 4349: # ----------------------------------------------------------- Interval timing
1.149 www 4350:
1.1153 www 4351: {
4352: # Caches needed for speedup of navmaps
4353: # We don't want to cache this for very long at all (5 seconds at most)
4354: #
4355: # The user for whom we cache
4356: my $cachedkey='';
4357: # The cached times for this user
4358: my %cachedtimes=();
4359: # When this was last done
4360: my $cachedtime=();
4361:
4362: sub load_all_first_access {
1.1154 raeburn 4363: my ($uname,$udom)=@_;
1.1156 www 4364: if (($cachedkey eq $uname.':'.$udom) &&
1.1174 raeburn 4365: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4366: return;
4367: }
4368: $cachedtime=time;
4369: $cachedkey=$uname.':'.$udom;
4370: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4371: }
4372:
1.504 albertel 4373: sub get_first_access {
1.1162 raeburn 4374: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4375: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4376: if ($argsymb) { $symb=$argsymb; }
4377: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4378: if ($argmap) { $map = $argmap; }
1.926 albertel 4379: if ($type eq 'course') {
4380: $res='course';
4381: } elsif ($type eq 'map') {
1.588 albertel 4382: $res=&symbread($map);
4383: } else {
4384: $res=$symb;
4385: }
1.1153 www 4386: &load_all_first_access($uname,$udom);
4387: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4388: }
4389:
4390: sub set_first_access {
1.1162 raeburn 4391: my ($type,$interval)=@_;
1.790 albertel 4392: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4393: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4394: if ($type eq 'course') {
4395: $res='course';
4396: } elsif ($type eq 'map') {
1.588 albertel 4397: $res=&symbread($map);
4398: } else {
4399: $res=$symb;
4400: }
1.1153 www 4401: $cachedkey='';
1.1162 raeburn 4402: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4403: if (!$firstaccess) {
1.1162 raeburn 4404: my $start = time;
4405: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4406: $udom,$uname);
4407: if ($putres eq 'ok') {
4408: &put('timerinterval',{"$courseid\0$res"=>$interval},
4409: $udom,$uname);
4410: &appenv(
4411: {
4412: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4413: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4414: }
4415: );
4416: }
4417: return $putres;
1.505 albertel 4418: }
4419: return 'already_set';
1.504 albertel 4420: }
1.1153 www 4421: }
1.110 www 4422: # --------------------------------------------- Set Expire Date for Spreadsheet
4423:
4424: sub expirespread {
4425: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4426: my $cid=$env{'request.course.id'};
1.110 www 4427: if ($cid) {
4428: my $now=time;
4429: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4430: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4431: $env{'course.'.$cid.'.num'}.
1.110 www 4432: ':nohist_expirationdates:'.
4433: &escape($key).'='.$now,
1.620 albertel 4434: $env{'course.'.$cid.'.home'})
1.110 www 4435: }
4436: return 'ok';
1.14 www 4437: }
4438:
1.109 www 4439: # ----------------------------------------------------- Devalidate Spreadsheets
4440:
4441: sub devalidate {
1.325 www 4442: my ($symb,$uname,$udom)=@_;
1.620 albertel 4443: my $cid=$env{'request.course.id'};
1.109 www 4444: if ($cid) {
1.391 matthew 4445: # delete the stored spreadsheets for
4446: # - the student level sheet of this user in course's homespace
4447: # - the assessment level sheet for this resource
4448: # for this user in user's homespace
1.553 albertel 4449: # - current conditional state info
1.325 www 4450: my $key=$uname.':'.$udom.':';
1.109 www 4451: my $status=
1.299 matthew 4452: &del('nohist_calculatedsheets',
1.391 matthew 4453: [$key.'studentcalc:'],
1.620 albertel 4454: $env{'course.'.$cid.'.domain'},
4455: $env{'course.'.$cid.'.num'})
1.133 albertel 4456: .' '.
4457: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4458: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4459: unless ($status eq 'ok ok') {
4460: &logthis('Could not devalidate spreadsheet '.
1.325 www 4461: $uname.' at '.$udom.' for '.
1.109 www 4462: $symb.': '.$status);
1.133 albertel 4463: }
1.553 albertel 4464: &delenv('user.state.'.$cid);
1.109 www 4465: }
4466: }
4467:
1.265 albertel 4468: sub get_scalar {
4469: my ($string,$end) = @_;
4470: my $value;
4471: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4472: $value = $1;
4473: } elsif ($$string =~ s/^([^&]*?)&//) {
4474: $value = $1;
4475: }
4476: return &unescape($value);
4477: }
4478:
4479: sub array2str {
4480: my (@array) = @_;
4481: my $result=&arrayref2str(\@array);
4482: $result=~s/^__ARRAY_REF__//;
4483: $result=~s/__END_ARRAY_REF__$//;
4484: return $result;
4485: }
4486:
1.204 albertel 4487: sub arrayref2str {
4488: my ($arrayref) = @_;
1.265 albertel 4489: my $result='__ARRAY_REF__';
1.204 albertel 4490: foreach my $elem (@$arrayref) {
1.265 albertel 4491: if(ref($elem) eq 'ARRAY') {
4492: $result.=&arrayref2str($elem).'&';
4493: } elsif(ref($elem) eq 'HASH') {
4494: $result.=&hashref2str($elem).'&';
4495: } elsif(ref($elem)) {
4496: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4497: } else {
4498: $result.=&escape($elem).'&';
4499: }
4500: }
4501: $result=~s/\&$//;
1.265 albertel 4502: $result .= '__END_ARRAY_REF__';
1.204 albertel 4503: return $result;
4504: }
4505:
1.168 albertel 4506: sub hash2str {
1.204 albertel 4507: my (%hash) = @_;
4508: my $result=&hashref2str(\%hash);
1.265 albertel 4509: $result=~s/^__HASH_REF__//;
4510: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4511: return $result;
4512: }
4513:
4514: sub hashref2str {
4515: my ($hashref)=@_;
1.265 albertel 4516: my $result='__HASH_REF__';
1.800 albertel 4517: foreach my $key (sort(keys(%$hashref))) {
4518: if (ref($key) eq 'ARRAY') {
4519: $result.=&arrayref2str($key).'=';
4520: } elsif (ref($key) eq 'HASH') {
4521: $result.=&hashref2str($key).'=';
4522: } elsif (ref($key)) {
1.265 albertel 4523: $result.='=';
1.800 albertel 4524: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4525: } else {
1.1132 raeburn 4526: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4527: }
4528:
1.800 albertel 4529: if(ref($hashref->{$key}) eq 'ARRAY') {
4530: $result.=&arrayref2str($hashref->{$key}).'&';
4531: } elsif(ref($hashref->{$key}) eq 'HASH') {
4532: $result.=&hashref2str($hashref->{$key}).'&';
4533: } elsif(ref($hashref->{$key})) {
1.265 albertel 4534: $result.='&';
1.800 albertel 4535: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4536: } else {
1.800 albertel 4537: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4538: }
4539: }
1.168 albertel 4540: $result=~s/\&$//;
1.265 albertel 4541: $result .= '__END_HASH_REF__';
1.168 albertel 4542: return $result;
4543: }
4544:
4545: sub str2hash {
1.265 albertel 4546: my ($string)=@_;
4547: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4548: return %$hash;
4549: }
4550:
4551: sub str2hashref {
1.168 albertel 4552: my ($string) = @_;
1.265 albertel 4553:
4554: my %hash;
4555:
4556: if($string !~ /^__HASH_REF__/) {
4557: if (! ($string eq '' || !defined($string))) {
4558: $hash{'error'}='Not hash reference';
4559: }
4560: return (\%hash, $string);
4561: }
4562:
4563: $string =~ s/^__HASH_REF__//;
4564:
4565: while($string !~ /^__END_HASH_REF__/) {
4566: #key
4567: my $key='';
4568: if($string =~ /^__HASH_REF__/) {
4569: ($key, $string)=&str2hashref($string);
4570: if(defined($key->{'error'})) {
4571: $hash{'error'}='Bad data';
4572: return (\%hash, $string);
4573: }
4574: } elsif($string =~ /^__ARRAY_REF__/) {
4575: ($key, $string)=&str2arrayref($string);
4576: if($key->[0] eq 'Array reference error') {
4577: $hash{'error'}='Bad data';
4578: return (\%hash, $string);
4579: }
4580: } else {
4581: $string =~ s/^(.*?)=//;
1.267 albertel 4582: $key=&unescape($1);
1.265 albertel 4583: }
4584: $string =~ s/^=//;
4585:
4586: #value
4587: my $value='';
4588: if($string =~ /^__HASH_REF__/) {
4589: ($value, $string)=&str2hashref($string);
4590: if(defined($value->{'error'})) {
4591: $hash{'error'}='Bad data';
4592: return (\%hash, $string);
4593: }
4594: } elsif($string =~ /^__ARRAY_REF__/) {
4595: ($value, $string)=&str2arrayref($string);
4596: if($value->[0] eq 'Array reference error') {
4597: $hash{'error'}='Bad data';
4598: return (\%hash, $string);
4599: }
4600: } else {
4601: $value=&get_scalar(\$string,'__END_HASH_REF__');
4602: }
4603: $string =~ s/^&//;
4604:
4605: $hash{$key}=$value;
1.204 albertel 4606: }
1.265 albertel 4607:
4608: $string =~ s/^__END_HASH_REF__//;
4609:
4610: return (\%hash, $string);
1.204 albertel 4611: }
4612:
4613: sub str2array {
1.265 albertel 4614: my ($string)=@_;
4615: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4616: return @$array;
4617: }
4618:
4619: sub str2arrayref {
1.204 albertel 4620: my ($string) = @_;
1.265 albertel 4621: my @array;
4622:
4623: if($string !~ /^__ARRAY_REF__/) {
4624: if (! ($string eq '' || !defined($string))) {
4625: $array[0]='Array reference error';
4626: }
4627: return (\@array, $string);
4628: }
4629:
4630: $string =~ s/^__ARRAY_REF__//;
4631:
4632: while($string !~ /^__END_ARRAY_REF__/) {
4633: my $value='';
4634: if($string =~ /^__HASH_REF__/) {
4635: ($value, $string)=&str2hashref($string);
4636: if(defined($value->{'error'})) {
4637: $array[0] ='Array reference error';
4638: return (\@array, $string);
4639: }
4640: } elsif($string =~ /^__ARRAY_REF__/) {
4641: ($value, $string)=&str2arrayref($string);
4642: if($value->[0] eq 'Array reference error') {
4643: $array[0] ='Array reference error';
4644: return (\@array, $string);
4645: }
4646: } else {
4647: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4648: }
4649: $string =~ s/^&//;
4650:
4651: push(@array, $value);
1.191 harris41 4652: }
1.265 albertel 4653:
4654: $string =~ s/^__END_ARRAY_REF__//;
4655:
4656: return (\@array, $string);
1.168 albertel 4657: }
4658:
1.167 albertel 4659: # -------------------------------------------------------------------Temp Store
4660:
1.168 albertel 4661: sub tmpreset {
4662: my ($symb,$namespace,$domain,$stuname) = @_;
4663: if (!$symb) {
4664: $symb=&symbread();
1.620 albertel 4665: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4666: }
4667: $symb=escape($symb);
4668:
1.620 albertel 4669: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4670: $namespace=~s/\//\_/g;
4671: $namespace=~s/\W//g;
4672:
1.620 albertel 4673: if (!$domain) { $domain=$env{'user.domain'}; }
4674: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4675: if ($domain eq 'public' && $stuname eq 'public') {
4676: $stuname=$ENV{'REMOTE_ADDR'};
4677: }
1.1117 foxr 4678: my $path=LONCAPA::tempdir();
1.168 albertel 4679: my %hash;
4680: if (tie(%hash,'GDBM_File',
4681: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4682: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4683: foreach my $key (keys(%hash)) {
1.180 albertel 4684: if ($key=~ /:$symb/) {
1.168 albertel 4685: delete($hash{$key});
4686: }
4687: }
4688: }
4689: }
4690:
1.167 albertel 4691: sub tmpstore {
1.168 albertel 4692: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4693:
4694: if (!$symb) {
4695: $symb=&symbread();
1.620 albertel 4696: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4697: }
4698: $symb=escape($symb);
4699:
4700: if (!$namespace) {
4701: # I don't think we would ever want to store this for a course.
4702: # it seems this will only be used if we don't have a course.
1.620 albertel 4703: #$namespace=$env{'request.course.id'};
1.168 albertel 4704: #if (!$namespace) {
1.620 albertel 4705: $namespace=$env{'request.state'};
1.168 albertel 4706: #}
4707: }
4708: $namespace=~s/\//\_/g;
4709: $namespace=~s/\W//g;
1.620 albertel 4710: if (!$domain) { $domain=$env{'user.domain'}; }
4711: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4712: if ($domain eq 'public' && $stuname eq 'public') {
4713: $stuname=$ENV{'REMOTE_ADDR'};
4714: }
1.168 albertel 4715: my $now=time;
4716: my %hash;
1.1117 foxr 4717: my $path=LONCAPA::tempdir();
1.168 albertel 4718: if (tie(%hash,'GDBM_File',
4719: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4720: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4721: $hash{"version:$symb"}++;
4722: my $version=$hash{"version:$symb"};
4723: my $allkeys='';
4724: foreach my $key (keys(%$storehash)) {
4725: $allkeys.=$key.':';
1.591 albertel 4726: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4727: }
4728: $hash{"$version:$symb:timestamp"}=$now;
4729: $allkeys.='timestamp';
4730: $hash{"$version:keys:$symb"}=$allkeys;
4731: if (untie(%hash)) {
4732: return 'ok';
4733: } else {
4734: return "error:$!";
4735: }
4736: } else {
4737: return "error:$!";
4738: }
4739: }
1.167 albertel 4740:
1.168 albertel 4741: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4742:
1.168 albertel 4743: sub tmprestore {
4744: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4745:
1.168 albertel 4746: if (!$symb) {
4747: $symb=&symbread();
1.620 albertel 4748: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4749: }
4750: $symb=escape($symb);
4751:
1.620 albertel 4752: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4753:
1.620 albertel 4754: if (!$domain) { $domain=$env{'user.domain'}; }
4755: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4756: if ($domain eq 'public' && $stuname eq 'public') {
4757: $stuname=$ENV{'REMOTE_ADDR'};
4758: }
1.168 albertel 4759: my %returnhash;
4760: $namespace=~s/\//\_/g;
4761: $namespace=~s/\W//g;
4762: my %hash;
1.1117 foxr 4763: my $path=LONCAPA::tempdir();
1.168 albertel 4764: if (tie(%hash,'GDBM_File',
4765: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4766: &GDBM_READER(),0640)) {
1.168 albertel 4767: my $version=$hash{"version:$symb"};
4768: $returnhash{'version'}=$version;
4769: my $scope;
4770: for ($scope=1;$scope<=$version;$scope++) {
4771: my $vkeys=$hash{"$scope:keys:$symb"};
4772: my @keys=split(/:/,$vkeys);
4773: my $key;
4774: $returnhash{"$scope:keys"}=$vkeys;
4775: foreach $key (@keys) {
1.591 albertel 4776: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4777: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4778: }
4779: }
1.168 albertel 4780: if (!(untie(%hash))) {
4781: return "error:$!";
4782: }
4783: } else {
4784: return "error:$!";
4785: }
4786: return %returnhash;
1.167 albertel 4787: }
4788:
1.9 www 4789: # ----------------------------------------------------------------------- Store
4790:
4791: sub store {
1.124 www 4792: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4793: my $home='';
4794:
1.168 albertel 4795: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4796:
1.213 www 4797: $symb=&symbclean($symb);
1.122 albertel 4798: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4799:
1.620 albertel 4800: if (!$domain) { $domain=$env{'user.domain'}; }
4801: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4802:
4803: &devalidate($symb,$stuname,$domain);
1.109 www 4804:
4805: $symb=escape($symb);
1.187 www 4806: if (!$namespace) {
1.620 albertel 4807: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4808: return '';
4809: }
4810: }
1.620 albertel 4811: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4812:
4813: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4814: $$storehash{'host'}=$perlvar{'lonHostID'};
4815:
1.12 www 4816: my $namevalue='';
1.800 albertel 4817: foreach my $key (keys(%$storehash)) {
4818: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4819: }
1.12 www 4820: $namevalue=~s/\&$//;
1.187 www 4821: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4822: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4823: }
4824:
1.47 www 4825: # -------------------------------------------------------------- Critical Store
4826:
4827: sub cstore {
1.124 www 4828: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4829: my $home='';
4830:
1.168 albertel 4831: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4832:
1.213 www 4833: $symb=&symbclean($symb);
1.122 albertel 4834: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4835:
1.620 albertel 4836: if (!$domain) { $domain=$env{'user.domain'}; }
4837: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4838:
4839: &devalidate($symb,$stuname,$domain);
1.109 www 4840:
4841: $symb=escape($symb);
1.187 www 4842: if (!$namespace) {
1.620 albertel 4843: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4844: return '';
4845: }
4846: }
1.620 albertel 4847: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4848:
4849: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4850: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4851:
1.47 www 4852: my $namevalue='';
1.800 albertel 4853: foreach my $key (keys(%$storehash)) {
4854: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4855: }
1.47 www 4856: $namevalue=~s/\&$//;
1.187 www 4857: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4858: return critical
4859: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4860: }
4861:
1.9 www 4862: # --------------------------------------------------------------------- Restore
4863:
4864: sub restore {
1.124 www 4865: my ($symb,$namespace,$domain,$stuname) = @_;
4866: my $home='';
4867:
1.168 albertel 4868: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4869:
1.122 albertel 4870: if (!$symb) {
1.1224 raeburn 4871: return if ($namespace eq 'courserequests');
4872: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4873: } else {
1.1224 raeburn 4874: unless ($namespace eq 'courserequests') {
4875: $symb=&escape(&symbclean($symb));
4876: }
1.122 albertel 4877: }
1.188 www 4878: if (!$namespace) {
1.620 albertel 4879: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4880: return '';
4881: }
4882: }
1.620 albertel 4883: if (!$domain) { $domain=$env{'user.domain'}; }
4884: if (!$stuname) { $stuname=$env{'user.name'}; }
4885: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4886: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4887:
1.12 www 4888: my %returnhash=();
1.800 albertel 4889: foreach my $line (split(/\&/,$answer)) {
4890: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4891: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4892: }
1.75 www 4893: my $version;
4894: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4895: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4896: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4897: }
1.75 www 4898: }
1.13 www 4899: return %returnhash;
1.34 www 4900: }
4901:
4902: # ---------------------------------------------------------- Course Description
1.1118 foxr 4903: #
4904: #
1.34 www 4905:
4906: sub coursedescription {
1.731 albertel 4907: my ($courseid,$args)=@_;
1.34 www 4908: $courseid=~s/^\///;
1.49 www 4909: $courseid=~s/\_/\//g;
1.34 www 4910: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4911: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4912: my $normalid=$cdomain.'_'.$cnum;
4913: # need to always cache even if we get errors otherwise we keep
4914: # trying and trying and trying to get the course description.
4915: my %envhash=();
4916: my %returnhash=();
1.731 albertel 4917:
4918: my $expiretime=600;
4919: if ($env{'request.course.id'} eq $normalid) {
4920: $expiretime=120;
4921: }
4922:
4923: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4924: if (!$args->{'freshen_cache'}
4925: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4926: foreach my $key (keys(%env)) {
4927: next if ($key !~ /^\Q$prefix\E(.*)/);
4928: my ($setting) = $1;
4929: $returnhash{$setting} = $env{$key};
4930: }
4931: return %returnhash;
4932: }
4933:
1.1118 foxr 4934: # get the data again
4935:
1.731 albertel 4936: if (!$args->{'one_time'}) {
4937: $envhash{'course.'.$normalid.'.last_cache'}=time;
4938: }
1.811 albertel 4939:
1.34 www 4940: if ($chome ne 'no_host') {
1.302 albertel 4941: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4942: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4943: my $username = $env{'user.name'}; # Defult username
4944: if(defined $args->{'user'}) {
4945: $username = $args->{'user'};
4946: }
1.129 albertel 4947: $returnhash{'home'}= $chome;
4948: $returnhash{'domain'} = $cdomain;
4949: $returnhash{'num'} = $cnum;
1.741 raeburn 4950: if (!defined($returnhash{'type'})) {
4951: $returnhash{'type'} = 'Course';
4952: }
1.130 albertel 4953: while (my ($name,$value) = each %returnhash) {
1.53 www 4954: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4955: }
1.270 www 4956: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4957: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4958: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4959: $envhash{'course.'.$normalid.'.home'}=$chome;
4960: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4961: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4962: }
4963: }
1.731 albertel 4964: if (!$args->{'one_time'}) {
1.949 raeburn 4965: &appenv(\%envhash);
1.731 albertel 4966: }
1.302 albertel 4967: return %returnhash;
1.461 www 4968: }
4969:
1.1080 raeburn 4970: sub update_released_required {
4971: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4972: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4973: $cid = $env{'request.course.id'};
4974: $cdom = $env{'course.'.$cid.'.domain'};
4975: $cnum = $env{'course.'.$cid.'.num'};
4976: $chome = $env{'course.'.$cid.'.home'};
4977: }
4978: if ($needsrelease) {
4979: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4980: my $needsupdate;
4981: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4982: $needsupdate = 1;
4983: } else {
4984: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4985: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4986: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4987: $needsupdate = 1;
4988: }
4989: }
4990: if ($needsupdate) {
4991: my %needshash = (
4992: 'internal.releaserequired' => $needsrelease,
4993: );
4994: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4995: if ($putresult eq 'ok') {
4996: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4997: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4998: if (ref($crsinfo{$cid}) eq 'HASH') {
4999: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5000: &courseidput($cdom,\%crsinfo,$chome,'notime');
5001: }
5002: }
5003: }
5004: }
5005: return;
5006: }
5007:
1.461 www 5008: # -------------------------------------------------See if a user is privileged
5009:
5010: sub privileged {
1.1219 raeburn 5011: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5012: my $now = time;
1.1219 raeburn 5013: my $roles;
5014: if (ref($possroles) eq 'ARRAY') {
5015: $roles = $possroles;
5016: } else {
5017: $roles = ['dc','su'];
5018: }
5019: if (ref($possdomains) eq 'ARRAY') {
5020: my %privileged = &privileged_by_domain($possdomains,$roles);
5021: foreach my $dom (@{$possdomains}) {
5022: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5023: (ref($privileged{$dom}) eq 'HASH')) {
5024: foreach my $role (@{$roles}) {
5025: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5026: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5027: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5028: return 1 unless (($end && $end < $now) ||
5029: ($start && $start > $now));
5030: }
5031: }
5032: }
5033: }
5034: }
5035: } else {
5036: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5037: my $now = time;
1.1170 droeschl 5038:
1.1219 raeburn 5039: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170 droeschl 5040: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5041: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5042: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5043: or ($tstart && $tstart > $now);
1.1170 droeschl 5044: }
1.1219 raeburn 5045: }
5046: }
5047: return 0;
5048: }
1.1170 droeschl 5049:
1.1219 raeburn 5050: sub privileged_by_domain {
5051: my ($domains,$roles) = @_;
5052: my %privileged = ();
5053: my $cachetime = 60*60*24;
5054: my $now = time;
5055: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5056: return %privileged;
5057: }
5058: foreach my $dom (@{$domains}) {
5059: next if (ref($privileged{$dom}) eq 'HASH');
5060: my $needroles;
5061: foreach my $role (@{$roles}) {
5062: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5063: if (defined($cached)) {
5064: if (ref($result) eq 'HASH') {
5065: $privileged{$dom}{$role} = $result;
5066: }
5067: } else {
5068: $needroles = 1;
5069: }
5070: }
5071: if ($needroles) {
5072: my %dompersonnel = &get_domain_roles($dom,$roles);
5073: $privileged{$dom} = {};
5074: foreach my $server (keys(%dompersonnel)) {
5075: if (ref($dompersonnel{$server}) eq 'HASH') {
5076: foreach my $item (keys(%{$dompersonnel{$server}})) {
5077: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5078: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5079: next if ($end && $end < $now);
5080: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5081: $dompersonnel{$server}{$item};
5082: }
5083: }
5084: }
5085: if (ref($privileged{$dom}) eq 'HASH') {
5086: foreach my $role (@{$roles}) {
5087: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5088: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5089: } else {
5090: my %hash = ();
5091: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5092: }
5093: }
5094: }
5095: }
5096: }
5097: return %privileged;
1.9 www 5098: }
1.1 albertel 5099:
1.103 harris41 5100: # -------------------------------------------------------- Get user privileges
1.11 www 5101:
5102: sub rolesinit {
1.1169 droeschl 5103: my ($domain, $username) = @_;
5104: my %userroles = ('user.login.time' => time);
5105: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5106:
5107: # firstaccess and timerinterval are related to timed maps/resources.
5108: # also, blocking can be triggered by an activating timer
5109: # it's saved in the user's %env.
5110: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5111: my %timerinterval = &dump('timerinterval', $domain, $username);
5112: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5113: %timerintchk, %timerintenv);
5114:
1.1162 raeburn 5115: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5116: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5117: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5118: }
1.1169 droeschl 5119:
1.1162 raeburn 5120: foreach my $key (keys(%timerinterval)) {
5121: my ($cid,$rest) = split(/\0/,$key);
5122: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5123: }
1.1169 droeschl 5124:
1.11 www 5125: my %allroles=();
1.1162 raeburn 5126: my %allgroups=();
1.11 www 5127:
1.1169 droeschl 5128: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5129: my $role = $rolesdump{$area};
5130: $area =~ s/\_\w\w$//;
5131:
5132: my ($trole, $tend, $tstart, $group_privs);
5133:
5134: if ($role =~ /^cr/) {
5135: # Custom role, defined by a user
5136: # e.g., user.role.cr/msu/smith/mynewrole
5137: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5138: $trole = $1;
5139: ($tend, $tstart) = split('_', $2);
5140: } else {
5141: $trole = $role;
5142: }
5143: } elsif ($role =~ m|^gr/|) {
5144: # Role of member in a group, defined within a course/community
5145: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5146: ($trole, $tend, $tstart) = split(/_/, $role);
5147: next if $tstart eq '-1';
5148: ($trole, $group_privs) = split(/\//, $trole);
5149: $group_privs = &unescape($group_privs);
5150: } else {
5151: # Just a normal role, defined in roles.tab
5152: ($trole, $tend, $tstart) = split(/_/,$role);
5153: }
5154:
5155: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5156: $username);
5157: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5158:
5159: # role expired or not available yet?
5160: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5161: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5162:
5163: next if $area eq '' or $trole eq '';
5164:
5165: my $spec = "$trole.$area";
5166: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5167:
5168: if ($trole =~ /^cr\//) {
5169: # Custom role, defined by a user
5170: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5171: } elsif ($trole eq 'gr') {
5172: # Role of a member in a group, defined within a course/community
5173: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5174: next;
5175: } else {
5176: # Normal role, defined in roles.tab
5177: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5178: }
5179:
5180: my $cid = $tdomain.'_'.$trest;
5181: unless ($firstaccchk{$cid}) {
5182: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5183: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5184: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5185: $coursetimerstarts{$cid}{$item};
5186: }
5187: }
5188: $firstaccchk{$cid} = 1;
5189: }
5190: unless ($timerintchk{$cid}) {
5191: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5192: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5193: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5194: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5195: }
1.12 www 5196: }
1.1169 droeschl 5197: $timerintchk{$cid} = 1;
1.191 harris41 5198: }
1.11 www 5199: }
1.1169 droeschl 5200:
5201: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5202: \%allroles, \%allgroups);
5203: $env{'user.adv'} = $userroles{'user.adv'};
5204:
1.1162 raeburn 5205: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5206: }
5207:
1.567 raeburn 5208: sub set_arearole {
1.1215 raeburn 5209: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5210: unless ($nolog) {
1.567 raeburn 5211: # log the associated role with the area
1.1215 raeburn 5212: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5213: }
1.743 albertel 5214: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5215: }
5216:
5217: sub custom_roleprivs {
5218: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5219: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
5220: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 5221: if (&hostname($homsvr) ne '') {
1.567 raeburn 5222: my ($rdummy,$roledef)=
5223: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5224: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5225: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5226: if (defined($syspriv)) {
1.1043 raeburn 5227: if ($trest =~ /^$match_community$/) {
5228: $syspriv =~ s/bre\&S//;
5229: }
1.567 raeburn 5230: $$allroles{'cm./'}.=':'.$syspriv;
5231: $$allroles{$spec.'./'}.=':'.$syspriv;
5232: }
5233: if ($tdomain ne '') {
5234: if (defined($dompriv)) {
5235: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5236: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5237: }
5238: if (($trest ne '') && (defined($coursepriv))) {
5239: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5240: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5241: }
5242: }
5243: }
5244: }
5245: }
5246:
1.678 raeburn 5247: sub group_roleprivs {
5248: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5249: my $access = 1;
5250: my $now = time;
5251: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5252: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5253: if ($access) {
1.811 albertel 5254: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5255: $$allgroups{$course}{$group} .=':'.$group_privs;
5256: }
5257: }
1.567 raeburn 5258:
5259: sub standard_roleprivs {
5260: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5261: if (defined($pr{$trole.':s'})) {
5262: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5263: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5264: }
5265: if ($tdomain ne '') {
5266: if (defined($pr{$trole.':d'})) {
5267: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5268: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5269: }
5270: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5271: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5272: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5273: }
5274: }
5275: }
5276:
5277: sub set_userprivs {
1.1064 raeburn 5278: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5279: my $author=0;
5280: my $adv=0;
1.678 raeburn 5281: my %grouproles = ();
5282: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5283: my @groupkeys;
1.1000 raeburn 5284: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5285: push(@groupkeys,$role);
5286: }
5287: if (ref($groups_roles) eq 'HASH') {
5288: foreach my $key (keys(%{$groups_roles})) {
5289: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5290: push(@groupkeys,$key);
5291: }
5292: }
5293: }
5294: if (@groupkeys > 0) {
5295: foreach my $role (@groupkeys) {
5296: my ($trole,$area,$sec,$extendedarea);
5297: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5298: $trole = $1;
5299: $area = $2;
5300: $sec = $3;
5301: $extendedarea = $area.$sec;
5302: if (exists($$allgroups{$area})) {
5303: foreach my $group (keys(%{$$allgroups{$area}})) {
5304: my $spec = $trole.'.'.$extendedarea;
5305: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5306: $$allgroups{$area}{$group};
1.1064 raeburn 5307: }
1.678 raeburn 5308: }
5309: }
5310: }
5311: }
5312: }
1.800 albertel 5313: foreach my $group (keys(%grouproles)) {
5314: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5315: }
1.800 albertel 5316: foreach my $role (keys(%{$allroles})) {
5317: my %thesepriv;
1.941 raeburn 5318: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5319: foreach my $item (split(/:/,$$allroles{$role})) {
5320: if ($item ne '') {
5321: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5322: if ($restrictions eq '') {
5323: $thesepriv{$privilege}='F';
5324: } elsif ($thesepriv{$privilege} ne 'F') {
5325: $thesepriv{$privilege}.=$restrictions;
5326: }
5327: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5328: }
5329: }
5330: my $thesestr='';
1.1104 raeburn 5331: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5332: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5333: }
5334: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5335: }
5336: return ($author,$adv);
5337: }
5338:
1.994 raeburn 5339: sub role_status {
1.1104 raeburn 5340: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5341: my @pwhere = ();
5342: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
5343: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
5344: unless (!defined($$role) || $$role eq '') {
5345: $$where=join('.',@pwhere);
5346: $$trolecode=$$role.'.'.$$where;
5347: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5348: $$tstatus='is';
1.1104 raeburn 5349: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5350: $$tstatus='future';
1.1034 raeburn 5351: if ($$tstart<$now) {
5352: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5353: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5354: my (%allroles,%allgroups,$group_privs,
5355: %groups_roles,@rolecodes);
1.1002 raeburn 5356: my %userroles = (
5357: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5358: );
1.1064 raeburn 5359: @rolecodes = ('cm');
1.1002 raeburn 5360: my $spec=$$role.'.'.$$where;
5361: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5362: if ($$role =~ /^cr\//) {
5363: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5364: push(@rolecodes,'cr');
1.1002 raeburn 5365: } elsif ($$role eq 'gr') {
1.1064 raeburn 5366: push(@rolecodes,$$role);
1.1002 raeburn 5367: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5368: $env{'user.name'});
1.1064 raeburn 5369: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5370: (undef,my $group_privs) = split(/\//,$trole);
5371: $group_privs = &unescape($group_privs);
5372: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5373: 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 5374: &get_groups_roles($tdomain,$trest,
5375: \%course_roles,\@rolecodes,
5376: \%groups_roles);
1.1002 raeburn 5377: } else {
1.1064 raeburn 5378: push(@rolecodes,$$role);
1.1002 raeburn 5379: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5380: }
1.1064 raeburn 5381: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5382: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5383: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5384: }
5385: }
1.1034 raeburn 5386: $$tstatus = 'is';
1.1002 raeburn 5387: }
1.994 raeburn 5388: }
5389: if ($$tend) {
1.1104 raeburn 5390: if ($$tend<$update) {
1.994 raeburn 5391: $$tstatus='expired';
5392: } elsif ($$tend<$now) {
5393: $$tstatus='will_not';
5394: }
5395: }
5396: }
5397: }
5398: }
5399:
1.1104 raeburn 5400: sub get_groups_roles {
5401: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5402: return unless((ref($cdom_courseroles) eq 'HASH') &&
5403: (ref($rolecodes) eq 'ARRAY') &&
5404: (ref($groups_roles) eq 'HASH'));
5405: if (keys(%{$cdom_courseroles}) > 0) {
5406: my ($cnum) = ($rest =~ /^($match_courseid)/);
5407: if ($cdom ne '' && $cnum ne '') {
5408: foreach my $key (keys(%{$cdom_courseroles})) {
5409: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5410: my $crsrole = $1;
5411: my $crssec = $2;
5412: if ($crsrole =~ /^cr/) {
5413: unless (grep(/^cr$/,@{$rolecodes})) {
5414: push(@{$rolecodes},'cr');
5415: }
5416: } else {
5417: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5418: push(@{$rolecodes},$crsrole);
5419: }
5420: }
5421: my $rolekey = "$crsrole./$cdom/$cnum";
5422: if ($crssec ne '') {
5423: $rolekey .= "/$crssec";
5424: }
5425: $rolekey .= './';
5426: $groups_roles->{$rolekey} = $rolecodes;
5427: }
5428: }
5429: }
5430: }
5431: return;
5432: }
5433:
5434: sub delete_env_groupprivs {
5435: my ($where,$courseroles,$possroles) = @_;
5436: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5437: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5438: unless (ref($courseroles->{$udom}) eq 'HASH') {
5439: %{$courseroles->{$udom}} =
5440: &get_my_roles('','','userroles',['active'],
5441: $possroles,[$udom],1);
5442: }
5443: if (ref($courseroles->{$udom}) eq 'HASH') {
5444: foreach my $item (keys(%{$courseroles->{$udom}})) {
5445: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5446: my $area = '/'.$cdom.'/'.$cnum;
5447: my $privkey = "user.priv.$crsrole.$area";
5448: if ($crssec ne '') {
5449: $privkey .= '/'.$crssec;
5450: }
5451: $privkey .= ".$area/$group";
5452: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5453: }
5454: }
5455: return;
5456: }
5457:
1.994 raeburn 5458: sub check_adhoc_privs {
1.1104 raeburn 5459: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5460: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5461: my $setprivs;
1.994 raeburn 5462: if ($env{$cckey}) {
5463: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5464: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5465: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5466: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5467: $setprivs = 1;
1.994 raeburn 5468: }
5469: } else {
1.1088 raeburn 5470: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5471: $setprivs = 1;
1.994 raeburn 5472: }
1.1185 raeburn 5473: return $setprivs;
1.994 raeburn 5474: }
5475:
5476: sub set_adhoc_privileges {
5477: # role can be cc or ca
1.1088 raeburn 5478: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5479: my $area = '/'.$dcdom.'/'.$pickedcourse;
5480: my $spec = $role.'.'.$area;
5481: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5482: $env{'user.name'},1);
1.994 raeburn 5483: my %ccrole = ();
5484: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5485: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5486: &appenv(\%userroles,[$role,'cm']);
5487: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5488: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5489: &appenv( {'request.role' => $spec,
5490: 'request.role.domain' => $dcdom,
5491: 'request.course.sec' => ''
5492: }
5493: );
5494: my $tadv=0;
5495: if (&allowed('adv') eq 'F') { $tadv=1; }
5496: &appenv({'request.role.adv' => $tadv});
5497: }
1.994 raeburn 5498: }
5499:
1.12 www 5500: # --------------------------------------------------------------- get interface
5501:
5502: sub get {
1.131 albertel 5503: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5504: my $items='';
1.800 albertel 5505: foreach my $item (@$storearr) {
5506: $items.=&escape($item).'&';
1.191 harris41 5507: }
1.12 www 5508: $items=~s/\&$//;
1.620 albertel 5509: if (!$udomain) { $udomain=$env{'user.domain'}; }
5510: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5511: my $uhome=&homeserver($uname,$udomain);
5512:
1.133 albertel 5513: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5514: my @pairs=split(/\&/,$rep);
1.273 albertel 5515: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5516: return @pairs;
5517: }
1.15 www 5518: my %returnhash=();
1.42 www 5519: my $i=0;
1.800 albertel 5520: foreach my $item (@$storearr) {
5521: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5522: $i++;
1.191 harris41 5523: }
1.15 www 5524: return %returnhash;
1.27 www 5525: }
5526:
5527: # --------------------------------------------------------------- del interface
5528:
5529: sub del {
1.133 albertel 5530: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5531: my $items='';
1.800 albertel 5532: foreach my $item (@$storearr) {
5533: $items.=&escape($item).'&';
1.191 harris41 5534: }
1.984 neumanie 5535:
1.27 www 5536: $items=~s/\&$//;
1.620 albertel 5537: if (!$udomain) { $udomain=$env{'user.domain'}; }
5538: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5539: my $uhome=&homeserver($uname,$udomain);
5540: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5541: }
5542:
5543: # -------------------------------------------------------------- dump interface
5544:
1.1180 droeschl 5545: sub unserialize {
5546: my ($rep, $escapedkeys) = @_;
5547:
5548: return {} if $rep =~ /^error/;
5549:
5550: my %returnhash=();
5551: foreach my $item (split /\&/, $rep) {
5552: my ($key, $value) = split(/=/, $item, 2);
5553: $key = unescape($key) unless $escapedkeys;
5554: next if $key =~ /^error: 2 /;
5555: $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
5556: }
5557: #return %returnhash;
5558: return \%returnhash;
5559: }
5560:
5561: # see Lond::dump_with_regexp
5562: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5563: sub dump {
1.1180 droeschl 5564: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5565: if (!$udomain) { $udomain=$env{'user.domain'}; }
5566: if (!$uname) { $uname=$env{'user.name'}; }
5567: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5568:
1.1180 droeschl 5569: my $reply;
5570: if (grep { $_ eq $uhome } current_machine_ids()) {
5571: # user is hosted on this machine
5572: $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5573: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5574: return %{unserialize($reply, $escapedkeys)};
5575: }
1.755 albertel 5576: if ($regexp) {
5577: $regexp=&escape($regexp);
5578: } else {
5579: $regexp='.';
5580: }
1.1166 raeburn 5581: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5582: my @pairs=split(/\&/,$rep);
5583: my %returnhash=();
1.1098 foxr 5584: if (!($rep =~ /^error/ )) {
5585: foreach my $item (@pairs) {
5586: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5587: $key = unescape($key) unless $escapedkeys;
5588: #$key = &unescape($key);
1.1098 foxr 5589: next if ($key =~ /^error: 2 /);
5590: $returnhash{$key}=&thaw_unescape($value);
5591: }
1.755 albertel 5592: }
5593: return %returnhash;
1.407 www 5594: }
5595:
1.1098 foxr 5596:
1.717 albertel 5597: # --------------------------------------------------------- dumpstore interface
5598:
5599: sub dumpstore {
5600: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5601: # same as dump but keys must be escaped. They may contain colon separated
5602: # lists of values that may themself contain colons (e.g. symbs).
5603: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5604: }
5605:
1.407 www 5606: # -------------------------------------------------------------- keys interface
5607:
5608: sub getkeys {
5609: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5610: if (!$udomain) { $udomain=$env{'user.domain'}; }
5611: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5612: my $uhome=&homeserver($uname,$udomain);
5613: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5614: my @keyarray=();
1.800 albertel 5615: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5616: next if ($key =~ /^error: 2 /);
1.800 albertel 5617: push(@keyarray,&unescape($key));
1.407 www 5618: }
5619: return @keyarray;
1.318 matthew 5620: }
5621:
1.319 matthew 5622: # --------------------------------------------------------------- currentdump
5623: sub currentdump {
1.328 matthew 5624: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5625: $courseid = $env{'request.course.id'} if (! defined($courseid));
5626: $sdom = $env{'user.domain'} if (! defined($sdom));
5627: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5628: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5629: my $rep;
5630:
5631: if (grep { $_ eq $uhome } current_machine_ids()) {
5632: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5633: $courseid)));
5634: } else {
5635: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5636: }
5637:
1.318 matthew 5638: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5639: #
1.318 matthew 5640: my %returnhash=();
1.319 matthew 5641: #
5642: if ($rep eq "unknown_cmd") {
5643: # an old lond will not know currentdump
5644: # Do a dump and make it look like a currentdump
1.822 albertel 5645: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5646: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5647: my %hash = @tmp;
5648: @tmp=();
1.424 matthew 5649: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5650: } else {
5651: my @pairs=split(/\&/,$rep);
1.800 albertel 5652: foreach my $pair (@pairs) {
5653: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5654: my ($symb,$param) = split(/:/,$key);
5655: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5656: &thaw_unescape($value);
1.319 matthew 5657: }
1.191 harris41 5658: }
1.12 www 5659: return %returnhash;
1.424 matthew 5660: }
5661:
5662: sub convert_dump_to_currentdump{
5663: my %hash = %{shift()};
5664: my %returnhash;
5665: # Code ripped from lond, essentially. The only difference
5666: # here is the unescaping done by lonnet::dump(). Conceivably
5667: # we might run in to problems with parameter names =~ /^v\./
5668: while (my ($key,$value) = each(%hash)) {
5669: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5670: $symb = &unescape($symb);
5671: $param = &unescape($param);
1.424 matthew 5672: next if ($v eq 'version' || $symb eq 'keys');
5673: next if (exists($returnhash{$symb}) &&
5674: exists($returnhash{$symb}->{$param}) &&
5675: $returnhash{$symb}->{'v.'.$param} > $v);
5676: $returnhash{$symb}->{$param}=$value;
5677: $returnhash{$symb}->{'v.'.$param}=$v;
5678: }
5679: #
5680: # Remove all of the keys in the hashes which keep track of
5681: # the version of the parameter.
5682: while (my ($symb,$param_hash) = each(%returnhash)) {
5683: # use a foreach because we are going to delete from the hash.
5684: foreach my $key (keys(%$param_hash)) {
5685: delete($param_hash->{$key}) if ($key =~ /^v\./);
5686: }
5687: }
5688: return \%returnhash;
1.12 www 5689: }
5690:
1.627 albertel 5691: # ------------------------------------------------------ critical inc interface
5692:
5693: sub cinc {
5694: return &inc(@_,'critical');
5695: }
5696:
1.449 matthew 5697: # --------------------------------------------------------------- inc interface
5698:
5699: sub inc {
1.627 albertel 5700: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5701: if (!$udomain) { $udomain=$env{'user.domain'}; }
5702: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5703: my $uhome=&homeserver($uname,$udomain);
5704: my $items='';
5705: if (! ref($store)) {
5706: # got a single value, so use that instead
5707: $items = &escape($store).'=&';
5708: } elsif (ref($store) eq 'SCALAR') {
5709: $items = &escape($$store).'=&';
5710: } elsif (ref($store) eq 'ARRAY') {
5711: $items = join('=&',map {&escape($_);} @{$store});
5712: } elsif (ref($store) eq 'HASH') {
5713: while (my($key,$value) = each(%{$store})) {
5714: $items.= &escape($key).'='.&escape($value).'&';
5715: }
5716: }
5717: $items=~s/\&$//;
1.627 albertel 5718: if ($critical) {
5719: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5720: } else {
5721: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5722: }
1.449 matthew 5723: }
5724:
1.12 www 5725: # --------------------------------------------------------------- put interface
5726:
5727: sub put {
1.134 albertel 5728: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5729: if (!$udomain) { $udomain=$env{'user.domain'}; }
5730: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5731: my $uhome=&homeserver($uname,$udomain);
1.12 www 5732: my $items='';
1.800 albertel 5733: foreach my $item (keys(%$storehash)) {
5734: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5735: }
1.12 www 5736: $items=~s/\&$//;
1.134 albertel 5737: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5738: }
5739:
1.631 albertel 5740: # ------------------------------------------------------------ newput interface
5741:
5742: sub newput {
5743: my ($namespace,$storehash,$udomain,$uname)=@_;
5744: if (!$udomain) { $udomain=$env{'user.domain'}; }
5745: if (!$uname) { $uname=$env{'user.name'}; }
5746: my $uhome=&homeserver($uname,$udomain);
5747: my $items='';
5748: foreach my $key (keys(%$storehash)) {
5749: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5750: }
5751: $items=~s/\&$//;
5752: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5753: }
5754:
5755: # --------------------------------------------------------- putstore interface
5756:
1.524 raeburn 5757: sub putstore {
1.715 albertel 5758: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5759: if (!$udomain) { $udomain=$env{'user.domain'}; }
5760: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5761: my $uhome=&homeserver($uname,$udomain);
5762: my $items='';
1.715 albertel 5763: foreach my $key (keys(%$storehash)) {
5764: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5765: }
1.715 albertel 5766: $items=~s/\&$//;
1.716 albertel 5767: my $esc_symb=&escape($symb);
5768: my $esc_v=&escape($version);
1.715 albertel 5769: my $reply =
1.716 albertel 5770: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5771: $uhome);
5772: if ($reply eq 'unknown_cmd') {
1.716 albertel 5773: # gfall back to way things use to be done
1.715 albertel 5774: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5775: $uname);
1.524 raeburn 5776: }
1.715 albertel 5777: return $reply;
5778: }
5779:
5780: sub old_putstore {
1.716 albertel 5781: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5782: if (!$udomain) { $udomain=$env{'user.domain'}; }
5783: if (!$uname) { $uname=$env{'user.name'}; }
5784: my $uhome=&homeserver($uname,$udomain);
5785: my %newstorehash;
1.800 albertel 5786: foreach my $item (keys(%$storehash)) {
5787: my $key = $version.':'.&escape($symb).':'.$item;
5788: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5789: }
5790: my $items='';
5791: my %allitems = ();
1.800 albertel 5792: foreach my $item (keys(%newstorehash)) {
5793: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5794: my $key = $1.':keys:'.$2;
5795: $allitems{$key} .= $3.':';
5796: }
1.800 albertel 5797: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5798: }
1.800 albertel 5799: foreach my $item (keys(%allitems)) {
5800: $allitems{$item} =~ s/\:$//;
5801: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5802: }
5803: $items=~s/\&$//;
5804: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5805: }
5806:
1.47 www 5807: # ------------------------------------------------------ critical put interface
5808:
5809: sub cput {
1.134 albertel 5810: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5811: if (!$udomain) { $udomain=$env{'user.domain'}; }
5812: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5813: my $uhome=&homeserver($uname,$udomain);
1.47 www 5814: my $items='';
1.800 albertel 5815: foreach my $item (keys(%$storehash)) {
5816: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5817: }
1.47 www 5818: $items=~s/\&$//;
1.134 albertel 5819: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5820: }
5821:
5822: # -------------------------------------------------------------- eget interface
5823:
5824: sub eget {
1.133 albertel 5825: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5826: my $items='';
1.800 albertel 5827: foreach my $item (@$storearr) {
5828: $items.=&escape($item).'&';
1.191 harris41 5829: }
1.12 www 5830: $items=~s/\&$//;
1.620 albertel 5831: if (!$udomain) { $udomain=$env{'user.domain'}; }
5832: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5833: my $uhome=&homeserver($uname,$udomain);
5834: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5835: my @pairs=split(/\&/,$rep);
5836: my %returnhash=();
1.42 www 5837: my $i=0;
1.800 albertel 5838: foreach my $item (@$storearr) {
5839: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5840: $i++;
1.191 harris41 5841: }
1.12 www 5842: return %returnhash;
5843: }
5844:
1.667 albertel 5845: # ------------------------------------------------------------ tmpput interface
5846: sub tmpput {
1.802 raeburn 5847: my ($storehash,$server,$context)=@_;
1.667 albertel 5848: my $items='';
1.800 albertel 5849: foreach my $item (keys(%$storehash)) {
5850: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5851: }
5852: $items=~s/\&$//;
1.802 raeburn 5853: if (defined($context)) {
5854: $items .= ':'.&escape($context);
5855: }
1.667 albertel 5856: return &reply("tmpput:$items",$server);
5857: }
5858:
5859: # ------------------------------------------------------------ tmpget interface
5860: sub tmpget {
1.688 albertel 5861: my ($token,$server)=@_;
5862: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5863: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5864: my %returnhash;
5865: foreach my $item (split(/\&/,$rep)) {
5866: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5867: next if ($key =~ /^error: 2 /);
1.667 albertel 5868: $returnhash{&unescape($key)}=&thaw_unescape($value);
5869: }
5870: return %returnhash;
5871: }
5872:
1.1113 raeburn 5873: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5874: sub tmpdel {
5875: my ($token,$server)=@_;
5876: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5877: return &reply("tmpdel:$token",$server);
5878: }
5879:
1.1198 raeburn 5880: # ------------------------------------------------------------ get_timebased_id
5881:
5882: sub get_timebased_id {
5883: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5884: $maxtries) = @_;
5885: my ($newid,$error,$dellock);
5886: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5887: return ('','ok','invalid call to get suffix');
5888: }
5889:
5890: # set defaults for any optional args for which values were not supplied
5891: if ($who eq '') {
5892: $who = $env{'user.name'}.':'.$env{'user.domain'};
5893: }
5894: if (!$locktries) {
5895: $locktries = 3;
5896: }
5897: if (!$maxtries) {
5898: $maxtries = 10;
5899: }
5900:
5901: if (($cdom eq '') || ($cnum eq '')) {
5902: if ($env{'request.course.id'}) {
5903: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5904: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5905: }
5906: if (($cdom eq '') || ($cnum eq '')) {
5907: return ('','ok','call to get suffix not in course context');
5908: }
5909: }
5910:
5911: # construct locking item
5912: my $lockhash = {
5913: $prefix."\0".'locked_'.$keyid => $who,
5914: };
5915: my $tries = 0;
5916:
5917: # attempt to get lock on nohist_$namespace file
5918: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5919: while (($gotlock ne 'ok') && $tries <$locktries) {
5920: $tries ++;
5921: sleep 1;
5922: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5923: }
5924:
5925: # attempt to get unique identifier, based on current timestamp
5926: if ($gotlock eq 'ok') {
5927: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
5928: my $id = time;
5929: $newid = $id;
5930: my $idtries = 0;
5931: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
5932: if ($idtype eq 'concat') {
5933: $newid = $id.$idtries;
5934: } else {
5935: $newid ++;
5936: }
5937: $idtries ++;
5938: }
5939: if (!exists($inuse{$prefix."\0".$newid})) {
5940: my %new_item = (
5941: $prefix."\0".$newid => $who,
5942: );
5943: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
5944: $cdom,$cnum);
5945: if ($putresult ne 'ok') {
5946: undef($newid);
5947: $error = 'error saving new item: '.$putresult;
5948: }
5949: } else {
5950: $error = ('error: no unique suffix available for the new item ');
5951: }
5952: # remove lock
5953: my @del_lock = ($prefix."\0".'locked_'.$keyid);
5954: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
5955: } else {
5956: $error = "error: could not obtain lockfile\n";
5957: $dellock = 'ok';
5958: }
5959: return ($newid,$dellock,$error);
5960: }
5961:
1.765 albertel 5962: # -------------------------------------------------- portfolio access checking
5963:
5964: sub portfolio_access {
1.766 albertel 5965: my ($requrl) = @_;
1.765 albertel 5966: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5967: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 5968: if ($result) {
5969: my %setters;
5970: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5971: my ($startblock,$endblock) =
5972: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5973: if ($startblock && $endblock) {
5974: return 'B';
5975: }
5976: } else {
5977: my ($startblock,$endblock) =
5978: &Apache::loncommon::blockcheck(\%setters,'port');
5979: if ($startblock && $endblock) {
5980: return 'B';
5981: }
5982: }
5983: }
1.765 albertel 5984: if ($result eq 'ok') {
1.766 albertel 5985: return 'F';
1.765 albertel 5986: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 5987: return 'A';
1.765 albertel 5988: }
1.766 albertel 5989: return '';
1.765 albertel 5990: }
5991:
5992: sub get_portfolio_access {
1.767 albertel 5993: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5994:
5995: if (!ref($access_hash)) {
5996: my $current_perms = &get_portfile_permissions($udom,$unum);
5997: my %access_controls = &get_access_controls($current_perms,$group,
5998: $file_name);
5999: $access_hash = $access_controls{$file_name};
6000: }
6001:
1.765 albertel 6002: my ($public,$guest,@domains,@users,@courses,@groups);
6003: my $now = time;
6004: if (ref($access_hash) eq 'HASH') {
6005: foreach my $key (keys(%{$access_hash})) {
6006: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6007: if ($start > $now) {
6008: next;
6009: }
6010: if ($end && $end<$now) {
6011: next;
6012: }
6013: if ($scope eq 'public') {
6014: $public = $key;
6015: last;
6016: } elsif ($scope eq 'guest') {
6017: $guest = $key;
6018: } elsif ($scope eq 'domains') {
6019: push(@domains,$key);
6020: } elsif ($scope eq 'users') {
6021: push(@users,$key);
6022: } elsif ($scope eq 'course') {
6023: push(@courses,$key);
6024: } elsif ($scope eq 'group') {
6025: push(@groups,$key);
6026: }
6027: }
6028: if ($public) {
6029: return 'ok';
6030: }
6031: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6032: if ($guest) {
6033: return $guest;
6034: }
6035: } else {
6036: if (@domains > 0) {
6037: foreach my $domkey (@domains) {
6038: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6039: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6040: return 'ok';
6041: }
6042: }
6043: }
6044: }
6045: if (@users > 0) {
6046: foreach my $userkey (@users) {
1.865 raeburn 6047: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6048: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6049: if (ref($item) eq 'HASH') {
6050: if (($item->{'uname'} eq $env{'user.name'}) &&
6051: ($item->{'udom'} eq $env{'user.domain'})) {
6052: return 'ok';
6053: }
6054: }
6055: }
6056: }
1.765 albertel 6057: }
6058: }
6059: my %roleshash;
6060: my @courses_and_groups = @courses;
6061: push(@courses_and_groups,@groups);
6062: if (@courses_and_groups > 0) {
6063: my (%allgroups,%allroles);
6064: my ($start,$end,$role,$sec,$group);
6065: foreach my $envkey (%env) {
1.1060 raeburn 6066: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6067: my $cid = $2.'_'.$3;
6068: if ($1 eq 'gr') {
6069: $group = $4;
6070: $allgroups{$cid}{$group} = $env{$envkey};
6071: } else {
6072: if ($4 eq '') {
6073: $sec = 'none';
6074: } else {
6075: $sec = $4;
6076: }
6077: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6078: }
1.811 albertel 6079: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6080: my $cid = $2.'_'.$3;
6081: if ($4 eq '') {
6082: $sec = 'none';
6083: } else {
6084: $sec = $4;
6085: }
6086: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6087: }
6088: }
6089: if (keys(%allroles) == 0) {
6090: return;
6091: }
6092: foreach my $key (@courses_and_groups) {
6093: my %content = %{$$access_hash{$key}};
6094: my $cnum = $content{'number'};
6095: my $cdom = $content{'domain'};
6096: my $cid = $cdom.'_'.$cnum;
6097: if (!exists($allroles{$cid})) {
6098: next;
6099: }
6100: foreach my $role_id (keys(%{$content{'roles'}})) {
6101: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6102: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6103: my @status = @{$content{'roles'}{$role_id}{'access'}};
6104: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6105: foreach my $role (keys(%{$allroles{$cid}})) {
6106: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6107: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6108: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6109: if (grep/^all$/,@sections) {
6110: return 'ok';
6111: } else {
6112: if (grep/^$sec$/,@sections) {
6113: return 'ok';
6114: }
6115: }
6116: }
6117: }
6118: if (keys(%{$allgroups{$cid}}) == 0) {
6119: if (grep/^none$/,@groups) {
6120: return 'ok';
6121: }
6122: } else {
6123: if (grep/^all$/,@groups) {
6124: return 'ok';
6125: }
6126: foreach my $group (keys(%{$allgroups{$cid}})) {
6127: if (grep/^$group$/,@groups) {
6128: return 'ok';
6129: }
6130: }
6131: }
6132: }
6133: }
6134: }
6135: }
6136: }
6137: if ($guest) {
6138: return $guest;
6139: }
6140: }
6141: }
6142: return;
6143: }
6144:
6145: sub course_group_datechecker {
6146: my ($dates,$now,$status) = @_;
6147: my ($start,$end) = split(/\./,$dates);
6148: if (!$start && !$end) {
6149: return 'ok';
6150: }
6151: if (grep/^active$/,@{$status}) {
6152: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6153: return 'ok';
6154: }
6155: }
6156: if (grep/^previous$/,@{$status}) {
6157: if ($end > $now ) {
6158: return 'ok';
6159: }
6160: }
6161: if (grep/^future$/,@{$status}) {
6162: if ($start > $now) {
6163: return 'ok';
6164: }
6165: }
6166: return;
6167: }
6168:
6169: sub parse_portfolio_url {
6170: my ($url) = @_;
6171:
6172: my ($type,$udom,$unum,$group,$file_name);
6173:
1.823 albertel 6174: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6175: $type = 1;
6176: $udom = $1;
6177: $unum = $2;
6178: $file_name = $3;
1.823 albertel 6179: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6180: $type = 2;
6181: $udom = $1;
6182: $unum = $2;
6183: $group = $3;
6184: $file_name = $3.'/'.$4;
6185: }
6186: if (wantarray) {
6187: return ($type,$udom,$unum,$file_name,$group);
6188: }
6189: return $type;
6190: }
6191:
6192: sub is_portfolio_url {
6193: my ($url) = @_;
6194: return scalar(&parse_portfolio_url($url));
6195: }
6196:
1.798 raeburn 6197: sub is_portfolio_file {
6198: my ($file) = @_;
1.820 raeburn 6199: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6200: return 1;
6201: }
6202: return;
6203: }
6204:
1.976 raeburn 6205: sub usertools_access {
1.1084 raeburn 6206: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6207: my ($access,%tools);
6208: if ($context eq '') {
6209: $context = 'tools';
6210: }
6211: if ($context eq 'requestcourses') {
6212: %tools = (
6213: official => 1,
6214: unofficial => 1,
1.1006 raeburn 6215: community => 1,
1.985 raeburn 6216: );
1.1183 raeburn 6217: } elsif ($context eq 'requestauthor') {
6218: %tools = (
6219: requestauthor => 1,
6220: );
1.985 raeburn 6221: } else {
6222: %tools = (
6223: aboutme => 1,
6224: blog => 1,
1.1177 raeburn 6225: webdav => 1,
1.985 raeburn 6226: portfolio => 1,
6227: );
6228: }
1.976 raeburn 6229: return if (!defined($tools{$tool}));
6230:
1.1242 raeburn 6231: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6232: $udom = $env{'user.domain'};
6233: $uname = $env{'user.name'};
6234: }
6235:
1.978 raeburn 6236: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6237: if ($action ne 'reload') {
1.985 raeburn 6238: if ($context eq 'requestcourses') {
6239: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6240: } elsif ($context eq 'requestauthor') {
6241: return $env{'environment.canrequest.author'};
1.985 raeburn 6242: } else {
6243: return $env{'environment.availabletools.'.$tool};
6244: }
6245: }
1.976 raeburn 6246: }
6247:
1.1183 raeburn 6248: my ($toolstatus,$inststatus,$envkey);
6249: if ($context eq 'requestauthor') {
6250: $envkey = $context;
6251: } else {
6252: $envkey = $context.'.'.$tool;
6253: }
1.976 raeburn 6254:
1.985 raeburn 6255: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6256: ($action ne 'reload')) {
1.1183 raeburn 6257: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6258: $inststatus = $env{'environment.inststatus'};
6259: } else {
1.1084 raeburn 6260: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6261: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6262: $inststatus = $userenvref->{'inststatus'};
6263: } else {
1.1183 raeburn 6264: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6265: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6266: $inststatus = $userenv{'inststatus'};
6267: }
1.976 raeburn 6268: }
6269:
6270: if ($toolstatus ne '') {
6271: if ($toolstatus) {
6272: $access = 1;
6273: } else {
6274: $access = 0;
6275: }
6276: return $access;
6277: }
6278:
1.1084 raeburn 6279: my ($is_adv,%domdef);
6280: if (ref($is_advref) eq 'HASH') {
6281: $is_adv = $is_advref->{'is_adv'};
6282: } else {
6283: $is_adv = &is_advanced_user($udom,$uname);
6284: }
6285: if (ref($domdefref) eq 'HASH') {
6286: %domdef = %{$domdefref};
6287: } else {
6288: %domdef = &get_domain_defaults($udom);
6289: }
1.976 raeburn 6290: if (ref($domdef{$tool}) eq 'HASH') {
6291: if ($is_adv) {
6292: if ($domdef{$tool}{'_LC_adv'} ne '') {
6293: if ($domdef{$tool}{'_LC_adv'}) {
6294: $access = 1;
6295: } else {
6296: $access = 0;
6297: }
6298: return $access;
6299: }
6300: }
6301: if ($inststatus ne '') {
6302: my ($hasaccess,$hasnoaccess);
6303: foreach my $affiliation (split(/:/,$inststatus)) {
6304: if ($domdef{$tool}{$affiliation} ne '') {
6305: if ($domdef{$tool}{$affiliation}) {
6306: $hasaccess = 1;
6307: } else {
6308: $hasnoaccess = 1;
6309: }
6310: }
6311: }
6312: if ($hasaccess || $hasnoaccess) {
6313: if ($hasaccess) {
6314: $access = 1;
6315: } elsif ($hasnoaccess) {
6316: $access = 0;
6317: }
6318: return $access;
6319: }
6320: } else {
6321: if ($domdef{$tool}{'default'} ne '') {
6322: if ($domdef{$tool}{'default'}) {
6323: $access = 1;
6324: } elsif ($domdef{$tool}{'default'} == 0) {
6325: $access = 0;
6326: }
6327: return $access;
6328: }
6329: }
6330: } else {
1.1177 raeburn 6331: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6332: $access = 1;
6333: } else {
6334: $access = 0;
6335: }
1.976 raeburn 6336: return $access;
6337: }
6338: }
6339:
1.1050 raeburn 6340: sub is_course_owner {
6341: my ($cdom,$cnum,$udom,$uname) = @_;
6342: if (($udom eq '') || ($uname eq '')) {
6343: $udom = $env{'user.domain'};
6344: $uname = $env{'user.name'};
6345: }
6346: unless (($udom eq '') || ($uname eq '')) {
6347: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6348: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6349: return 1;
6350: } else {
6351: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6352: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6353: return 1;
6354: }
6355: }
6356: }
6357: }
6358: return;
6359: }
6360:
1.976 raeburn 6361: sub is_advanced_user {
6362: my ($udom,$uname) = @_;
1.1085 raeburn 6363: if ($udom ne '' && $uname ne '') {
6364: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6365: if (wantarray) {
6366: return ($env{'user.adv'},$env{'user.author'});
6367: } else {
6368: return $env{'user.adv'};
6369: }
1.1085 raeburn 6370: }
6371: }
1.976 raeburn 6372: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6373: my %allroles;
1.1128 raeburn 6374: my ($is_adv,$is_author);
1.976 raeburn 6375: foreach my $role (keys(%roleshash)) {
6376: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6377: my $area = '/'.$tdomain.'/'.$trest;
6378: if ($sec ne '') {
6379: $area .= '/'.$sec;
6380: }
6381: if (($area ne '') && ($trole ne '')) {
6382: my $spec=$trole.'.'.$area;
6383: if ($trole =~ /^cr\//) {
6384: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6385: } elsif ($trole ne 'gr') {
6386: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6387: }
1.1128 raeburn 6388: if ($trole eq 'au') {
6389: $is_author = 1;
6390: }
1.976 raeburn 6391: }
6392: }
6393: foreach my $role (keys(%allroles)) {
6394: last if ($is_adv);
6395: foreach my $item (split(/:/,$allroles{$role})) {
6396: if ($item ne '') {
6397: my ($privilege,$restrictions)=split(/&/,$item);
6398: if ($privilege eq 'adv') {
6399: $is_adv = 1;
6400: last;
6401: }
6402: }
6403: }
6404: }
1.1128 raeburn 6405: if (wantarray) {
6406: return ($is_adv,$is_author);
6407: }
1.976 raeburn 6408: return $is_adv;
6409: }
1.798 raeburn 6410:
1.1035 raeburn 6411: sub check_can_request {
1.1036 raeburn 6412: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6413: my $canreq = 0;
6414: my ($types,$typename) = &Apache::loncommon::course_types();
6415: my @options = ('approval','validate','autolimit');
6416: my $optregex = join('|',@options);
6417: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6418: foreach my $type (@{$types}) {
6419: if (&usertools_access($env{'user.name'},
6420: $env{'user.domain'},
6421: $type,undef,'requestcourses')) {
6422: $canreq ++;
1.1036 raeburn 6423: if (ref($request_domains) eq 'HASH') {
6424: push(@{$request_domains->{$type}},$env{'user.domain'});
6425: }
1.1035 raeburn 6426: if ($dom eq $env{'user.domain'}) {
6427: $can_request->{$type} = 1;
6428: }
6429: }
6430: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6431: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6432: if (@curr > 0) {
1.1036 raeburn 6433: foreach my $item (@curr) {
6434: if (ref($request_domains) eq 'HASH') {
6435: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6436: if ($otherdom ne '') {
6437: if (ref($request_domains->{$type}) eq 'ARRAY') {
6438: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6439: push(@{$request_domains->{$type}},$otherdom);
6440: }
6441: } else {
6442: push(@{$request_domains->{$type}},$otherdom);
6443: }
6444: }
6445: }
6446: }
6447: unless($dom eq $env{'user.domain'}) {
6448: $canreq ++;
1.1035 raeburn 6449: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6450: $can_request->{$type} = 1;
6451: }
6452: }
6453: }
6454: }
6455: }
6456: }
6457: return $canreq;
6458: }
6459:
1.341 www 6460: # ---------------------------------------------- Custom access rule evaluation
6461:
6462: sub customaccess {
6463: my ($priv,$uri)=@_;
1.807 albertel 6464: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6465: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6466: $udom = &LONCAPA::clean_domain($udom);
6467: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6468: my $access=0;
1.800 albertel 6469: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6470: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6471: if ($type eq 'user') {
6472: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6473: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6474: if ($tdom) {
6475: if ($tdom ne $env{'user.domain'}) { next; }
6476: }
1.896 albertel 6477: if ($tuname) {
6478: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6479: }
6480: $access=($effect eq 'allow');
6481: last;
6482: }
6483: } else {
6484: if ($role) {
6485: if ($role ne $urole) { next; }
6486: }
6487: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6488: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6489: if ($tdom) {
6490: if ($tdom ne $udom) { next; }
6491: }
6492: if ($tcrs) {
6493: if ($tcrs ne $ucrs) { next; }
6494: }
6495: if ($tsec) {
6496: if ($tsec ne $usec) { next; }
6497: }
6498: $access=($effect eq 'allow');
6499: last;
6500: }
6501: if ($realm eq '' && $role eq '') {
6502: $access=($effect eq 'allow');
6503: }
1.402 bowersj2 6504: }
1.341 www 6505: }
6506: return $access;
6507: }
6508:
1.103 harris41 6509: # ------------------------------------------------- Check for a user privilege
1.12 www 6510:
6511: sub allowed {
1.810 raeburn 6512: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6513: my $ver_orguri=$uri;
1.439 www 6514: $uri=&deversion($uri);
1.152 www 6515: my $orguri=$uri;
1.52 www 6516: $uri=&declutter($uri);
1.809 raeburn 6517:
1.810 raeburn 6518: if ($priv eq 'evb') {
6519: # Evade communication block restrictions for specified role in a course
6520: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6521: return $1;
6522: } else {
6523: return;
6524: }
6525: }
6526:
1.620 albertel 6527: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6528: # Free bre access to adm and meta resources
1.775 albertel 6529: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6530: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6531: && ($priv eq 'bre')) {
1.14 www 6532: return 'F';
1.159 www 6533: }
6534:
1.545 banghart 6535: # Free bre access to user's own portfolio contents
1.714 raeburn 6536: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6537: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6538: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6539: my %setters;
6540: my ($startblock,$endblock) =
6541: &Apache::loncommon::blockcheck(\%setters,'port');
6542: if ($startblock && $endblock) {
6543: return 'B';
6544: } else {
6545: return 'F';
6546: }
1.545 banghart 6547: }
6548:
1.762 raeburn 6549: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6550: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6551: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6552: if (exists($env{'request.course.id'})) {
6553: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6554: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6555: if (($domain eq $cdom) && ($name eq $cnum)) {
6556: my $courseprivid=$env{'request.course.id'};
6557: $courseprivid=~s/\_/\//;
6558: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6559: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6560: return $1;
1.762 raeburn 6561: } else {
6562: if ($env{'request.course.sec'}) {
6563: $courseprivid.='/'.$env{'request.course.sec'};
6564: }
6565: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6566: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6567: return $2;
6568: }
1.714 raeburn 6569: }
6570: }
6571: }
6572: }
6573:
1.159 www 6574: # Free bre to public access
6575:
6576: if ($priv eq 'bre') {
1.238 www 6577: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6578: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6579: return 'F';
6580: }
1.238 www 6581: if ($copyright eq 'priv') {
6582: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6583: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6584: return '';
6585: }
6586: }
6587: if ($copyright eq 'domain') {
6588: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6589: unless (($env{'user.domain'} eq $1) ||
6590: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6591: return '';
6592: }
1.262 matthew 6593: }
1.620 albertel 6594: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6595: # Library role, so allow browsing of resources in this domain.
6596: return 'F';
1.238 www 6597: }
1.341 www 6598: if ($copyright eq 'custom') {
6599: unless (&customaccess($priv,$uri)) { return ''; }
6600: }
1.14 www 6601: }
1.264 matthew 6602: # Domain coordinator is trying to create a course
1.620 albertel 6603: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6604: # uri is the requested domain in this case.
6605: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6606: # a role of dc for the domain in question.
1.620 albertel 6607: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6608: }
1.29 www 6609:
1.52 www 6610: my $thisallowed='';
6611: my $statecond=0;
6612: my $courseprivid='';
6613:
1.1039 raeburn 6614: my $ownaccess;
1.1043 raeburn 6615: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6616: if (($priv eq 'bro') && ($env{'user.author'})) {
6617: if ($uri eq '') {
6618: $ownaccess = 1;
6619: } else {
6620: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6621: my $udom = $env{'user.domain'};
6622: my $uname = $env{'user.name'};
6623: if ($uri =~ m{^\Q$udom\E/?$}) {
6624: $ownaccess = 1;
1.1040 raeburn 6625: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6626: unless ($uri =~ m{\.\./}) {
6627: $ownaccess = 1;
6628: }
6629: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6630: my $now = time;
6631: if ($uri =~ m{^([^/]+)/?$}) {
6632: my $adom = $1;
6633: foreach my $key (keys(%env)) {
1.1042 raeburn 6634: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6635: my ($start,$end) = split('.',$env{$key});
6636: if (($now >= $start) && (!$end || $end < $now)) {
6637: $ownaccess = 1;
6638: last;
6639: }
6640: }
6641: }
6642: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6643: my $adom = $1;
6644: my $aname = $2;
1.1042 raeburn 6645: foreach my $role ('ca','aa') {
6646: if ($env{"user.role.$role./$adom/$aname"}) {
6647: my ($start,$end) =
6648: split('.',$env{"user.role.$role./$adom/$aname"});
6649: if (($now >= $start) && (!$end || $end < $now)) {
6650: $ownaccess = 1;
6651: last;
6652: }
1.1039 raeburn 6653: }
6654: }
6655: }
6656: }
6657: }
6658: }
6659: }
6660:
1.52 www 6661: # Course
6662:
1.620 albertel 6663: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6664: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6665: $thisallowed.=$1;
6666: }
1.52 www 6667: }
1.29 www 6668:
1.52 www 6669: # Domain
6670:
1.620 albertel 6671: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6672: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6673: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6674: $thisallowed.=$1;
6675: }
1.12 www 6676: }
1.52 www 6677:
1.1141 raeburn 6678: # User who is not author or co-author might still be able to edit
6679: # resource of an author in the domain (e.g., if Domain Coordinator).
6680: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6681: (&allowed('mdc',$env{'request.course.id'}))) {
6682: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6683: $thisallowed.=$1;
6684: }
6685: }
6686:
1.52 www 6687: # Course: uri itself is a course
1.66 www 6688: my $courseuri=$uri;
6689: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6690: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6691:
1.620 albertel 6692: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6693: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6694: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6695: $thisallowed.=$1;
6696: }
1.12 www 6697: }
1.29 www 6698:
1.665 albertel 6699: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6700: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6701: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6702: $thisallowed='';
1.671 raeburn 6703: my ($match)=&is_on_map($uri);
6704: if ($match) {
6705: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6706: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6707: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6708: if (@blockers > 0) {
6709: $thisallowed = 'B';
6710: } else {
6711: $thisallowed.=$1;
6712: }
1.671 raeburn 6713: }
6714: } else {
1.705 albertel 6715: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6716: if ($refuri) {
6717: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6718: $thisallowed='F';
1.671 raeburn 6719: } else {
6720: $refuri=&declutter($refuri);
6721: my ($match) = &is_on_map($refuri);
6722: if ($match) {
1.1162 raeburn 6723: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6724: if (@blockers > 0) {
6725: $thisallowed = 'B';
6726: } else {
6727: $thisallowed='F';
6728: }
1.671 raeburn 6729: }
1.669 raeburn 6730: }
1.671 raeburn 6731: }
6732: }
1.314 www 6733: }
1.492 albertel 6734:
1.766 albertel 6735: if ($priv eq 'bre'
6736: && $thisallowed ne 'F'
6737: && $thisallowed ne '2'
6738: && &is_portfolio_url($uri)) {
6739: $thisallowed = &portfolio_access($uri);
6740: }
6741:
1.52 www 6742: # Full access at system, domain or course-wide level? Exit.
1.29 www 6743: if ($thisallowed=~/F/) {
6744: return 'F';
6745: }
6746:
1.52 www 6747: # If this is generating or modifying users, exit with special codes
1.29 www 6748:
1.643 www 6749: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6750: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6751: my ($audom,$auname)=split('/',$uri);
1.643 www 6752: # no author name given, so this just checks on the general right to make a co-author in this domain
6753: unless ($auname) { return $thisallowed; }
6754: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6755: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6756: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6757: ($audom ne $env{'request.role.domain'}))) { return ''; }
6758: }
1.52 www 6759: return $thisallowed;
6760: }
6761: #
1.103 harris41 6762: # Gathered so far: system, domain and course wide privileges
1.52 www 6763: #
6764: # Course: See if uri or referer is an individual resource that is part of
6765: # the course
6766:
1.620 albertel 6767: if ($env{'request.course.id'}) {
1.232 www 6768:
1.620 albertel 6769: $courseprivid=$env{'request.course.id'};
6770: if ($env{'request.course.sec'}) {
6771: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6772: }
6773: $courseprivid=~s/\_/\//;
6774: my $checkreferer=1;
1.232 www 6775: my ($match,$cond)=&is_on_map($uri);
6776: if ($match) {
6777: $statecond=$cond;
1.620 albertel 6778: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6779: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6780: my $value = $1;
6781: if ($priv eq 'bre') {
6782: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6783: if (@blockers > 0) {
6784: $thisallowed = 'B';
6785: } else {
6786: $thisallowed.=$value;
6787: }
6788: } else {
6789: $thisallowed.=$value;
6790: }
1.52 www 6791: $checkreferer=0;
6792: }
1.29 www 6793: }
1.83 www 6794:
1.148 www 6795: if ($checkreferer) {
1.620 albertel 6796: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6797: unless ($refuri) {
1.800 albertel 6798: foreach my $key (keys(%env)) {
6799: if ($key=~/^httpref\..*\*/) {
6800: my $pattern=$key;
1.156 www 6801: $pattern=~s/^httpref\.\/res\///;
1.148 www 6802: $pattern=~s/\*/\[\^\/\]\+/g;
6803: $pattern=~s/\//\\\//g;
1.152 www 6804: if ($orguri=~/$pattern/) {
1.800 albertel 6805: $refuri=$env{$key};
1.148 www 6806: }
6807: }
1.191 harris41 6808: }
1.148 www 6809: }
1.232 www 6810:
1.148 www 6811: if ($refuri) {
1.152 www 6812: $refuri=&declutter($refuri);
1.232 www 6813: my ($match,$cond)=&is_on_map($refuri);
6814: if ($match) {
6815: my $refstatecond=$cond;
1.620 albertel 6816: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6817: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6818: my $value = $1;
6819: if ($priv eq 'bre') {
6820: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6821: if (@blockers > 0) {
6822: $thisallowed = 'B';
6823: } else {
6824: $thisallowed.=$value;
6825: }
6826: } else {
6827: $thisallowed.=$value;
6828: }
1.53 www 6829: $uri=$refuri;
6830: $statecond=$refstatecond;
1.52 www 6831: }
6832: }
1.148 www 6833: }
1.29 www 6834: }
1.52 www 6835: }
1.29 www 6836:
1.52 www 6837: #
1.103 harris41 6838: # Gathered now: all privileges that could apply, and condition number
1.52 www 6839: #
6840: #
6841: # Full or no access?
6842: #
1.29 www 6843:
1.52 www 6844: if ($thisallowed=~/F/) {
6845: return 'F';
6846: }
1.29 www 6847:
1.52 www 6848: unless ($thisallowed) {
6849: return '';
6850: }
1.29 www 6851:
1.52 www 6852: # Restrictions exist, deal with them
6853: #
6854: # C:according to course preferences
6855: # R:according to resource settings
6856: # L:unless locked
6857: # X:according to user session state
6858: #
6859:
6860: # Possibly locked functionality, check all courses
1.54 www 6861: # Locks might take effect only after 10 minutes cache expiration for other
6862: # courses, and 2 minutes for current course
1.52 www 6863:
6864: my $envkey;
6865: if ($thisallowed=~/L/) {
1.1000 raeburn 6866: foreach $envkey (keys(%env)) {
1.54 www 6867: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6868: my $courseid=$2;
6869: my $roleid=$1.'.'.$2;
1.92 www 6870: $courseid=~s/^\///;
1.54 www 6871: my $expiretime=600;
1.620 albertel 6872: if ($env{'request.role'} eq $roleid) {
1.54 www 6873: $expiretime=120;
6874: }
6875: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6876: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6877: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6878: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6879: }
1.620 albertel 6880: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6881: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6882: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6883: &log($env{'user.domain'},$env{'user.name'},
6884: $env{'user.home'},
1.57 www 6885: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6886: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6887: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6888: return '';
6889: }
6890: }
1.620 albertel 6891: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6892: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6893: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6894: &log($env{'user.domain'},$env{'user.name'},
6895: $env{'user.home'},
1.57 www 6896: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6897: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6898: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6899: return '';
6900: }
6901: }
6902: }
1.29 www 6903: }
1.52 www 6904: }
6905:
6906: #
6907: # Rest of the restrictions depend on selected course
6908: #
6909:
1.620 albertel 6910: unless ($env{'request.course.id'}) {
1.766 albertel 6911: if ($thisallowed eq 'A') {
6912: return 'A';
1.814 raeburn 6913: } elsif ($thisallowed eq 'B') {
6914: return 'B';
1.766 albertel 6915: } else {
6916: return '1';
6917: }
1.52 www 6918: }
1.29 www 6919:
1.52 www 6920: #
6921: # Now user is definitely in a course
6922: #
1.53 www 6923:
6924:
6925: # Course preferences
6926:
6927: if ($thisallowed=~/C/) {
1.620 albertel 6928: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6929: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6930: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6931: =~/\Q$rolecode\E/) {
1.1103 raeburn 6932: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6933: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6934: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6935: $env{'request.course.id'});
6936: }
1.237 www 6937: return '';
6938: }
6939:
1.620 albertel 6940: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6941: =~/\Q$unamedom\E/) {
1.1103 raeburn 6942: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6943: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6944: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6945: $env{'request.course.id'});
6946: }
1.54 www 6947: return '';
6948: }
1.53 www 6949: }
6950:
6951: # Resource preferences
6952:
6953: if ($thisallowed=~/R/) {
1.620 albertel 6954: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6955: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6956: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6957: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6958: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6959: }
6960: return '';
1.54 www 6961: }
1.53 www 6962: }
1.30 www 6963:
1.246 www 6964: # Restricted by state or randomout?
1.30 www 6965:
1.52 www 6966: if ($thisallowed=~/X/) {
1.620 albertel 6967: if ($env{'acc.randomout'}) {
1.579 albertel 6968: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 6969: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 6970: return '';
6971: }
1.247 www 6972: }
6973: if (&condval($statecond)) {
1.52 www 6974: return '2';
6975: } else {
6976: return '';
6977: }
6978: }
1.30 www 6979:
1.766 albertel 6980: if ($thisallowed eq 'A') {
6981: return 'A';
1.814 raeburn 6982: } elsif ($thisallowed eq 'B') {
6983: return 'B';
1.766 albertel 6984: }
1.52 www 6985: return 'F';
1.232 www 6986: }
1.1162 raeburn 6987:
1.1192 raeburn 6988: # ------------------------------------------- Check construction space access
6989:
6990: sub constructaccess {
6991: my ($url,$setpriv)=@_;
6992:
6993: # We do not allow editing of previous versions of files
6994: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
6995:
6996: # Get username and domain from URL
6997: my ($ownername,$ownerdomain,$ownerhome);
6998:
6999: ($ownerdomain,$ownername) =
7000: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7001:
7002: # The URL does not really point to any authorspace, forget it
7003: unless (($ownername) && ($ownerdomain)) { return ''; }
7004:
7005: # Now we need to see if the user has access to the authorspace of
7006: # $ownername at $ownerdomain
7007:
7008: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7009: # Real author for this?
7010: $ownerhome = $env{'user.home'};
7011: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7012: return ($ownername,$ownerdomain,$ownerhome);
7013: }
7014: } else {
7015: # Co-author for this?
7016: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7017: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7018: $ownerhome = &homeserver($ownername,$ownerdomain);
7019: return ($ownername,$ownerdomain,$ownerhome);
7020: }
7021: }
7022:
7023: # We don't have any access right now. If we are not possibly going to do anything about this,
7024: # we might as well leave
7025: unless ($setpriv) { return ''; }
7026:
7027: # Backdoor access?
7028: my $allowed=&allowed('eco',$ownerdomain);
7029: # Nope
7030: unless ($allowed) { return ''; }
7031: # Looks like we may have access, but could be locked by the owner of the construction space
7032: if ($allowed eq 'U') {
7033: my %blocked=&get('environment',['domcoord.author'],
7034: $ownerdomain,$ownername);
7035: # Is blocked by owner
7036: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7037: }
7038: if (($allowed eq 'F') || ($allowed eq 'U')) {
7039: # Grant temporary access
7040: my $then=$env{'user.login.time'};
1.1209 raeburn 7041: my $update=$env{'user.update.time'};
1.1192 raeburn 7042: if (!$update) { $update = $then; }
7043: my $refresh=$env{'user.refresh.time'};
7044: if (!$refresh) { $refresh = $update; }
7045: my $now = time;
7046: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7047: $now,'ca','constructaccess');
7048: $ownerhome = &homeserver($ownername,$ownerdomain);
7049: return($ownername,$ownerdomain,$ownerhome);
7050: }
7051: # No business here
7052: return '';
7053: }
7054:
1.1162 raeburn 7055: sub get_comm_blocks {
7056: my ($cdom,$cnum) = @_;
7057: if ($cdom eq '' || $cnum eq '') {
7058: return unless ($env{'request.course.id'});
7059: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7060: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7061: }
7062: my %commblocks;
7063: my $hashid=$cdom.'_'.$cnum;
7064: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7065: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7066: %commblocks = %{$blocksref};
7067: } else {
7068: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7069: my $cachetime = 600;
7070: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7071: }
7072: return %commblocks;
7073: }
7074:
7075: sub has_comm_blocking {
7076: my ($priv,$symb,$uri,$blocks) = @_;
7077: return unless ($env{'request.course.id'});
7078: return unless ($priv eq 'bre');
7079: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7080: my %commblocks;
7081: if (ref($blocks) eq 'HASH') {
7082: %commblocks = %{$blocks};
7083: } else {
7084: %commblocks = &get_comm_blocks();
7085: }
7086: return unless (keys(%commblocks) > 0);
7087: if (!$symb) { $symb=&symbread($uri,1); }
7088: my ($map,$resid,undef)=&decode_symb($symb);
7089: my %tocheck = (
7090: maps => $map,
7091: resources => $symb,
7092: );
7093: my @blockers;
7094: my $now = time;
1.1163 raeburn 7095: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7096: foreach my $block (keys(%commblocks)) {
7097: if ($block =~ /^(\d+)____(\d+)$/) {
7098: my ($start,$end) = ($1,$2);
7099: if ($start <= $now && $end >= $now) {
7100: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7101: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7102: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7103: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7104: unless (grep(/^\Q$block\E$/,@blockers)) {
7105: push(@blockers,$block);
7106: }
7107: }
7108: }
7109: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7110: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7111: unless (grep(/^\Q$block\E$/,@blockers)) {
7112: push(@blockers,$block);
7113: }
7114: }
7115: }
7116: }
7117: }
7118: }
7119: } elsif ($block =~ /^firstaccess____(.+)$/) {
7120: my $item = $1;
1.1163 raeburn 7121: my @to_test;
1.1162 raeburn 7122: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7123: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7124: my $check_interval;
7125: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7126: my @interval;
7127: my $type = 'map';
7128: if ($item eq 'course') {
7129: $type = 'course';
7130: @interval=&EXT("resource.0.interval");
7131: } else {
7132: if ($item =~ /___\d+___/) {
7133: $type = 'resource';
7134: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7135: if (ref($navmap)) {
7136: my $res = $navmap->getBySymb($item);
7137: push(@to_test,$res);
7138: }
1.1162 raeburn 7139: } else {
7140: my $mapsymb = &symbread($item,1);
7141: if ($mapsymb) {
7142: if (ref($navmap)) {
7143: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7144: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7145: foreach my $res (@to_test) {
1.1162 raeburn 7146: my $symb = $res->symb();
7147: next if ($symb eq $mapsymb);
7148: if ($symb ne '') {
7149: @interval=&EXT("resource.0.interval",$symb);
7150: last;
7151: }
7152: }
7153: }
7154: }
7155: }
7156: }
7157: if ($interval[0] =~ /\d+/) {
7158: my $first_access;
7159: if ($type eq 'resource') {
7160: $first_access=&get_first_access($interval[1],$item);
7161: } elsif ($type eq 'map') {
7162: $first_access=&get_first_access($interval[1],undef,$item);
7163: } else {
7164: $first_access=&get_first_access($interval[1]);
7165: }
7166: if ($first_access) {
7167: my $timesup = $first_access+$interval[0];
7168: if ($timesup > $now) {
1.1163 raeburn 7169: foreach my $res (@to_test) {
7170: if ($res->is_problem()) {
7171: if ($res->completable()) {
7172: unless (grep(/^\Q$block\E$/,@blockers)) {
7173: push(@blockers,$block);
7174: }
7175: last;
7176: }
7177: }
1.1162 raeburn 7178: }
7179: }
7180: }
7181: }
7182: }
7183: }
7184: }
7185: }
7186: }
7187: return @blockers;
7188: }
7189:
7190: sub check_docs_block {
7191: my ($docsblock,$tocheck) =@_;
7192: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7193: return;
7194: }
7195: if (ref($docsblock->{'maps'}) eq 'HASH') {
7196: if ($tocheck->{'maps'}) {
7197: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7198: return 1;
7199: }
7200: }
7201: }
7202: if (ref($docsblock->{'resources'}) eq 'HASH') {
7203: if ($tocheck->{'resources'}) {
7204: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7205: return 1;
7206: }
7207: }
7208: }
7209: return;
7210: }
7211:
1.1133 foxr 7212: #
7213: # Removes the versino from a URI and
7214: # splits it in to its filename and path to the filename.
7215: # Seems like File::Basename could have done this more clearly.
7216: # Parameters:
7217: # $uri - input URI
7218: # Returns:
7219: # Two element list consisting of
7220: # $pathname - the URI up to and excluding the trailing /
7221: # $filename - The part of the URI following the last /
7222: # NOTE:
7223: # Another realization of this is simply:
7224: # use File::Basename;
7225: # ...
7226: # $uri = shift;
7227: # $filename = basename($uri);
7228: # $path = dirname($uri);
7229: # return ($filename, $path);
7230: #
7231: # The implementation below is probably faster however.
7232: #
1.710 albertel 7233: sub split_uri_for_cond {
7234: my $uri=&deversion(&declutter(shift));
7235: my @uriparts=split(/\//,$uri);
7236: my $filename=pop(@uriparts);
7237: my $pathname=join('/',@uriparts);
7238: return ($pathname,$filename);
7239: }
1.232 www 7240: # --------------------------------------------------- Is a resource on the map?
7241:
7242: sub is_on_map {
1.710 albertel 7243: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7244: #Trying to find the conditional for the file
1.620 albertel 7245: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7246: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7247: if ($match) {
1.289 bowersj2 7248: return (1,$1);
7249: } else {
1.434 www 7250: return (0,0);
1.289 bowersj2 7251: }
1.12 www 7252: }
7253:
1.427 www 7254: # --------------------------------------------------------- Get symb from alias
7255:
7256: sub get_symb_from_alias {
7257: my $symb=shift;
7258: my ($map,$resid,$url)=&decode_symb($symb);
7259: # Already is a symb
7260: if ($url) { return $symb; }
7261: # Must be an alias
7262: my $aliassymb='';
7263: my %bighash;
1.620 albertel 7264: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7265: &GDBM_READER(),0640)) {
7266: my $rid=$bighash{'mapalias_'.$symb};
7267: if ($rid) {
7268: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7269: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7270: $resid,$bighash{'src_'.$rid});
1.427 www 7271: }
7272: untie %bighash;
7273: }
7274: return $aliassymb;
7275: }
7276:
1.12 www 7277: # ----------------------------------------------------------------- Define Role
7278:
7279: sub definerole {
7280: if (allowed('mcr','/')) {
7281: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7282: foreach my $role (split(':',$sysrole)) {
7283: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7284: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7285: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7286: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7287: return "refused:s:$crole&$cqual";
7288: }
7289: }
1.191 harris41 7290: }
1.800 albertel 7291: foreach my $role (split(':',$domrole)) {
7292: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7293: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7294: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7295: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7296: return "refused:d:$crole&$cqual";
7297: }
7298: }
1.191 harris41 7299: }
1.800 albertel 7300: foreach my $role (split(':',$courole)) {
7301: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7302: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7303: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7304: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7305: return "refused:c:$crole&$cqual";
7306: }
7307: }
1.191 harris41 7308: }
1.620 albertel 7309: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7310: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7311: "rolesdef_$rolename=".
7312: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7313: return reply($command,$env{'user.home'});
1.12 www 7314: } else {
7315: return 'refused';
7316: }
1.105 harris41 7317: }
7318:
7319: # ---------------- Make a metadata query against the network of library servers
7320:
7321: sub metadata_query {
1.1237 raeburn 7322: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7323: my %rhash;
1.845 albertel 7324: my %libserv = &all_library();
1.244 matthew 7325: my @server_list = (defined($server_array) ? @$server_array
7326: : keys(%libserv) );
7327: for my $server (@server_list) {
1.1237 raeburn 7328: my $domains = '';
7329: if (ref($domains_hash) eq 'HASH') {
7330: $domains = $domains_hash->{$server};
7331: }
1.118 harris41 7332: unless ($custom or $customshow) {
1.1237 raeburn 7333: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7334: $rhash{$server}=$reply;
7335: }
7336: else {
7337: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7338: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7339: $server);
7340: $rhash{$server}=$reply;
7341: }
1.112 harris41 7342: }
1.118 harris41 7343: return \%rhash;
1.240 www 7344: }
7345:
7346: # ----------------------------------------- Send log queries and wait for reply
7347:
7348: sub log_query {
7349: my ($uname,$udom,$query,%filters)=@_;
7350: my $uhome=&homeserver($uname,$udom);
7351: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7352: my $uhost=&hostname($uhome);
1.800 albertel 7353: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7354: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7355: $uhome);
1.479 albertel 7356: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7357: return get_query_reply($queryid);
7358: }
7359:
1.818 raeburn 7360: # -------------------------- Update MySQL table for portfolio file
7361:
7362: sub update_portfolio_table {
1.821 raeburn 7363: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7364: if ($group ne '') {
7365: $file_name =~s /^\Q$group\E//;
7366: }
1.818 raeburn 7367: my $homeserver = &homeserver($uname,$udom);
7368: my $queryid=
1.821 raeburn 7369: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7370: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7371: my $reply = &get_query_reply($queryid);
7372: return $reply;
7373: }
7374:
1.899 raeburn 7375: # -------------------------- Update MySQL allusers table
7376:
7377: sub update_allusers_table {
7378: my ($uname,$udom,$names) = @_;
7379: my $homeserver = &homeserver($uname,$udom);
7380: my $queryid=
7381: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7382: 'lastname='.&escape($names->{'lastname'}).'%%'.
7383: 'firstname='.&escape($names->{'firstname'}).'%%'.
7384: 'middlename='.&escape($names->{'middlename'}).'%%'.
7385: 'generation='.&escape($names->{'generation'}).'%%'.
7386: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7387: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7388: return;
1.899 raeburn 7389: }
7390:
1.508 raeburn 7391: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7392:
7393: sub fetch_enrollment_query {
1.511 raeburn 7394: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7395: my $homeserver;
1.547 raeburn 7396: my $maxtries = 1;
1.508 raeburn 7397: if ($context eq 'automated') {
7398: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7399: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7400: } else {
7401: $homeserver = &homeserver($cnum,$dom);
7402: }
1.838 albertel 7403: my $host=&hostname($homeserver);
1.506 raeburn 7404: my $cmd = '';
1.1000 raeburn 7405: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7406: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7407: }
7408: $cmd =~ s/%%$//;
7409: $cmd = &escape($cmd);
7410: my $query = 'fetchenrollment';
1.620 albertel 7411: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7412: unless ($queryid=~/^\Q$host\E\_/) {
7413: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7414: return 'error: '.$queryid;
7415: }
1.506 raeburn 7416: my $reply = &get_query_reply($queryid);
1.547 raeburn 7417: my $tries = 1;
7418: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7419: $reply = &get_query_reply($queryid);
7420: $tries ++;
7421: }
1.526 raeburn 7422: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7423: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7424: } else {
1.901 albertel 7425: my @responses = split(/:/,$reply);
1.515 raeburn 7426: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7427: foreach my $line (@responses) {
7428: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7429: $$replyref{$key} = $value;
7430: }
7431: } else {
1.1117 foxr 7432: my $pathname = LONCAPA::tempdir();
1.800 albertel 7433: foreach my $line (@responses) {
7434: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7435: $$replyref{$key} = $value;
7436: if ($value > 0) {
1.800 albertel 7437: foreach my $item (@{$$affiliatesref{$key}}) {
7438: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7439: my $destname = $pathname.'/'.$filename;
7440: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7441: if ($xml_classlist =~ /^error/) {
7442: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7443: } else {
1.506 raeburn 7444: if ( open(FILE,">$destname") ) {
7445: print FILE &unescape($xml_classlist);
7446: close(FILE);
1.526 raeburn 7447: } else {
7448: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7449: }
7450: }
7451: }
7452: }
7453: }
7454: }
7455: return 'ok';
7456: }
7457: return 'error';
7458: }
7459:
1.242 www 7460: sub get_query_reply {
7461: my $queryid=shift;
1.1117 foxr 7462: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7463: my $reply='';
7464: for (1..100) {
7465: sleep 2;
7466: if (-e $replyfile.'.end') {
1.448 albertel 7467: if (open(my $fh,$replyfile)) {
1.904 albertel 7468: $reply = join('',<$fh>);
7469: close($fh);
1.240 www 7470: } else { return 'error: reply_file_error'; }
1.242 www 7471: return &unescape($reply);
7472: }
1.240 www 7473: }
1.242 www 7474: return 'timeout:'.$queryid;
1.240 www 7475: }
7476:
7477: sub courselog_query {
1.241 www 7478: #
7479: # possible filters:
7480: # url: url or symb
7481: # username
7482: # domain
7483: # action: view, submit, grade
7484: # start: timestamp
7485: # end: timestamp
7486: #
1.240 www 7487: my (%filters)=@_;
1.620 albertel 7488: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7489: if ($filters{'url'}) {
7490: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7491: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7492: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7493: }
1.620 albertel 7494: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7495: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7496: return &log_query($cname,$cdom,'courselog',%filters);
7497: }
7498:
7499: sub userlog_query {
1.858 raeburn 7500: #
7501: # possible filters:
7502: # action: log check role
7503: # start: timestamp
7504: # end: timestamp
7505: #
1.240 www 7506: my ($uname,$udom,%filters)=@_;
7507: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7508: }
7509:
1.506 raeburn 7510: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7511:
7512: sub auto_run {
1.508 raeburn 7513: my ($cnum,$cdom) = @_;
1.876 raeburn 7514: my $response = 0;
7515: my $settings;
7516: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7517: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7518: $settings = $domconfig{'autoenroll'};
7519: if ($settings->{'run'} eq '1') {
7520: $response = 1;
7521: }
7522: } else {
1.934 raeburn 7523: my $homeserver;
7524: if (&is_course($cdom,$cnum)) {
7525: $homeserver = &homeserver($cnum,$cdom);
7526: } else {
7527: $homeserver = &domain($cdom,'primary');
7528: }
7529: if ($homeserver ne 'no_host') {
7530: $response = &reply('autorun:'.$cdom,$homeserver);
7531: }
1.876 raeburn 7532: }
1.506 raeburn 7533: return $response;
7534: }
1.776 albertel 7535:
1.506 raeburn 7536: sub auto_get_sections {
1.508 raeburn 7537: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7538: my $homeserver;
7539: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7540: $homeserver = &homeserver($cnum,$cdom);
7541: }
7542: if (!defined($homeserver)) {
7543: if ($cdom =~ /^$match_domain$/) {
7544: $homeserver = &domain($cdom,'primary');
7545: }
7546: }
7547: my @secs;
7548: if (defined($homeserver)) {
7549: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7550: unless ($response eq 'refused') {
7551: @secs = split(/:/,$response);
7552: }
1.506 raeburn 7553: }
7554: return @secs;
7555: }
1.776 albertel 7556:
1.506 raeburn 7557: sub auto_new_course {
1.1099 raeburn 7558: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7559: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7560: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7561: return $response;
7562: }
1.776 albertel 7563:
1.506 raeburn 7564: sub auto_validate_courseID {
1.508 raeburn 7565: my ($cnum,$cdom,$inst_course_id) = @_;
7566: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7567: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7568: return $response;
7569: }
1.776 albertel 7570:
1.1007 raeburn 7571: sub auto_validate_instcode {
1.1020 raeburn 7572: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7573: my ($homeserver,$response);
7574: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7575: $homeserver = &homeserver($cnum,$cdom);
7576: }
7577: if (!defined($homeserver)) {
7578: if ($cdom =~ /^$match_domain$/) {
7579: $homeserver = &domain($cdom,'primary');
7580: }
7581: }
1.1065 raeburn 7582: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7583: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 7584: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7585: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7586: }
7587:
1.506 raeburn 7588: sub auto_create_password {
1.873 raeburn 7589: my ($cnum,$cdom,$authparam,$udom) = @_;
7590: my ($homeserver,$response);
1.506 raeburn 7591: my $create_passwd = 0;
7592: my $authchk = '';
1.873 raeburn 7593: if ($udom =~ /^$match_domain$/) {
7594: $homeserver = &domain($udom,'primary');
7595: }
7596: if ($homeserver eq '') {
7597: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7598: $homeserver = &homeserver($cnum,$cdom);
7599: }
7600: }
7601: if ($homeserver eq '') {
7602: $authchk = 'nodomain';
1.506 raeburn 7603: } else {
1.873 raeburn 7604: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7605: if ($response eq 'refused') {
7606: $authchk = 'refused';
7607: } else {
1.901 albertel 7608: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7609: }
1.506 raeburn 7610: }
7611: return ($authparam,$create_passwd,$authchk);
7612: }
7613:
1.706 raeburn 7614: sub auto_photo_permission {
7615: my ($cnum,$cdom,$students) = @_;
7616: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7617: my ($outcome,$perm_reqd,$conditions) =
7618: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7619: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7620: return (undef,undef);
7621: }
1.706 raeburn 7622: return ($outcome,$perm_reqd,$conditions);
7623: }
7624:
7625: sub auto_checkphotos {
7626: my ($uname,$udom,$pid) = @_;
7627: my $homeserver = &homeserver($uname,$udom);
7628: my ($result,$resulttype);
7629: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7630: &escape($uname).':'.&escape($pid),
7631: $homeserver));
1.709 albertel 7632: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7633: return (undef,undef);
7634: }
1.706 raeburn 7635: if ($outcome) {
7636: ($result,$resulttype) = split(/:/,$outcome);
7637: }
7638: return ($result,$resulttype);
7639: }
7640:
7641: sub auto_photochoice {
7642: my ($cnum,$cdom) = @_;
7643: my $homeserver = &homeserver($cnum,$cdom);
7644: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7645: &escape($cdom),
7646: $homeserver)));
1.709 albertel 7647: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7648: return (undef,undef);
7649: }
1.706 raeburn 7650: return ($update,$comment);
7651: }
7652:
7653: sub auto_photoupdate {
7654: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7655: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7656: my $host=&hostname($homeserver);
1.706 raeburn 7657: my $cmd = '';
7658: my $maxtries = 1;
1.800 albertel 7659: foreach my $affiliate (keys(%{$affiliatesref})) {
7660: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7661: }
7662: $cmd =~ s/%%$//;
7663: $cmd = &escape($cmd);
7664: my $query = 'institutionalphotos';
7665: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7666: unless ($queryid=~/^\Q$host\E\_/) {
7667: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7668: return 'error: '.$queryid;
7669: }
7670: my $reply = &get_query_reply($queryid);
7671: my $tries = 1;
7672: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7673: $reply = &get_query_reply($queryid);
7674: $tries ++;
7675: }
7676: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7677: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7678: } else {
7679: my @responses = split(/:/,$reply);
7680: my $outcome = shift(@responses);
7681: foreach my $item (@responses) {
7682: my ($key,$value) = split(/=/,$item);
7683: $$photo{$key} = $value;
7684: }
7685: return $outcome;
7686: }
7687: return 'error';
7688: }
7689:
1.521 raeburn 7690: sub auto_instcode_format {
1.793 albertel 7691: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7692: $cat_order) = @_;
1.521 raeburn 7693: my $courses = '';
1.772 raeburn 7694: my @homeservers;
1.521 raeburn 7695: if ($caller eq 'global') {
1.841 albertel 7696: my %servers = &get_servers($codedom,'library');
7697: foreach my $tryserver (keys(%servers)) {
7698: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7699: push(@homeservers,$tryserver);
7700: }
1.584 raeburn 7701: }
1.1022 raeburn 7702: } elsif ($caller eq 'requests') {
7703: if ($codedom =~ /^$match_domain$/) {
7704: my $chome = &domain($codedom,'primary');
7705: unless ($chome eq 'no_host') {
7706: push(@homeservers,$chome);
7707: }
7708: }
1.521 raeburn 7709: } else {
1.772 raeburn 7710: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7711: }
1.793 albertel 7712: foreach my $code (keys(%{$instcodes})) {
7713: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7714: }
7715: chop($courses);
1.772 raeburn 7716: my $ok_response = 0;
7717: my $response;
7718: while (@homeservers > 0 && $ok_response == 0) {
7719: my $server = shift(@homeservers);
7720: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7721: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7722: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7723: split(/:/,$response);
1.772 raeburn 7724: %{$codes} = (%{$codes},&str2hash($codes_str));
7725: push(@{$codetitles},&str2array($codetitles_str));
7726: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7727: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7728: $ok_response = 1;
7729: }
7730: }
7731: if ($ok_response) {
1.521 raeburn 7732: return 'ok';
1.772 raeburn 7733: } else {
7734: return $response;
1.521 raeburn 7735: }
7736: }
7737:
1.792 raeburn 7738: sub auto_instcode_defaults {
7739: my ($domain,$returnhash,$code_order) = @_;
7740: my @homeservers;
1.841 albertel 7741:
7742: my %servers = &get_servers($domain,'library');
7743: foreach my $tryserver (keys(%servers)) {
7744: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7745: push(@homeservers,$tryserver);
7746: }
1.792 raeburn 7747: }
1.841 albertel 7748:
1.792 raeburn 7749: my $response;
1.841 albertel 7750: foreach my $server (@homeservers) {
1.792 raeburn 7751: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7752: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7753:
7754: foreach my $pair (split(/\&/,$response)) {
7755: my ($name,$value)=split(/\=/,$pair);
7756: if ($name eq 'code_order') {
7757: @{$code_order} = split(/\&/,&unescape($value));
7758: } else {
7759: $returnhash->{&unescape($name)}=&unescape($value);
7760: }
7761: }
7762: return 'ok';
1.792 raeburn 7763: }
1.841 albertel 7764:
7765: return $response;
1.1003 raeburn 7766: }
7767:
7768: sub auto_possible_instcodes {
1.1007 raeburn 7769: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7770: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7771: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7772: return;
7773: }
1.1003 raeburn 7774: my (@homeservers,$uhome);
7775: if (defined(&domain($domain,'primary'))) {
7776: $uhome=&domain($domain,'primary');
7777: push(@homeservers,&domain($domain,'primary'));
7778: } else {
7779: my %servers = &get_servers($domain,'library');
7780: foreach my $tryserver (keys(%servers)) {
7781: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7782: push(@homeservers,$tryserver);
7783: }
7784: }
7785: }
7786: my $response;
7787: foreach my $server (@homeservers) {
7788: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7789: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7790: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7791: split(':',$response);
7792: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7793: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7794: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7795: my ($name,$value)=split('=',$item);
7796: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7797: }
7798: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7799: my ($name,$value)=split('=',$item);
7800: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7801: }
7802: return 'ok';
7803: }
7804: return $response;
7805: }
1.792 raeburn 7806:
1.1010 raeburn 7807: sub auto_courserequest_checks {
7808: my ($dom) = @_;
1.1020 raeburn 7809: my ($homeserver,%validations);
7810: if ($dom =~ /^$match_domain$/) {
7811: $homeserver = &domain($dom,'primary');
7812: }
7813: unless ($homeserver eq 'no_host') {
7814: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7815: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7816: my @items = split(/&/,$response);
7817: foreach my $item (@items) {
7818: my ($key,$value) = split('=',$item);
7819: $validations{&unescape($key)} = &thaw_unescape($value);
7820: }
7821: }
7822: }
1.1010 raeburn 7823: return %validations;
7824: }
7825:
1.1020 raeburn 7826: sub auto_courserequest_validation {
7827: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7828: my ($homeserver,$response);
7829: if ($dom =~ /^$match_domain$/) {
7830: $homeserver = &domain($dom,'primary');
7831: }
7832: unless ($homeserver eq 'no_host') {
1.1021 raeburn 7833:
1.1020 raeburn 7834: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7835: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 7836: ':'.&escape($instcode).':'.&escape($instseclist),
7837: $homeserver));
7838: }
7839: return $response;
7840: }
7841:
1.777 albertel 7842: sub auto_validate_class_sec {
1.918 raeburn 7843: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7844: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7845: my $ownerlist;
7846: if (ref($owners) eq 'ARRAY') {
7847: $ownerlist = join(',',@{$owners});
7848: } else {
7849: $ownerlist = $owners;
7850: }
1.773 raeburn 7851: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7852: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7853: return $response;
7854: }
7855:
1.679 raeburn 7856: # ------------------------------------------------------- Course Group routines
7857:
7858: sub get_coursegroups {
1.809 raeburn 7859: my ($cdom,$cnum,$group,$namespace) = @_;
7860: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7861: }
7862:
1.679 raeburn 7863: sub modify_coursegroup {
7864: my ($cdom,$cnum,$groupsettings) = @_;
7865: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7866: }
7867:
1.809 raeburn 7868: sub toggle_coursegroup_status {
7869: my ($cdom,$cnum,$group,$action) = @_;
7870: my ($from_namespace,$to_namespace);
7871: if ($action eq 'delete') {
7872: $from_namespace = 'coursegroups';
7873: $to_namespace = 'deleted_groups';
7874: } else {
7875: $from_namespace = 'deleted_groups';
7876: $to_namespace = 'coursegroups';
7877: }
7878: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7879: if (my $tmp = &error(%curr_group)) {
7880: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7881: return ('read error',$tmp);
7882: } else {
7883: my %savedsettings = %curr_group;
1.809 raeburn 7884: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7885: my $deloutcome;
7886: if ($result eq 'ok') {
1.809 raeburn 7887: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7888: } else {
7889: return ('write error',$result);
7890: }
7891: if ($deloutcome eq 'ok') {
7892: return 'ok';
7893: } else {
7894: return ('delete error',$deloutcome);
7895: }
7896: }
7897: }
7898:
1.679 raeburn 7899: sub modify_group_roles {
1.957 raeburn 7900: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7901: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7902: my $role = 'gr/'.&escape($userprivs);
7903: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7904: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7905: if ($result eq 'ok') {
7906: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7907: }
1.679 raeburn 7908: return $result;
7909: }
7910:
7911: sub modify_coursegroup_membership {
7912: my ($cdom,$cnum,$membership) = @_;
7913: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7914: return $result;
7915: }
7916:
1.682 raeburn 7917: sub get_active_groups {
7918: my ($udom,$uname,$cdom,$cnum) = @_;
7919: my $now = time;
7920: my %groups = ();
7921: foreach my $key (keys(%env)) {
1.811 albertel 7922: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7923: my ($start,$end) = split(/\./,$env{$key});
7924: if (($end!=0) && ($end<$now)) { next; }
7925: if (($start!=0) && ($start>$now)) { next; }
7926: if ($1 eq $cdom && $2 eq $cnum) {
7927: $groups{$3} = $env{$key} ;
7928: }
7929: }
7930: }
7931: return %groups;
7932: }
7933:
1.683 raeburn 7934: sub get_group_membership {
7935: my ($cdom,$cnum,$group) = @_;
7936: return(&dump('groupmembership',$cdom,$cnum,$group));
7937: }
7938:
7939: sub get_users_groups {
7940: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 7941: my @usersgroups;
1.683 raeburn 7942: my $cachetime=1800;
7943:
7944: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 7945: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7946: if (defined($cached)) {
1.734 albertel 7947: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 7948: } else {
7949: $grouplist = '';
1.816 raeburn 7950: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 7951: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 7952: my $access_end = $env{'course.'.$courseid.
7953: '.default_enrollment_end_date'};
7954: my $now = time;
7955: foreach my $key (keys(%roleshash)) {
7956: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7957: my $group = $1;
7958: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7959: my $start = $2;
7960: my $end = $1;
7961: if ($start == -1) { next; } # deleted from group
7962: if (($start!=0) && ($start>$now)) { next; }
7963: if (($end!=0) && ($end<$now)) {
7964: if ($access_end && $access_end < $now) {
7965: if ($access_end - $end < 86400) {
7966: push(@usersgroups,$group);
1.733 raeburn 7967: }
7968: }
1.817 raeburn 7969: next;
1.733 raeburn 7970: }
1.817 raeburn 7971: push(@usersgroups,$group);
1.683 raeburn 7972: }
7973: }
7974: }
1.817 raeburn 7975: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7976: $grouplist = join(':',@usersgroups);
7977: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 7978: }
1.733 raeburn 7979: return @usersgroups;
1.683 raeburn 7980: }
7981:
7982: sub devalidate_getgroups_cache {
7983: my ($udom,$uname,$cdom,$cnum)=@_;
7984: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 7985:
1.683 raeburn 7986: my $hashid="$udom:$uname:$courseid";
7987: &devalidate_cache_new('getgroups',$hashid);
7988: }
7989:
1.12 www 7990: # ------------------------------------------------------------------ Plain Text
7991:
7992: sub plaintext {
1.988 raeburn 7993: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 7994: if ($short =~ m{^cr/}) {
1.758 albertel 7995: return (split('/',$short))[-1];
7996: }
1.742 raeburn 7997: if (!defined($cid)) {
7998: $cid = $env{'request.course.id'};
7999: }
8000: my %rolenames = (
1.1008 raeburn 8001: Course => 'std',
8002: Community => 'alt1',
1.742 raeburn 8003: );
1.1037 raeburn 8004: if ($cid ne '') {
8005: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8006: unless ($forcedefault) {
8007: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8008: &Apache::lonlocal::mt_escape(\$roletext);
8009: return &Apache::lonlocal::mt($roletext);
8010: }
8011: }
8012: }
8013: if ((defined($type)) && (defined($rolenames{$type})) &&
8014: (defined($rolenames{$type})) &&
8015: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8016: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8017: } elsif ($cid ne '') {
8018: my $crstype = $env{'course.'.$cid.'.type'};
8019: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8020: (defined($prp{$short}{$rolenames{$crstype}}))) {
8021: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8022: }
1.742 raeburn 8023: }
1.1037 raeburn 8024: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8025: }
8026:
8027: # ----------------------------------------------------------------- Assign Role
8028:
8029: sub assignrole {
1.957 raeburn 8030: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8031: $context)=@_;
1.21 www 8032: my $mrole;
8033: if ($role =~ /^cr\//) {
1.393 www 8034: my $cwosec=$url;
1.811 albertel 8035: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8036: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8037: my $refused = 1;
8038: if ($context eq 'requestcourses') {
8039: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8040: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8041: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8042: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8043: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8044: if ($crsenv{'internal.courseowner'} eq
8045: $env{'user.name'}.':'.$env{'user.domain'}) {
8046: $refused = '';
8047: }
8048: }
8049: }
8050: }
8051: }
8052: if ($refused) {
8053: &logthis('Refused custom assignrole: '.
8054: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8055: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8056: return 'refused';
8057: }
1.104 www 8058: }
1.21 www 8059: $mrole='cr';
1.678 raeburn 8060: } elsif ($role =~ /^gr\//) {
8061: my $cwogrp=$url;
1.811 albertel 8062: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8063: unless (&allowed('mdg',$cwogrp)) {
8064: &logthis('Refused group assignrole: '.
8065: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8066: $env{'user.name'}.' at '.$env{'user.domain'});
8067: return 'refused';
8068: }
8069: $mrole='gr';
1.21 www 8070: } else {
1.82 www 8071: my $cwosec=$url;
1.811 albertel 8072: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8073: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8074: my $refused;
8075: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8076: if (!(&allowed('c'.$role,$url))) {
8077: $refused = 1;
8078: }
8079: } else {
8080: $refused = 1;
8081: }
1.947 raeburn 8082: if ($refused) {
1.1045 raeburn 8083: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8084: if (!$selfenroll && $context eq 'course') {
8085: my %crsenv;
8086: if ($role eq 'cc' || $role eq 'co') {
8087: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8088: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8089: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8090: if ($crsenv{'internal.courseowner'} eq
8091: $env{'user.name'}.':'.$env{'user.domain'}) {
8092: $refused = '';
8093: }
8094: }
8095: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8096: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8097: if ($crsenv{'internal.courseowner'} eq
8098: $env{'user.name'}.':'.$env{'user.domain'}) {
8099: $refused = '';
8100: }
8101: }
8102: }
8103: }
8104: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8105: $refused = '';
1.1017 raeburn 8106: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8107: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8108: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8109: my $wrongcc;
8110: if ($cnum =~ /^$match_community$/) {
8111: $wrongcc = 1 if ($role eq 'cc');
8112: } else {
8113: $wrongcc = 1 if ($role eq 'co');
8114: }
8115: unless ($wrongcc) {
8116: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8117: if ($crsenv{'internal.courseowner'} eq
8118: $env{'user.name'}.':'.$env{'user.domain'}) {
8119: $refused = '';
8120: }
1.1017 raeburn 8121: }
8122: }
1.1183 raeburn 8123: } elsif ($context eq 'requestauthor') {
8124: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8125: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8126: if ($env{'environment.requestauthor'} eq 'automatic') {
8127: $refused = '';
8128: } else {
8129: my %domdefaults = &get_domain_defaults($udom);
8130: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8131: my $checkbystatus;
8132: if ($env{'user.adv'}) {
8133: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8134: if ($disposition eq 'automatic') {
8135: $refused = '';
8136: } elsif ($disposition eq '') {
8137: $checkbystatus = 1;
8138: }
8139: } else {
8140: $checkbystatus = 1;
8141: }
8142: if ($checkbystatus) {
8143: if ($env{'environment.inststatus'}) {
8144: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8145: foreach my $type (@inststatuses) {
8146: if (($type ne '') &&
8147: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8148: $refused = '';
8149: }
8150: }
8151: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8152: $refused = '';
8153: }
8154: }
8155: }
8156: }
8157: }
1.1017 raeburn 8158: }
8159: if ($refused) {
1.947 raeburn 8160: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8161: ' '.$role.' '.$end.' '.$start.' by '.
8162: $env{'user.name'}.' at '.$env{'user.domain'});
8163: return 'refused';
8164: }
1.932 raeburn 8165: }
1.1131 raeburn 8166: } elsif ($role eq 'au') {
8167: if ($url ne '/'.$udom.'/') {
8168: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8169: ' to assign author role for '.$uname.':'.$udom.
8170: ' in domain: '.$url.' refused (wrong domain).');
8171: return 'refused';
8172: }
1.104 www 8173: }
1.21 www 8174: $mrole=$role;
8175: }
1.620 albertel 8176: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8177: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8178: if ($end) { $command.='_'.$end; }
1.21 www 8179: if ($start) {
8180: if ($end) {
1.81 www 8181: $command.='_'.$start;
1.21 www 8182: } else {
1.81 www 8183: $command.='_0_'.$start;
1.21 www 8184: }
8185: }
1.739 raeburn 8186: my $origstart = $start;
8187: my $origend = $end;
1.957 raeburn 8188: my $delflag;
1.357 www 8189: # actually delete
8190: if ($deleteflag) {
1.373 www 8191: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8192: # modify command to delete the role
1.620 albertel 8193: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8194: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8195: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8196: # set start and finish to negative values for userrolelog
8197: $start=-1;
8198: $end=-1;
1.957 raeburn 8199: $delflag = 1;
1.357 www 8200: }
8201: }
8202: # send command
1.349 www 8203: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8204: # log new user role if status is ok
1.349 www 8205: if ($answer eq 'ok') {
1.663 raeburn 8206: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8207: if (($role eq 'cc') || ($role eq 'in') ||
8208: ($role eq 'ep') || ($role eq 'ad') ||
8209: ($role eq 'ta') || ($role eq 'st') ||
8210: ($role=~/^cr/) || ($role eq 'gr') ||
8211: ($role eq 'co')) {
1.1200 raeburn 8212: # for course roles, perform group memberships changes triggered by role change.
8213: unless ($role =~ /^gr/) {
8214: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8215: $origstart,$selfenroll,$context);
8216: }
1.1184 raeburn 8217: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8218: $selfenroll,$context);
8219: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8220: ($role eq 'au') || ($role eq 'dc')) {
8221: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8222: $context);
8223: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8224: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8225: $context);
8226: }
1.1053 raeburn 8227: if ($role eq 'cc') {
8228: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8229: }
1.349 www 8230: }
8231: return $answer;
1.169 harris41 8232: }
8233:
1.1053 raeburn 8234: sub autoupdate_coowners {
8235: my ($url,$end,$start,$uname,$udom) = @_;
8236: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8237: if (($cdom ne '') && ($cnum ne '')) {
8238: my $now = time;
8239: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8240: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8241: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8242: my $instcode = $coursehash{'internal.coursecode'};
8243: if ($instcode ne '') {
1.1056 raeburn 8244: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8245: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8246: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8247: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8248: if ($result eq 'valid') {
8249: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8250: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8251: push(@newcoowners,$coowner);
8252: }
8253: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8254: push(@newcoowners,$uname.':'.$udom);
8255: }
8256: @newcoowners = sort(@newcoowners);
8257: } else {
8258: push(@newcoowners,$uname.':'.$udom);
8259: }
8260: } else {
8261: if ($coursehash{'internal.co-owners'}) {
8262: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8263: unless ($coowner eq $uname.':'.$udom) {
8264: push(@newcoowners,$coowner);
8265: }
8266: }
8267: unless (@newcoowners > 0) {
8268: $delcoowners = 1;
8269: $coowners = '';
8270: }
8271: }
8272: }
8273: if (@newcoowners || $delcoowners) {
8274: &store_coowners($cdom,$cnum,$coursehash{'home'},
8275: $delcoowners,@newcoowners);
8276: }
8277: }
8278: }
8279: }
8280: }
8281: }
8282: }
8283:
8284: sub store_coowners {
8285: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8286: my $cid = $cdom.'_'.$cnum;
8287: my ($coowners,$delresult,$putresult);
8288: if (@newcoowners) {
8289: $coowners = join(',',@newcoowners);
8290: my %coownershash = (
8291: 'internal.co-owners' => $coowners,
8292: );
8293: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8294: if ($putresult eq 'ok') {
8295: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8296: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8297: }
8298: }
8299: }
8300: if ($delcoowners) {
8301: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8302: if ($delresult eq 'ok') {
8303: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8304: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8305: }
8306: }
8307: }
8308: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8309: my %crsinfo =
8310: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8311: if (ref($crsinfo{$cid}) eq 'HASH') {
8312: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8313: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8314: }
8315: }
8316: }
8317:
1.169 harris41 8318: # -------------------------------------------------- Modify user authentication
1.197 www 8319: # Overrides without validation
8320:
1.169 harris41 8321: sub modifyuserauth {
8322: my ($udom,$uname,$umode,$upass)=@_;
8323: my $uhome=&homeserver($uname,$udom);
1.197 www 8324: unless (&allowed('mau',$udom)) { return 'refused'; }
8325: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8326: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8327: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8328: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8329: &escape($upass),$uhome);
1.620 albertel 8330: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8331: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8332: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8333: &log($udom,,$uname,$uhome,
1.620 albertel 8334: 'Authentication changed by '.$env{'user.domain'}.', '.
8335: $env{'user.name'}.', '.$umode.
1.197 www 8336: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8337: unless ($reply eq 'ok') {
1.197 www 8338: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8339: return 'error: '.$reply;
8340: }
1.170 harris41 8341: return 'ok';
1.80 www 8342: }
8343:
1.81 www 8344: # --------------------------------------------------------------- Modify a user
1.80 www 8345:
1.81 www 8346: sub modifyuser {
1.206 matthew 8347: my ($udom, $uname, $uid,
8348: $umode, $upass, $first,
8349: $middle, $last, $gene,
1.1058 raeburn 8350: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8351: $udom= &LONCAPA::clean_domain($udom);
8352: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8353: my $showcandelete = 'none';
8354: if (ref($candelete) eq 'ARRAY') {
8355: if (@{$candelete} > 0) {
8356: $showcandelete = join(', ',@{$candelete});
8357: }
8358: }
1.81 www 8359: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8360: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8361: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8362: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8363: ' desiredhome not specified').
1.620 albertel 8364: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8365: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8366: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8367: my $newuser;
8368: if ($uhome eq 'no_host') {
8369: $newuser = 1;
8370: }
1.80 www 8371: # ----------------------------------------------------------------- Create User
1.406 albertel 8372: if (($uhome eq 'no_host') &&
8373: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8374: my $unhome='';
1.844 albertel 8375: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8376: $unhome = $desiredhome;
1.620 albertel 8377: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8378: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8379: } else { # load balancing routine for determining $unhome
1.81 www 8380: my $loadm=10000000;
1.841 albertel 8381: my %servers = &get_servers($udom,'library');
8382: foreach my $tryserver (keys(%servers)) {
8383: my $answer=reply('load',$tryserver);
8384: if (($answer=~/\d+/) && ($answer<$loadm)) {
8385: $loadm=$answer;
8386: $unhome=$tryserver;
8387: }
1.80 www 8388: }
8389: }
8390: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8391: return 'error: unable to find a home server for '.$uname.
8392: ' in domain '.$udom;
1.80 www 8393: }
8394: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8395: &escape($upass),$unhome);
8396: unless ($reply eq 'ok') {
8397: return 'error: '.$reply;
8398: }
1.230 stredwic 8399: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8400: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8401: return 'error: unable verify users home machine.';
1.80 www 8402: }
1.209 matthew 8403: } # End of creation of new user
1.80 www 8404: # ---------------------------------------------------------------------- Add ID
8405: if ($uid) {
8406: $uid=~tr/A-Z/a-z/;
8407: my %uidhash=&idrget($udom,$uname);
1.196 www 8408: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8409: && (!$forceid)) {
1.80 www 8410: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8411: return 'error: user id "'.$uid.'" does not match '.
8412: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8413: }
8414: } else {
8415: &idput($udom,($uname => $uid));
8416: }
8417: }
8418: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8419: my @tmp=&get('environment',
1.899 raeburn 8420: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8421: 'permanentemail','inststatus'],
1.134 albertel 8422: $udom,$uname);
1.1075 raeburn 8423: my (%names,%oldnames);
1.313 matthew 8424: if ($tmp[0] =~ m/^error:.*/) {
8425: %names=();
8426: } else {
8427: %names = @tmp;
1.1075 raeburn 8428: %oldnames = %names;
1.313 matthew 8429: }
1.388 www 8430: #
1.1058 raeburn 8431: # If name, email and/or uid are blank (e.g., because an uploaded file
8432: # of users did not contain them), do not overwrite existing values
8433: # unless field is in $candelete array ref.
8434: #
8435:
8436: my @fields = ('firstname','middlename','lastname','generation',
8437: 'permanentemail','id');
8438: my %newvalues;
8439: if (ref($candelete) eq 'ARRAY') {
8440: foreach my $field (@fields) {
8441: if (grep(/^\Q$field\E$/,@{$candelete})) {
8442: if ($field eq 'firstname') {
8443: $names{$field} = $first;
8444: } elsif ($field eq 'middlename') {
8445: $names{$field} = $middle;
8446: } elsif ($field eq 'lastname') {
8447: $names{$field} = $last;
8448: } elsif ($field eq 'generation') {
8449: $names{$field} = $gene;
8450: } elsif ($field eq 'permanentemail') {
8451: $names{$field} = $email;
8452: } elsif ($field eq 'id') {
8453: $names{$field} = $uid;
8454: }
8455: }
8456: }
8457: }
1.388 www 8458: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8459: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8460: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8461: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8462: if ($email) {
8463: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8464: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8465: }
1.899 raeburn 8466: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8467: if (defined($inststatus)) {
8468: $names{'inststatus'} = '';
8469: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8470: if (ref($usertypes) eq 'HASH') {
8471: my @okstatuses;
8472: foreach my $item (split(/:/,$inststatus)) {
8473: if (defined($usertypes->{$item})) {
8474: push(@okstatuses,$item);
8475: }
8476: }
8477: if (@okstatuses) {
8478: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8479: }
8480: }
8481: }
1.1075 raeburn 8482: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8483: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8484: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8485: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8486: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8487: } else {
8488: $logmsg .= ' during self creation';
8489: }
1.1075 raeburn 8490: my $changed;
8491: if ($newuser) {
8492: $changed = 1;
8493: } else {
8494: foreach my $field (@fields) {
8495: if ($names{$field} ne $oldnames{$field}) {
8496: $changed = 1;
8497: last;
8498: }
8499: }
8500: }
8501: unless ($changed) {
8502: $logmsg = 'No changes in user information needed for: '.$logmsg;
8503: &logthis($logmsg);
8504: return 'ok';
8505: }
8506: my $reply = &put('environment', \%names, $udom,$uname);
8507: if ($reply ne 'ok') {
8508: return 'error: '.$reply;
8509: }
1.1087 raeburn 8510: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8511: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8512: }
1.1075 raeburn 8513: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8514: &devalidate_cache_new('namescache',$uname.':'.$udom);
8515: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8516: &logthis($logmsg);
1.134 albertel 8517: return 'ok';
1.80 www 8518: }
8519:
1.81 www 8520: # -------------------------------------------------------------- Modify student
1.80 www 8521:
1.81 www 8522: sub modifystudent {
8523: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8524: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216 raeburn 8525: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8526: if (!$cid) {
1.620 albertel 8527: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8528: return 'not_in_class';
8529: }
1.80 www 8530: }
8531: # --------------------------------------------------------------- Make the user
1.81 www 8532: my $reply=&modifyuser
1.209 matthew 8533: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8534: $desiredhome,$email,$inststatus);
1.80 www 8535: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8536: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 8537: # student's environment
1.297 matthew 8538: $uid = undef if (!$forceid);
1.455 albertel 8539: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 8540: $gene,$usec,$end,$start,$type,$locktype,
8541: $cid,$selfenroll,$context,$credits);
1.297 matthew 8542: return $reply;
8543: }
8544:
8545: sub modify_student_enrollment {
1.1216 raeburn 8546: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8547: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8548: my ($cdom,$cnum,$chome);
8549: if (!$cid) {
1.620 albertel 8550: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8551: return 'not_in_class';
8552: }
1.620 albertel 8553: $cdom=$env{'course.'.$cid.'.domain'};
8554: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8555: } else {
8556: ($cdom,$cnum)=split(/_/,$cid);
8557: }
1.620 albertel 8558: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8559: if (!$chome) {
1.457 raeburn 8560: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8561: }
1.455 albertel 8562: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8563: # Make sure the user exists
1.81 www 8564: my $uhome=&homeserver($uname,$udom);
8565: if (($uhome eq '') || ($uhome eq 'no_host')) {
8566: return 'error: no such user';
8567: }
1.297 matthew 8568: # Get student data if we were not given enough information
8569: if (!defined($first) || $first eq '' ||
8570: !defined($last) || $last eq '' ||
8571: !defined($uid) || $uid eq '' ||
8572: !defined($middle) || $middle eq '' ||
8573: !defined($gene) || $gene eq '') {
1.294 matthew 8574: # They did not supply us with enough data to enroll the student, so
8575: # we need to pick up more information.
1.297 matthew 8576: my %tmp = &get('environment',
1.294 matthew 8577: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8578: ,$udom,$uname);
8579:
1.800 albertel 8580: #foreach my $key (keys(%tmp)) {
8581: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8582: #}
1.294 matthew 8583: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8584: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8585: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8586: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8587: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8588: }
1.556 albertel 8589: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8590: my $user = "$uname:$udom";
8591: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8592: my $reply=cput('classlist',
1.1148 raeburn 8593: {$user =>
1.1216 raeburn 8594: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8595: $cdom,$cnum);
1.1148 raeburn 8596: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8597: &devalidate_getsection_cache($udom,$uname,$cid);
8598: } else {
1.81 www 8599: return 'error: '.$reply;
8600: }
1.297 matthew 8601: # Add student role to user
1.83 www 8602: my $uurl='/'.$cid;
1.81 www 8603: $uurl=~s/\_/\//g;
8604: if ($usec) {
8605: $uurl.='/'.$usec;
8606: }
1.1148 raeburn 8607: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8608: $selfenroll,$context);
8609: if ($result ne 'ok') {
8610: if ($old_entry{$user} ne '') {
8611: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8612: } else {
8613: $reply = &del('classlist',[$user],$cdom,$cnum);
8614: }
8615: }
8616: return $result;
1.21 www 8617: }
8618:
1.556 albertel 8619: sub format_name {
8620: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8621: my $name;
8622: if ($first ne 'lastname') {
8623: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8624: } else {
8625: if ($lastname=~/\S/) {
8626: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8627: $name=~s/\s+,/,/;
8628: } else {
8629: $name.= $firstname.' '.$middlename.' '.$generation;
8630: }
8631: }
8632: $name=~s/^\s+//;
8633: $name=~s/\s+$//;
8634: $name=~s/\s+/ /g;
8635: return $name;
8636: }
8637:
1.84 www 8638: # ------------------------------------------------- Write to course preferences
8639:
8640: sub writecoursepref {
8641: my ($courseid,%prefs)=@_;
8642: $courseid=~s/^\///;
8643: $courseid=~s/\_/\//g;
8644: my ($cdomain,$cnum)=split(/\//,$courseid);
8645: my $chome=homeserver($cnum,$cdomain);
8646: if (($chome eq '') || ($chome eq 'no_host')) {
8647: return 'error: no such course';
8648: }
8649: my $cstring='';
1.800 albertel 8650: foreach my $pref (keys(%prefs)) {
8651: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8652: }
1.84 www 8653: $cstring=~s/\&$//;
8654: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8655: }
8656:
8657: # ---------------------------------------------------------- Make/modify course
8658:
8659: sub createcourse {
1.741 raeburn 8660: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8661: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8662: $url=&declutter($url);
8663: my $cid='';
1.1028 raeburn 8664: if ($context eq 'requestcourses') {
8665: my $can_create = 0;
8666: my ($ownername,$ownerdom) = split(':',$course_owner);
8667: if ($udom eq $ownerdom) {
8668: if (&usertools_access($ownername,$ownerdom,$category,undef,
8669: $context)) {
8670: $can_create = 1;
8671: }
8672: } else {
8673: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8674: $category);
8675: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8676: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8677: if (@curr > 0) {
8678: my @options = qw(approval validate autolimit);
8679: my $optregex = join('|',@options);
8680: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8681: $can_create = 1;
8682: }
8683: }
8684: }
8685: }
8686: if ($can_create) {
8687: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8688: unless (&allowed('ccc',$udom)) {
8689: return 'refused';
8690: }
1.1017 raeburn 8691: }
8692: } else {
8693: return 'refused';
8694: }
1.1028 raeburn 8695: } elsif (!&allowed('ccc',$udom)) {
8696: return 'refused';
1.84 www 8697: }
1.1011 raeburn 8698: # --------------------------------------------------------------- Get Unique ID
8699: my $uname;
8700: if ($cnum =~ /^$match_courseid$/) {
8701: my $chome=&homeserver($cnum,$udom,'true');
8702: if (($chome eq '') || ($chome eq 'no_host')) {
8703: $uname = $cnum;
8704: } else {
1.1038 raeburn 8705: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8706: }
8707: } else {
1.1038 raeburn 8708: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8709: }
8710: return $uname if ($uname =~ /^error/);
8711: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8712: if (!defined($course_server)) {
8713: if (defined(&domain($udom,'primary'))) {
8714: $course_server = &domain($udom,'primary');
8715: } else {
8716: $course_server = $env{'user.home'};
8717: }
8718: }
8719: my %host_servers =
8720: &Apache::lonnet::get_servers($udom,'library');
8721: unless ($host_servers{$course_server}) {
8722: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8723: }
1.84 www 8724: # ------------------------------------------------------------- Make the course
8725: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8726: $course_server);
1.84 www 8727: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8728: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8729: if (($uhome eq '') || ($uhome eq 'no_host')) {
8730: return 'error: no such course';
8731: }
1.271 www 8732: # ----------------------------------------------------------------- Course made
1.516 raeburn 8733: # log existence
1.1029 raeburn 8734: my $now = time;
1.918 raeburn 8735: my $newcourse = {
8736: $udom.'_'.$uname => {
1.921 raeburn 8737: description => $description,
8738: inst_code => $inst_code,
8739: owner => $course_owner,
8740: type => $crstype,
1.1029 raeburn 8741: creator => $env{'user.name'}.':'.
8742: $env{'user.domain'},
8743: created => $now,
8744: context => $context,
1.918 raeburn 8745: },
8746: };
1.921 raeburn 8747: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8748: # set toplevel url
1.271 www 8749: my $topurl=$url;
8750: unless ($nonstandard) {
8751: # ------------------------------------------ For standard courses, make top url
8752: my $mapurl=&clutter($url);
1.278 www 8753: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8754: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8755: <map>
8756: <resource id="1" type="start"></resource>
8757: <resource id="2" src="$mapurl"></resource>
8758: <resource id="3" type="finish"></resource>
8759: <link index="1" from="1" to="2"></link>
8760: <link index="2" from="2" to="3"></link>
8761: </map>
8762: ENDINITMAP
8763: $topurl=&declutter(
1.638 albertel 8764: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8765: );
8766: }
8767: # ----------------------------------------------------------- Write preferences
1.84 www 8768: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8769: ('description' => $description,
8770: 'url' => $topurl,
8771: 'internal.creator' => $env{'user.name'}.':'.
8772: $env{'user.domain'},
8773: 'internal.created' => $now,
8774: 'internal.creationcontext' => $context)
8775: );
1.84 www 8776: return '/'.$udom.'/'.$uname;
8777: }
8778:
1.1011 raeburn 8779: # ------------------------------------------------------------------- Create ID
8780: sub generate_coursenum {
1.1038 raeburn 8781: my ($udom,$crstype) = @_;
1.1011 raeburn 8782: my $domdesc = &domain($udom);
8783: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8784: my $first;
8785: if ($crstype eq 'Community') {
8786: $first = '0';
8787: } else {
8788: $first = int(1+rand(9));
8789: }
8790: my $uname=$first.
1.1011 raeburn 8791: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8792: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8793: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8794: # ----------------------------------------------- Make sure that does not exist
8795: my $uhome=&homeserver($uname,$udom,'true');
8796: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8797: if ($crstype eq 'Community') {
8798: $first = '0';
8799: } else {
8800: $first = int(1+rand(9));
8801: }
8802: $uname=$first.
1.1011 raeburn 8803: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8804: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8805: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8806: $uhome=&homeserver($uname,$udom,'true');
8807: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8808: return 'error: unable to generate unique course-ID';
8809: }
8810: }
8811: return $uname;
8812: }
8813:
1.813 albertel 8814: sub is_course {
1.1167 droeschl 8815: my ($cdom, $cnum) = scalar(@_) == 1 ?
8816: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8817:
8818: return unless $cdom and $cnum;
8819:
8820: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8821: '.');
8822:
1.1219 raeburn 8823: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8824: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8825: }
8826:
1.1015 raeburn 8827: sub store_userdata {
8828: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8829: my $result;
1.1016 raeburn 8830: if ($datakey ne '') {
1.1013 raeburn 8831: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8832: if ($udom eq '' || $uname eq '') {
8833: $udom = $env{'user.domain'};
8834: $uname = $env{'user.name'};
8835: }
8836: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8837: if (($uhome eq '') || ($uhome eq 'no_host')) {
8838: $result = 'error: no_host';
8839: } else {
8840: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8841: $storehash->{'host'} = $perlvar{'lonHostID'};
8842:
8843: my $namevalue='';
8844: foreach my $key (keys(%{$storehash})) {
8845: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8846: }
8847: $namevalue=~s/\&$//;
1.1224 raeburn 8848: unless ($namespace eq 'courserequests') {
8849: $datakey = &escape($datakey);
8850: }
1.1105 raeburn 8851: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8852: $namevalue,$uhome);
1.1013 raeburn 8853: }
8854: } else {
8855: $result = 'error: data to store was not a hash reference';
8856: }
8857: } else {
8858: $result= 'error: invalid requestkey';
8859: }
8860: return $result;
8861: }
8862:
1.21 www 8863: # ---------------------------------------------------------- Assign Custom Role
8864:
8865: sub assigncustomrole {
1.957 raeburn 8866: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8867: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8868: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8869: }
8870:
8871: # ----------------------------------------------------------------- Revoke Role
8872:
8873: sub revokerole {
1.957 raeburn 8874: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8875: my $now=time;
1.965 raeburn 8876: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8877: }
8878:
8879: # ---------------------------------------------------------- Revoke Custom Role
8880:
8881: sub revokecustomrole {
1.957 raeburn 8882: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8883: my $now=time;
1.357 www 8884: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8885: $deleteflag,$selfenroll,$context);
1.17 www 8886: }
8887:
1.533 banghart 8888: # ------------------------------------------------------------ Disk usage
1.535 albertel 8889: sub diskusage {
1.955 raeburn 8890: my ($udom,$uname,$directorypath,$getpropath)=@_;
8891: $directorypath =~ s/\/$//;
8892: my $listing=&reply('du2:'.&escape($directorypath).':'
8893: .&escape($getpropath).':'.&escape($uname).':'
8894: .&escape($udom),homeserver($uname,$udom));
8895: if ($listing eq 'unknown_cmd') {
8896: if ($getpropath) {
8897: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8898: }
8899: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8900: }
1.514 albertel 8901: return $listing;
1.512 banghart 8902: }
8903:
1.566 banghart 8904: sub is_locked {
1.1096 raeburn 8905: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8906: my @check;
8907: my $is_locked;
1.1093 raeburn 8908: push (@check,$file_name);
1.613 albertel 8909: my %locked = &get('file_permissions',\@check,
1.620 albertel 8910: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8911: my ($tmp)=keys(%locked);
8912: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8913:
1.566 banghart 8914: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8915: $is_locked = 'false';
8916: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8917: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8918: $is_locked = 'true';
1.1096 raeburn 8919: if (ref($which) eq 'ARRAY') {
8920: push(@{$which},$entry);
8921: } else {
8922: last;
8923: }
1.745 raeburn 8924: }
8925: }
1.566 banghart 8926: } else {
8927: $is_locked = 'false';
8928: }
1.1093 raeburn 8929: return $is_locked;
1.566 banghart 8930: }
8931:
1.759 albertel 8932: sub declutter_portfile {
8933: my ($file) = @_;
1.833 albertel 8934: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 8935: return $file;
8936: }
8937:
1.559 banghart 8938: # ------------------------------------------------------------- Mark as Read Only
8939:
8940: sub mark_as_readonly {
8941: my ($domain,$user,$files,$what) = @_;
1.613 albertel 8942: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8943: my ($tmp)=keys(%current_permissions);
8944: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 8945: foreach my $file (@{$files}) {
1.759 albertel 8946: $file = &declutter_portfile($file);
1.561 banghart 8947: push(@{$current_permissions{$file}},$what);
1.559 banghart 8948: }
1.613 albertel 8949: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8950: return;
8951: }
8952:
1.572 banghart 8953: # ------------------------------------------------------------Save Selected Files
8954:
8955: sub save_selected_files {
8956: my ($user, $path, @files) = @_;
8957: my $filename = $user."savedfiles";
1.573 banghart 8958: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 8959: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 8960: foreach my $file (@files) {
1.620 albertel 8961: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 8962: }
8963: foreach my $file (@other_files) {
1.574 banghart 8964: print (OUT $file."\n");
1.572 banghart 8965: }
1.574 banghart 8966: close (OUT);
1.572 banghart 8967: return 'ok';
8968: }
8969:
1.574 banghart 8970: sub clear_selected_files {
8971: my ($user) = @_;
8972: my $filename = $user."savedfiles";
1.1117 foxr 8973: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 8974: print (OUT undef);
8975: close (OUT);
8976: return ("ok");
8977: }
8978:
1.572 banghart 8979: sub files_in_path {
8980: my ($user, $path) = @_;
8981: my $filename = $user."savedfiles";
8982: my %return_files;
1.1117 foxr 8983: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 8984: while (my $line_in = <IN>) {
1.574 banghart 8985: chomp ($line_in);
8986: my @paths_and_file = split (m!/!, $line_in);
8987: my $file_part = pop (@paths_and_file);
8988: my $path_part = join ('/', @paths_and_file);
1.573 banghart 8989: $path_part.='/';
8990: my $path_and_file = $path_part.$file_part;
8991: if ($path_part eq $path) {
8992: $return_files{$file_part}= 'selected';
8993: }
8994: }
1.574 banghart 8995: close (IN);
8996: return (\%return_files);
1.572 banghart 8997: }
8998:
8999: # called in portfolio select mode, to show files selected NOT in current directory
9000: sub files_not_in_path {
9001: my ($user, $path) = @_;
9002: my $filename = $user."savedfiles";
9003: my @return_files;
9004: my $path_part;
1.1117 foxr 9005: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9006: while (my $line = <IN>) {
1.572 banghart 9007: #ok, I know it's clunky, but I want it to work
1.800 albertel 9008: my @paths_and_file = split(m|/|, $line);
9009: my $file_part = pop(@paths_and_file);
9010: chomp($file_part);
9011: my $path_part = join('/', @paths_and_file);
1.572 banghart 9012: $path_part .= '/';
9013: my $path_and_file = $path_part.$file_part;
9014: if ($path_part ne $path) {
1.800 albertel 9015: push(@return_files, ($path_and_file));
1.572 banghart 9016: }
9017: }
1.800 albertel 9018: close(OUT);
1.574 banghart 9019: return (@return_files);
1.572 banghart 9020: }
9021:
1.745 raeburn 9022: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9023:
1.745 raeburn 9024: sub get_portfile_permissions {
9025: my ($domain,$user) = @_;
1.613 albertel 9026: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9027: my ($tmp)=keys(%current_permissions);
9028: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9029: return \%current_permissions;
9030: }
9031:
9032: #---------------------------------------------Get portfolio file access controls
9033:
1.749 raeburn 9034: sub get_access_controls {
1.745 raeburn 9035: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9036: my %access;
9037: my $real_file = $file;
9038: $file =~ s/\.meta$//;
1.745 raeburn 9039: if (defined($file)) {
1.749 raeburn 9040: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9041: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9042: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9043: }
9044: }
1.745 raeburn 9045: } else {
1.749 raeburn 9046: foreach my $key (keys(%{$current_permissions})) {
9047: if ($key =~ /\0accesscontrol$/) {
9048: if (defined($group)) {
9049: if ($key !~ m-^\Q$group\E/-) {
9050: next;
9051: }
9052: }
9053: my ($fullpath) = split(/\0/,$key);
9054: if (ref($$current_permissions{$key}) eq 'HASH') {
9055: foreach my $control (keys(%{$$current_permissions{$key}})) {
9056: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9057: }
9058: }
9059: }
9060: }
9061: }
9062: return %access;
9063: }
9064:
9065: sub modify_access_controls {
9066: my ($file_name,$changes,$domain,$user)=@_;
9067: my ($outcome,$deloutcome);
9068: my %store_permissions;
9069: my %new_values;
9070: my %new_control;
9071: my %translation;
9072: my @deletions = ();
9073: my $now = time;
9074: if (exists($$changes{'activate'})) {
9075: if (ref($$changes{'activate'}) eq 'HASH') {
9076: my @newitems = sort(keys(%{$$changes{'activate'}}));
9077: my $numnew = scalar(@newitems);
9078: for (my $i=0; $i<$numnew; $i++) {
9079: my $newkey = $newitems[$i];
9080: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9081: if ($newkey =~ /^\d+:/) {
9082: $newkey =~ s/^(\d+)/$newid/;
9083: $translation{$1} = $newid;
9084: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9085: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9086: $translation{$1} = $newid;
9087: }
1.749 raeburn 9088: $new_values{$file_name."\0".$newkey} =
9089: $$changes{'activate'}{$newitems[$i]};
9090: $new_control{$newkey} = $now;
9091: }
9092: }
9093: }
9094: my %todelete;
9095: my %changed_items;
9096: foreach my $action ('delete','update') {
9097: if (exists($$changes{$action})) {
9098: if (ref($$changes{$action}) eq 'HASH') {
9099: foreach my $key (keys(%{$$changes{$action}})) {
9100: my ($itemnum) = ($key =~ /^([^:]+):/);
9101: if ($action eq 'delete') {
9102: $todelete{$itemnum} = 1;
9103: } else {
9104: $changed_items{$itemnum} = $key;
9105: }
9106: }
1.745 raeburn 9107: }
9108: }
1.749 raeburn 9109: }
9110: # get lock on access controls for file.
9111: my $lockhash = {
9112: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9113: ':'.$env{'user.domain'},
9114: };
9115: my $tries = 0;
9116: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9117:
9118: while (($gotlock ne 'ok') && $tries <3) {
9119: $tries ++;
9120: sleep 1;
9121: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9122: }
9123: if ($gotlock eq 'ok') {
9124: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9125: my ($tmp)=keys(%curr_permissions);
9126: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9127: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9128: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9129: if (ref($curr_controls) eq 'HASH') {
9130: foreach my $control_item (keys(%{$curr_controls})) {
9131: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9132: if (defined($todelete{$itemnum})) {
9133: push(@deletions,$file_name."\0".$control_item);
9134: } else {
9135: if (defined($changed_items{$itemnum})) {
9136: $new_control{$changed_items{$itemnum}} = $now;
9137: push(@deletions,$file_name."\0".$control_item);
9138: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9139: } else {
9140: $new_control{$control_item} = $$curr_controls{$control_item};
9141: }
9142: }
1.745 raeburn 9143: }
9144: }
9145: }
1.970 raeburn 9146: my ($group);
9147: if (&is_course($domain,$user)) {
9148: ($group,my $file) = split(/\//,$file_name,2);
9149: }
1.749 raeburn 9150: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9151: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9152: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9153: # remove lock
9154: my @del_lock = ($file_name."\0".'locked_access_records');
9155: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9156: my $sqlresult =
1.970 raeburn 9157: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9158: $group);
1.749 raeburn 9159: } else {
9160: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9161: }
1.749 raeburn 9162: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9163: }
9164:
1.827 raeburn 9165: sub make_public_indefinitely {
9166: my ($requrl) = @_;
9167: my $now = time;
9168: my $action = 'activate';
9169: my $aclnum = 0;
9170: if (&is_portfolio_url($requrl)) {
9171: my (undef,$udom,$unum,$file_name,$group) =
9172: &parse_portfolio_url($requrl);
9173: my $current_perms = &get_portfile_permissions($udom,$unum);
9174: my %access_controls = &get_access_controls($current_perms,
9175: $group,$file_name);
9176: foreach my $key (keys(%{$access_controls{$file_name}})) {
9177: my ($num,$scope,$end,$start) =
9178: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9179: if ($scope eq 'public') {
9180: if ($start <= $now && $end == 0) {
9181: $action = 'none';
9182: } else {
9183: $action = 'update';
9184: $aclnum = $num;
9185: }
9186: last;
9187: }
9188: }
9189: if ($action eq 'none') {
9190: return 'ok';
9191: } else {
9192: my %changes;
9193: my $newend = 0;
9194: my $newstart = $now;
9195: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9196: $changes{$action}{$newkey} = {
9197: type => 'public',
9198: time => {
9199: start => $newstart,
9200: end => $newend,
9201: },
9202: };
9203: my ($outcome,$deloutcome,$new_values,$translation) =
9204: &modify_access_controls($file_name,\%changes,$udom,$unum);
9205: return $outcome;
9206: }
9207: } else {
9208: return 'invalid';
9209: }
9210: }
9211:
1.745 raeburn 9212: #------------------------------------------------------Get Marked as Read Only
9213:
9214: sub get_marked_as_readonly {
9215: my ($domain,$user,$what,$group) = @_;
9216: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9217: my @readonly_files;
1.629 banghart 9218: my $cmp1=$what;
9219: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9220: while (my ($file_name,$value) = each(%{$current_permissions})) {
9221: if (defined($group)) {
9222: if ($file_name !~ m-^\Q$group\E/-) {
9223: next;
9224: }
9225: }
1.561 banghart 9226: if (ref($value) eq "ARRAY"){
9227: foreach my $stored_what (@{$value}) {
1.629 banghart 9228: my $cmp2=$stored_what;
1.759 albertel 9229: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9230: $cmp2=join('',@{$stored_what});
1.745 raeburn 9231: }
1.629 banghart 9232: if ($cmp1 eq $cmp2) {
1.561 banghart 9233: push(@readonly_files, $file_name);
1.745 raeburn 9234: last;
1.563 banghart 9235: } elsif (!defined($what)) {
9236: push(@readonly_files, $file_name);
1.745 raeburn 9237: last;
1.561 banghart 9238: }
9239: }
1.745 raeburn 9240: }
1.561 banghart 9241: }
9242: return @readonly_files;
9243: }
1.577 banghart 9244: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9245:
1.577 banghart 9246: sub get_marked_as_readonly_hash {
1.745 raeburn 9247: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9248: my %readonly_files;
1.745 raeburn 9249: while (my ($file_name,$value) = each(%{$current_permissions})) {
9250: if (defined($group)) {
9251: if ($file_name !~ m-^\Q$group\E/-) {
9252: next;
9253: }
9254: }
1.577 banghart 9255: if (ref($value) eq "ARRAY"){
9256: foreach my $stored_what (@{$value}) {
1.745 raeburn 9257: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9258: foreach my $lock_descriptor(@{$stored_what}) {
9259: if ($lock_descriptor eq 'graded') {
9260: $readonly_files{$file_name} = 'graded';
9261: } elsif ($lock_descriptor eq 'handback') {
9262: $readonly_files{$file_name} = 'handback';
9263: } else {
9264: if (!exists($readonly_files{$file_name})) {
9265: $readonly_files{$file_name} = 'locked';
9266: }
9267: }
1.745 raeburn 9268: }
1.750 banghart 9269: }
1.577 banghart 9270: }
9271: }
9272: }
9273: return %readonly_files;
9274: }
1.559 banghart 9275: # ------------------------------------------------------------ Unmark as Read Only
9276:
9277: sub unmark_as_readonly {
1.629 banghart 9278: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9279: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9280: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9281: $file_name = &declutter_portfile($file_name);
1.634 albertel 9282: my $symb_crs = $what;
9283: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9284: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9285: my ($tmp)=keys(%current_permissions);
9286: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9287: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9288: foreach my $file (@readonly_files) {
1.759 albertel 9289: my $clean_file = &declutter_portfile($file);
9290: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9291: my $current_locks = $current_permissions{$file};
1.563 banghart 9292: my @new_locks;
9293: my @del_keys;
9294: if (ref($current_locks) eq "ARRAY"){
9295: foreach my $locker (@{$current_locks}) {
1.632 albertel 9296: my $compare=$locker;
1.749 raeburn 9297: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9298: $compare=join('',@{$locker});
1.746 raeburn 9299: if ($compare ne $symb_crs) {
9300: push(@new_locks, $locker);
9301: }
1.563 banghart 9302: }
9303: }
1.650 albertel 9304: if (scalar(@new_locks) > 0) {
1.563 banghart 9305: $current_permissions{$file} = \@new_locks;
9306: } else {
9307: push(@del_keys, $file);
1.613 albertel 9308: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9309: delete($current_permissions{$file});
1.563 banghart 9310: }
9311: }
1.561 banghart 9312: }
1.613 albertel 9313: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9314: return;
9315: }
1.512 banghart 9316:
1.17 www 9317: # ------------------------------------------------------------ Directory lister
9318:
9319: sub dirlist {
1.955 raeburn 9320: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9321: $uri=~s/^\///;
9322: $uri=~s/\/$//;
1.253 stredwic 9323: my ($udom, $uname);
1.955 raeburn 9324: if ($getuserdir) {
1.253 stredwic 9325: $udom = $userdomain;
9326: $uname = $username;
1.955 raeburn 9327: } else {
9328: (undef,$udom,$uname)=split(/\//,$uri);
9329: if(defined($userdomain)) {
9330: $udom = $userdomain;
9331: }
9332: if(defined($username)) {
9333: $uname = $username;
9334: }
1.253 stredwic 9335: }
1.955 raeburn 9336: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9337:
1.955 raeburn 9338: $dirRoot = $perlvar{'lonDocRoot'};
9339: if (defined($getpropath)) {
9340: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9341: $dirRoot =~ s/\/$//;
1.955 raeburn 9342: } elsif (defined($getuserdir)) {
9343: my $subdir=$uname.'__';
9344: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9345: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9346: ."/$udom/$subdir/$uname";
9347: } elsif (defined($alternateRoot)) {
9348: $dirRoot = $alternateRoot;
1.751 banghart 9349: }
1.253 stredwic 9350:
9351: if($udom) {
9352: if($uname) {
1.1135 raeburn 9353: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9354: if ($uhome eq 'no_host') {
9355: return ([],'no_host');
9356: }
1.955 raeburn 9357: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9358: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9359: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9360: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9361: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9362: } else {
9363: @listing_results = map { &unescape($_); } split(/:/,$listing);
9364: }
1.605 matthew 9365: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9366: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9367: @listing_results = split(/:/,$listing);
9368: } else {
9369: @listing_results = map { &unescape($_); } split(/:/,$listing);
9370: }
1.1135 raeburn 9371: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9372: ($listing eq 'rejected') || ($listing eq 'refused') ||
9373: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9374: return ([],$listing);
9375: } else {
9376: return (\@listing_results);
1.1135 raeburn 9377: }
1.955 raeburn 9378: } elsif(!$alternateRoot) {
1.1136 raeburn 9379: my (%allusers,%listerror);
1.841 albertel 9380: my %servers = &get_servers($udom,'library');
1.955 raeburn 9381: foreach my $tryserver (keys(%servers)) {
9382: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9383: &escape($udom),$tryserver);
9384: if ($listing eq 'unknown_cmd') {
9385: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9386: $udom, $tryserver);
9387: } else {
9388: @listing_results = map { &unescape($_); } split(/:/,$listing);
9389: }
1.841 albertel 9390: if ($listing eq 'unknown_cmd') {
9391: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9392: $udom, $tryserver);
9393: @listing_results = split(/:/,$listing);
9394: } else {
9395: @listing_results =
9396: map { &unescape($_); } split(/:/,$listing);
9397: }
1.1136 raeburn 9398: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9399: ($listing eq 'rejected') || ($listing eq 'refused') ||
9400: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9401: $listerror{$tryserver} = $listing;
9402: } else {
1.841 albertel 9403: foreach my $line (@listing_results) {
9404: my ($entry) = split(/&/,$line,2);
9405: $allusers{$entry} = 1;
9406: }
9407: }
1.253 stredwic 9408: }
1.1136 raeburn 9409: my @alluserslist=();
1.800 albertel 9410: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9411: push(@alluserslist,$user.'&user');
1.253 stredwic 9412: }
1.1136 raeburn 9413: return (\@alluserslist);
1.253 stredwic 9414: } else {
1.1136 raeburn 9415: return ([],'missing username');
1.253 stredwic 9416: }
1.955 raeburn 9417: } elsif(!defined($getpropath)) {
1.1136 raeburn 9418: my $path = $perlvar{'lonDocRoot'}.'/res/';
9419: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9420: return (\@all_domains);
1.955 raeburn 9421: } else {
1.1136 raeburn 9422: return ([],'missing domain');
1.275 stredwic 9423: }
9424: }
9425:
9426: # --------------------------------------------- GetFileTimestamp
9427: # This function utilizes dirlist and returns the date stamp for
9428: # when it was last modified. It will also return an error of -1
9429: # if an error occurs
9430:
9431: sub GetFileTimestamp {
1.955 raeburn 9432: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9433: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9434: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9435: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9436: undef,$getuserdir);
9437: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9438: return -1;
9439: }
9440: if (ref($fileref) eq 'ARRAY') {
9441: my @stats = split('&',$fileref->[0]);
1.375 matthew 9442: # @stats contains first the filename, then the stat output
9443: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9444: } else {
9445: return -1;
1.253 stredwic 9446: }
1.26 www 9447: }
9448:
1.712 albertel 9449: sub stat_file {
9450: my ($uri) = @_;
1.787 albertel 9451: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9452:
1.955 raeburn 9453: my ($udom,$uname,$file);
1.712 albertel 9454: if ($uri =~ m-^/(uploaded|editupload)/-) {
9455: ($udom,$uname,$file) =
1.811 albertel 9456: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9457: $file = 'userfiles/'.$file;
9458: }
9459: if ($uri =~ m-^/res/-) {
9460: ($udom,$uname) =
1.807 albertel 9461: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9462: $file = $uri;
9463: }
9464:
9465: if (!$udom || !$uname || !$file) {
9466: # unable to handle the uri
9467: return ();
9468: }
1.956 raeburn 9469: my $getpropath;
9470: if ($file =~ /^userfiles\//) {
9471: $getpropath = 1;
9472: }
1.1136 raeburn 9473: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9474: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9475: return ();
9476: } else {
9477: if (ref($listref) eq 'ARRAY') {
9478: my @stats = split('&',$listref->[0]);
9479: shift(@stats); #filename is first
9480: return @stats;
9481: }
1.712 albertel 9482: }
9483: return ();
9484: }
9485:
1.26 www 9486: # -------------------------------------------------------- Value of a Condition
9487:
1.713 albertel 9488: # gets the value of a specific preevaluated condition
9489: # stored in the string $env{user.state.<cid>}
9490: # or looks up a condition reference in the bighash and if if hasn't
9491: # already been evaluated recurses into docondval to get the value of
9492: # the condition, then memoizing it to
9493: # $env{user.state.<cid>.<condition>}
1.40 www 9494: sub directcondval {
9495: my $number=shift;
1.620 albertel 9496: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9497: &Apache::lonuserstate::evalstate();
9498: }
1.713 albertel 9499: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9500: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9501: } elsif ($number =~ /^_/) {
9502: my $sub_condition;
9503: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9504: &GDBM_READER(),0640)) {
9505: $sub_condition=$bighash{'conditions'.$number};
9506: untie(%bighash);
9507: }
9508: my $value = &docondval($sub_condition);
1.949 raeburn 9509: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9510: return $value;
9511: }
1.620 albertel 9512: if ($env{'user.state.'.$env{'request.course.id'}}) {
9513: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9514: } else {
9515: return 2;
9516: }
9517: }
9518:
1.713 albertel 9519: # get the collection of conditions for this resource
1.26 www 9520: sub condval {
9521: my $condidx=shift;
1.54 www 9522: my $allpathcond='';
1.713 albertel 9523: foreach my $cond (split(/\|/,$condidx)) {
9524: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9525: $allpathcond.=
9526: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9527: }
1.191 harris41 9528: }
1.54 www 9529: $allpathcond=~s/\|$//;
1.713 albertel 9530: return &docondval($allpathcond);
9531: }
9532:
9533: #evaluates an expression of conditions
9534: sub docondval {
9535: my ($allpathcond) = @_;
9536: my $result=0;
9537: if ($env{'request.course.id'}
9538: && defined($allpathcond)) {
9539: my $operand='|';
9540: my @stack;
9541: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9542: if ($chunk eq '(') {
9543: push @stack,($operand,$result);
9544: } elsif ($chunk eq ')') {
9545: my $before=pop @stack;
9546: if (pop @stack eq '&') {
9547: $result=$result>$before?$before:$result;
9548: } else {
9549: $result=$result>$before?$result:$before;
9550: }
9551: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9552: $operand=$chunk;
9553: } else {
9554: my $new=directcondval($chunk);
9555: if ($operand eq '&') {
9556: $result=$result>$new?$new:$result;
9557: } else {
9558: $result=$result>$new?$result:$new;
9559: }
9560: }
9561: }
1.26 www 9562: }
9563: return $result;
1.421 albertel 9564: }
9565:
9566: # ---------------------------------------------------- Devalidate courseresdata
9567:
9568: sub devalidatecourseresdata {
9569: my ($coursenum,$coursedomain)=@_;
9570: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9571: &devalidate_cache_new('courseres',$hashid);
1.28 www 9572: }
9573:
1.763 www 9574:
1.200 www 9575: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9576: #
9577: # Parameters:
9578: # $coursenum - Number of the course.
9579: # $coursedomain - Domain at which the course was created.
9580: # Returns:
9581: # A hash of the course parameters along (I think) with timestamps
9582: # and version info.
1.877 foxr 9583:
1.624 albertel 9584: sub get_courseresdata {
9585: my ($coursenum,$coursedomain)=@_;
1.200 www 9586: my $coursehom=&homeserver($coursenum,$coursedomain);
9587: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9588: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9589: my %dumpreply;
1.417 albertel 9590: unless (defined($cached)) {
1.624 albertel 9591: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9592: $result=\%dumpreply;
1.251 albertel 9593: my ($tmp) = keys(%dumpreply);
9594: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9595: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9596: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9597: return $tmp;
1.416 albertel 9598: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9599: $result=undef;
1.599 albertel 9600: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9601: }
9602: }
1.624 albertel 9603: return $result;
9604: }
9605:
1.633 albertel 9606: sub devalidateuserresdata {
9607: my ($uname,$udom)=@_;
9608: my $hashid="$udom:$uname";
9609: &devalidate_cache_new('userres',$hashid);
9610: }
9611:
1.624 albertel 9612: sub get_userresdata {
9613: my ($uname,$udom)=@_;
9614: #most student don\'t have any data set, check if there is some data
9615: if (&EXT_cache_status($udom,$uname)) { return undef; }
9616:
9617: my $hashid="$udom:$uname";
9618: my ($result,$cached)=&is_cached_new('userres',$hashid);
9619: if (!defined($cached)) {
9620: my %resourcedata=&dump('resourcedata',$udom,$uname);
9621: $result=\%resourcedata;
9622: &do_cache_new('userres',$hashid,$result,600);
9623: }
9624: my ($tmp)=keys(%$result);
9625: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9626: return $result;
9627: }
9628: #error 2 occurs when the .db doesn't exist
9629: if ($tmp!~/error: 2 /) {
1.672 albertel 9630: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9631: " Trying to get resource data for ".
9632: $uname." at ".$udom.": ".
9633: $tmp."</font>");
9634: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9635: #&EXT_cache_set($udom,$uname);
9636: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9637: undef($tmp); # not really an error so don't send it back
1.624 albertel 9638: }
9639: return $tmp;
9640: }
1.879 foxr 9641: #----------------------------------------------- resdata - return resource data
9642: # Purpose:
9643: # Return resource data for either users or for a course.
9644: # Parameters:
9645: # $name - Course/user name.
9646: # $domain - Name of the domain the user/course is registered on.
9647: # $type - Type of thing $name is (must be 'course' or 'user'
9648: # @which - Array of names of resources desired.
9649: # Returns:
9650: # The value of the first reasource in @which that is found in the
9651: # resource hash.
9652: # Exceptional Conditions:
9653: # If the $type passed in is not valid (not the string 'course' or
9654: # 'user', an undefined reference is returned.
9655: # If none of the resources are found, an undef is returned
1.624 albertel 9656: sub resdata {
9657: my ($name,$domain,$type,@which)=@_;
9658: my $result;
9659: if ($type eq 'course') {
9660: $result=&get_courseresdata($name,$domain);
9661: } elsif ($type eq 'user') {
9662: $result=&get_userresdata($name,$domain);
9663: }
9664: if (!ref($result)) { return $result; }
1.251 albertel 9665: foreach my $item (@which) {
1.927 albertel 9666: if (defined($result->{$item->[0]})) {
9667: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9668: }
1.250 albertel 9669: }
1.291 albertel 9670: return undef;
1.200 www 9671: }
9672:
1.1236 raeburn 9673: sub get_numsuppfiles {
9674: my ($cnum,$cdom,$ignorecache)=@_;
9675: my $hashid=$cnum.':'.$cdom;
9676: my ($suppcount,$cached);
9677: unless ($ignorecache) {
9678: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9679: }
9680: unless (defined($cached)) {
9681: my $chome=&homeserver($cnum,$cdom);
9682: unless ($chome eq 'no_host') {
9683: ($suppcount,my $errors) = (0,0);
9684: my $suppmap = 'supplemental.sequence';
9685: ($suppcount,$errors) =
9686: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9687: }
9688: &do_cache_new('suppcount',$hashid,$suppcount,600);
9689: }
9690: return $suppcount;
9691: }
9692:
1.379 matthew 9693: #
9694: # EXT resource caching routines
9695: #
9696:
9697: sub clear_EXT_cache_status {
1.383 albertel 9698: &delenv('cache.EXT.');
1.379 matthew 9699: }
9700:
9701: sub EXT_cache_status {
9702: my ($target_domain,$target_user) = @_;
1.383 albertel 9703: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9704: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9705: # We know already the user has no data
9706: return 1;
9707: } else {
9708: return 0;
9709: }
9710: }
9711:
9712: sub EXT_cache_set {
9713: my ($target_domain,$target_user) = @_;
1.383 albertel 9714: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9715: #&appenv({$cachename => time});
1.379 matthew 9716: }
9717:
1.28 www 9718: # --------------------------------------------------------- Value of a Variable
1.58 www 9719: sub EXT {
1.715 albertel 9720:
1.1228 raeburn 9721: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9722: unless ($varname) { return ''; }
1.218 albertel 9723: #get real user name/domain, courseid and symb
9724: my $courseid;
1.359 albertel 9725: my $publicuser;
1.427 www 9726: if ($symbparm) {
9727: $symbparm=&get_symb_from_alias($symbparm);
9728: }
1.218 albertel 9729: if (!($uname && $udom)) {
1.790 albertel 9730: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9731: if (!$symbparm) { $symbparm=$cursymb; }
9732: } else {
1.620 albertel 9733: $courseid=$env{'request.course.id'};
1.218 albertel 9734: }
1.48 www 9735: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9736: my $rest;
1.320 albertel 9737: if (defined($therest[0])) {
1.48 www 9738: $rest=join('.',@therest);
9739: } else {
9740: $rest='';
9741: }
1.320 albertel 9742:
1.57 www 9743: my $qualifierrest=$qualifier;
9744: if ($rest) { $qualifierrest.='.'.$rest; }
9745: my $spacequalifierrest=$space;
9746: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9747: if ($realm eq 'user') {
1.48 www 9748: # --------------------------------------------------------------- user.resource
9749: if ($space eq 'resource') {
1.651 albertel 9750: if ( (defined($Apache::lonhomework::parsing_a_problem)
9751: || defined($Apache::lonhomework::parsing_a_task))
9752: &&
1.744 albertel 9753: ($symbparm eq &symbread()) ) {
9754: # if we are in the middle of processing the resource the
9755: # get the value we are planning on committing
9756: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9757: return $Apache::lonhomework::results{$qualifierrest};
9758: } else {
9759: return $Apache::lonhomework::history{$qualifierrest};
9760: }
1.335 albertel 9761: } else {
1.359 albertel 9762: my %restored;
1.620 albertel 9763: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9764: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9765: } else {
9766: %restored=&restore($symbparm,$courseid,$udom,$uname);
9767: }
1.335 albertel 9768: return $restored{$qualifierrest};
9769: }
1.48 www 9770: # ----------------------------------------------------------------- user.access
9771: } elsif ($space eq 'access') {
1.218 albertel 9772: # FIXME - not supporting calls for a specific user
1.48 www 9773: return &allowed($qualifier,$rest);
9774: # ------------------------------------------ user.preferences, user.environment
9775: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9776: if (($uname eq $env{'user.name'}) &&
9777: ($udom eq $env{'user.domain'})) {
9778: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9779: } else {
1.359 albertel 9780: my %returnhash;
9781: if (!$publicuser) {
9782: %returnhash=&userenvironment($udom,$uname,
9783: $qualifierrest);
9784: }
1.218 albertel 9785: return $returnhash{$qualifierrest};
9786: }
1.48 www 9787: # ----------------------------------------------------------------- user.course
9788: } elsif ($space eq 'course') {
1.218 albertel 9789: # FIXME - not supporting calls for a specific user
1.620 albertel 9790: return $env{join('.',('request.course',$qualifier))};
1.48 www 9791: # ------------------------------------------------------------------- user.role
9792: } elsif ($space eq 'role') {
1.218 albertel 9793: # FIXME - not supporting calls for a specific user
1.620 albertel 9794: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9795: if ($qualifier eq 'value') {
9796: return $role;
9797: } elsif ($qualifier eq 'extent') {
9798: return $where;
9799: }
9800: # ----------------------------------------------------------------- user.domain
9801: } elsif ($space eq 'domain') {
1.218 albertel 9802: return $udom;
1.48 www 9803: # ------------------------------------------------------------------- user.name
9804: } elsif ($space eq 'name') {
1.218 albertel 9805: return $uname;
1.48 www 9806: # ---------------------------------------------------- Any other user namespace
1.29 www 9807: } else {
1.359 albertel 9808: my %reply;
9809: if (!$publicuser) {
9810: %reply=&get($space,[$qualifierrest],$udom,$uname);
9811: }
9812: return $reply{$qualifierrest};
1.48 www 9813: }
1.236 www 9814: } elsif ($realm eq 'query') {
9815: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9816: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9817: [$spacequalifierrest]);
1.620 albertel 9818: return $env{'form.'.$spacequalifierrest};
1.236 www 9819: } elsif ($realm eq 'request') {
1.48 www 9820: # ------------------------------------------------------------- request.browser
9821: if ($space eq 'browser') {
1.1145 bisitz 9822: return $env{'browser.'.$qualifier};
1.57 www 9823: # ------------------------------------------------------------ request.filename
9824: } else {
1.620 albertel 9825: return $env{'request.'.$spacequalifierrest};
1.29 www 9826: }
1.28 www 9827: } elsif ($realm eq 'course') {
1.48 www 9828: # ---------------------------------------------------------- course.description
1.620 albertel 9829: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9830: } elsif ($realm eq 'resource') {
1.165 www 9831:
1.620 albertel 9832: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9833: if (!$symbparm) { $symbparm=&symbread(); }
9834: }
1.693 albertel 9835:
1.1232 raeburn 9836: if ($qualifier eq '') {
9837: if ($space eq 'title') {
9838: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9839: return &gettitle($symbparm);
9840: }
1.693 albertel 9841:
1.1232 raeburn 9842: if ($space eq 'map') {
9843: my ($map) = &decode_symb($symbparm);
9844: return &symbread($map);
9845: }
9846: if ($space eq 'maptitle') {
9847: my ($map) = &decode_symb($symbparm);
9848: return &gettitle($map);
9849: }
9850: if ($space eq 'filename') {
9851: if ($symbparm) {
9852: return &clutter((&decode_symb($symbparm))[2]);
9853: }
9854: return &hreflocation('',$env{'request.filename'});
1.905 albertel 9855: }
1.1232 raeburn 9856:
1.1233 raeburn 9857: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
9858: if ($space eq 'visibleparts') {
9859: my $navmap = Apache::lonnavmaps::navmap->new();
9860: my $item;
9861: if (ref($navmap)) {
9862: my $res = $navmap->getBySymb($symbparm);
9863: my $parts = $res->parts();
9864: if (ref($parts) eq 'ARRAY') {
9865: $item = join(',',@{$parts});
9866: }
9867: undef($navmap);
1.1232 raeburn 9868: }
1.1233 raeburn 9869: return $item;
1.1232 raeburn 9870: }
9871: }
9872: }
1.693 albertel 9873:
9874: my ($section, $group, @groups);
1.593 albertel 9875: my ($courselevelm,$courselevel);
1.1228 raeburn 9876: if (($courseid eq '') && ($cid)) {
9877: $courseid = $cid;
9878: }
9879: if (($symbparm && $courseid) &&
9880: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 9881:
1.218 albertel 9882: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9883:
1.60 www 9884: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9885: my $symbp=$symbparm;
1.735 albertel 9886: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9887:
9888: my $symbparm=$symbp.'.'.$spacequalifierrest;
9889: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9890:
1.620 albertel 9891: if (($env{'user.name'} eq $uname) &&
9892: ($env{'user.domain'} eq $udom)) {
9893: $section=$env{'request.course.sec'};
1.733 raeburn 9894: @groups = split(/:/,$env{'request.course.groups'});
9895: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9896: } else {
1.539 albertel 9897: if (! defined($usection)) {
1.551 albertel 9898: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9899: } else {
9900: $section = $usection;
9901: }
1.733 raeburn 9902: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9903: }
9904:
9905: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9906: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9907: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9908:
1.593 albertel 9909: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9910: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9911: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9912:
1.60 www 9913: # ----------------------------------------------------------- first, check user
1.624 albertel 9914:
9915: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9916: ([$courselevelr,'resource'],
9917: [$courselevelm,'map' ],
9918: [$courselevel, 'course' ]));
1.931 albertel 9919: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9920:
1.594 albertel 9921: # ------------------------------------------------ second, check some of course
1.684 raeburn 9922: my $coursereply;
1.691 raeburn 9923: if (@groups > 0) {
9924: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9925: $mapparm,$spacequalifierrest);
1.927 albertel 9926: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9927: }
1.96 www 9928:
1.684 raeburn 9929: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9930: $env{'course.'.$courseid.'.domain'},
9931: 'course',
9932: ([$seclevelr, 'resource'],
9933: [$seclevelm, 'map' ],
9934: [$seclevel, 'course' ],
9935: [$courselevelr,'resource']));
9936: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 9937:
1.60 www 9938: # ------------------------------------------------------ third, check map parms
1.218 albertel 9939: my %parmhash=();
9940: my $thisparm='';
9941: if (tie(%parmhash,'GDBM_File',
1.620 albertel 9942: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 9943: &GDBM_READER(),0640)) {
1.218 albertel 9944: $thisparm=$parmhash{$symbparm};
9945: untie(%parmhash);
9946: }
1.927 albertel 9947: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 9948: }
1.594 albertel 9949: # ------------------------------------------ fourth, look in resource metadata
1.71 www 9950:
1.218 albertel 9951: $spacequalifierrest=~s/\./\_/;
1.282 albertel 9952: my $filename;
9953: if (!$symbparm) { $symbparm=&symbread(); }
9954: if ($symbparm) {
1.409 www 9955: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 9956: } else {
1.620 albertel 9957: $filename=$env{'request.filename'};
1.282 albertel 9958: }
9959: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 9960: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 9961: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 9962: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 9963:
1.927 albertel 9964: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 9965: if ($symbparm && defined($courseid) &&
1.620 albertel 9966: $courseid eq $env{'request.course.id'}) {
1.624 albertel 9967: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9968: $env{'course.'.$courseid.'.domain'},
9969: 'course',
1.927 albertel 9970: ([$courselevelm,'map' ],
9971: [$courselevel, 'course']));
9972: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 9973: }
1.145 www 9974: # ------------------------------------------------------------------ Cascade up
1.218 albertel 9975: unless ($space eq '0') {
1.336 albertel 9976: my @parts=split(/_/,$space);
9977: my $id=pop(@parts);
9978: my $part=join('_',@parts);
9979: if ($part eq '') { $part='0'; }
1.927 albertel 9980: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 9981: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 9982: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 9983: }
1.395 albertel 9984: if ($recurse) { return undef; }
9985: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 9986: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 9987: # ---------------------------------------------------- Any other user namespace
9988: } elsif ($realm eq 'environment') {
9989: # ----------------------------------------------------------------- environment
1.620 albertel 9990: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9991: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 9992: } else {
1.770 albertel 9993: if ($uname eq 'anonymous' && $udom eq '') {
9994: return '';
9995: }
1.219 albertel 9996: my %returnhash=&userenvironment($udom,$uname,
9997: $spacequalifierrest);
9998: return $returnhash{$spacequalifierrest};
9999: }
1.28 www 10000: } elsif ($realm eq 'system') {
1.48 www 10001: # ----------------------------------------------------------------- system.time
10002: if ($space eq 'time') {
10003: return time;
10004: }
1.696 albertel 10005: } elsif ($realm eq 'server') {
10006: # ----------------------------------------------------------------- system.time
10007: if ($space eq 'name') {
10008: return $ENV{'SERVER_NAME'};
10009: }
1.28 www 10010: }
1.48 www 10011: return '';
1.61 www 10012: }
10013:
1.927 albertel 10014: sub get_reply {
10015: my ($reply_value) = @_;
1.940 raeburn 10016: if (ref($reply_value) eq 'ARRAY') {
10017: if (wantarray) {
10018: return @$reply_value;
10019: }
10020: return $reply_value->[0];
10021: } else {
10022: return $reply_value;
1.927 albertel 10023: }
10024: }
10025:
1.691 raeburn 10026: sub check_group_parms {
10027: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10028: my @groupitems = ();
10029: my $resultitem;
1.927 albertel 10030: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10031: foreach my $group (@{$groups}) {
10032: foreach my $level (@levels) {
1.927 albertel 10033: my $item = $courseid.'.['.$group.'].'.$level->[0];
10034: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10035: }
10036: }
10037: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10038: $env{'course.'.$courseid.'.domain'},
10039: 'course',@groupitems);
10040: return $coursereply;
10041: }
10042:
10043: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10044: my ($courseid,@groups) = @_;
10045: @groups = sort(@groups);
1.691 raeburn 10046: return @groups;
10047: }
10048:
1.395 albertel 10049: sub packages_tab_default {
10050: my ($uri,$varname)=@_;
10051: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10052:
10053: my (@extension,@specifics,$do_default);
10054: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10055: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10056: if ($pack_type eq 'default') {
10057: $do_default=1;
10058: } elsif ($pack_type eq 'extension') {
10059: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10060: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10061: # only look at packages defaults for packages that this id is
1.738 albertel 10062: push(@specifics,[$package,$pack_type,$pack_part]);
10063: }
10064: }
10065: # first look for a package that matches the requested part id
10066: foreach my $package (@specifics) {
10067: my (undef,$pack_type,$pack_part)=@{$package};
10068: next if ($pack_part ne $part);
10069: if (defined($packagetab{"$pack_type&$name&default"})) {
10070: return $packagetab{"$pack_type&$name&default"};
10071: }
10072: }
10073: # look for any possible matching non extension_ package
10074: foreach my $package (@specifics) {
10075: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10076: if (defined($packagetab{"$pack_type&$name&default"})) {
10077: return $packagetab{"$pack_type&$name&default"};
10078: }
1.585 albertel 10079: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10080: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10081: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10082: }
10083: }
1.738 albertel 10084: # look for any posible extension_ match
10085: foreach my $package (@extension) {
10086: my ($package,$pack_type)=@{$package};
10087: if (defined($packagetab{"$pack_type&$name&default"})) {
10088: return $packagetab{"$pack_type&$name&default"};
10089: }
10090: if (defined($packagetab{$package."&$name&default"})) {
10091: return $packagetab{$package."&$name&default"};
10092: }
10093: }
10094: # look for a global default setting
10095: if ($do_default && defined($packagetab{"default&$name&default"})) {
10096: return $packagetab{"default&$name&default"};
10097: }
1.395 albertel 10098: return undef;
10099: }
10100:
1.334 albertel 10101: sub add_prefix_and_part {
10102: my ($prefix,$part)=@_;
10103: my $keyroot;
10104: if (defined($prefix) && $prefix !~ /^__/) {
10105: # prefix that has a part already
10106: $keyroot=$prefix;
10107: } elsif (defined($prefix)) {
10108: # prefix that is missing a part
10109: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10110: } else {
10111: # no prefix at all
10112: if (defined($part)) { $keyroot='_'.$part; }
10113: }
10114: return $keyroot;
10115: }
10116:
1.71 www 10117: # ---------------------------------------------------------------- Get metadata
10118:
1.599 albertel 10119: my %metaentry;
1.1070 www 10120: my %importedpartids;
1.71 www 10121: sub metadata {
1.176 www 10122: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10123: $uri=&declutter($uri);
1.288 albertel 10124: # if it is a non metadata possible uri return quickly
1.529 albertel 10125: if (($uri eq '') ||
10126: (($uri =~ m|^/*adm/|) &&
1.1217 raeburn 10127: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10128: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10129: return undef;
10130: }
1.1140 www 10131: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 10132: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10133: return undef;
1.288 albertel 10134: }
1.73 www 10135: my $filename=$uri;
10136: $uri=~s/\.meta$//;
1.172 www 10137: #
10138: # Is the metadata already cached?
1.177 www 10139: # Look at timestamp of caching
1.172 www 10140: # Everything is cached by the main uri, libraries are never directly cached
10141: #
1.428 albertel 10142: if (!defined($liburi)) {
1.599 albertel 10143: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10144: if (defined($cached)) { return $result->{':'.$what}; }
10145: }
10146: {
1.1069 www 10147: # Imported parts would go here
1.1070 www 10148: my %importedids=();
10149: my @origfileimportpartids=();
1.1069 www 10150: my $importedparts=0;
1.172 www 10151: #
10152: # Is this a recursive call for a library?
10153: #
1.599 albertel 10154: # if (! exists($metacache{$uri})) {
10155: # $metacache{$uri}={};
10156: # }
1.924 albertel 10157: my $cachetime = 60*60;
1.171 www 10158: if ($liburi) {
10159: $liburi=&declutter($liburi);
10160: $filename=$liburi;
1.401 bowersj2 10161: } else {
1.599 albertel 10162: &devalidate_cache_new('meta',$uri);
10163: undef(%metaentry);
1.401 bowersj2 10164: }
1.140 www 10165: my %metathesekeys=();
1.73 www 10166: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10167: my $metastring;
1.1140 www 10168: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10169: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10170: $metastring =
1.929 albertel 10171: &Apache::lonnet::ssi_body($which,
1.924 albertel 10172: ('grade_target' => 'meta'));
10173: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10174: } elsif (($uri !~ m -^(editupload)/-) &&
10175: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10176: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10177: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10178: $metastring=&getfile($file);
1.489 albertel 10179: }
1.208 albertel 10180: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10181: my $token;
1.140 www 10182: undef %metathesekeys;
1.71 www 10183: while ($token=$parser->get_token) {
1.339 albertel 10184: if ($token->[0] eq 'S') {
10185: if (defined($token->[2]->{'package'})) {
1.172 www 10186: #
10187: # This is a package - get package info
10188: #
1.339 albertel 10189: my $package=$token->[2]->{'package'};
10190: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10191: if (defined($token->[2]->{'id'})) {
10192: $keyroot.='_'.$token->[2]->{'id'};
10193: }
1.599 albertel 10194: if ($metaentry{':packages'}) {
10195: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10196: } else {
1.599 albertel 10197: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10198: }
1.736 albertel 10199: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10200: my $part=$keyroot;
10201: $part=~s/^\_//;
1.736 albertel 10202: if ($pack_entry=~/^\Q$package\E\&/ ||
10203: $pack_entry=~/^\Q$package\E_0\&/) {
10204: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10205: # ignore package.tab specified default values
10206: # here &package_tab_default() will fetch those
10207: if ($subp eq 'default') { next; }
1.736 albertel 10208: my $value=$packagetab{$pack_entry};
1.432 albertel 10209: my $unikey;
10210: if ($pack =~ /_0$/) {
10211: $unikey='parameter_0_'.$name;
10212: $part=0;
10213: } else {
10214: $unikey='parameter'.$keyroot.'_'.$name;
10215: }
1.339 albertel 10216: if ($subp eq 'display') {
10217: $value.=' [Part: '.$part.']';
10218: }
1.599 albertel 10219: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10220: $metathesekeys{$unikey}=1;
1.599 albertel 10221: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10222: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10223: }
1.599 albertel 10224: if (defined($metaentry{':'.$unikey.'.default'})) {
10225: $metaentry{':'.$unikey}=
10226: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10227: }
1.339 albertel 10228: }
10229: }
10230: } else {
1.172 www 10231: #
10232: # This is not a package - some other kind of start tag
1.339 albertel 10233: #
10234: my $entry=$token->[1];
1.1068 www 10235: my $unikey='';
1.175 www 10236:
1.339 albertel 10237: if ($entry eq 'import') {
1.175 www 10238: #
10239: # Importing a library here
1.339 albertel 10240: #
1.1067 www 10241: my $location=$parser->get_text('/import');
10242: my $dir=$filename;
10243: $dir=~s|[^/]*$||;
10244: $location=&filelocation($dir,$location);
1.1069 www 10245:
1.1068 www 10246: my $importmode=$token->[2]->{'importmode'};
10247: if ($importmode eq 'problem') {
1.1069 www 10248: # Import as problem/response
1.1068 www 10249: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10250: } elsif ($importmode eq 'part') {
10251: # Import as part(s)
1.1069 www 10252: $importedparts=1;
10253: # We need to get the original file and the imported file to get the part order correct
10254: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10255: # Load and inspect original file
1.1070 www 10256: if ($#origfileimportpartids<0) {
10257: undef(%importedpartids);
10258: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10259: my $origfile=&getfile($origfilelocation);
10260: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10261: }
10262:
1.1069 www 10263: # Load and inspect imported file
10264: my $impfile=&getfile($location);
10265: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10266: if ($#impfilepartids>=0) {
10267: # This problem had parts
1.1070 www 10268: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10269: } else {
10270: # Importing by turning a single problem into a problem part
10271: # It gets the import-tags ID as part-ID
10272: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10273: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10274: }
1.1068 www 10275: } else {
10276: # Normal import
10277: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10278: if (defined($token->[2]->{'id'})) {
10279: $unikey.='_'.$token->[2]->{'id'};
10280: }
1.1067 www 10281: }
10282:
1.339 albertel 10283: if ($depthcount<20) {
1.736 albertel 10284: my $metadata =
10285: &metadata($uri,'keys', $location,$unikey,
10286: $depthcount+1);
10287: foreach my $meta (split(',',$metadata)) {
10288: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10289: $metathesekeys{$meta}=1;
1.339 albertel 10290: }
1.1068 www 10291:
10292: }
1.1067 www 10293: } else {
10294: #
10295: # Not importing, some other kind of non-package, non-library start tag
10296: #
10297: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10298: if (defined($token->[2]->{'id'})) {
10299: $unikey.='_'.$token->[2]->{'id'};
10300: }
1.339 albertel 10301: if (defined($token->[2]->{'name'})) {
10302: $unikey.='_'.$token->[2]->{'name'};
10303: }
10304: $metathesekeys{$unikey}=1;
1.736 albertel 10305: foreach my $param (@{$token->[3]}) {
10306: $metaentry{':'.$unikey.'.'.$param} =
10307: $token->[2]->{$param};
1.339 albertel 10308: }
10309: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10310: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10311: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10312: # only ws inside the tag, and not in default, so use default
10313: # as value
1.599 albertel 10314: $metaentry{':'.$unikey}=$default;
1.908 albertel 10315: } elsif ( $internaltext =~ /\S/ ) {
10316: # something interesting inside the tag
10317: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10318: } else {
1.908 albertel 10319: # no interesting values, don't set a default
1.339 albertel 10320: }
1.172 www 10321: # end of not-a-package not-a-library import
1.339 albertel 10322: }
1.172 www 10323: # end of not-a-package start tag
1.339 albertel 10324: }
1.172 www 10325: # the next is the end of "start tag"
1.339 albertel 10326: }
10327: }
1.483 albertel 10328: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10329: $extension = lc($extension);
10330: if ($extension eq 'htm') { $extension='html'; }
10331:
1.737 albertel 10332: foreach my $key (keys(%packagetab)) {
1.483 albertel 10333: #no specific packages #how's our extension
10334: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10335: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10336: \%metathesekeys);
10337: }
1.883 albertel 10338:
10339: if (!exists($metaentry{':packages'})
10340: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10341: foreach my $key (keys(%packagetab)) {
1.483 albertel 10342: #no specific packages well let's get default then
10343: if ($key!~/^default&/) { next; }
1.488 albertel 10344: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10345: \%metathesekeys);
10346: }
10347: }
1.338 www 10348: # are there custom rights to evaluate
1.599 albertel 10349: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10350:
1.338 www 10351: #
10352: # Importing a rights file here
1.339 albertel 10353: #
10354: unless ($depthcount) {
1.599 albertel 10355: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10356: my $dir=$filename;
10357: $dir=~s|[^/]*$||;
10358: $location=&filelocation($dir,$location);
1.736 albertel 10359: my $rights_metadata =
10360: &metadata($uri,'keys',$location,'_rights',
10361: $depthcount+1);
10362: foreach my $rights (split(',',$rights_metadata)) {
10363: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10364: $metathesekeys{$rights}=1;
1.339 albertel 10365: }
10366: }
10367: }
1.737 albertel 10368: # uniqifiy package listing
10369: my %seen;
10370: my @uniq_packages =
10371: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10372: $metaentry{':packages'} = join(',',@uniq_packages);
10373:
1.1070 www 10374: if ($importedparts) {
10375: # We had imported parts and need to rebuild partorder
10376: $metaentry{':partorder'}='';
10377: $metathesekeys{'partorder'}=1;
10378: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10379: if ($origfileimportpartids[$index] eq 'part') {
10380: # original part, part of the problem
10381: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10382: } else {
10383: # we have imported parts at this position
10384: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10385: }
10386: }
10387: $metaentry{':partorder'}=~s/^\,//;
10388: }
10389:
1.737 albertel 10390: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10391: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10392: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 10393: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10394: # this is the end of "was not already recently cached
1.71 www 10395: }
1.599 albertel 10396: return $metaentry{':'.$what};
1.261 albertel 10397: }
10398:
1.488 albertel 10399: sub metadata_create_package_def {
1.483 albertel 10400: my ($uri,$key,$package,$metathesekeys)=@_;
10401: my ($pack,$name,$subp)=split(/\&/,$key);
10402: if ($subp eq 'default') { next; }
10403:
1.599 albertel 10404: if (defined($metaentry{':packages'})) {
10405: $metaentry{':packages'}.=','.$package;
1.483 albertel 10406: } else {
1.599 albertel 10407: $metaentry{':packages'}=$package;
1.483 albertel 10408: }
10409: my $value=$packagetab{$key};
10410: my $unikey;
10411: $unikey='parameter_0_'.$name;
1.599 albertel 10412: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10413: $$metathesekeys{$unikey}=1;
1.599 albertel 10414: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10415: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10416: }
1.599 albertel 10417: if (defined($metaentry{':'.$unikey.'.default'})) {
10418: $metaentry{':'.$unikey}=
10419: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10420: }
10421: }
10422:
1.261 albertel 10423: sub metadata_generate_part0 {
10424: my ($metadata,$metacache,$uri) = @_;
10425: my %allnames;
1.737 albertel 10426: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10427: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10428: my $part=$$metacache{':'.$metakey.'.part'};
10429: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10430: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10431: $allnames{$name}=$part;
10432: }
10433: }
10434: }
10435: foreach my $name (keys(%allnames)) {
10436: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10437: my $key=":parameter_0_$name";
1.261 albertel 10438: $$metacache{"$key.part"}='0';
10439: $$metacache{"$key.name"}=$name;
1.428 albertel 10440: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10441: $allnames{$name}.'_'.$name.
10442: '.type'};
1.428 albertel 10443: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10444: '.display'};
1.644 www 10445: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10446: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10447: $$metacache{"$key.display"}=$olddis;
10448: }
1.71 www 10449: }
10450:
1.764 albertel 10451: # ------------------------------------------------------ Devalidate title cache
10452:
10453: sub devalidate_title_cache {
10454: my ($url)=@_;
10455: if (!$env{'request.course.id'}) { return; }
10456: my $symb=&symbread($url);
10457: if (!$symb) { return; }
10458: my $key=$env{'request.course.id'}."\0".$symb;
10459: &devalidate_cache_new('title',$key);
10460: }
10461:
1.1014 droeschl 10462: # ------------------------------------------------- Get the title of a course
10463:
10464: sub current_course_title {
10465: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10466: }
1.301 www 10467: # ------------------------------------------------- Get the title of a resource
10468:
10469: sub gettitle {
10470: my $urlsymb=shift;
10471: my $symb=&symbread($urlsymb);
1.534 albertel 10472: if ($symb) {
1.620 albertel 10473: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10474: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10475: if (defined($cached)) {
10476: return $result;
10477: }
1.534 albertel 10478: my ($map,$resid,$url)=&decode_symb($symb);
10479: my $title='';
1.907 albertel 10480: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10481: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10482: } else {
10483: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10484: &GDBM_READER(),0640)) {
10485: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10486: $title=$bighash{'title_'.$mapid.'.'.$resid};
10487: untie(%bighash);
10488: }
1.534 albertel 10489: }
10490: $title=~s/\&colon\;/\:/gs;
10491: if ($title) {
1.1159 www 10492: # Remember both $symb and $title for dynamic metadata
10493: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10494: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10495: # Cache this title and then return it
1.599 albertel 10496: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10497: }
10498: $urlsymb=$url;
10499: }
10500: my $title=&metadata($urlsymb,'title');
10501: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10502: return $title;
1.301 www 10503: }
1.613 albertel 10504:
1.614 albertel 10505: sub get_slot {
10506: my ($which,$cnum,$cdom)=@_;
10507: if (!$cnum || !$cdom) {
1.790 albertel 10508: (undef,my $courseid)=&whichuser();
1.620 albertel 10509: $cdom=$env{'course.'.$courseid.'.domain'};
10510: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10511: }
1.703 albertel 10512: my $key=join("\0",'slots',$cdom,$cnum,$which);
10513: my %slotinfo;
10514: if (exists($remembered{$key})) {
10515: $slotinfo{$which} = $remembered{$key};
10516: } else {
10517: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10518: &Apache::lonhomework::showhash(%slotinfo);
10519: my ($tmp)=keys(%slotinfo);
10520: if ($tmp=~/^error:/) { return (); }
10521: $remembered{$key} = $slotinfo{$which};
10522: }
1.616 albertel 10523: if (ref($slotinfo{$which}) eq 'HASH') {
10524: return %{$slotinfo{$which}};
10525: }
10526: return $slotinfo{$which};
1.614 albertel 10527: }
1.1150 raeburn 10528:
10529: sub get_reservable_slots {
10530: my ($cnum,$cdom,$uname,$udom) = @_;
10531: my $now = time;
10532: my $reservable_info;
10533: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10534: if (exists($remembered{$key})) {
10535: $reservable_info = $remembered{$key};
10536: } else {
10537: my %resv;
10538: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10539: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10540: $reservable_info = \%resv;
10541: $remembered{$key} = $reservable_info;
10542: }
10543: return $reservable_info;
10544: }
10545:
10546: sub get_course_slots {
10547: my ($cnum,$cdom) = @_;
10548: my $hashid=$cnum.':'.$cdom;
10549: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10550: if (defined($cached)) {
10551: if (ref($result) eq 'HASH') {
10552: return %{$result};
10553: }
10554: } else {
10555: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10556: my ($tmp) = keys(%slots);
10557: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 10558: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10559: return %slots;
10560: }
10561: }
10562: return;
10563: }
10564:
10565: sub devalidate_slots_cache {
10566: my ($cnum,$cdom)=@_;
10567: my $hashid=$cnum.':'.$cdom;
10568: &devalidate_cache_new('allslots',$hashid);
10569: }
10570:
1.1181 raeburn 10571: sub get_coursechange {
10572: my ($cdom,$cnum) = @_;
10573: if ($cdom eq '' || $cnum eq '') {
10574: return unless ($env{'request.course.id'});
10575: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10576: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10577: }
10578: my $hashid=$cdom.'_'.$cnum;
10579: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10580: if ((defined($cached)) && ($change ne '')) {
10581: return $change;
10582: } else {
10583: my %crshash;
10584: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10585: if ($crshash{'internal.contentchange'} eq '') {
10586: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10587: if ($change eq '') {
10588: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10589: $change = $crshash{'internal.created'};
10590: }
10591: } else {
10592: $change = $crshash{'internal.contentchange'};
10593: }
10594: my $cachetime = 600;
10595: &do_cache_new('crschange',$hashid,$change,$cachetime);
10596: }
10597: return $change;
10598: }
10599:
10600: sub devalidate_coursechange_cache {
10601: my ($cnum,$cdom)=@_;
10602: my $hashid=$cnum.':'.$cdom;
10603: &devalidate_cache_new('crschange',$hashid);
10604: }
10605:
1.31 www 10606: # ------------------------------------------------- Update symbolic store links
10607:
10608: sub symblist {
10609: my ($mapname,%newhash)=@_;
1.438 www 10610: $mapname=&deversion(&declutter($mapname));
1.31 www 10611: my %hash;
1.620 albertel 10612: if (($env{'request.course.fn'}) && (%newhash)) {
10613: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10614: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10615: foreach my $url (keys(%newhash)) {
1.711 albertel 10616: next if ($url eq 'last_known'
10617: && $env{'form.no_update_last_known'});
10618: $hash{declutter($url)}=&encode_symb($mapname,
10619: $newhash{$url}->[1],
10620: $newhash{$url}->[0]);
1.191 harris41 10621: }
1.31 www 10622: if (untie(%hash)) {
10623: return 'ok';
10624: }
10625: }
10626: }
10627: return 'error';
1.212 www 10628: }
10629:
10630: # --------------------------------------------------------------- Verify a symb
10631:
10632: sub symbverify {
1.1190 raeburn 10633: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10634: my $thisfn=$thisurl;
1.439 www 10635: $thisfn=&declutter($thisfn);
1.215 www 10636: # direct jump to resource in page or to a sequence - will construct own symbs
10637: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10638: # check URL part
1.409 www 10639: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10640:
1.431 www 10641: unless ($url eq $thisfn) { return 0; }
1.213 www 10642:
1.216 www 10643: $symb=&symbclean($symb);
1.510 www 10644: $thisurl=&deversion($thisurl);
1.439 www 10645: $thisfn=&deversion($thisfn);
1.213 www 10646:
10647: my %bighash;
10648: my $okay=0;
1.431 www 10649:
1.620 albertel 10650: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10651: &GDBM_READER(),0640)) {
1.1204 raeburn 10652: my $noclutter;
1.1032 raeburn 10653: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10654: $thisurl =~ s/\?.+$//;
1.1204 raeburn 10655: if ($map =~ m{^uploaded/.+\.page$}) {
10656: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10657: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10658: $noclutter = 1;
10659: }
10660: }
10661: my $ids;
10662: if ($noclutter) {
10663: $ids=$bighash{'ids_'.$thisurl};
10664: } else {
10665: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10666: }
1.1102 raeburn 10667: unless ($ids) {
10668: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10669: $ids=$bighash{$idkey};
1.216 www 10670: }
10671: if ($ids) {
10672: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 10673: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 10674: $symb =~ s/\?.+$//;
1.1202 raeburn 10675: }
1.800 albertel 10676: foreach my $id (split(/\,/,$ids)) {
10677: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10678: if (
10679: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 10680: eq $symb) {
10681: if (ref($encstate)) {
10682: $$encstate = $bighash{'encrypted_'.$id};
10683: }
1.620 albertel 10684: if (($env{'request.role.adv'}) ||
1.1101 raeburn 10685: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10686: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 10687: $okay=1;
1.1202 raeburn 10688: last;
1.582 albertel 10689: }
10690: }
1.216 www 10691: }
10692: }
1.213 www 10693: untie(%bighash);
10694: }
10695: return $okay;
1.31 www 10696: }
10697:
1.210 www 10698: # --------------------------------------------------------------- Clean-up symb
10699:
10700: sub symbclean {
10701: my $symb=shift;
1.568 albertel 10702: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10703: # remove version from map
10704: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10705:
1.210 www 10706: # remove version from URL
10707: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10708:
1.507 www 10709: # remove wrapper
10710:
1.510 www 10711: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10712: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10713: return $symb;
1.409 www 10714: }
10715:
10716: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10717:
10718: sub encode_symb {
10719: my ($map,$resid,$url)=@_;
10720: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10721: }
1.409 www 10722:
10723: sub decode_symb {
1.568 albertel 10724: my $symb=shift;
10725: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10726: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10727: return (&fixversion($map),$resid,&fixversion($url));
10728: }
10729:
10730: sub fixversion {
10731: my $fn=shift;
1.609 banghart 10732: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10733: my %bighash;
10734: my $uri=&clutter($fn);
1.620 albertel 10735: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10736: # is this cached?
1.599 albertel 10737: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10738: if (defined($cached)) { return $result; }
10739: # unfortunately not cached, or expired
1.620 albertel 10740: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10741: &GDBM_READER(),0640)) {
10742: if ($bighash{'version_'.$uri}) {
10743: my $version=$bighash{'version_'.$uri};
1.444 www 10744: unless (($version eq 'mostrecent') ||
10745: ($version==&getversion($uri))) {
1.440 www 10746: $uri=~s/\.(\w+)$/\.$version\.$1/;
10747: }
10748: }
10749: untie %bighash;
1.413 www 10750: }
1.599 albertel 10751: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10752: }
10753:
10754: sub deversion {
10755: my $url=shift;
10756: $url=~s/\.\d+\.(\w+)$/\.$1/;
10757: return $url;
1.210 www 10758: }
10759:
1.31 www 10760: # ------------------------------------------------------ Return symb list entry
10761:
10762: sub symbread {
1.249 www 10763: my ($thisfn,$donotrecurse)=@_;
1.1206 raeburn 10764: my $cache_str;
10765: if ($thisfn ne '') {
10766: $cache_str='request.symbread.cached.'.$thisfn;
10767: if ($env{$cache_str} ne '') {
1.1179 raeburn 10768: return $env{$cache_str};
10769: }
1.1206 raeburn 10770: } else {
1.242 www 10771: # no filename provided? try from environment
1.620 albertel 10772: if ($env{'request.symb'}) {
10773: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 10774: }
1.620 albertel 10775: $thisfn=$env{'request.filename'};
1.44 www 10776: }
1.569 albertel 10777: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10778: # is that filename actually a symb? Verify, clean, and return
10779: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10780: if (&symbverify($thisfn,$1)) {
1.620 albertel 10781: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10782: }
1.242 www 10783: }
1.44 www 10784: $thisfn=declutter($thisfn);
1.31 www 10785: my %hash;
1.37 www 10786: my %bighash;
10787: my $syval='';
1.620 albertel 10788: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10789: my $targetfn = $thisfn;
1.609 banghart 10790: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10791: $targetfn = 'adm/wrapper/'.$thisfn;
10792: }
1.687 albertel 10793: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10794: $targetfn=$1;
10795: }
1.620 albertel 10796: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10797: &GDBM_READER(),0640)) {
1.481 raeburn 10798: $syval=$hash{$targetfn};
1.37 www 10799: untie(%hash);
10800: }
10801: # ---------------------------------------------------------- There was an entry
10802: if ($syval) {
1.601 albertel 10803: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10804: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10805: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10806: #return $env{$cache_str}='';
1.601 albertel 10807: #}
10808: #$syval.=$1;
10809: #}
1.37 www 10810: } else {
10811: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10812: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10813: &GDBM_READER(),0640)) {
1.37 www 10814: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10815: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10816: unless ($ids) {
10817: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10818: }
10819: unless ($ids) {
10820: # alias?
10821: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10822: }
1.37 www 10823: if ($ids) {
10824: # ------------------------------------------------------------------- Has ID(s)
10825: my @possibilities=split(/\,/,$ids);
1.39 www 10826: if ($#possibilities==0) {
10827: # ----------------------------------------------- There is only one possibility
1.37 www 10828: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10829: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10830: $resid,$thisfn);
1.249 www 10831: } elsif (!$donotrecurse) {
1.39 www 10832: # ------------------------------------------ There is more than one possibility
10833: my $realpossible=0;
1.800 albertel 10834: foreach my $id (@possibilities) {
10835: my $file=$bighash{'src_'.$id};
1.39 www 10836: if (&allowed('bre',$file)) {
1.800 albertel 10837: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10838: if ($bighash{'map_type_'.$mapid} ne 'page') {
10839: $realpossible++;
1.626 albertel 10840: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10841: $resid,$thisfn);
1.39 www 10842: }
10843: }
1.191 harris41 10844: }
1.39 www 10845: if ($realpossible!=1) { $syval=''; }
1.249 www 10846: } else {
10847: $syval='';
1.37 www 10848: }
10849: }
10850: untie(%bighash)
1.481 raeburn 10851: }
1.31 www 10852: }
1.62 www 10853: if ($syval) {
1.620 albertel 10854: return $env{$cache_str}=$syval;
1.62 www 10855: }
1.31 www 10856: }
1.949 raeburn 10857: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10858: return $env{$cache_str}='';
1.31 www 10859: }
10860:
10861: # ---------------------------------------------------------- Return random seed
10862:
1.32 www 10863: sub numval {
10864: my $txt=shift;
10865: $txt=~tr/A-J/0-9/;
10866: $txt=~tr/a-j/0-9/;
10867: $txt=~tr/K-T/0-9/;
10868: $txt=~tr/k-t/0-9/;
10869: $txt=~tr/U-Z/0-5/;
10870: $txt=~tr/u-z/0-5/;
10871: $txt=~s/\D//g;
1.564 albertel 10872: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10873: return int($txt);
1.368 albertel 10874: }
10875:
1.484 albertel 10876: sub numval2 {
10877: my $txt=shift;
10878: $txt=~tr/A-J/0-9/;
10879: $txt=~tr/a-j/0-9/;
10880: $txt=~tr/K-T/0-9/;
10881: $txt=~tr/k-t/0-9/;
10882: $txt=~tr/U-Z/0-5/;
10883: $txt=~tr/u-z/0-5/;
10884: $txt=~s/\D//g;
10885: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10886: my $total;
10887: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10888: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10889: return int($total);
10890: }
10891:
1.575 albertel 10892: sub numval3 {
10893: use integer;
10894: my $txt=shift;
10895: $txt=~tr/A-J/0-9/;
10896: $txt=~tr/a-j/0-9/;
10897: $txt=~tr/K-T/0-9/;
10898: $txt=~tr/k-t/0-9/;
10899: $txt=~tr/U-Z/0-5/;
10900: $txt=~tr/u-z/0-5/;
10901: $txt=~s/\D//g;
10902: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10903: my $total;
10904: foreach my $val (@txts) { $total+=$val; }
10905: if ($_64bit) { $total=(($total<<32)>>32); }
10906: return $total;
10907: }
10908:
1.675 albertel 10909: sub digest {
10910: my ($data)=@_;
10911: my $digest=&Digest::MD5::md5($data);
10912: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10913: my ($e,$f);
10914: {
10915: use integer;
10916: $e=($a+$b);
10917: $f=($c+$d);
10918: if ($_64bit) {
10919: $e=(($e<<32)>>32);
10920: $f=(($f<<32)>>32);
10921: }
10922: }
10923: if (wantarray) {
10924: return ($e,$f);
10925: } else {
10926: my $g;
10927: {
10928: use integer;
10929: $g=($e+$f);
10930: if ($_64bit) {
10931: $g=(($g<<32)>>32);
10932: }
10933: }
10934: return $g;
10935: }
10936: }
10937:
1.368 albertel 10938: sub latest_rnd_algorithm_id {
1.675 albertel 10939: return '64bit5';
1.366 albertel 10940: }
1.32 www 10941:
1.503 albertel 10942: sub get_rand_alg {
10943: my ($courseid)=@_;
1.790 albertel 10944: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 10945: if ($courseid) {
1.620 albertel 10946: return $env{"course.$courseid.rndseed"};
1.503 albertel 10947: }
10948: return &latest_rnd_algorithm_id();
10949: }
10950:
1.562 albertel 10951: sub validCODE {
10952: my ($CODE)=@_;
10953: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10954: return 0;
10955: }
10956:
1.491 albertel 10957: sub getCODE {
1.620 albertel 10958: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 10959: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10960: defined($Apache::lonhomework::parsing_a_task) ) &&
10961: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 10962: return $Apache::lonhomework::history{'resource.CODE'};
10963: }
10964: return undef;
10965: }
1.1133 foxr 10966: #
10967: # Determines the random seed for a specific context:
10968: #
10969: # parameters:
10970: # symb - in course context the symb for the seed.
10971: # course_id - The course id of the form domain_coursenum.
10972: # domain - Domain for the user.
10973: # course - Course for the user.
10974: # cenv - environment of the course.
10975: #
10976: # NOTE:
10977: # All parameters are picked out of the environment if missing
10978: # or not defined.
10979: # If a symb cannot be determined the current time is used instead.
10980: #
10981: # For a given well defined symb, courside, domain, username,
10982: # and course environment, the seed is reproducible.
10983: #
1.31 www 10984: sub rndseed {
1.1133 foxr 10985: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 10986: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 10987: if (!defined($symb)) {
1.366 albertel 10988: unless ($symb=$wsymb) { return time; }
10989: }
1.1146 foxr 10990: if (!defined $courseid) {
10991: $courseid=$wcourseid;
10992: }
10993: if (!defined $domain) { $domain=$wdomain; }
10994: if (!defined $username) { $username=$wusername }
1.1133 foxr 10995:
10996: my $which;
10997: if (defined($cenv->{'rndseed'})) {
10998: $which = $cenv->{'rndseed'};
10999: } else {
11000: $which =&get_rand_alg($courseid);
11001: }
1.491 albertel 11002: if (defined(&getCODE())) {
1.1133 foxr 11003:
1.675 albertel 11004: if ($which eq '64bit5') {
11005: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11006: } elsif ($which eq '64bit4') {
1.575 albertel 11007: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11008: } else {
11009: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11010: }
1.675 albertel 11011: } elsif ($which eq '64bit5') {
11012: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11013: } elsif ($which eq '64bit4') {
11014: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11015: } elsif ($which eq '64bit3') {
11016: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11017: } elsif ($which eq '64bit2') {
11018: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11019: } elsif ($which eq '64bit') {
11020: return &rndseed_64bit($symb,$courseid,$domain,$username);
11021: }
11022: return &rndseed_32bit($symb,$courseid,$domain,$username);
11023: }
11024:
11025: sub rndseed_32bit {
11026: my ($symb,$courseid,$domain,$username)=@_;
11027: {
11028: use integer;
11029: my $symbchck=unpack("%32C*",$symb) << 27;
11030: my $symbseed=numval($symb) << 22;
11031: my $namechck=unpack("%32C*",$username) << 17;
11032: my $nameseed=numval($username) << 12;
11033: my $domainseed=unpack("%32C*",$domain) << 7;
11034: my $courseseed=unpack("%32C*",$courseid);
11035: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11036: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11037: #&logthis("rndseed :$num:$symb");
1.564 albertel 11038: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11039: return $num;
11040: }
11041: }
11042:
11043: sub rndseed_64bit {
11044: my ($symb,$courseid,$domain,$username)=@_;
11045: {
11046: use integer;
11047: my $symbchck=unpack("%32S*",$symb) << 21;
11048: my $symbseed=numval($symb) << 10;
11049: my $namechck=unpack("%32S*",$username);
11050:
11051: my $nameseed=numval($username) << 21;
11052: my $domainseed=unpack("%32S*",$domain) << 10;
11053: my $courseseed=unpack("%32S*",$courseid);
11054:
11055: my $num1=$symbchck+$symbseed+$namechck;
11056: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11057: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11058: #&logthis("rndseed :$num:$symb");
1.564 albertel 11059: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11060: return "$num1,$num2";
1.155 albertel 11061: }
1.366 albertel 11062: }
11063:
1.443 albertel 11064: sub rndseed_64bit2 {
11065: my ($symb,$courseid,$domain,$username)=@_;
11066: {
11067: use integer;
11068: # strings need to be an even # of cahracters long, it it is odd the
11069: # last characters gets thrown away
11070: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11071: my $symbseed=numval($symb) << 10;
11072: my $namechck=unpack("%32S*",$username.' ');
11073:
11074: my $nameseed=numval($username) << 21;
1.501 albertel 11075: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11076: my $courseseed=unpack("%32S*",$courseid.' ');
11077:
11078: my $num1=$symbchck+$symbseed+$namechck;
11079: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11080: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11081: #&logthis("rndseed :$num:$symb");
1.803 albertel 11082: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11083: return "$num1,$num2";
11084: }
11085: }
11086:
11087: sub rndseed_64bit3 {
11088: my ($symb,$courseid,$domain,$username)=@_;
11089: {
11090: use integer;
11091: # strings need to be an even # of cahracters long, it it is odd the
11092: # last characters gets thrown away
11093: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11094: my $symbseed=numval2($symb) << 10;
11095: my $namechck=unpack("%32S*",$username.' ');
11096:
11097: my $nameseed=numval2($username) << 21;
1.443 albertel 11098: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11099: my $courseseed=unpack("%32S*",$courseid.' ');
11100:
11101: my $num1=$symbchck+$symbseed+$namechck;
11102: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11103: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11104: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11105: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11106:
1.503 albertel 11107: return "$num1:$num2";
1.443 albertel 11108: }
11109: }
11110:
1.575 albertel 11111: sub rndseed_64bit4 {
11112: my ($symb,$courseid,$domain,$username)=@_;
11113: {
11114: use integer;
11115: # strings need to be an even # of cahracters long, it it is odd the
11116: # last characters gets thrown away
11117: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11118: my $symbseed=numval3($symb) << 10;
11119: my $namechck=unpack("%32S*",$username.' ');
11120:
11121: my $nameseed=numval3($username) << 21;
11122: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11123: my $courseseed=unpack("%32S*",$courseid.' ');
11124:
11125: my $num1=$symbchck+$symbseed+$namechck;
11126: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11127: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11128: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11129: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11130:
1.575 albertel 11131: return "$num1:$num2";
11132: }
11133: }
11134:
1.675 albertel 11135: sub rndseed_64bit5 {
11136: my ($symb,$courseid,$domain,$username)=@_;
11137: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11138: return "$num1:$num2";
11139: }
11140:
1.366 albertel 11141: sub rndseed_CODE_64bit {
11142: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11143: {
1.366 albertel 11144: use integer;
1.443 albertel 11145: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11146: my $symbseed=numval2($symb);
1.491 albertel 11147: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11148: my $CODEseed=numval(&getCODE());
1.443 albertel 11149: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11150: my $num1=$symbseed+$CODEchck;
11151: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11152: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11153: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11154: if ($_64bit) { $num1=(($num1<<32)>>32); }
11155: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11156: return "$num1:$num2";
1.366 albertel 11157: }
11158: }
11159:
1.575 albertel 11160: sub rndseed_CODE_64bit4 {
11161: my ($symb,$courseid,$domain,$username)=@_;
11162: {
11163: use integer;
11164: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11165: my $symbseed=numval3($symb);
11166: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11167: my $CODEseed=numval3(&getCODE());
11168: my $courseseed=unpack("%32S*",$courseid.' ');
11169: my $num1=$symbseed+$CODEchck;
11170: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11171: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11172: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11173: if ($_64bit) { $num1=(($num1<<32)>>32); }
11174: if ($_64bit) { $num2=(($num2<<32)>>32); }
11175: return "$num1:$num2";
11176: }
11177: }
11178:
1.675 albertel 11179: sub rndseed_CODE_64bit5 {
11180: my ($symb,$courseid,$domain,$username)=@_;
11181: my $code = &getCODE();
11182: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11183: return "$num1:$num2";
11184: }
11185:
1.366 albertel 11186: sub setup_random_from_rndseed {
11187: my ($rndseed)=@_;
1.503 albertel 11188: if ($rndseed =~/([,:])/) {
11189: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 11190: &Math::Random::random_set_seed(abs($num1),abs($num2));
11191: } else {
11192: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11193: }
1.36 albertel 11194: }
11195:
1.474 albertel 11196: sub latest_receipt_algorithm_id {
1.835 albertel 11197: return 'receipt3';
1.474 albertel 11198: }
11199:
1.480 www 11200: sub recunique {
11201: my $fucourseid=shift;
11202: my $unique;
1.835 albertel 11203: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11204: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11205: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11206: } else {
11207: $unique=$perlvar{'lonReceipt'};
11208: }
11209: return unpack("%32C*",$unique);
11210: }
11211:
11212: sub recprefix {
11213: my $fucourseid=shift;
11214: my $prefix;
1.835 albertel 11215: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11216: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11217: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11218: } else {
11219: $prefix=$perlvar{'lonHostID'};
11220: }
11221: return unpack("%32C*",$prefix);
11222: }
11223:
1.76 www 11224: sub ireceipt {
1.474 albertel 11225: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11226:
11227: my $return =&recprefix($fucourseid).'-';
11228:
11229: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11230: $env{'request.state'} eq 'construct') {
11231: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11232: return $return;
11233: }
11234:
1.76 www 11235: my $cuname=unpack("%32C*",$funame);
11236: my $cudom=unpack("%32C*",$fudom);
11237: my $cucourseid=unpack("%32C*",$fucourseid);
11238: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11239: my $cunique=&recunique($fucourseid);
1.474 albertel 11240: my $cpart=unpack("%32S*",$part);
1.835 albertel 11241: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11242:
1.790 albertel 11243: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11244:
11245: $return.= ($cunique%$cuname+
11246: $cunique%$cudom+
11247: $cusymb%$cuname+
11248: $cusymb%$cudom+
11249: $cucourseid%$cuname+
11250: $cucourseid%$cudom+
11251: $cpart%$cuname+
11252: $cpart%$cudom);
11253: } else {
11254: $return.= ($cunique%$cuname+
11255: $cunique%$cudom+
11256: $cusymb%$cuname+
11257: $cusymb%$cudom+
11258: $cucourseid%$cuname+
11259: $cucourseid%$cudom);
11260: }
11261: return $return;
1.76 www 11262: }
11263:
11264: sub receipt {
1.474 albertel 11265: my ($part)=@_;
1.790 albertel 11266: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11267: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11268: }
1.260 ng 11269:
1.790 albertel 11270: sub whichuser {
11271: my ($passedsymb)=@_;
11272: my ($symb,$courseid,$domain,$name,$publicuser);
11273: if (defined($env{'form.grade_symb'})) {
11274: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11275: my $allowed=&allowed('vgr',$tmp_courseid);
11276: if (!$allowed &&
11277: exists($env{'request.course.sec'}) &&
11278: $env{'request.course.sec'} !~ /^\s*$/) {
11279: $allowed=&allowed('vgr',$tmp_courseid.
11280: '/'.$env{'request.course.sec'});
11281: }
11282: if ($allowed) {
11283: ($symb)=&get_env_multiple('form.grade_symb');
11284: $courseid=$tmp_courseid;
11285: ($domain)=&get_env_multiple('form.grade_domain');
11286: ($name)=&get_env_multiple('form.grade_username');
11287: return ($symb,$courseid,$domain,$name,$publicuser);
11288: }
11289: }
11290: if (!$passedsymb) {
11291: $symb=&symbread();
11292: } else {
11293: $symb=$passedsymb;
11294: }
11295: $courseid=$env{'request.course.id'};
11296: $domain=$env{'user.domain'};
11297: $name=$env{'user.name'};
11298: if ($name eq 'public' && $domain eq 'public') {
11299: if (!defined($env{'form.username'})) {
11300: $env{'form.username'}.=time.rand(10000000);
11301: }
11302: $name.=$env{'form.username'};
11303: }
11304: return ($symb,$courseid,$domain,$name,$publicuser);
11305:
11306: }
11307:
1.36 albertel 11308: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11309: # returns either the contents of the file or
11310: # -1 if the file doesn't exist
1.481 raeburn 11311: #
11312: # if the target is a file that was uploaded via DOCS,
11313: # a check will be made to see if a current copy exists on the local server,
11314: # if it does this will be served, otherwise a copy will be retrieved from
11315: # the home server for the course and stored in /home/httpd/html/userfiles on
11316: # the local server.
1.472 albertel 11317:
1.36 albertel 11318: sub getfile {
1.538 albertel 11319: my ($file) = @_;
1.609 banghart 11320: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11321: &repcopy($file);
11322: return &readfile($file);
11323: }
11324:
11325: sub repcopy_userfile {
11326: my ($file)=@_;
1.1142 raeburn 11327: my $londocroot = $perlvar{'lonDocRoot'};
11328: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11329: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11330: my ($cdom,$cnum,$filename) =
1.811 albertel 11331: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11332: my $uri="/uploaded/$cdom/$cnum/$filename";
11333: if (-e "$file") {
1.828 www 11334: # we already have a local copy, check it out
1.538 albertel 11335: my @fileinfo = stat($file);
1.828 www 11336: my $rtncode;
11337: my $info;
1.538 albertel 11338: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11339: if ($lwpresp ne 'ok') {
1.828 www 11340: # there is no such file anymore, even though we had a local copy
1.482 albertel 11341: if ($rtncode eq '404') {
1.538 albertel 11342: unlink($file);
1.482 albertel 11343: }
11344: return -1;
11345: }
11346: if ($info < $fileinfo[9]) {
1.828 www 11347: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11348: return 'ok';
1.828 www 11349: } else {
11350: # the file is outdated, get rid of it
11351: unlink($file);
1.482 albertel 11352: }
1.828 www 11353: }
11354: # one way or the other, at this point, we don't have the file
11355: # construct the correct path for the file
11356: my @parts = ($cdom,$cnum);
11357: if ($filename =~ m|^(.+)/[^/]+$|) {
11358: push @parts, split(/\//,$1);
11359: }
11360: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11361: foreach my $part (@parts) {
11362: $path .= '/'.$part;
11363: if (!-e $path) {
11364: mkdir($path,0770);
1.482 albertel 11365: }
11366: }
1.828 www 11367: # now the path exists for sure
11368: # get a user agent
11369: my $ua=new LWP::UserAgent;
11370: my $transferfile=$file.'.in.transfer';
11371: # FIXME: this should flock
11372: if (-e $transferfile) { return 'ok'; }
11373: my $request;
11374: $uri=~s/^\///;
1.980 raeburn 11375: my $homeserver = &homeserver($cnum,$cdom);
11376: my $protocol = $protocol{$homeserver};
11377: $protocol = 'http' if ($protocol ne 'https');
11378: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11379: my $response=$ua->request($request,$transferfile);
11380: # did it work?
11381: if ($response->is_error()) {
11382: unlink($transferfile);
11383: &logthis("Userfile repcopy failed for $uri");
11384: return -1;
11385: }
11386: # worked, rename the transfer file
11387: rename($transferfile,$file);
1.607 raeburn 11388: return 'ok';
1.481 raeburn 11389: }
11390:
1.517 albertel 11391: sub tokenwrapper {
11392: my $uri=shift;
1.980 raeburn 11393: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11394: $uri=~s|^/||;
1.620 albertel 11395: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11396: my $token=$1;
1.552 albertel 11397: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11398: if ($udom && $uname && $file) {
11399: $file=~s|(\?\.*)*$||;
1.949 raeburn 11400: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11401: my $homeserver = &homeserver($uname,$udom);
11402: my $protocol = $protocol{$homeserver};
11403: $protocol = 'http' if ($protocol ne 'https');
11404: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11405: (($uri=~/\?/)?'&':'?').'token='.$token.
11406: '&tokenissued='.$perlvar{'lonHostID'};
11407: } else {
11408: return '/adm/notfound.html';
11409: }
11410: }
11411:
1.828 www 11412: # call with reqtype HEAD: get last modification time
11413: # call with reqtype GET: get the file contents
11414: # Do not call this with reqtype GET for large files! It loads everything into memory
11415: #
1.481 raeburn 11416: sub getuploaded {
11417: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11418: $uri=~s/^\///;
1.980 raeburn 11419: my $homeserver = &homeserver($cnum,$cdom);
11420: my $protocol = $protocol{$homeserver};
11421: $protocol = 'http' if ($protocol ne 'https');
11422: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11423: my $ua=new LWP::UserAgent;
11424: my $request=new HTTP::Request($reqtype,$uri);
11425: my $response=$ua->request($request);
11426: $$rtncode = $response->code;
1.482 albertel 11427: if (! $response->is_success()) {
11428: return 'failed';
11429: }
11430: if ($reqtype eq 'HEAD') {
1.486 www 11431: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11432: } elsif ($reqtype eq 'GET') {
11433: $$info = $response->content;
1.472 albertel 11434: }
1.482 albertel 11435: return 'ok';
1.36 albertel 11436: }
11437:
1.481 raeburn 11438: sub readfile {
11439: my $file = shift;
11440: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11441: my $fh;
11442: open($fh,"<$file");
11443: my $a='';
1.800 albertel 11444: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11445: return $a;
11446: }
11447:
1.36 albertel 11448: sub filelocation {
1.590 banghart 11449: my ($dir,$file) = @_;
11450: my $location;
11451: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11452:
11453: if ($file =~ m-^/adm/-) {
11454: $file=~s-^/adm/wrapper/-/-;
11455: $file=~s-^/adm/coursedocs/showdoc/-/-;
11456: }
1.882 albertel 11457:
1.1139 www 11458: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11459: $location = $file;
1.609 banghart 11460: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11461: my ($udom,$uname,$filename)=
1.811 albertel 11462: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11463: my $home=&homeserver($uname,$udom);
11464: my $is_me=0;
11465: my @ids=¤t_machine_ids();
11466: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11467: if ($is_me) {
1.1117 foxr 11468: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11469: } else {
11470: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11471: $udom.'/'.$uname.'/'.$filename;
11472: }
1.882 albertel 11473: } elsif ($file =~ m-^/adm/-) {
11474: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11475: } else {
11476: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11477: $file=~s:^/(res|priv)/:/:;
11478: my $space=$1;
1.590 banghart 11479: if ( !( $file =~ m:^/:) ) {
11480: $location = $dir. '/'.$file;
11481: } else {
1.1142 raeburn 11482: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11483: }
1.59 albertel 11484: }
1.590 banghart 11485: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11486: while ($location=~m{/\.\./}) {
11487: if ($location =~ m{/[^/]+/\.\./}) {
11488: $location=~ s{/[^/]+/\.\./}{/}g;
11489: } else {
11490: $location=~ s{/\.\./}{/}g;
11491: }
11492: } #remove dir/..
1.590 banghart 11493: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11494: return $location;
1.46 www 11495: }
1.36 albertel 11496:
1.46 www 11497: sub hreflocation {
11498: my ($dir,$file)=@_;
1.980 raeburn 11499: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11500: $file=filelocation($dir,$file);
1.700 albertel 11501: } elsif ($file=~m-^/adm/-) {
11502: $file=~s-^/adm/wrapper/-/-;
11503: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11504: }
11505: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11506: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11507: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11508: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11509: {/uploaded/$1/$2/}x;
1.46 www 11510: }
1.913 albertel 11511: if ($file=~ m{^/userfiles/}) {
11512: $file =~ s{^/userfiles/}{/uploaded/};
11513: }
1.462 albertel 11514: return $file;
1.465 albertel 11515: }
11516:
1.1139 www 11517:
11518:
11519:
11520:
1.465 albertel 11521: sub current_machine_domains {
1.853 albertel 11522: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11523: }
11524:
11525: sub machine_domains {
11526: my ($hostname) = @_;
1.465 albertel 11527: my @domains;
1.838 albertel 11528: my %hostname = &all_hostnames();
1.465 albertel 11529: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11530: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11531: if ($hostname eq $name) {
1.844 albertel 11532: push(@domains,&host_domain($id));
1.465 albertel 11533: }
11534: }
11535: return @domains;
11536: }
11537:
11538: sub current_machine_ids {
1.853 albertel 11539: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11540: }
11541:
11542: sub machine_ids {
11543: my ($hostname) = @_;
11544: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11545: my @ids;
1.888 albertel 11546: my %name_to_host = &all_names();
1.889 albertel 11547: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11548: return @{ $name_to_host{$hostname} };
11549: }
11550: return;
1.31 www 11551: }
11552:
1.824 raeburn 11553: sub additional_machine_domains {
11554: my @domains;
11555: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11556: while( my $line = <$fh>) {
11557: $line =~ s/\s//g;
11558: push(@domains,$line);
11559: }
11560: return @domains;
11561: }
11562:
11563: sub default_login_domain {
11564: my $domain = $perlvar{'lonDefDomain'};
11565: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11566: foreach my $posdom (¤t_machine_domains(),
11567: &additional_machine_domains()) {
11568: if (lc($posdom) eq lc($testdomain)) {
11569: $domain=$posdom;
11570: last;
11571: }
11572: }
11573: return $domain;
11574: }
11575:
1.31 www 11576: # ------------------------------------------------------------- Declutters URLs
11577:
11578: sub declutter {
11579: my $thisfn=shift;
1.569 albertel 11580: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 11581: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 11582: $thisfn=~s/^\///;
1.697 albertel 11583: $thisfn=~s|^adm/wrapper/||;
11584: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11585: $thisfn=~s/^res\///;
1.1172 bisitz 11586: $thisfn=~s/^priv\///;
1.1032 raeburn 11587: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11588: $thisfn=~s/\?.+$//;
11589: }
1.268 www 11590: return $thisfn;
11591: }
11592:
11593: # ------------------------------------------------------------- Clutter up URLs
11594:
11595: sub clutter {
11596: my $thisfn='/'.&declutter(shift);
1.887 albertel 11597: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11598: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11599: $thisfn='/res'.$thisfn;
11600: }
1.1031 raeburn 11601: if ($thisfn !~m|^/adm|) {
11602: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11603: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11604: } else {
11605: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11606: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11607: if ($embstyle eq 'ssi'
11608: || ($embstyle eq 'hdn')
11609: || ($embstyle eq 'rat')
11610: || ($embstyle eq 'prv')
11611: || ($embstyle eq 'ign')) {
11612: #do nothing with these
11613: } elsif (($embstyle eq 'img')
1.695 albertel 11614: || ($embstyle eq 'emb')
11615: || ($embstyle eq 'wrp')) {
11616: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11617: } elsif ($embstyle eq 'unk'
11618: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11619: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11620: } else {
1.718 www 11621: # &logthis("Got a blank emb style");
1.695 albertel 11622: }
1.694 albertel 11623: }
11624: }
1.31 www 11625: return $thisfn;
1.12 www 11626: }
11627:
1.787 albertel 11628: sub clutter_with_no_wrapper {
11629: my $uri = &clutter(shift);
11630: if ($uri =~ m-^/adm/-) {
11631: $uri =~ s-^/adm/wrapper/-/-;
11632: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11633: }
11634: return $uri;
11635: }
11636:
1.557 albertel 11637: sub freeze_escape {
11638: my ($value)=@_;
11639: if (ref($value)) {
11640: $value=&nfreeze($value);
11641: return '__FROZEN__'.&escape($value);
11642: }
11643: return &escape($value);
11644: }
11645:
1.11 www 11646:
1.557 albertel 11647: sub thaw_unescape {
11648: my ($value)=@_;
11649: if ($value =~ /^__FROZEN__/) {
11650: substr($value,0,10,undef);
11651: $value=&unescape($value);
11652: return &thaw($value);
11653: }
11654: return &unescape($value);
11655: }
11656:
1.436 albertel 11657: sub correct_line_ends {
11658: my ($result)=@_;
11659: $$result =~s/\r\n/\n/mg;
11660: $$result =~s/\r/\n/mg;
1.415 albertel 11661: }
1.1 albertel 11662: # ================================================================ Main Program
11663:
1.184 www 11664: sub goodbye {
1.204 albertel 11665: &logthis("Starting Shut down");
1.443 albertel 11666: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11667: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11668: #converted
1.599 albertel 11669: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11670: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11671: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11672: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11673: #1.1 only
1.870 albertel 11674: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11675: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11676: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11677: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11678: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11679: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11680: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11681: &flushcourselogs();
11682: &logthis("Shutting down");
11683: }
11684:
1.852 albertel 11685: sub get_dns {
1.1210 raeburn 11686: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11687: if (!$ignore_cache) {
11688: my ($content,$cached)=
11689: &Apache::lonnet::is_cached_new('dns',$url);
11690: if ($cached) {
1.1210 raeburn 11691: &$func($content,$hashref);
1.869 albertel 11692: return;
11693: }
11694: }
11695:
11696: my %alldns;
1.852 albertel 11697: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11698: foreach my $dns (<$config>) {
11699: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11700: my $line = $1;
11701: my ($host,$protocol) = split(/:/,$line);
11702: if ($protocol ne 'https') {
11703: $protocol = 'http';
11704: }
11705: $alldns{$host} = $protocol;
1.869 albertel 11706: }
11707: while (%alldns) {
11708: my ($dns) = keys(%alldns);
1.852 albertel 11709: my $ua=new LWP::UserAgent;
1.1134 raeburn 11710: $ua->timeout(30);
1.979 raeburn 11711: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11712: my $response=$ua->request($request);
1.979 raeburn 11713: delete($alldns{$dns});
1.852 albertel 11714: next if ($response->is_error());
11715: my @content = split("\n",$response->content);
1.1210 raeburn 11716: unless ($nocache) {
1.1219 raeburn 11717: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 11718: }
11719: &$func(\@content,$hashref);
1.869 albertel 11720: return;
1.852 albertel 11721: }
11722: close($config);
1.871 albertel 11723: my $which = (split('/',$url))[3];
11724: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11725: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11726: my @content = <$config>;
1.1210 raeburn 11727: &$func(\@content,$hashref);
11728: return;
11729: }
11730:
11731: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 11732: sub parse_dns_checksums_tab {
1.1210 raeburn 11733: my ($lines,$hashref) = @_;
11734: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11735: my $loncaparev = &get_server_loncaparev($machine_dom);
11736: my ($release,$timestamp) = split(/\-/,$loncaparev);
11737: my (%chksum,%revnum);
11738: if (ref($lines) eq 'ARRAY') {
11739: chomp(@{$lines});
1.1238 raeburn 11740: my $version = shift(@{$lines});
11741: if ($version eq $release) {
1.1210 raeburn 11742: foreach my $line (@{$lines}) {
1.1238 raeburn 11743: my ($file,$version,$shasum) = split(/,/,$line);
11744: $chksum{$file} = $shasum;
11745: $revnum{$file} = $version;
1.1210 raeburn 11746: }
11747: if (ref($hashref) eq 'HASH') {
11748: %{$hashref} = (
11749: sums => \%chksum,
11750: versions => \%revnum,
11751: );
11752: }
11753: }
11754: }
1.869 albertel 11755: return;
1.852 albertel 11756: }
1.1210 raeburn 11757:
11758: sub fetch_dns_checksums {
1.1238 raeburn 11759: my %checksums;
11760: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11761: my $loncaparev = &get_server_loncaparev($machine_dom);
11762: my ($release,$timestamp) = split(/\-/,$loncaparev);
11763: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 11764: \%checksums);
1.1210 raeburn 11765: return \%checksums;
11766: }
11767:
1.327 albertel 11768: # ------------------------------------------------------------ Read domain file
11769: {
1.852 albertel 11770: my $loaded;
1.846 albertel 11771: my %domain;
11772:
1.852 albertel 11773: sub parse_domain_tab {
11774: my ($lines) = @_;
11775: foreach my $line (@$lines) {
11776: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11777:
1.846 albertel 11778: chomp($line);
1.852 albertel 11779: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11780: my %this_domain;
11781: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11782: 'lang_def', 'city', 'longi', 'lati',
11783: 'primary') {
11784: $this_domain{$field} = shift(@elements);
11785: }
11786: $domain{$name} = \%this_domain;
1.852 albertel 11787: }
11788: }
1.864 albertel 11789:
11790: sub reset_domain_info {
11791: undef($loaded);
11792: undef(%domain);
11793: }
11794:
1.852 albertel 11795: sub load_domain_tab {
1.869 albertel 11796: my ($ignore_cache) = @_;
11797: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11798: my $fh;
11799: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11800: my @lines = <$fh>;
11801: &parse_domain_tab(\@lines);
1.448 albertel 11802: }
1.852 albertel 11803: close($fh);
11804: $loaded = 1;
1.327 albertel 11805: }
1.846 albertel 11806:
11807: sub domain {
1.852 albertel 11808: &load_domain_tab() if (!$loaded);
11809:
1.846 albertel 11810: my ($name,$what) = @_;
11811: return if ( !exists($domain{$name}) );
11812:
11813: if (!$what) {
11814: return $domain{$name}{'description'};
11815: }
11816: return $domain{$name}{$what};
11817: }
1.974 raeburn 11818:
11819: sub domain_info {
11820: &load_domain_tab() if (!$loaded);
11821: return %domain;
11822: }
11823:
1.327 albertel 11824: }
11825:
11826:
1.1 albertel 11827: # ------------------------------------------------------------- Read hosts file
11828: {
1.838 albertel 11829: my %hostname;
1.844 albertel 11830: my %hostdom;
1.845 albertel 11831: my %libserv;
1.852 albertel 11832: my $loaded;
1.888 albertel 11833: my %name_to_host;
1.1074 raeburn 11834: my %internetdom;
1.1107 raeburn 11835: my %LC_dns_serv;
1.852 albertel 11836:
11837: sub parse_hosts_tab {
11838: my ($file) = @_;
11839: foreach my $configline (@$file) {
11840: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11841: chomp($configline);
11842: if ($configline =~ /^\^/) {
11843: if ($configline =~ /^\^([\w.\-]+)/) {
11844: $LC_dns_serv{$1} = 1;
11845: }
11846: next;
11847: }
1.1074 raeburn 11848: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11849: $name=~s/\s//g;
11850: if ($id && $domain && $role && $name) {
11851: $hostname{$id}=$name;
1.888 albertel 11852: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11853: $hostdom{$id}=$domain;
11854: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11855: if (defined($protocol)) {
11856: if ($protocol eq 'https') {
11857: $protocol{$id} = $protocol;
11858: } else {
11859: $protocol{$id} = 'http';
11860: }
1.968 raeburn 11861: } else {
1.969 raeburn 11862: $protocol{$id} = 'http';
1.968 raeburn 11863: }
1.1074 raeburn 11864: if (defined($intdom)) {
11865: $internetdom{$id} = $intdom;
11866: }
1.852 albertel 11867: }
11868: }
11869: }
1.864 albertel 11870:
11871: sub reset_hosts_info {
1.897 albertel 11872: &purge_remembered();
1.864 albertel 11873: &reset_domain_info();
11874: &reset_hosts_ip_info();
1.892 albertel 11875: undef(%name_to_host);
1.864 albertel 11876: undef(%hostname);
11877: undef(%hostdom);
11878: undef(%libserv);
11879: undef($loaded);
11880: }
1.1 albertel 11881:
1.852 albertel 11882: sub load_hosts_tab {
1.869 albertel 11883: my ($ignore_cache) = @_;
11884: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11885: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11886: my @config = <$config>;
11887: &parse_hosts_tab(\@config);
11888: close($config);
11889: $loaded=1;
1.1 albertel 11890: }
1.852 albertel 11891:
1.838 albertel 11892: sub hostname {
1.852 albertel 11893: &load_hosts_tab() if (!$loaded);
11894:
1.838 albertel 11895: my ($lonid) = @_;
11896: return $hostname{$lonid};
11897: }
1.845 albertel 11898:
1.838 albertel 11899: sub all_hostnames {
1.852 albertel 11900: &load_hosts_tab() if (!$loaded);
11901:
1.838 albertel 11902: return %hostname;
11903: }
1.845 albertel 11904:
1.888 albertel 11905: sub all_names {
11906: &load_hosts_tab() if (!$loaded);
11907:
11908: return %name_to_host;
11909: }
11910:
1.974 raeburn 11911: sub all_host_domain {
11912: &load_hosts_tab() if (!$loaded);
11913: return %hostdom;
11914: }
11915:
1.845 albertel 11916: sub is_library {
1.852 albertel 11917: &load_hosts_tab() if (!$loaded);
11918:
1.845 albertel 11919: return exists($libserv{$_[0]});
11920: }
11921:
11922: sub all_library {
1.852 albertel 11923: &load_hosts_tab() if (!$loaded);
11924:
1.845 albertel 11925: return %libserv;
11926: }
11927:
1.1062 droeschl 11928: sub unique_library {
11929: #2x reverse removes all hostnames that appear more than once
11930: my %unique = reverse &all_library();
11931: return reverse %unique;
11932: }
11933:
1.841 albertel 11934: sub get_servers {
1.852 albertel 11935: &load_hosts_tab() if (!$loaded);
11936:
1.841 albertel 11937: my ($domain,$type) = @_;
11938: my %possible_hosts = ($type eq 'library') ? %libserv
11939: : %hostname;
11940: my %result;
1.842 albertel 11941: if (ref($domain) eq 'ARRAY') {
11942: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 11943: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 11944: $result{$host} = $hostname;
11945: }
11946: }
11947: } else {
11948: while ( my ($host,$hostname) = each(%possible_hosts)) {
11949: if ($hostdom{$host} eq $domain) {
11950: $result{$host} = $hostname;
11951: }
1.841 albertel 11952: }
11953: }
11954: return %result;
11955: }
1.845 albertel 11956:
1.1062 droeschl 11957: sub get_unique_servers {
11958: my %unique = reverse &get_servers(@_);
11959: return reverse %unique;
11960: }
11961:
1.844 albertel 11962: sub host_domain {
1.852 albertel 11963: &load_hosts_tab() if (!$loaded);
11964:
1.844 albertel 11965: my ($lonid) = @_;
11966: return $hostdom{$lonid};
11967: }
11968:
1.841 albertel 11969: sub all_domains {
1.852 albertel 11970: &load_hosts_tab() if (!$loaded);
11971:
1.841 albertel 11972: my %seen;
11973: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11974: return @uniq;
11975: }
1.1074 raeburn 11976:
11977: sub internet_dom {
11978: &load_hosts_tab() if (!$loaded);
11979:
11980: my ($lonid) = @_;
11981: return $internetdom{$lonid};
11982: }
1.1107 raeburn 11983:
11984: sub is_LC_dns {
11985: &load_hosts_tab() if (!$loaded);
11986:
11987: my ($hostname) = @_;
11988: return exists($LC_dns_serv{$hostname});
11989: }
11990:
1.1 albertel 11991: }
11992:
1.847 albertel 11993: {
11994: my %iphost;
1.856 albertel 11995: my %name_to_ip;
11996: my %lonid_to_ip;
1.869 albertel 11997:
1.847 albertel 11998: sub get_hosts_from_ip {
11999: my ($ip) = @_;
12000: my %iphosts = &get_iphost();
12001: if (ref($iphosts{$ip})) {
12002: return @{$iphosts{$ip}};
12003: }
12004: return;
1.839 albertel 12005: }
1.864 albertel 12006:
12007: sub reset_hosts_ip_info {
12008: undef(%iphost);
12009: undef(%name_to_ip);
12010: undef(%lonid_to_ip);
12011: }
1.856 albertel 12012:
12013: sub get_host_ip {
12014: my ($lonid) = @_;
12015: if (exists($lonid_to_ip{$lonid})) {
12016: return $lonid_to_ip{$lonid};
12017: }
12018: my $name=&hostname($lonid);
12019: my $ip = gethostbyname($name);
12020: return if (!$ip || length($ip) ne 4);
12021: $ip=inet_ntoa($ip);
12022: $name_to_ip{$name} = $ip;
12023: $lonid_to_ip{$lonid} = $ip;
12024: return $ip;
12025: }
1.847 albertel 12026:
12027: sub get_iphost {
1.869 albertel 12028: my ($ignore_cache) = @_;
1.894 albertel 12029:
1.869 albertel 12030: if (!$ignore_cache) {
12031: if (%iphost) {
12032: return %iphost;
12033: }
12034: my ($ip_info,$cached)=
12035: &Apache::lonnet::is_cached_new('iphost','iphost');
12036: if ($cached) {
12037: %iphost = %{$ip_info->[0]};
12038: %name_to_ip = %{$ip_info->[1]};
12039: %lonid_to_ip = %{$ip_info->[2]};
12040: return %iphost;
12041: }
12042: }
1.894 albertel 12043:
12044: # get yesterday's info for fallback
12045: my %old_name_to_ip;
12046: my ($ip_info,$cached)=
12047: &Apache::lonnet::is_cached_new('iphost','iphost');
12048: if ($cached) {
12049: %old_name_to_ip = %{$ip_info->[1]};
12050: }
12051:
1.888 albertel 12052: my %name_to_host = &all_names();
12053: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12054: my $ip;
12055: if (!exists($name_to_ip{$name})) {
12056: $ip = gethostbyname($name);
12057: if (!$ip || length($ip) ne 4) {
1.894 albertel 12058: if (defined($old_name_to_ip{$name})) {
12059: $ip = $old_name_to_ip{$name};
12060: &logthis("Can't find $name defaulting to old $ip");
12061: } else {
12062: &logthis("Name $name no IP found");
12063: next;
12064: }
12065: } else {
12066: $ip=inet_ntoa($ip);
1.847 albertel 12067: }
12068: $name_to_ip{$name} = $ip;
12069: } else {
12070: $ip = $name_to_ip{$name};
1.653 albertel 12071: }
1.888 albertel 12072: foreach my $id (@{ $name_to_host{$name} }) {
12073: $lonid_to_ip{$id} = $ip;
12074: }
12075: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12076: }
1.1219 raeburn 12077: &do_cache_new('iphost','iphost',
12078: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12079: 48*60*60);
1.869 albertel 12080:
1.847 albertel 12081: return %iphost;
1.598 albertel 12082: }
12083:
1.992 raeburn 12084: #
12085: # Given a DNS returns the loncapa host name for that DNS
12086: #
12087: sub host_from_dns {
12088: my ($dns) = @_;
12089: my @hosts;
12090: my $ip;
12091:
1.993 raeburn 12092: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12093: $ip = $name_to_ip{$dns};
12094: }
12095: if (!$ip) {
12096: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12097: if (length($ip) == 4) {
12098: $ip = &IO::Socket::inet_ntoa($ip);
12099: }
12100: }
12101: if ($ip) {
12102: @hosts = get_hosts_from_ip($ip);
12103: return $hosts[0];
12104: }
12105: return undef;
1.986 foxr 12106: }
1.992 raeburn 12107:
1.1074 raeburn 12108: sub get_internet_names {
12109: my ($lonid) = @_;
12110: return if ($lonid eq '');
12111: my ($idnref,$cached)=
12112: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12113: if ($cached) {
12114: return $idnref;
12115: }
12116: my $ip = &get_host_ip($lonid);
12117: my @hosts = &get_hosts_from_ip($ip);
12118: my %iphost = &get_iphost();
12119: my (@idns,%seen);
12120: foreach my $id (@hosts) {
12121: my $dom = &host_domain($id);
12122: my $prim_id = &domain($dom,'primary');
12123: my $prim_ip = &get_host_ip($prim_id);
12124: next if ($seen{$prim_ip});
12125: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12126: foreach my $id (@{$iphost{$prim_ip}}) {
12127: my $intdom = &internet_dom($id);
12128: unless (grep(/^\Q$intdom\E$/,@idns)) {
12129: push(@idns,$intdom);
12130: }
12131: }
12132: }
12133: $seen{$prim_ip} = 1;
12134: }
1.1219 raeburn 12135: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12136: }
12137:
1.986 foxr 12138: }
12139:
1.1079 raeburn 12140: sub all_loncaparevs {
12141: 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);
12142: }
12143:
1.1227 raeburn 12144: # ---------------------------------------------------------- Read loncaparev table
12145: {
12146: sub load_loncaparevs {
12147: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12148: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12149: while (my $configline=<$config>) {
12150: chomp($configline);
12151: my ($hostid,$loncaparev)=split(/:/,$configline);
12152: $loncaparevs{$hostid}=$loncaparev;
12153: }
12154: close($config);
12155: }
12156: }
12157: }
12158: }
12159:
12160: # ---------------------------------------------------------- Read serverhostID table
12161: {
12162: sub load_serverhomeIDs {
12163: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12164: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12165: while (my $configline=<$config>) {
12166: chomp($configline);
12167: my ($name,$id)=split(/:/,$configline);
12168: $serverhomeIDs{$name}=$id;
12169: }
12170: close($config);
12171: }
12172: }
12173: }
12174: }
12175:
12176:
1.862 albertel 12177: BEGIN {
12178:
12179: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12180: unless ($readit) {
12181: {
12182: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12183: %perlvar = (%perlvar,%{$configvars});
12184: }
12185:
12186:
1.1 albertel 12187: # ------------------------------------------------------ Read spare server file
12188: {
1.448 albertel 12189: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12190:
12191: while (my $configline=<$config>) {
12192: chomp($configline);
1.284 matthew 12193: if ($configline) {
1.784 albertel 12194: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12195: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12196: push(@{ $spareid{$type} }, $host);
1.1 albertel 12197: }
12198: }
1.448 albertel 12199: close($config);
1.1 albertel 12200: }
1.11 www 12201: # ------------------------------------------------------------ Read permissions
12202: {
1.448 albertel 12203: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12204:
12205: while (my $configline=<$config>) {
1.448 albertel 12206: chomp($configline);
12207: if ($configline) {
12208: my ($role,$perm)=split(/ /,$configline);
12209: if ($perm ne '') { $pr{$role}=$perm; }
12210: }
1.11 www 12211: }
1.448 albertel 12212: close($config);
1.11 www 12213: }
12214:
12215: # -------------------------------------------- Read plain texts for permissions
12216: {
1.448 albertel 12217: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12218:
12219: while (my $configline=<$config>) {
1.448 albertel 12220: chomp($configline);
12221: if ($configline) {
1.742 raeburn 12222: my ($short,@plain)=split(/:/,$configline);
12223: %{$prp{$short}} = ();
12224: if (@plain > 0) {
12225: $prp{$short}{'std'} = $plain[0];
12226: for (my $i=1; $i<@plain; $i++) {
12227: $prp{$short}{'alt'.$i} = $plain[$i];
12228: }
12229: }
1.448 albertel 12230: }
1.135 www 12231: }
1.448 albertel 12232: close($config);
1.135 www 12233: }
12234:
12235: # ---------------------------------------------------------- Read package table
12236: {
1.448 albertel 12237: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12238:
12239: while (my $configline=<$config>) {
1.483 albertel 12240: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12241: chomp($configline);
12242: my ($short,$plain)=split(/:/,$configline);
12243: my ($pack,$name)=split(/\&/,$short);
12244: if ($plain ne '') {
12245: $packagetab{$pack.'&'.$name.'&name'}=$name;
12246: $packagetab{$short}=$plain;
12247: }
1.11 www 12248: }
1.448 albertel 12249: close($config);
1.329 matthew 12250: }
12251:
1.1073 raeburn 12252: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 12253:
12254: &load_loncaparevs();
1.1073 raeburn 12255:
1.1074 raeburn 12256: # ---------------------------------------------------------- Read serverhostID table
12257:
1.1227 raeburn 12258: &load_serverhomeIDs();
12259:
12260: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12261: {
12262: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12263: if (-e $file) {
12264: my $parser = HTML::LCParser->new($file);
12265: while (my $token = $parser->get_token()) {
12266: if ($token->[0] eq 'S') {
12267: my $item = $token->[1];
12268: my $name = $token->[2]{'name'};
12269: my $value = $token->[2]{'value'};
12270: if ($item ne '' && $name ne '' && $value ne '') {
12271: my $release = $parser->get_text();
12272: $release =~ s/(^\s*|\s*$ )//gx;
12273: $needsrelease{$item.':'.$name.':'.$value} = $release;
12274: }
12275: }
12276: }
12277: }
1.1073 raeburn 12278: }
12279:
1.1138 raeburn 12280: # ---------------------------------------------------------- Read managers table
12281: {
12282: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12283: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12284: while (my $configline=<$config>) {
12285: chomp($configline);
12286: next if ($configline =~ /^\#/);
12287: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12288: $managerstab{$configline} = 1;
12289: }
12290: }
12291: close($config);
12292: }
12293: }
12294: }
12295:
1.329 matthew 12296: # ------------- set up temporary directory
12297: {
1.1117 foxr 12298: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12299:
1.11 www 12300: }
12301:
1.794 albertel 12302: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12303: 'compress_threshold'=> 20_000,
12304: });
1.185 www 12305:
1.281 www 12306: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12307: $dumpcount=0;
1.958 www 12308: $locknum=0;
1.22 www 12309:
1.163 harris41 12310: &logtouch();
1.672 albertel 12311: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12312: $readit=1;
1.564 albertel 12313: {
12314: use integer;
12315: my $test=(2**32)+1;
1.568 albertel 12316: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12317: &logthis(" Detected 64bit platform ($_64bit)");
12318: }
1.1214 raeburn 12319:
12320: {
12321: eval {
12322: ($apache) =
12323: (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
12324: };
12325: if ($@) {
12326: $apache = 1.3;
1.1213 raeburn 12327: }
12328: }
1.1214 raeburn 12329:
1.195 www 12330: }
1.1 albertel 12331: }
1.179 www 12332:
1.1 albertel 12333: 1;
1.191 harris41 12334: __END__
12335:
1.243 albertel 12336: =pod
12337:
1.191 harris41 12338: =head1 NAME
12339:
1.243 albertel 12340: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12341:
12342: =head1 SYNOPSIS
12343:
1.243 albertel 12344: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12345:
12346: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12347:
1.243 albertel 12348: Common parameters:
12349:
12350: =over 4
12351:
12352: =item *
12353:
12354: $uname : an internal username (if $cname expecting a course Id specifically)
12355:
12356: =item *
12357:
12358: $udom : a domain (if $cdom expecting a course's domain specifically)
12359:
12360: =item *
12361:
12362: $symb : a resource instance identifier
12363:
12364: =item *
12365:
12366: $namespace : the name of a .db file that contains the data needed or
12367: being set.
12368:
12369: =back
12370:
1.394 bowersj2 12371: =head1 OVERVIEW
1.191 harris41 12372:
1.394 bowersj2 12373: lonnet provides subroutines which interact with the
12374: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12375: about classes, users, and resources.
1.243 albertel 12376:
12377: For many of these objects you can also use this to store data about
12378: them or modify them in various ways.
1.191 harris41 12379:
1.394 bowersj2 12380: =head2 Symbs
1.191 harris41 12381:
1.394 bowersj2 12382: To identify a specific instance of a resource, LON-CAPA uses symbols
12383: or "symbs"X<symb>. These identifiers are built from the URL of the
12384: map, the resource number of the resource in the map, and the URL of
12385: the resource itself. The latter is somewhat redundant, but might help
12386: if maps change.
12387:
12388: An example is
12389:
12390: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12391:
12392: The respective map entry is
12393:
12394: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12395: title="Problem 2">
12396: </resource>
12397:
12398: Symbs are used by the random number generator, as well as to store and
12399: restore data specific to a certain instance of for example a problem.
12400:
12401: =head2 Storing And Retrieving Data
12402:
12403: X<store()>X<cstore()>X<restore()>Three of the most important functions
12404: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12405: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12406: is is the non-critical message twin of cstore. These functions are for
12407: handlers to store a perl hash to a user's permanent data space in an
12408: easy manner, and to retrieve it again on another call. It is expected
12409: that a handler would use this once at the beginning to retrieve data,
12410: and then again once at the end to send only the new data back.
12411:
12412: The data is stored in the user's data directory on the user's
12413: homeserver under the ID of the course.
12414:
12415: The hash that is returned by restore will have all of the previous
12416: value for all of the elements of the hash.
12417:
12418: Example:
12419:
12420: #creating a hash
12421: my %hash;
12422: $hash{'foo'}='bar';
12423:
12424: #storing it
12425: &Apache::lonnet::cstore(\%hash);
12426:
12427: #changing a value
12428: $hash{'foo'}='notbar';
12429:
12430: #adding a new value
12431: $hash{'bar'}='foo';
12432: &Apache::lonnet::cstore(\%hash);
12433:
12434: #retrieving the hash
12435: my %history=&Apache::lonnet::restore();
12436:
12437: #print the hash
12438: foreach my $key (sort(keys(%history))) {
12439: print("\%history{$key} = $history{$key}");
12440: }
12441:
12442: Will print out:
1.191 harris41 12443:
1.394 bowersj2 12444: %history{1:foo} = bar
12445: %history{1:keys} = foo:timestamp
12446: %history{1:timestamp} = 990455579
12447: %history{2:bar} = foo
12448: %history{2:foo} = notbar
12449: %history{2:keys} = foo:bar:timestamp
12450: %history{2:timestamp} = 990455580
12451: %history{bar} = foo
12452: %history{foo} = notbar
12453: %history{timestamp} = 990455580
12454: %history{version} = 2
12455:
12456: Note that the special hash entries C<keys>, C<version> and
12457: C<timestamp> were added to the hash. C<version> will be equal to the
12458: total number of versions of the data that have been stored. The
12459: C<timestamp> attribute will be the UNIX time the hash was
12460: stored. C<keys> is available in every historical section to list which
12461: keys were added or changed at a specific historical revision of a
12462: hash.
12463:
12464: B<Warning>: do not store the hash that restore returns directly. This
12465: will cause a mess since it will restore the historical keys as if the
12466: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12467:
1.394 bowersj2 12468: Calling convention:
1.191 harris41 12469:
1.1225 raeburn 12470: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12471: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12472:
1.394 bowersj2 12473: For more detailed information, see lonnet specific documentation.
1.191 harris41 12474:
1.394 bowersj2 12475: =head1 RETURN MESSAGES
1.191 harris41 12476:
1.394 bowersj2 12477: =over 4
1.191 harris41 12478:
1.394 bowersj2 12479: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12480:
1.394 bowersj2 12481: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12482: when the connection is brought back up
1.191 harris41 12483:
1.394 bowersj2 12484: =item * B<con_failed>: unable to contact remote host and unable to save message
12485: for later delivery
1.191 harris41 12486:
1.967 bisitz 12487: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12488:
1.394 bowersj2 12489: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12490: that was requested
1.191 harris41 12491:
1.243 albertel 12492: =back
1.191 harris41 12493:
1.243 albertel 12494: =head1 PUBLIC SUBROUTINES
1.191 harris41 12495:
1.243 albertel 12496: =head2 Session Environment Functions
1.191 harris41 12497:
1.243 albertel 12498: =over 4
1.191 harris41 12499:
1.394 bowersj2 12500: =item *
12501: X<appenv()>
1.949 raeburn 12502: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12503: the user envirnoment file, and will be restored for each access this
1.620 albertel 12504: user makes during this session, also modifies the %env for the current
1.949 raeburn 12505: process. Optional rolesarrayref - if defined contains a reference to an array
12506: of roles which are exempt from the restriction on modifying user.role entries
12507: in the user's environment.db and in %env.
1.191 harris41 12508:
12509: =item *
1.394 bowersj2 12510: X<delenv()>
1.987 raeburn 12511: B<delenv($delthis,$regexp)>: removes all items from the session
12512: environment file that begin with $delthis. If the
12513: optional second arg - $regexp - is true, $delthis is treated as a
12514: regular expression, otherwise \Q$delthis\E is used.
12515: The values are also deleted from the current processes %env.
1.191 harris41 12516:
1.795 albertel 12517: =item * get_env_multiple($name)
12518:
12519: gets $name from the %env hash, it seemlessly handles the cases where multiple
12520: values may be defined and end up as an array ref.
12521:
12522: returns an array of values
12523:
1.243 albertel 12524: =back
12525:
12526: =head2 User Information
1.191 harris41 12527:
1.243 albertel 12528: =over 4
1.191 harris41 12529:
12530: =item *
1.394 bowersj2 12531: X<queryauthenticate()>
12532: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12533: authentication scheme
12534:
12535: =item *
1.394 bowersj2 12536: X<authenticate()>
1.1073 raeburn 12537: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12538: authenticate user from domain's lib servers (first use the current
12539: one). C<$upass> should be the users password.
1.1073 raeburn 12540: $checkdefauth is optional (value is 1 if a check should be made to
12541: authenticate user using default authentication method, and allow
12542: account creation if username does not have account in the domain).
12543: $clientcancheckhost is optional (value is 1 if checking whether the
12544: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12545:
12546: =item *
1.394 bowersj2 12547: X<homeserver()>
12548: B<homeserver($uname,$udom)>: find the server which has
12549: the user's directory and files (there must be only one), this caches
12550: the answer, and also caches if there is a borken connection.
1.191 harris41 12551:
12552: =item *
1.394 bowersj2 12553: X<idget()>
12554: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12555: (IDs are a unique resource in a domain, there must be only 1 ID per
12556: username, and only 1 username per ID in a specific domain) (returns
12557: hash: id=>name,id=>name)
1.191 harris41 12558:
12559: =item *
1.394 bowersj2 12560: X<idrget()>
12561: B<idrget($udom,@unames)>: find the IDs behind a list of
12562: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12563:
12564: =item *
1.394 bowersj2 12565: X<idput()>
12566: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12567:
12568: =item *
1.394 bowersj2 12569: X<rolesinit()>
1.1169 droeschl 12570: B<rolesinit($udom,$username)>: get user privileges.
12571: returns user role, first access and timer interval hashes
1.243 albertel 12572:
12573: =item *
1.1171 droeschl 12574: X<privileged()>
12575: B<privileged($username,$domain)>: returns a true if user has a
12576: privileged and active role (i.e. su or dc), false otherwise.
12577:
12578: =item *
1.551 albertel 12579: X<getsection()>
12580: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12581: course $cname, return section name/number or '' for "not in course"
12582: and '-1' for "no section"
12583:
12584: =item *
1.394 bowersj2 12585: X<userenvironment()>
12586: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12587: passed in @what from the requested user's environment, returns a hash
12588:
1.858 raeburn 12589: =item *
12590: X<userlog_query()>
1.859 albertel 12591: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12592: activity.log file. %filters defines filters applied when parsing the
12593: log file. These can be start or end timestamps, or the type of action
12594: - log to look for Login or Logout events, check for Checkin or
12595: Checkout, role for role selection. The response is in the form
12596: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12597: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12598:
1.243 albertel 12599: =back
12600:
12601: =head2 User Roles
12602:
12603: =over 4
12604:
12605: =item *
12606:
1.810 raeburn 12607: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12608: F: full access
12609: U,I,K: authentication modes (cxx only)
12610: '': forbidden
12611: 1: user needs to choose course
12612: 2: browse allowed
1.766 albertel 12613: A: passphrase authentication needed
1.243 albertel 12614:
12615: =item *
12616:
1.1192 raeburn 12617: constructaccess($url,$setpriv) : check for access to construction space URL
12618:
12619: See if the owner domain and name in the URL match those in the
12620: expected environment. If so, return three element list
12621: ($ownername,$ownerdomain,$ownerhome).
12622:
12623: Otherwise return the null string.
12624:
12625: If second argument 'setpriv' is true, it assigns the privileges,
12626: and returns the same three element list, unless the owner has
12627: blocked "ad hoc" Domain Coordinator access to the Author Space,
12628: in which case the null string is returned.
12629:
12630: =item *
12631:
1.243 albertel 12632: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12633: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12634: and course level
12635:
12636: =item *
12637:
1.988 raeburn 12638: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12639: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12640: $type is Course (default) or Community.
1.988 raeburn 12641: If $forcedefault evaluates to true, text returned will be default
12642: text for $type. Otherwise, if this is a course, the text returned
12643: will be a custom name for the role (if defined in the course's
12644: environment). If no custom name is defined the default is returned.
12645:
1.832 raeburn 12646: =item *
12647:
1.1219 raeburn 12648: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12649: All arguments are optional. Returns a hash of a roles, either for
12650: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12651: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12652: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12653: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12654: For each key, value is set to colon-separated start and end times for
12655: the role. If no username and domain are specified, will default to
1.934 raeburn 12656: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12657: of role statuses (active, future or previous), roles
12658: (e.g., cc,in, st etc.) and domains of the roles which can be used
12659: to restrict the list of roles reported. If no array ref is
12660: provided for types, will default to return only active roles.
1.834 albertel 12661:
1.1195 raeburn 12662: =item *
12663:
12664: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 12665: user: $uname:$udom has a role in the course: $cdom_$cnum.
12666:
12667: Additional optional arguments are: $type (if role checking is to be restricted
12668: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 12669: available roles) or future (roles available in the future), and
12670: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 12671: have active Domain Coordinator role in course's domain or in additional
12672: domains (specified in 'Domains to check for privileged users' in course
12673: environment -- set via: Course Settings -> Classlists and staff listing).
12674:
12675: =item *
12676:
12677: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12678: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12679: $possdomains and $possroles are optional array refs -- to domains to check and
12680: roles to check. If $possdomains is not specified, a dump will be done of the
12681: users' roles.db to check for a dc or su role in any domain. This can be
12682: time consuming if &privileged is called repeatedly (e.g., when displaying a
12683: classlist), so in such cases, supplying a $possdomains array is preferred, as
12684: this then allows &privileged_by_domain() to be used, which caches the identity
12685: of privileged users, eliminating the need for repeated calls to &dump().
12686:
12687: =item *
12688:
12689: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12690: where the outer hash keys are domains specified in the $possdomains array ref,
12691: next inner hash keys are privileged roles specified in the $roles array ref,
12692: and the innermost hash contains key = value pairs for username:domain = end:start
12693: for active or future "privileged" users with that role in that domain. To avoid
12694: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12695: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 12696:
1.243 albertel 12697: =back
12698:
12699: =head2 User Modification
12700:
12701: =over 4
12702:
12703: =item *
12704:
1.957 raeburn 12705: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12706: user for the level given by URL. Optional start and end dates (leave empty
12707: string or zero for "no date")
1.191 harris41 12708:
12709: =item *
12710:
1.243 albertel 12711: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12712: change a users, password, possible return values are: ok,
12713: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12714: refused
1.191 harris41 12715:
12716: =item *
12717:
1.243 albertel 12718: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12719:
12720: =item *
12721:
1.1058 raeburn 12722: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12723: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12724:
12725: will update user information (firstname,middlename,lastname,generation,
12726: permanentemail), and if forceid is true, student/employee ID also.
12727: A user's institutional affiliation(s) can also be updated.
12728: User information fields will not be overwritten with empty entries
12729: unless the field is included in the $candelete array reference.
12730: This array is included when a single user is modified via "Manage Users",
12731: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12732:
12733: =item *
12734:
1.286 matthew 12735: modifystudent
12736:
1.957 raeburn 12737: modify a student's enrollment and identification information.
1.1235 raeburn 12738: The course id is resolved based on the current user's environment.
12739: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12740: associated with a course.
12741:
1.297 matthew 12742: This call is essentially a wrapper for lonnet::modifyuser and
12743: lonnet::modify_student_enrollment
1.286 matthew 12744:
12745: Inputs:
12746:
12747: =over 4
12748:
1.957 raeburn 12749: =item B<$udom> Student's loncapa domain
1.286 matthew 12750:
1.957 raeburn 12751: =item B<$uname> Student's loncapa login name
1.286 matthew 12752:
1.964 bisitz 12753: =item B<$uid> Student/Employee ID
1.286 matthew 12754:
1.957 raeburn 12755: =item B<$umode> Student's authentication mode
1.286 matthew 12756:
1.957 raeburn 12757: =item B<$upass> Student's password
1.286 matthew 12758:
1.957 raeburn 12759: =item B<$first> Student's first name
1.286 matthew 12760:
1.957 raeburn 12761: =item B<$middle> Student's middle name
1.286 matthew 12762:
1.957 raeburn 12763: =item B<$last> Student's last name
1.286 matthew 12764:
1.957 raeburn 12765: =item B<$gene> Student's generation
1.286 matthew 12766:
1.957 raeburn 12767: =item B<$usec> Student's section in course
1.286 matthew 12768:
12769: =item B<$end> Unix time of the roles expiration
12770:
12771: =item B<$start> Unix time of the roles start date
12772:
12773: =item B<$forceid> If defined, allow $uid to be changed
12774:
12775: =item B<$desiredhome> server to use as home server for student
12776:
1.957 raeburn 12777: =item B<$email> Student's permanent e-mail address
12778:
12779: =item B<$type> Type of enrollment (auto or manual)
12780:
1.963 raeburn 12781: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12782:
12783: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12784:
1.963 raeburn 12785: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12786:
1.963 raeburn 12787: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12788:
1.1216 raeburn 12789: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12790:
12791: =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 12792:
1.286 matthew 12793: =back
1.297 matthew 12794:
12795: =item *
12796:
12797: modify_student_enrollment
12798:
1.1235 raeburn 12799: Change a student's enrollment status in a class. The environment variable
1.297 matthew 12800: 'role.request.course' must be defined for this function to proceed.
12801:
12802: Inputs:
12803:
12804: =over 4
12805:
1.1235 raeburn 12806: =item $udom, student's domain
1.297 matthew 12807:
1.1235 raeburn 12808: =item $uname, student's name
1.297 matthew 12809:
1.1235 raeburn 12810: =item $uid, student's user id
1.297 matthew 12811:
1.1235 raeburn 12812: =item $first, student's first name
1.297 matthew 12813:
12814: =item $middle
12815:
12816: =item $last
12817:
12818: =item $gene
12819:
12820: =item $usec
12821:
12822: =item $end
12823:
12824: =item $start
12825:
1.957 raeburn 12826: =item $type
12827:
12828: =item $locktype
12829:
12830: =item $cid
12831:
12832: =item $selfenroll
12833:
12834: =item $context
12835:
1.1216 raeburn 12836: =item $credits, number of credits student will earn from this class
12837:
1.297 matthew 12838: =back
12839:
1.191 harris41 12840:
12841: =item *
12842:
1.243 albertel 12843: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12844: custom role; give a custom role to a user for the level given by URL. Specify
12845: name and domain of role author, and role name
1.191 harris41 12846:
12847: =item *
12848:
1.243 albertel 12849: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12850:
12851: =item *
12852:
1.243 albertel 12853: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12854:
12855: =back
12856:
12857: =head2 Course Infomation
12858:
12859: =over 4
1.191 harris41 12860:
12861: =item *
12862:
1.1118 foxr 12863: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12864: specified course id, including all environment settings for the
12865: course, the description of the course will be in the hash under the
12866: key 'description'
1.191 harris41 12867:
1.1118 foxr 12868: $options is an optional parameter that if supplied is a hash reference that controls
12869: what how this function works. It has the following key/values:
12870:
12871: =over 4
12872:
12873: =item freshen_cache
12874:
12875: If defined, and the environment cache for the course is valid, it is
12876: returned in the returned hash.
12877:
12878: =item one_time
12879:
12880: If defined, the last cache time is set to _now_
12881:
12882: =item user
12883:
12884: If defined, the supplied username is used instead of the current user.
12885:
12886:
12887: =back
12888:
1.191 harris41 12889: =item *
12890:
1.624 albertel 12891: resdata($name,$domain,$type,@which) : request for current parameter
12892: setting for a specific $type, where $type is either 'course' or 'user',
12893: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 12894: answers for 10 minutes.
1.243 albertel 12895:
1.877 foxr 12896: =item *
12897:
12898: get_courseresdata($courseid, $domain) : dump the entire course resource
12899: data base, returning a hash that is keyed by the resource name and has
12900: values that are the resource value. I believe that the timestamps and
12901: versions are also returned.
12902:
1.1236 raeburn 12903: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12904: supplemental content area. This routine caches the number of files for
12905: 10 minutes.
12906:
1.243 albertel 12907: =back
12908:
12909: =head2 Course Modification
12910:
12911: =over 4
1.191 harris41 12912:
12913: =item *
12914:
1.243 albertel 12915: writecoursepref($courseid,%prefs) : write preferences (environment
12916: database) for a course
1.191 harris41 12917:
12918: =item *
12919:
1.1011 raeburn 12920: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12921:
12922: =item *
12923:
1.1038 raeburn 12924: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 12925:
1.1167 droeschl 12926: =item *
12927:
12928: is_course($courseid), is_course($cdom, $cnum)
12929:
12930: Accepts either a combined $courseid (in the form of domain_courseid) or the
12931: two component version $cdom, $cnum. It checks if the specified course exists.
12932:
12933: Returns:
12934: undef if the course doesn't exist, otherwise
12935: in scalar context the combined courseid.
12936: in list context the two components of the course identifier, domain and
12937: courseid.
12938:
1.243 albertel 12939: =back
12940:
12941: =head2 Resource Subroutines
12942:
12943: =over 4
1.191 harris41 12944:
12945: =item *
12946:
1.243 albertel 12947: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 12948:
12949: =item *
12950:
1.243 albertel 12951: repcopy($filename) : subscribes to the requested file, and attempts to
12952: replicate from the owning library server, Might return
1.607 raeburn 12953: 'unavailable', 'not_found', 'forbidden', 'ok', or
12954: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 12955: resource. Expects the local filesystem pathname
12956: (/home/httpd/html/res/....)
12957:
12958: =back
12959:
12960: =head2 Resource Information
12961:
12962: =over 4
1.191 harris41 12963:
12964: =item *
12965:
1.1228 raeburn 12966: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
12967: and returns the value of a variety of different possible values,
12968: $varname should be a request string, and the other parameters can be
12969: used to specify who and what one is asking about. Ordinarily, $cid
12970: does not need to be specified, as it is retrived from
12971: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
12972: within lonuserstate::loadmap() when initializing a course, before
12973: $env{'request.course.id'} has been set, so it needs to be provided
12974: in that one case.
1.243 albertel 12975:
12976: Possible values for $varname are environment.lastname (or other item
12977: from the envirnment hash), user.name (or someother aspect about the
12978: user), resource.0.maxtries (or some other part and parameter of a
12979: resource)
1.204 albertel 12980:
12981: =item *
12982:
1.243 albertel 12983: directcondval($number) : get current value of a condition; reads from a state
12984: string
1.204 albertel 12985:
12986: =item *
12987:
1.243 albertel 12988: condval($condidx) : value of condition index based on state
1.204 albertel 12989:
12990: =item *
12991:
1.243 albertel 12992: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12993: resource's metadata, $what should be either a specific key, or either
12994: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12995: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12996:
12997: this function automatically caches all requests
1.191 harris41 12998:
12999: =item *
13000:
1.243 albertel 13001: metadata_query($query,$custom,$customshow) : make a metadata query against the
13002: network of library servers; returns file handle of where SQL and regex results
13003: will be stored for query
1.191 harris41 13004:
13005: =item *
13006:
1.243 albertel 13007: symbread($filename) : return symbolic list entry (filename argument optional);
13008: returns the data handle
1.191 harris41 13009:
13010: =item *
13011:
1.1190 raeburn 13012: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13013: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13014: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 13015: on failure, user must be in a course, as it assumes the existence of
13016: the course initial hash, and uses $env('request.course.id'}. The third
13017: arg is an optional reference to a scalar. If this arg is passed in the
13018: call to symbverify, it will be set to 1 if the symb has been set to be
13019: encrypted; otherwise it will be null.
1.191 harris41 13020:
13021: =item *
13022:
1.243 albertel 13023: symbclean($symb) : removes versions numbers from a symb, returns the
13024: cleaned symb
1.191 harris41 13025:
13026: =item *
13027:
1.243 albertel 13028: is_on_map($uri) : checks if the $uri is somewhere on the current
13029: course map, user must be in a course for it to work.
1.191 harris41 13030:
13031: =item *
13032:
1.243 albertel 13033: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13034:
13035: =item *
13036:
1.243 albertel 13037: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13038: a random seed, all arguments are optional, if they aren't sent it uses the
13039: environment to derive them. Note: if symb isn't sent and it can't get one
13040: from &symbread it will use the current time as its return value
1.191 harris41 13041:
13042: =item *
13043:
1.243 albertel 13044: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13045: unfakeable, receipt
1.191 harris41 13046:
13047: =item *
13048:
1.620 albertel 13049: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13050:
13051: =item *
13052:
1.243 albertel 13053: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13054:
13055: =item *
13056:
1.243 albertel 13057: 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 13058:
13059: =item *
13060:
1.243 albertel 13061: 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 13062:
13063: =item *
13064:
1.243 albertel 13065: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13066:
13067: =item *
13068:
1.243 albertel 13069: devalidate($symb) : devalidate temporary spreadsheet calculations,
13070: forcing spreadsheet to reevaluate the resource scores next time.
13071:
1.1195 raeburn 13072: =item *
13073:
1.1196 raeburn 13074: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13075: when viewing in course context.
1.1195 raeburn 13076:
1.1196 raeburn 13077: input: six args -- filename (decluttered), course number, course domain,
13078: url, symb (if registered) and group (if this is a
13079: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 13080:
1.1196 raeburn 13081: output: array of five scalars --
1.1195 raeburn 13082: $cfile -- url for file editing if editable on current server
13083: $home -- homeserver of resource (i.e., for author if published,
13084: or course if uploaded.).
13085: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 13086: $forceedit -- 1 if icon/link should be to go to edit mode
13087: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 13088:
13089: =item *
13090:
13091: is_course_upload($file,$cnum,$cdom)
13092:
13093: Used in course context to determine if current file was uploaded to
13094: the course (i.e., would be found in /userfiles/docs on the course's
13095: homeserver.
13096:
13097: input: 3 args -- filename (decluttered), course number and course domain.
13098: output: boolean -- 1 if file was uploaded.
13099:
1.243 albertel 13100: =back
13101:
13102: =head2 Storing/Retreiving Data
13103:
13104: =over 4
1.191 harris41 13105:
13106: =item *
13107:
1.243 albertel 13108: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13109: for this url; hashref needs to be given and should be a \%hashname; the
13110: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13111: be derived from the env
1.191 harris41 13112:
13113: =item *
13114:
1.243 albertel 13115: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13116: uses critical subroutine
1.191 harris41 13117:
13118: =item *
13119:
1.243 albertel 13120: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13121: all args are optional
1.191 harris41 13122:
13123: =item *
13124:
1.717 albertel 13125: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13126: dumps the complete (or key matching regexp) namespace into a hash
13127: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13128: normally &store()ed into
13129:
13130: $range should be either an integer '100' (give me the first 100
13131: matching records)
13132: or be two integers sperated by a - with no spaces
13133: '30-50' (give me the 30th through the 50th matching
13134: records)
13135:
13136:
13137: =item *
13138:
13139: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13140: replaces a &store() version of data with a replacement set of data
13141: for a particular resource in a namespace passed in the $storehash hash
13142: reference
13143:
13144: =item *
13145:
1.243 albertel 13146: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13147: works very similar to store/cstore, but all data is stored in a
13148: temporary location and can be reset using tmpreset, $storehash should
13149: be a hash reference, returns nothing on success
1.191 harris41 13150:
13151: =item *
13152:
1.243 albertel 13153: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13154: similar to restore, but all data is stored in a temporary location and
13155: can be reset using tmpreset. Returns a hash of values on success,
13156: error string otherwise.
1.191 harris41 13157:
13158: =item *
13159:
1.243 albertel 13160: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13161: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13162:
13163: =item *
13164:
1.243 albertel 13165: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13166: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13167:
13168: =item *
13169:
1.243 albertel 13170: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13171: namesp ($udom and $uname are optional)
1.191 harris41 13172:
13173: =item *
13174:
1.702 albertel 13175: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13176: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13177: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13178:
1.702 albertel 13179: $range should be either an integer '100' (give me the first 100
13180: matching records)
13181: or be two integers sperated by a - with no spaces
13182: '30-50' (give me the 30th through the 50th matching
13183: records)
1.449 matthew 13184: =item *
13185:
13186: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13187: $store can be a scalar, an array reference, or if the amount to be
13188: incremented is > 1, a hash reference.
13189:
13190: ($udom and $uname are optional)
1.191 harris41 13191:
13192: =item *
13193:
1.243 albertel 13194: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13195: ($udom and $uname are optional)
1.191 harris41 13196:
13197: =item *
13198:
1.243 albertel 13199: cput($namespace,$storehash,$udom,$uname) : critical put
13200: ($udom and $uname are optional)
1.191 harris41 13201:
13202: =item *
13203:
1.748 albertel 13204: newput($namespace,$storehash,$udom,$uname) :
13205:
13206: Attempts to store the items in the $storehash, but only if they don't
13207: currently exist, if this succeeds you can be certain that you have
13208: successfully created a new key value pair in the $namespace db.
13209:
13210:
13211: Args:
13212: $namespace: name of database to store values to
13213: $storehash: hashref to store to the db
13214: $udom: (optional) domain of user containing the db
13215: $uname: (optional) name of user caontaining the db
13216:
13217: Returns:
13218: 'ok' -> succeeded in storing all keys of $storehash
13219: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13220: least <key> already existed in the db (other
13221: requested keys may also already exist)
1.967 bisitz 13222: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13223: 'con_lost' -> unable to contact request server
13224: 'refused' -> action was not allowed by remote machine
13225:
13226:
13227: =item *
13228:
1.243 albertel 13229: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13230: reference filled in from namesp (encrypts the return communication)
13231: ($udom and $uname are optional)
1.191 harris41 13232:
13233: =item *
13234:
1.243 albertel 13235: log($udom,$name,$home,$message) : write to permanent log for user; use
13236: critical subroutine
13237:
1.806 raeburn 13238: =item *
13239:
1.860 raeburn 13240: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13241: array reference filled in from namespace found in domain level on either
13242: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13243:
13244: =item *
13245:
1.860 raeburn 13246: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13247: domain level either on specified domain server ($uhome) or primary domain
13248: server ($udom and $uhome are optional)
1.806 raeburn 13249:
1.943 raeburn 13250: =item *
13251:
1.1240 raeburn 13252: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13253: for: authentication, language, quotas, timezone, date locale, and portal URL in
13254: the target domain.
13255:
13256: May also include additional key => value pairs for the following groups:
13257:
13258: =over
13259:
13260: =item
13261: disk quotas (MB allocated by default to portfolios and authoring spaces).
13262:
13263: =over
13264:
13265: =item defaultquota, authorquota
13266:
13267: =back
13268:
13269: =item
13270: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13271: portfolio for users).
13272:
13273: =over
13274:
13275: =item
13276: aboutme, blog, webdav, portfolio
13277:
13278: =back
13279:
13280: =item
13281: requestcourses: ability to request courses, and how requests are processed.
13282:
13283: =over
13284:
13285: =item
13286: official, unofficial, community
13287:
13288: =back
13289:
13290: =item
13291: inststatus: types of institutional affiliation, and order in which they are displayed.
13292:
13293: =over
13294:
13295: =item
13296: inststatustypes, inststatusorder
13297:
13298: =back
13299:
13300: =item
13301: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13302: for course's uploaded content.
13303:
13304: =over
13305:
13306: =item
13307: canuse_pdfforms, officialcredits, unofficialcredits, officialquota, unofficialquota, communityquota
13308:
13309: =back
13310:
13311: =item
13312: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13313: on your servers.
13314:
13315: =over
13316:
13317: =item
13318: remotesessions, hostedsessions
13319:
13320: =back
13321:
13322: =back
13323:
13324: In cases where a domain coordinator has never used the "Set Domain Configuration"
13325: utility to create a configuration.db file on a domain's primary library server
13326: only the following domain defaults: auth_def, auth_arg_def, lang_def
13327: -- corresponding values are authentication type (internal, krb4, krb5,
13328: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13329: will be available. Values are retrieved from cache (if current), unless the
13330: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13331: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13332:
13333: Typical usage:
1.943 raeburn 13334:
1.1240 raeburn 13335: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13336:
1.243 albertel 13337: =back
13338:
13339: =head2 Network Status Functions
13340:
13341: =over 4
1.191 harris41 13342:
13343: =item *
13344:
1.1137 raeburn 13345: dirlist() : return directory list based on URI (first arg).
13346:
13347: Inputs: 1 required, 5 optional.
13348:
13349: =over
13350:
13351: =item
13352: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13353:
13354: =item
13355: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13356:
13357: =item
13358: $username - username of user/course to be listed. Extracted from $uri if absent.
13359:
13360: =item
13361: $getpropath - boolean: 1 if prepend path using &propath().
13362:
13363: =item
13364: $getuserdir - boolean: 1 if prepend path for "userfiles".
13365:
13366: =item
13367: $alternateRoot - path to prepend in place of path from $uri.
13368:
13369: =back
13370:
13371: Returns: Array of up to two items.
13372:
13373: =over
13374:
13375: a reference to an array of files/subdirectories
13376:
13377: =over
13378:
13379: Each element in the array of files/subdirectories is a & separated list of
13380: item name and the result of running stat on the item. If dirlist was requested
13381: for a file instead of a directory, the item name will be ''. For a directory
13382: listing, if the item is a metadata file, the element will end &N&M
13383: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13384: default copyright set (1).
13385:
13386: =back
13387:
13388: a scalar containing error condition (if encountered).
13389:
13390: =over
13391:
13392: =item
13393: no_host (no homeserver identified for $username:$domain).
13394:
13395: =item
13396: no_such_host (server contacted for listing not identified as valid host).
13397:
13398: =item
13399: con_lost (connection to remote server failed).
13400:
13401: =item
13402: refused (invalid $username:$domain received on lond side).
13403:
13404: =item
13405: no_such_dir (directory at specified path on lond side does not exist).
13406:
13407: =item
13408: empty (directory at specified path on lond side is empty).
13409:
13410: =over
13411:
13412: This is currently not encountered because the &ls3, &ls2,
13413: &ls (_handler) routines on the lond side do not filter out
13414: . and .. from a directory listing.
13415:
13416: =back
13417:
13418: =back
13419:
13420: =back
1.191 harris41 13421:
13422: =item *
13423:
1.243 albertel 13424: spareserver() : find server with least workload from spare.tab
13425:
1.986 foxr 13426:
13427: =item *
13428:
13429: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13430: if there is no corresponding loncapa host.
13431:
1.243 albertel 13432: =back
13433:
1.986 foxr 13434:
1.243 albertel 13435: =head2 Apache Request
13436:
13437: =over 4
1.191 harris41 13438:
13439: =item *
13440:
1.243 albertel 13441: ssi($url,%hash) : server side include, does a complete request cycle on url to
13442: localhost, posts hash
13443:
13444: =back
13445:
13446: =head2 Data to String to Data
13447:
13448: =over 4
1.191 harris41 13449:
13450: =item *
13451:
1.243 albertel 13452: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13453: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13454:
13455: =item *
13456:
1.243 albertel 13457: hashref2str($hashref) : convert a hashref into a string complete with
13458: escaping and '=' and '&' separators, supports elements that are
13459: arrayrefs and hashrefs
1.191 harris41 13460:
13461: =item *
13462:
1.243 albertel 13463: arrayref2str($arrayref) : convert an arrayref into a string complete
13464: with escaping and '&' separators, supports elements that are arrayrefs
13465: and hashrefs
1.191 harris41 13466:
13467: =item *
13468:
1.243 albertel 13469: str2hash($string) : convert string to hash using unescaping and
13470: splitting on '=' and '&', supports elements that are arrayrefs and
13471: hashrefs
1.191 harris41 13472:
13473: =item *
13474:
1.243 albertel 13475: str2array($string) : convert string to hash using unescaping and
13476: splitting on '&', supports elements that are arrayrefs and hashrefs
13477:
13478: =back
13479:
13480: =head2 Logging Routines
13481:
13482:
13483: These routines allow one to make log messages in the lonnet.log and
13484: lonnet.perm logfiles.
1.191 harris41 13485:
1.1119 foxr 13486: =over 4
13487:
1.191 harris41 13488: =item *
13489:
1.243 albertel 13490: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13491:
13492: =item *
13493:
1.243 albertel 13494: logthis() : append message to the normal lonnet.log file, it gets
13495: preiodically rolled over and deleted.
1.191 harris41 13496:
13497: =item *
13498:
1.243 albertel 13499: logperm() : append a permanent message to lonnet.perm.log, this log
13500: file never gets deleted by any automated portion of the system, only
13501: messages of critical importance should go in here.
13502:
1.1119 foxr 13503:
1.243 albertel 13504: =back
13505:
13506: =head2 General File Helper Routines
13507:
13508: =over 4
1.191 harris41 13509:
13510: =item *
13511:
1.481 raeburn 13512: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13513: (a) files in /uploaded
13514: (i) If a local copy of the file exists -
13515: compares modification date of local copy with last-modified date for
13516: definitive version stored on home server for course. If local copy is
13517: stale, requests a new version from the home server and stores it.
13518: If the original has been removed from the home server, then local copy
13519: is unlinked.
13520: (ii) If local copy does not exist -
13521: requests the file from the home server and stores it.
13522:
13523: If $caller is 'uploadrep':
13524: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13525: for request for files originally uploaded via DOCS.
13526: - returns 'ok' if fresh local copy now available, -1 otherwise.
13527:
13528: Otherwise:
13529: This indicates a call from the content generation phase of the request.
13530: - returns the entire contents of the file or -1.
13531:
13532: (b) files in /res
13533: - returns the entire contents of a file or -1;
13534: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13535:
1.712 albertel 13536:
13537: =item *
13538:
13539: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13540: reference
13541:
13542: returns either a stat() list of data about the file or an empty list
13543: if the file doesn't exist or couldn't find out about it (connection
13544: problems or user unknown)
13545:
1.191 harris41 13546: =item *
13547:
1.243 albertel 13548: filelocation($dir,$file) : returns file system location of a file
13549: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13550: directory that relative $file lookups are to looked in ($dir of /a/dir
13551: and a file of ../bob will become /a/bob)
1.191 harris41 13552:
13553: =item *
13554:
13555: hreflocation($dir,$file) : returns file system location or a URL; same as
13556: filelocation except for hrefs
13557:
13558: =item *
13559:
13560: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13561:
1.243 albertel 13562: =back
13563:
1.608 albertel 13564: =head2 Usererfile file routines (/uploaded*)
13565:
13566: =over 4
13567:
13568: =item *
13569:
13570: userfileupload(): main rotine for putting a file in a user or course's
13571: filespace, arguments are,
13572:
1.620 albertel 13573: formname - required - this is the name of the element in $env where the
1.608 albertel 13574: filename, and the contents of the file to create/modifed exist
1.620 albertel 13575: the filename is in $env{'form.'.$formname.'.filename'} and the
13576: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13577: context - if coursedoc, store the file in the course of the active role
13578: of the current user;
13579: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13580: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13581: subdir - required - subdirectory to put the file in under ../userfiles/
13582: if undefined, it will be placed in "unknown"
13583:
13584: (This routine calls clean_filename() to remove any dangerous
13585: characters from the filename, and then calls finuserfileupload() to
13586: complete the transaction)
13587:
13588: returns either the url of the uploaded file (/uploaded/....) if successful
13589: and /adm/notfound.html if unsuccessful
13590:
13591: =item *
13592:
13593: clean_filename(): routine for cleaing a filename up for storage in
13594: userfile space, argument is:
13595:
13596: filename - proposed filename
13597:
13598: returns: the new clean filename
13599:
13600: =item *
13601:
1.1090 raeburn 13602: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13603: userspace, probably shouldn't be called directly
13604:
13605: docuname: username or courseid of destination for the file
13606: docudom: domain of user/course of destination for the file
13607: formname: same as for userfileupload()
1.1090 raeburn 13608: fname: filename (including subdirectories) for the file
13609: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13610: allfiles: reference to hash used to store objects found by parser
13611: codebase: reference to hash used for codebases of java objects found by parser
13612: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13613: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13614: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13615: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13616: context: if 'overwrite', will move the uploaded file from its temporary location to
13617: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13618: mimetype: reference to scalar to accommodate mime type determined
13619: from File::MMagic if $parser = parse.
1.608 albertel 13620:
13621: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13622: and /adm/notfound.html if unsuccessful (or an error message if context
13623: was 'overwrite').
13624:
1.608 albertel 13625:
13626: =item *
13627:
13628: renameuserfile(): renames an existing userfile to a new name
13629:
13630: Args:
13631: docuname: username or courseid of destination for the file
13632: docudom: domain of user/course of destination for the file
13633: old: current file name (including any subdirs under userfiles)
13634: new: desired file name (including any subdirs under userfiles)
13635:
13636: =item *
13637:
13638: mkdiruserfile(): creates a directory is a userfiles dir
13639:
13640: Args:
13641: docuname: username or courseid of destination for the file
13642: docudom: domain of user/course of destination for the file
13643: dir: dir to create (including any subdirs under userfiles)
13644:
13645: =item *
13646:
13647: removeuserfile(): removes a file that exists in userfiles
13648:
13649: Args:
13650: docuname: username or courseid of destination for the file
13651: docudom: domain of user/course of destination for the file
13652: fname: filname to delete (including any subdirs under userfiles)
13653:
13654: =item *
13655:
13656: removeuploadedurl(): convience function for removeuserfile()
13657:
13658: Args:
13659: url: a full /uploaded/... url to delete
13660:
1.747 albertel 13661: =item *
13662:
13663: get_portfile_permissions():
13664: Args:
13665: domain: domain of user or course contain the portfolio files
13666: user: name of user or num of course contain the portfolio files
13667: Returns:
13668: hashref of a dump of the proper file_permissions.db
13669:
13670:
13671: =item *
13672:
13673: get_access_controls():
13674:
13675: Args:
13676: current_permissions: the hash ref returned from get_portfile_permissions()
13677: group: (optional) the group you want the files associated with
13678: file: (optional) the file you want access info on
13679:
13680: Returns:
1.749 raeburn 13681: a hash (keys are file names) of hashes containing
13682: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13683: values are XML containing access control settings (see below)
1.747 albertel 13684:
13685: Internal notes:
13686:
1.749 raeburn 13687: access controls are stored in file_permissions.db as key=value pairs.
13688: key -> path to file/file_name\0uniqueID:scope_end_start
13689: where scope -> public,guest,course,group,domains or users.
13690: end -> UNIX time for end of access (0 -> no end date)
13691: start -> UNIX time for start of access
13692:
13693: value -> XML description of access control
13694: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13695: <start></start>
13696: <end></end>
13697:
13698: <password></password> for scope type = guest
13699:
13700: <domain></domain> for scope type = course or group
13701: <number></number>
13702: <roles id="">
13703: <role></role>
13704: <access></access>
13705: <section></section>
13706: <group></group>
13707: </roles>
13708:
13709: <dom></dom> for scope type = domains
13710:
13711: <users> for scope type = users
13712: <user>
13713: <uname></uname>
13714: <udom></udom>
13715: </user>
13716: </users>
13717: </scope>
13718:
13719: Access data is also aggregated for each file in an additional key=value pair:
13720: key -> path to file/file_name\0accesscontrol
13721: value -> reference to hash
13722: hash contains key = value pairs
13723: where key = uniqueID:scope_end_start
13724: value = UNIX time record was last updated
13725:
13726: Used to improve speed of look-ups of access controls for each file.
13727:
13728: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13729:
1.1198 raeburn 13730: =item *
13731:
1.749 raeburn 13732: modify_access_controls():
13733:
13734: Modifies access controls for a portfolio file
13735: Args
13736: 1. file name
13737: 2. reference to hash of required changes,
13738: 3. domain
13739: 4. username
13740: where domain,username are the domain of the portfolio owner
13741: (either a user or a course)
13742:
13743: Returns:
13744: 1. result of additions or updates ('ok' or 'error', with error message).
13745: 2. result of deletions ('ok' or 'error', with error message).
13746: 3. reference to hash of any new or updated access controls.
13747: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13748: key = integer (inbound ID)
1.1198 raeburn 13749: value = uniqueID
13750:
13751: =item *
13752:
13753: get_timebased_id():
13754:
13755: Attempts to get a unique timestamp-based suffix for use with items added to a
13756: course via the Course Editor (e.g., folders, composite pages,
13757: group bulletin boards).
13758:
13759: Args: (first three required; six others optional)
13760:
13761: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13762: docssequence, or name of group
13763:
13764: 2. keyid (alphanumeric): name of temporary locking key in hash,
13765: e.g., num, boardids
13766:
13767: 3. namespace: name of gdbm file used to store suffixes already assigned;
13768: file will be named nohist_namespace.db
13769:
13770: 4. cdom: domain of course; default is current course domain from %env
13771:
13772: 5. cnum: course number; default is current course number from %env
13773:
13774: 6. idtype: set to concat if an additional digit is to be appended to the
13775: unix timestamp to form the suffix, if the plain timestamp is already
13776: in use. Default is to not do this, but simply increment the unix
13777: timestamp by 1 until a unique key is obtained.
13778:
13779: 7. who: holder of locking key; defaults to user:domain for user.
13780:
13781: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13782: retrying); default is 3.
13783:
13784: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13785:
13786: Returns:
13787:
13788: 1. suffix obtained (numeric)
13789:
13790: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13791:
13792: 3. error: contains (localized) error message if an error occurred.
13793:
1.747 albertel 13794:
1.608 albertel 13795: =back
13796:
1.243 albertel 13797: =head2 HTTP Helper Routines
13798:
13799: =over 4
13800:
1.191 harris41 13801: =item *
13802:
13803: escape() : unpack non-word characters into CGI-compatible hex codes
13804:
13805: =item *
13806:
13807: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13808:
1.243 albertel 13809: =back
13810:
13811: =head1 PRIVATE SUBROUTINES
13812:
13813: =head2 Underlying communication routines (Shouldn't call)
13814:
13815: =over 4
13816:
13817: =item *
13818:
13819: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13820:
13821: =item *
13822:
13823: reply() : uses subreply to send a message to remote machine, logs all failures
13824:
13825: =item *
13826:
13827: critical() : passes a critical message to another server; if cannot
13828: get through then place message in connection buffer directory and
13829: returns con_delayed, if incapable of saving message, returns
13830: con_failed
13831:
13832: =item *
13833:
13834: reconlonc() : tries to reconnect lonc client processes.
13835:
13836: =back
13837:
13838: =head2 Resource Access Logging
13839:
13840: =over 4
13841:
13842: =item *
13843:
13844: flushcourselogs() : flush (save) buffer logs and access logs
13845:
13846: =item *
13847:
13848: courselog($what) : save message for course in hash
13849:
13850: =item *
13851:
13852: courseacclog($what) : save message for course using &courselog(). Perform
13853: special processing for specific resource types (problems, exams, quizzes, etc).
13854:
1.191 harris41 13855: =item *
13856:
13857: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13858: as a PerlChildExitHandler
1.243 albertel 13859:
13860: =back
13861:
13862: =head2 Other
13863:
13864: =over 4
13865:
13866: =item *
13867:
13868: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 13869:
13870: =back
13871:
13872: =cut
1.877 foxr 13873:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>