Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1246
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1246 ! raeburn 4: # $Id: lonnet.pm,v 1.1245 2013/12/13 02:10:33 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.1182 foxr 78:
1.1173 foxr 79: use Encode;
80:
1.1245 raeburn 81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 82: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
83: %managerstab);
1.871 albertel 84:
85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
86: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
87: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 88: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 89:
1.1 albertel 90: use IO::Socket;
1.31 www 91: use GDBM_File;
1.208 albertel 92: use HTML::LCParser;
1.88 www 93: use Fcntl qw(:flock);
1.870 albertel 94: use Storable qw(thaw nfreeze);
1.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.1245 raeburn 609: my ($r,$name,$userhashref) = @_;
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.1245 raeburn 640:
641: if (ref($userhashref) eq 'HASH') {
642: $userhashref->{'name'} = $disk_env{'user.name'};
643: $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212 raeburn 644: }
1.1245 raeburn 645:
1.916 albertel 646: return $handle;
647: }
648:
1.830 albertel 649: sub timed_flock {
650: my ($file,$lock_type) = @_;
651: my $failed=0;
652: eval {
653: local $SIG{__DIE__}='DEFAULT';
654: local $SIG{ALRM}=sub {
655: $failed=1;
656: die("failed lock");
657: };
658: alarm(13);
659: flock($file,$lock_type);
660: alarm(0);
661: };
662: if ($failed) {
663: return undef;
664: } else {
665: return 1;
666: }
667: }
668:
1.5 www 669: # ---------------------------------------------------------- Append Environment
670:
671: sub appenv {
1.949 raeburn 672: my ($newenv,$roles) = @_;
673: if (ref($newenv) eq 'HASH') {
674: foreach my $key (keys(%{$newenv})) {
675: my $refused = 0;
676: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
677: $refused = 1;
678: if (ref($roles) eq 'ARRAY') {
679: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
680: if (grep(/^\Q$role\E$/,@{$roles})) {
681: $refused = 0;
682: }
683: }
684: }
685: if ($refused) {
686: &logthis("<font color=\"blue\">WARNING: ".
687: "Attempt to modify environment ".$key." to ".$newenv->{$key}
688: .'</font>');
689: delete($newenv->{$key});
690: } else {
691: $env{$key}=$newenv->{$key};
692: }
693: }
694: my $opened = open(my $env_file,'+<',$env{'user.environment'});
695: if ($opened
696: && &timed_flock($env_file,LOCK_EX)
697: &&
698: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
699: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
700: while (my ($key,$value) = each(%{$newenv})) {
701: $disk_env{$key} = $value;
702: }
703: untie(%disk_env);
1.35 www 704: }
1.191 harris41 705: }
1.56 www 706: return 'ok';
707: }
708: # ----------------------------------------------------- Delete from Environment
709:
710: sub delenv {
1.1104 raeburn 711: my ($delthis,$regexp,$roles) = @_;
712: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
713: my $refused = 1;
714: if (ref($roles) eq 'ARRAY') {
715: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
716: if (grep(/^\Q$role\E$/,@{$roles})) {
717: $refused = 0;
718: }
719: }
720: if ($refused) {
721: &logthis("<font color=\"blue\">WARNING: ".
722: "Attempt to delete from environment ".$delthis);
723: return 'error';
724: }
1.56 www 725: }
1.917 albertel 726: my $opened = open(my $env_file,'+<',$env{'user.environment'});
727: if ($opened
1.915 albertel 728: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 729: &&
730: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
731: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 732: foreach my $key (keys(%disk_env)) {
1.987 raeburn 733: if ($regexp) {
734: if ($key=~/^$delthis/) {
735: delete($env{$key});
736: delete($disk_env{$key});
737: }
738: } else {
739: if ($key=~/^\Q$delthis\E/) {
740: delete($env{$key});
741: delete($disk_env{$key});
742: }
743: }
1.448 albertel 744: }
1.783 albertel 745: untie(%disk_env);
1.5 www 746: }
747: return 'ok';
1.369 albertel 748: }
749:
1.790 albertel 750: sub get_env_multiple {
751: my ($name) = @_;
752: my @values;
753: if (defined($env{$name})) {
754: # exists is it an array
755: if (ref($env{$name})) {
756: @values=@{ $env{$name} };
757: } else {
758: $values[0]=$env{$name};
759: }
760: }
761: return(@values);
762: }
763:
1.958 www 764: # ------------------------------------------------------------------- Locking
765:
766: sub set_lock {
767: my ($text)=@_;
768: $locknum++;
769: my $id=$$.'-'.$locknum;
770: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
771: 'session.lock.'.$id => $text});
772: return $id;
773: }
774:
775: sub get_locks {
776: my $num=0;
777: my %texts=();
778: foreach my $lock (split(/\,/,$env{'session.locks'})) {
779: if ($lock=~/\w/) {
780: $num++;
781: $texts{$lock}=$env{'session.lock.'.$lock};
782: }
783: }
784: return ($num,%texts);
785: }
786:
787: sub remove_lock {
788: my ($id)=@_;
789: my $newlocks='';
790: foreach my $lock (split(/\,/,$env{'session.locks'})) {
791: if (($lock=~/\w/) && ($lock ne $id)) {
792: $newlocks.=','.$lock;
793: }
794: }
795: &appenv({'session.locks' => $newlocks});
796: &delenv('session.lock.'.$id);
797: }
798:
799: sub remove_all_locks {
800: my $activelocks=$env{'session.locks'};
801: foreach my $lock (split(/\,/,$env{'session.locks'})) {
802: if ($lock=~/\w/) {
803: &remove_lock($lock);
804: }
805: }
806: }
807:
808:
1.369 albertel 809: # ------------------------------------------ Find out current server userload
810: sub userload {
811: my $numusers=0;
812: {
813: opendir(LONIDS,$perlvar{'lonIDsDir'});
814: my $filename;
815: my $curtime=time;
816: while ($filename=readdir(LONIDS)) {
1.925 albertel 817: next if ($filename eq '.' || $filename eq '..');
818: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 819: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 820: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 821: }
822: closedir(LONIDS);
823: }
824: my $userloadpercent=0;
825: my $maxuserload=$perlvar{'lonUserLoadLim'};
826: if ($maxuserload) {
1.371 albertel 827: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 828: }
1.372 albertel 829: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 830: return $userloadpercent;
1.283 www 831: }
832:
1.1 albertel 833: # ------------------------------ Find server with least workload from spare.tab
1.11 www 834:
1.1 albertel 835: sub spareserver {
1.1083 raeburn 836: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 837: my $spare_server;
1.370 albertel 838: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 839: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
840: : $userloadpercent;
1.1083 raeburn 841: my ($uint_dom,$remotesessions);
842: if (($udom ne '') && (&domain($udom) ne '')) {
843: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
844: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
845: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
846: $remotesessions = $udomdefaults{'remotesessions'};
847: }
1.1123 raeburn 848: my $spareshash = &this_host_spares($udom);
849: if (ref($spareshash) eq 'HASH') {
850: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
851: foreach my $try_server (@{ $spareshash->{'primary'} }) {
852: if ($uint_dom) {
853: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
854: $try_server));
855: }
856: ($spare_server, $lowest_load) =
857: &compare_server_load($try_server, $spare_server, $lowest_load);
858: }
1.1083 raeburn 859: }
1.784 albertel 860:
1.1123 raeburn 861: my $found_server = ($spare_server ne '' && $lowest_load < 100);
862:
863: if (!$found_server) {
864: if (ref($spareshash->{'default'}) eq 'ARRAY') {
865: foreach my $try_server (@{ $spareshash->{'default'} }) {
866: if ($uint_dom) {
867: next unless (&spare_can_host($udom,$uint_dom,
868: $remotesessions,$try_server));
869: }
870: ($spare_server, $lowest_load) =
871: &compare_server_load($try_server, $spare_server, $lowest_load);
872: }
873: }
874: }
1.784 albertel 875: }
876:
877: if (!$want_server_name) {
1.968 raeburn 878: my $protocol = 'http';
879: if ($protocol{$spare_server} eq 'https') {
880: $protocol = $protocol{$spare_server};
881: }
1.1001 raeburn 882: if (defined($spare_server)) {
883: my $hostname = &hostname($spare_server);
1.1083 raeburn 884: if (defined($hostname)) {
1.1001 raeburn 885: $spare_server = $protocol.'://'.$hostname;
886: }
887: }
1.784 albertel 888: }
889: return $spare_server;
890: }
891:
892: sub compare_server_load {
893: my ($try_server, $spare_server, $lowest_load) = @_;
894:
895: my $loadans = &reply('load', $try_server);
896: my $userloadans = &reply('userload',$try_server);
897:
898: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 899: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 900: }
901:
902: my $load;
903: if ($loadans =~ /\d/) {
904: if ($userloadans =~ /\d/) {
905: #both are numbers, pick the bigger one
906: $load = ($loadans > $userloadans) ? $loadans
907: : $userloadans;
1.411 albertel 908: } else {
1.784 albertel 909: $load = $loadans;
1.411 albertel 910: }
1.784 albertel 911: } else {
912: $load = $userloadans;
913: }
914:
915: if (($load =~ /\d/) && ($load < $lowest_load)) {
916: $spare_server = $try_server;
917: $lowest_load = $load;
1.370 albertel 918: }
1.784 albertel 919: return ($spare_server,$lowest_load);
1.202 matthew 920: }
1.914 albertel 921:
922: # --------------------------- ask offload servers if user already has a session
923: sub find_existing_session {
924: my ($udom,$uname) = @_;
1.1123 raeburn 925: my $spareshash = &this_host_spares($udom);
926: if (ref($spareshash) eq 'HASH') {
927: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
928: foreach my $try_server (@{ $spareshash->{'primary'} }) {
929: return $try_server if (&has_user_session($try_server, $udom, $uname));
930: }
931: }
932: if (ref($spareshash->{'default'}) eq 'ARRAY') {
933: foreach my $try_server (@{ $spareshash->{'default'} }) {
934: return $try_server if (&has_user_session($try_server, $udom, $uname));
935: }
936: }
1.914 albertel 937: }
938: return;
939: }
940:
941: # -------------------------------- ask if server already has a session for user
942: sub has_user_session {
943: my ($lonid,$udom,$uname) = @_;
944: my $result = &reply(join(':','userhassession',
945: map {&escape($_)} ($udom,$uname)),$lonid);
946: return 1 if ($result eq 'ok');
947:
948: return 0;
949: }
950:
1.1076 raeburn 951: # --------- determine least loaded server in a user's domain which allows login
952:
953: sub choose_server {
1.1115 raeburn 954: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 955: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 956: my %servers = &get_servers($udom);
1.1076 raeburn 957: my $lowest_load = 30000;
1.1151 raeburn 958: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 959: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 960: my $loginvia;
961: if ($checkloginvia) {
962: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 963: if ($loginvia) {
964: my ($server,$path) = split(/:/,$loginvia);
965: ($login_host, $lowest_load) =
966: &compare_server_load($server, $login_host, $lowest_load);
967: if ($login_host eq $server) {
968: $portal_path = $path;
1.1151 raeburn 969: $isredirect = 1;
1.1116 raeburn 970: }
971: } else {
972: ($login_host, $lowest_load) =
973: &compare_server_load($lonhost, $login_host, $lowest_load);
974: if ($login_host eq $lonhost) {
975: $portal_path = '';
1.1151 raeburn 976: $isredirect = '';
1.1116 raeburn 977: }
978: }
979: } else {
1.1076 raeburn 980: ($login_host, $lowest_load) =
1.1116 raeburn 981: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 982: }
983: }
984: if ($login_host ne '') {
1.1116 raeburn 985: $hostname = &hostname($login_host);
1.1076 raeburn 986: }
1.1151 raeburn 987: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 988: }
989:
1.202 matthew 990: # --------------------------------------------- Try to change a user's password
991:
992: sub changepass {
1.799 raeburn 993: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 994: $currentpass = &escape($currentpass);
995: $newpass = &escape($newpass);
1.1030 raeburn 996: my $lonhost = $perlvar{'lonHostID'};
997: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 998: $server);
999: if (! $answer) {
1000: &logthis("No reply on password change request to $server ".
1001: "by $uname in domain $udom.");
1002: } elsif ($answer =~ "^ok") {
1003: &logthis("$uname in $udom successfully changed their password ".
1004: "on $server.");
1005: } elsif ($answer =~ "^pwchange_failure") {
1006: &logthis("$uname in $udom was unable to change their password ".
1007: "on $server. The action was blocked by either lcpasswd ".
1008: "or pwchange");
1009: } elsif ($answer =~ "^non_authorized") {
1010: &logthis("$uname in $udom did not get their password correct when ".
1011: "attempting to change it on $server.");
1012: } elsif ($answer =~ "^auth_mode_error") {
1013: &logthis("$uname in $udom attempted to change their password despite ".
1014: "not being locally or internally authenticated on $server.");
1015: } elsif ($answer =~ "^unknown_user") {
1016: &logthis("$uname in $udom attempted to change their password ".
1017: "on $server but were unable to because $server is not ".
1018: "their home server.");
1019: } elsif ($answer =~ "^refused") {
1020: &logthis("$server refused to change $uname in $udom password because ".
1021: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1022: } elsif ($answer =~ "invalid_client") {
1023: &logthis("$server refused to change $uname in $udom password because ".
1024: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1025: }
1026: return $answer;
1.1 albertel 1027: }
1028:
1.169 harris41 1029: # ----------------------- Try to determine user's current authentication scheme
1030:
1031: sub queryauthenticate {
1032: my ($uname,$udom)=@_;
1.456 albertel 1033: my $uhome=&homeserver($uname,$udom);
1034: if (!$uhome) {
1035: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1036: return 'no_host';
1037: }
1038: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1039: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1040: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1041: }
1.456 albertel 1042: return $answer;
1.169 harris41 1043: }
1044:
1.1 albertel 1045: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1046:
1.1 albertel 1047: sub authenticate {
1.1073 raeburn 1048: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1049: $upass=&escape($upass);
1050: $uname= &LONCAPA::clean_username($uname);
1.836 www 1051: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1052: my $newhome;
1.836 www 1053: if ((!$uhome) || ($uhome eq 'no_host')) {
1054: # Maybe the machine was offline and only re-appeared again recently?
1055: &reconlonc();
1056: # One more
1.952 raeburn 1057: $uhome=&homeserver($uname,$udom,1);
1058: if (($uhome eq 'no_host') && $checkdefauth) {
1059: if (defined(&domain($udom,'primary'))) {
1060: $newhome=&domain($udom,'primary');
1061: }
1062: if ($newhome ne '') {
1063: $uhome = $newhome;
1064: }
1065: }
1.836 www 1066: if ((!$uhome) || ($uhome eq 'no_host')) {
1067: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1068: return 'no_host';
1069: }
1.1 albertel 1070: }
1.1073 raeburn 1071: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1072: if ($answer eq 'authorized') {
1.952 raeburn 1073: if ($newhome) {
1074: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1075: return 'no_account_on_host';
1076: } else {
1077: &logthis("User $uname at $udom authorized by $uhome");
1078: return $uhome;
1079: }
1.471 albertel 1080: }
1081: if ($answer eq 'non_authorized') {
1082: &logthis("User $uname at $udom rejected by $uhome");
1083: return 'no_host';
1.9 www 1084: }
1.471 albertel 1085: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1086: return 'no_host';
1087: }
1088:
1.1073 raeburn 1089: sub can_host_session {
1.1074 raeburn 1090: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1091: my $canhost = 1;
1.1074 raeburn 1092: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1093: if (ref($remotesessions) eq 'HASH') {
1094: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1095: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1096: $canhost = 0;
1097: } else {
1098: $canhost = 1;
1099: }
1100: }
1101: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1102: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1103: $canhost = 1;
1104: } else {
1105: $canhost = 0;
1106: }
1107: }
1108: if ($canhost) {
1109: if ($remotesessions->{'version'} ne '') {
1110: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1111: if ($reqmajor ne '' && $reqminor ne '') {
1112: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1113: my $major = $1;
1114: my $minor = $2;
1115: if (($major < $reqmajor ) ||
1116: (($major == $reqmajor) && ($minor < $reqminor))) {
1117: $canhost = 0;
1118: }
1119: } else {
1120: $canhost = 0;
1121: }
1122: }
1123: }
1124: }
1125: }
1126: if ($canhost) {
1127: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1128: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1129: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1130: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1131: if (($uint_dom ne '') &&
1132: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1133: $canhost = 0;
1134: } else {
1135: $canhost = 1;
1136: }
1137: }
1138: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1139: if (($uint_dom ne '') &&
1140: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1141: $canhost = 1;
1142: } else {
1143: $canhost = 0;
1144: }
1145: }
1146: }
1147: }
1148: return $canhost;
1149: }
1150:
1.1083 raeburn 1151: sub spare_can_host {
1152: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1153: my $canhost=1;
1154: my @intdoms;
1155: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1156: if (ref($internet_names) eq 'ARRAY') {
1157: @intdoms = @{$internet_names};
1158: }
1159: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1160: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1161: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1162: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1163: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1164: $canhost = &can_host_session($udom,$try_server,$remoterev,
1165: $remotesessions,
1166: $defdomdefaults{'hostedsessions'});
1167: }
1168: return $canhost;
1169: }
1170:
1.1123 raeburn 1171: sub this_host_spares {
1172: my ($dom) = @_;
1.1126 raeburn 1173: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1174: my @hosts = ¤t_machine_ids();
1175: foreach my $lonhost (@hosts) {
1176: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1177: $dom_in_use = $dom;
1178: $lonhost_in_use = $lonhost;
1.1123 raeburn 1179: last;
1180: }
1181: }
1.1126 raeburn 1182: if ($dom_in_use ne '') {
1183: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1184: }
1185: if (ref($result) ne 'HASH') {
1186: $lonhost_in_use = $perlvar{'lonHostID'};
1187: $dom_in_use = &host_domain($lonhost_in_use);
1188: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1189: if (ref($result) ne 'HASH') {
1190: $result = \%spareid;
1191: }
1192: }
1193: return $result;
1194: }
1195:
1196: sub spares_for_offload {
1197: my ($dom_in_use,$lonhost_in_use) = @_;
1198: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1199: if (defined($cached)) {
1200: return $result;
1201: } else {
1.1126 raeburn 1202: my $cachetime = 60*60*24;
1203: my %domconfig =
1204: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1205: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1206: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1207: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1208: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1209: }
1210: }
1211: }
1212: }
1.1126 raeburn 1213: return;
1.1123 raeburn 1214: }
1215:
1.1129 raeburn 1216: sub get_lonbalancer_config {
1217: my ($servers) = @_;
1218: my ($currbalancer,$currtargets);
1219: if (ref($servers) eq 'HASH') {
1220: foreach my $server (keys(%{$servers})) {
1221: my %what = (
1222: spareid => 1,
1223: perlvar => 1,
1224: );
1225: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1226: if ($result eq 'ok') {
1227: if (ref($returnhash) eq 'HASH') {
1228: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1229: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1230: $currbalancer = $server;
1231: $currtargets = {};
1232: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1233: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1234: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1235: }
1236: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1237: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1238: }
1239: }
1240: last;
1241: }
1242: }
1243: }
1244: }
1245: }
1246: }
1247: return ($currbalancer,$currtargets);
1248: }
1249:
1250: sub check_loadbalancing {
1251: my ($uname,$udom) = @_;
1.1191 raeburn 1252: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1253: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1254: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1255: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1256: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1257: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1258: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1259: my $serverhomedom = &host_domain($lonhost);
1260:
1261: my $cachetime = 60*60*24;
1262:
1263: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1264: $dom_in_use = $udom;
1265: $homeintdom = 1;
1266: } else {
1267: $dom_in_use = $serverhomedom;
1268: }
1269: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1270: unless (defined($cached)) {
1271: my %domconfig =
1272: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1273: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1274: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1275: }
1276: }
1277: if (ref($result) eq 'HASH') {
1.1191 raeburn 1278: ($is_balancer,$currtargets,$currrules) =
1279: &check_balancer_result($result,@hosts);
1.1129 raeburn 1280: if ($is_balancer) {
1281: if (ref($currrules) eq 'HASH') {
1282: if ($homeintdom) {
1283: if ($uname ne '') {
1284: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1285: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1286: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1287: $rule_in_effect = $currrules->{'_LC_author'};
1288: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1289: $rule_in_effect = $currrules->{'_LC_adv'}
1290: }
1291: }
1292: if ($rule_in_effect eq '') {
1293: my %userenv = &userenvironment($udom,$uname,'inststatus');
1294: if ($userenv{'inststatus'} ne '') {
1295: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1296: my ($othertitle,$usertypes,$types) =
1297: &Apache::loncommon::sorted_inst_types($udom);
1298: if (ref($types) eq 'ARRAY') {
1299: foreach my $type (@{$types}) {
1300: if (grep(/^\Q$type\E$/,@statuses)) {
1301: if (exists($currrules->{$type})) {
1302: $rule_in_effect = $currrules->{$type};
1303: }
1304: }
1305: }
1306: }
1307: } else {
1308: if (exists($currrules->{'default'})) {
1309: $rule_in_effect = $currrules->{'default'};
1310: }
1311: }
1312: }
1313: } else {
1314: if (exists($currrules->{'default'})) {
1315: $rule_in_effect = $currrules->{'default'};
1316: }
1317: }
1318: } else {
1319: if ($currrules->{'_LC_external'} ne '') {
1320: $rule_in_effect = $currrules->{'_LC_external'};
1321: }
1322: }
1323: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1324: $uname,$udom);
1325: }
1326: }
1327: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1328: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1329: unless (defined($cached)) {
1330: my %domconfig =
1331: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1332: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1333: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1334: }
1335: }
1336: if (ref($result) eq 'HASH') {
1.1191 raeburn 1337: ($is_balancer,$currtargets,$currrules) =
1338: &check_balancer_result($result,@hosts);
1339: if ($is_balancer) {
1.1129 raeburn 1340: if (ref($currrules) eq 'HASH') {
1341: if ($currrules->{'_LC_internetdom'} ne '') {
1342: $rule_in_effect = $currrules->{'_LC_internetdom'};
1343: }
1344: }
1345: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1346: $uname,$udom);
1347: }
1348: } else {
1349: if ($perlvar{'lonBalancer'} eq 'yes') {
1350: $is_balancer = 1;
1351: $offloadto = &this_host_spares($dom_in_use);
1352: }
1353: }
1354: } else {
1355: if ($perlvar{'lonBalancer'} eq 'yes') {
1356: $is_balancer = 1;
1357: $offloadto = &this_host_spares($dom_in_use);
1358: }
1359: }
1.1176 raeburn 1360: if ($is_balancer) {
1361: my $lowest_load = 30000;
1362: if (ref($offloadto) eq 'HASH') {
1363: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1364: foreach my $try_server (@{$offloadto->{'primary'}}) {
1365: ($otherserver,$lowest_load) =
1366: &compare_server_load($try_server,$otherserver,$lowest_load);
1367: }
1.1129 raeburn 1368: }
1.1176 raeburn 1369: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1370:
1.1176 raeburn 1371: if (!$found_server) {
1372: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1373: foreach my $try_server (@{$offloadto->{'default'}}) {
1374: ($otherserver,$lowest_load) =
1375: &compare_server_load($try_server,$otherserver,$lowest_load);
1376: }
1377: }
1378: }
1379: } elsif (ref($offloadto) eq 'ARRAY') {
1380: if (@{$offloadto} == 1) {
1381: $otherserver = $offloadto->[0];
1382: } elsif (@{$offloadto} > 1) {
1383: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1384: ($otherserver,$lowest_load) =
1385: &compare_server_load($try_server,$otherserver,$lowest_load);
1386: }
1387: }
1388: }
1.1176 raeburn 1389: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1390: $is_balancer = 0;
1391: if ($uname ne '' && $udom ne '') {
1392: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1393:
1394: &appenv({'user.loadbalexempt' => $lonhost,
1395: 'user.loadbalcheck.time' => time});
1396: }
1.1129 raeburn 1397: }
1398: }
1399: }
1400: return ($is_balancer,$otherserver);
1401: }
1402:
1.1191 raeburn 1403: sub check_balancer_result {
1404: my ($result,@hosts) = @_;
1405: my ($is_balancer,$currtargets,$currrules);
1406: if (ref($result) eq 'HASH') {
1407: if ($result->{'lonhost'} ne '') {
1408: my $currbalancer = $result->{'lonhost'};
1409: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1410: $is_balancer = 1;
1411: $currtargets = $result->{'targets'};
1412: $currrules = $result->{'rules'};
1413: }
1414: } else {
1415: foreach my $key (keys(%{$result})) {
1416: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1417: (ref($result->{$key}) eq 'HASH')) {
1418: $is_balancer = 1;
1419: $currrules = $result->{$key}{'rules'};
1420: $currtargets = $result->{$key}{'targets'};
1421: last;
1422: }
1423: }
1424: }
1425: }
1426: return ($is_balancer,$currtargets,$currrules);
1427: }
1428:
1.1129 raeburn 1429: sub get_loadbalancer_targets {
1430: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1431: my $offloadto;
1.1175 raeburn 1432: if ($rule_in_effect eq 'none') {
1433: return [$perlvar{'lonHostID'}];
1434: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1435: $offloadto = $currtargets;
1436: } else {
1437: if ($rule_in_effect eq 'homeserver') {
1438: my $homeserver = &homeserver($uname,$udom);
1439: if ($homeserver ne 'no_host') {
1440: $offloadto = [$homeserver];
1441: }
1442: } elsif ($rule_in_effect eq 'externalbalancer') {
1443: my %domconfig =
1444: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1445: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1446: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1447: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1448: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1449: }
1450: }
1451: } else {
1.1178 raeburn 1452: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1453: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1454: if (&hostname($remotebalancer) ne '') {
1455: $offloadto = [$remotebalancer];
1456: }
1457: }
1458: } elsif (&hostname($rule_in_effect) ne '') {
1459: $offloadto = [$rule_in_effect];
1460: }
1461: }
1462: return $offloadto;
1463: }
1464:
1.1127 raeburn 1465: sub internet_dom_servers {
1466: my ($dom) = @_;
1467: my (%uniqservers,%servers);
1468: my $primaryserver = &hostname(&domain($dom,'primary'));
1469: my @machinedoms = &machine_domains($primaryserver);
1470: foreach my $mdom (@machinedoms) {
1471: my %currservers = %servers;
1472: my %server = &get_servers($mdom);
1473: %servers = (%currservers,%server);
1474: }
1475: my %by_hostname;
1476: foreach my $id (keys(%servers)) {
1477: push(@{$by_hostname{$servers{$id}}},$id);
1478: }
1479: foreach my $hostname (sort(keys(%by_hostname))) {
1480: if (@{$by_hostname{$hostname}} > 1) {
1481: my $match = 0;
1482: foreach my $id (@{$by_hostname{$hostname}}) {
1483: if (&host_domain($id) eq $dom) {
1484: $uniqservers{$id} = $hostname;
1485: $match = 1;
1486: }
1487: }
1488: unless ($match) {
1489: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1490: }
1491: } else {
1492: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1493: }
1494: }
1495: return %uniqservers;
1496: }
1497:
1.1 albertel 1498: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1499:
1.599 albertel 1500: my %homecache;
1.1 albertel 1501: sub homeserver {
1.230 stredwic 1502: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1503: my $index="$uname:$udom";
1.426 albertel 1504:
1.599 albertel 1505: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1506:
1507: my %servers = &get_servers($udom,'library');
1508: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1509: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1510: exists($badServerCache{$tryserver}));
1.841 albertel 1511:
1512: my $answer=reply("home:$udom:$uname",$tryserver);
1513: if ($answer eq 'found') {
1514: delete($badServerCache{$tryserver});
1515: return $homecache{$index}=$tryserver;
1516: } elsif ($answer eq 'no_host') {
1517: $badServerCache{$tryserver}=1;
1518: }
1.1 albertel 1519: }
1520: return 'no_host';
1.70 www 1521: }
1522:
1523: # ------------------------------------- Find the usernames behind a list of IDs
1524:
1525: sub idget {
1526: my ($udom,@ids)=@_;
1527: my %returnhash=();
1528:
1.841 albertel 1529: my %servers = &get_servers($udom,'library');
1530: foreach my $tryserver (keys(%servers)) {
1531: my $idlist=join('&',@ids);
1532: $idlist=~tr/A-Z/a-z/;
1533: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1534: my @answer=();
1535: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1536: @answer=split(/\&/,$reply);
1537: } ;
1538: my $i;
1539: for ($i=0;$i<=$#ids;$i++) {
1540: if ($answer[$i]) {
1541: $returnhash{$ids[$i]}=$answer[$i];
1542: }
1543: }
1544: }
1.70 www 1545: return %returnhash;
1546: }
1547:
1548: # ------------------------------------- Find the IDs behind a list of usernames
1549:
1550: sub idrget {
1551: my ($udom,@unames)=@_;
1552: my %returnhash=();
1.800 albertel 1553: foreach my $uname (@unames) {
1554: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1555: }
1.70 www 1556: return %returnhash;
1557: }
1558:
1559: # ------------------------------- Store away a list of names and associated IDs
1560:
1561: sub idput {
1562: my ($udom,%ids)=@_;
1563: my %servers=();
1.800 albertel 1564: foreach my $uname (keys(%ids)) {
1565: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1566: my $uhom=&homeserver($uname,$udom);
1.70 www 1567: if ($uhom ne 'no_host') {
1.800 albertel 1568: my $id=&escape($ids{$uname});
1.70 www 1569: $id=~tr/A-Z/a-z/;
1.800 albertel 1570: my $esc_unam=&escape($uname);
1.70 www 1571: if ($servers{$uhom}) {
1.800 albertel 1572: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1573: } else {
1.800 albertel 1574: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1575: }
1576: }
1.191 harris41 1577: }
1.800 albertel 1578: foreach my $server (keys(%servers)) {
1579: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1580: }
1.344 www 1581: }
1582:
1.1231 raeburn 1583: # ---------------------------------------- Delete unwanted IDs from ids.db file
1584:
1585: sub iddel {
1586: my ($udom,$idshashref,$uhome)=@_;
1587: my %result=();
1588: unless (ref($idshashref) eq 'HASH') {
1589: return %result;
1590: }
1591: my %servers=();
1592: while (my ($id,$uname) = each(%{$idshashref})) {
1593: my $uhom;
1594: if ($uhome) {
1595: $uhom = $uhome;
1596: } else {
1597: $uhom=&homeserver($uname,$udom);
1598: }
1599: if ($uhom ne 'no_host') {
1600: if ($servers{$uhom}) {
1601: $servers{$uhom}.='&'.&escape($id);
1602: } else {
1603: $servers{$uhom}=&escape($id);
1604: }
1605: }
1606: }
1607: foreach my $server (keys(%servers)) {
1608: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1609: }
1610: return %result;
1611: }
1612:
1.1023 raeburn 1613: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1614: sub dump_dom {
1.1165 droeschl 1615: my ($namespace, $udom, $regexp) = @_;
1616:
1617: $udom ||= $env{'user.domain'};
1618:
1619: return () unless $udom;
1620:
1621: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1622: }
1623:
1.1023 raeburn 1624: # ------------------------------------------ get items from domain db files
1.806 raeburn 1625:
1626: sub get_dom {
1.860 raeburn 1627: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1628: my $items='';
1629: foreach my $item (@$storearr) {
1630: $items.=&escape($item).'&';
1631: }
1632: $items=~s/\&$//;
1.860 raeburn 1633: if (!$udom) {
1634: $udom=$env{'user.domain'};
1635: if (defined(&domain($udom,'primary'))) {
1636: $uhome=&domain($udom,'primary');
1637: } else {
1.874 albertel 1638: undef($uhome);
1.860 raeburn 1639: }
1640: } else {
1641: if (!$uhome) {
1642: if (defined(&domain($udom,'primary'))) {
1643: $uhome=&domain($udom,'primary');
1644: }
1645: }
1646: }
1647: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1648: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1649: my %returnhash;
1.875 albertel 1650: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1651: return %returnhash;
1652: }
1.806 raeburn 1653: my @pairs=split(/\&/,$rep);
1654: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1655: return @pairs;
1656: }
1657: my $i=0;
1658: foreach my $item (@$storearr) {
1659: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1660: $i++;
1661: }
1662: return %returnhash;
1663: } else {
1.880 banghart 1664: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1665: }
1666: }
1667:
1668: # -------------------------------------------- put items in domain db files
1669:
1670: sub put_dom {
1.860 raeburn 1671: my ($namespace,$storehash,$udom,$uhome)=@_;
1672: if (!$udom) {
1673: $udom=$env{'user.domain'};
1674: if (defined(&domain($udom,'primary'))) {
1675: $uhome=&domain($udom,'primary');
1676: } else {
1.874 albertel 1677: undef($uhome);
1.860 raeburn 1678: }
1679: } else {
1680: if (!$uhome) {
1681: if (defined(&domain($udom,'primary'))) {
1682: $uhome=&domain($udom,'primary');
1683: }
1684: }
1685: }
1686: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1687: my $items='';
1688: foreach my $item (keys(%$storehash)) {
1689: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1690: }
1691: $items=~s/\&$//;
1692: return &reply("putdom:$udom:$namespace:$items",$uhome);
1693: } else {
1.860 raeburn 1694: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1695: }
1696: }
1697:
1.1023 raeburn 1698: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1699: sub newput_dom {
1.1023 raeburn 1700: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1701: my $result;
1702: if (!$udom) {
1703: $udom=$env{'user.domain'};
1704: }
1.1023 raeburn 1705: if ($udom) {
1706: my $uname = &get_domainconfiguser($udom);
1707: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1708: }
1709: return $result;
1710: }
1711:
1.1023 raeburn 1712: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1713: sub del_dom {
1.1023 raeburn 1714: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1715: if (ref($storearr) eq 'ARRAY') {
1716: if (!$udom) {
1717: $udom=$env{'user.domain'};
1718: }
1.1023 raeburn 1719: if ($udom) {
1720: my $uname = &get_domainconfiguser($udom);
1721: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1722: }
1723: }
1724: }
1725:
1.1023 raeburn 1726: # ----------------------------------construct domainconfig user for a domain
1727: sub get_domainconfiguser {
1728: my ($udom) = @_;
1729: return $udom.'-domainconfig';
1730: }
1731:
1.837 raeburn 1732: sub retrieve_inst_usertypes {
1733: my ($udom) = @_;
1734: my (%returnhash,@order);
1.989 raeburn 1735: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1736: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1737: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1738: %returnhash = %{$domdefs{'inststatustypes'}};
1739: @order = @{$domdefs{'inststatusorder'}};
1740: } else {
1741: if (defined(&domain($udom,'primary'))) {
1742: my $uhome=&domain($udom,'primary');
1743: my $rep=&reply("inst_usertypes:$udom",$uhome);
1744: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1745: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1746: return (\%returnhash,\@order);
1747: }
1748: my ($hashitems,$orderitems) = split(/:/,$rep);
1749: my @pairs=split(/\&/,$hashitems);
1750: foreach my $item (@pairs) {
1751: my ($key,$value)=split(/=/,$item,2);
1752: $key = &unescape($key);
1753: next if ($key =~ /^error: 2 /);
1754: $returnhash{$key}=&thaw_unescape($value);
1755: }
1756: my @esc_order = split(/\&/,$orderitems);
1757: foreach my $item (@esc_order) {
1758: push(@order,&unescape($item));
1759: }
1760: } else {
1761: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1762: }
1763: }
1764: return (\%returnhash,\@order);
1765: }
1766:
1.868 raeburn 1767: sub is_domainimage {
1768: my ($url) = @_;
1769: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1770: if (&domain($1) ne '') {
1771: return '1';
1772: }
1773: }
1774: return;
1775: }
1776:
1.899 raeburn 1777: sub inst_directory_query {
1778: my ($srch) = @_;
1779: my $udom = $srch->{'srchdomain'};
1780: my %results;
1781: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1782: my $outcome;
1.899 raeburn 1783: if ($homeserver ne '') {
1.904 albertel 1784: my $queryid=&reply("querysend:instdirsearch:".
1785: &escape($srch->{'srchby'}).':'.
1786: &escape($srch->{'srchterm'}).':'.
1787: &escape($srch->{'srchtype'}),$homeserver);
1788: my $host=&hostname($homeserver);
1789: if ($queryid !~/^\Q$host\E\_/) {
1790: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1791: return;
1792: }
1793: my $response = &get_query_reply($queryid);
1794: my $maxtries = 5;
1795: my $tries = 1;
1796: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1797: $response = &get_query_reply($queryid);
1798: $tries ++;
1799: }
1800:
1801: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1802: if ($response eq 'unavailable') {
1803: $outcome = $response;
1804: } else {
1805: $outcome = 'ok';
1806: my @matches = split(/\n/,$response);
1807: foreach my $match (@matches) {
1808: my ($key,$value) = split(/=/,$match);
1809: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1810: }
1.899 raeburn 1811: }
1812: }
1813: }
1.909 raeburn 1814: return ($outcome,%results);
1.899 raeburn 1815: }
1816:
1817: sub usersearch {
1818: my ($srch) = @_;
1819: my $dom = $srch->{'srchdomain'};
1820: my %results;
1821: my %libserv = &all_library();
1822: my $query = 'usersearch';
1823: foreach my $tryserver (keys(%libserv)) {
1824: if (&host_domain($tryserver) eq $dom) {
1825: my $host=&hostname($tryserver);
1826: my $queryid=
1.911 raeburn 1827: &reply("querysend:".&escape($query).':'.
1828: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1829: &escape($srch->{'srchtype'}).':'.
1830: &escape($srch->{'srchterm'}),$tryserver);
1831: if ($queryid !~/^\Q$host\E\_/) {
1832: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1833: next;
1.899 raeburn 1834: }
1835: my $reply = &get_query_reply($queryid);
1836: my $maxtries = 1;
1837: my $tries = 1;
1838: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1839: $reply = &get_query_reply($queryid);
1840: $tries ++;
1841: }
1842: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1843: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1844: } else {
1.911 raeburn 1845: my @matches;
1846: if ($reply =~ /\n/) {
1847: @matches = split(/\n/,$reply);
1848: } else {
1849: @matches = split(/\&/,$reply);
1850: }
1.899 raeburn 1851: foreach my $match (@matches) {
1852: my ($uname,$udom,%userhash);
1.911 raeburn 1853: foreach my $entry (split(/:/,$match)) {
1854: my ($key,$value) =
1855: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1856: $userhash{$key} = $value;
1857: if ($key eq 'username') {
1858: $uname = $value;
1859: } elsif ($key eq 'domain') {
1860: $udom = $value;
1.911 raeburn 1861: }
1.899 raeburn 1862: }
1863: $results{$uname.':'.$udom} = \%userhash;
1864: }
1865: }
1866: }
1867: }
1868: return %results;
1869: }
1870:
1.912 raeburn 1871: sub get_instuser {
1872: my ($udom,$uname,$id) = @_;
1873: my $homeserver = &domain($udom,'primary');
1874: my ($outcome,%results);
1875: if ($homeserver ne '') {
1876: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1877: &escape($id).':'.&escape($udom),$homeserver);
1878: my $host=&hostname($homeserver);
1879: if ($queryid !~/^\Q$host\E\_/) {
1880: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1881: return;
1882: }
1883: my $response = &get_query_reply($queryid);
1884: my $maxtries = 5;
1885: my $tries = 1;
1886: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1887: $response = &get_query_reply($queryid);
1888: $tries ++;
1889: }
1890: if (!&error($response) && $response ne 'refused') {
1891: if ($response eq 'unavailable') {
1892: $outcome = $response;
1893: } else {
1894: $outcome = 'ok';
1895: my @matches = split(/\n/,$response);
1896: foreach my $match (@matches) {
1897: my ($key,$value) = split(/=/,$match);
1898: $results{&unescape($key)} = &thaw_unescape($value);
1899: }
1900: }
1901: }
1902: }
1903: my %userinfo;
1904: if (ref($results{$uname}) eq 'HASH') {
1905: %userinfo = %{$results{$uname}};
1906: }
1907: return ($outcome,%userinfo);
1908: }
1909:
1910: sub inst_rulecheck {
1.923 raeburn 1911: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1912: my %returnhash;
1913: if ($udom ne '') {
1914: if (ref($rules) eq 'ARRAY') {
1915: @{$rules} = map {&escape($_);} (@{$rules});
1916: my $rulestr = join(':',@{$rules});
1917: my $homeserver=&domain($udom,'primary');
1918: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1919: my $response;
1920: if ($item eq 'username') {
1921: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1922: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1923: $homeserver));
1.923 raeburn 1924: } elsif ($item eq 'id') {
1925: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1926: ':'.&escape($id).':'.$rulestr,
1927: $homeserver));
1.945 raeburn 1928: } elsif ($item eq 'selfcreate') {
1929: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1930: &escape($udom).':'.&escape($uname).
1931: ':'.$rulestr,$homeserver));
1.923 raeburn 1932: }
1.912 raeburn 1933: if ($response ne 'refused') {
1934: my @pairs=split(/\&/,$response);
1935: foreach my $item (@pairs) {
1936: my ($key,$value)=split(/=/,$item,2);
1937: $key = &unescape($key);
1938: next if ($key =~ /^error: 2 /);
1939: $returnhash{$key}=&thaw_unescape($value);
1940: }
1941: }
1942: }
1943: }
1944: }
1945: return %returnhash;
1946: }
1947:
1948: sub inst_userrules {
1.923 raeburn 1949: my ($udom,$check) = @_;
1.912 raeburn 1950: my (%ruleshash,@ruleorder);
1951: if ($udom ne '') {
1952: my $homeserver=&domain($udom,'primary');
1953: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1954: my $response;
1955: if ($check eq 'id') {
1956: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1957: $homeserver);
1.943 raeburn 1958: } elsif ($check eq 'email') {
1959: $response=&reply('instemailrules:'.&escape($udom),
1960: $homeserver);
1.923 raeburn 1961: } else {
1962: $response=&reply('instuserrules:'.&escape($udom),
1963: $homeserver);
1964: }
1.912 raeburn 1965: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1966: ($response ne 'unknown_cmd') &&
1.912 raeburn 1967: ($response ne 'no_such_host')) {
1968: my ($hashitems,$orderitems) = split(/:/,$response);
1969: my @pairs=split(/\&/,$hashitems);
1970: foreach my $item (@pairs) {
1971: my ($key,$value)=split(/=/,$item,2);
1972: $key = &unescape($key);
1973: next if ($key =~ /^error: 2 /);
1974: $ruleshash{$key}=&thaw_unescape($value);
1975: }
1976: my @esc_order = split(/\&/,$orderitems);
1977: foreach my $item (@esc_order) {
1978: push(@ruleorder,&unescape($item));
1979: }
1980: }
1981: }
1982: }
1983: return (\%ruleshash,\@ruleorder);
1984: }
1985:
1.976 raeburn 1986: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1987:
1988: sub get_domain_defaults {
1.1240 raeburn 1989: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 1990: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 1991: my $cachetime = 60*60*24;
1.1240 raeburn 1992: unless ($ignore_cache) {
1993: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1994: if (defined($cached)) {
1995: if (ref($result) eq 'HASH') {
1996: return %{$result};
1997: }
1.943 raeburn 1998: }
1999: }
2000: my %domdefaults;
2001: my %domconfig =
1.989 raeburn 2002: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2003: 'requestcourses','inststatus',
1.1183 raeburn 2004: 'coursedefaults','usersessions',
2005: 'requestauthor'],$domain);
1.943 raeburn 2006: if (ref($domconfig{'defaults'}) eq 'HASH') {
2007: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2008: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2009: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2010: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2011: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2012: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2013: } else {
2014: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2015: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2016: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2017: }
1.976 raeburn 2018: if (ref($domconfig{'quotas'}) eq 'HASH') {
2019: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2020: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2021: } else {
2022: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2023: }
1.1177 raeburn 2024: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2025: foreach my $item (@usertools) {
2026: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2027: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2028: }
2029: }
1.1229 raeburn 2030: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2031: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2032: }
1.976 raeburn 2033: }
1.985 raeburn 2034: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1246 ! raeburn 2035: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2036: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2037: }
2038: }
1.1183 raeburn 2039: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2040: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2041: }
1.989 raeburn 2042: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2043: foreach my $item ('inststatustypes','inststatusorder') {
2044: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2045: }
2046: }
1.1047 raeburn 2047: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2048: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1216 raeburn 2049: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2050: $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
2051: $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
1.1246 ! raeburn 2052: $domdefaults{'textbookcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'textbook'};
1.1216 raeburn 2053: }
1.1230 raeburn 2054: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2055: $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
2056: $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
1.1246 ! raeburn 2057: $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};
! 2058: $domdefaults{'textbookquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'textbook'};
1.1230 raeburn 2059: }
1.1047 raeburn 2060: }
1.1073 raeburn 2061: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2062: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2063: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2064: }
2065: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2066: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2067: }
2068: }
1.1219 raeburn 2069: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2070: return %domdefaults;
2071: }
2072:
1.344 www 2073: # --------------------------------------------------- Assign a key to a student
2074:
2075: sub assign_access_key {
1.364 www 2076: #
2077: # a valid key looks like uname:udom#comments
2078: # comments are being appended
2079: #
1.498 www 2080: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2081: $kdom=
1.620 albertel 2082: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2083: $knum=
1.620 albertel 2084: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2085: $cdom=
1.620 albertel 2086: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2087: $cnum=
1.620 albertel 2088: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2089: $udom=$env{'user.name'} unless (defined($udom));
2090: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2091: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2092: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2093: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2094: # assigned to this person
2095: # - this should not happen,
1.345 www 2096: # unless something went wrong
2097: # the first time around
2098: # ready to assign
1.364 www 2099: $logentry=$1.'; '.$logentry;
1.496 www 2100: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2101: $kdom,$knum) eq 'ok') {
1.345 www 2102: # key now belongs to user
1.346 www 2103: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2104: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2105: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2106: return 'ok';
2107: } else {
2108: return
2109: 'error: Count not permanently assign key, will need to be re-entered later.';
2110: }
2111: } else {
2112: return 'error: Could not assign key, try again later.';
2113: }
1.364 www 2114: } elsif (!$existing{$ckey}) {
1.345 www 2115: # the key does not exist
2116: return 'error: The key does not exist';
2117: } else {
2118: # the key is somebody else's
2119: return 'error: The key is already in use';
2120: }
1.344 www 2121: }
2122:
1.364 www 2123: # ------------------------------------------ put an additional comment on a key
2124:
2125: sub comment_access_key {
2126: #
2127: # a valid key looks like uname:udom#comments
2128: # comments are being appended
2129: #
2130: my ($ckey,$cdom,$cnum,$logentry)=@_;
2131: $cdom=
1.620 albertel 2132: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2133: $cnum=
1.620 albertel 2134: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2135: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2136: if ($existing{$ckey}) {
2137: $existing{$ckey}.='; '.$logentry;
2138: # ready to assign
1.367 www 2139: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2140: $cdom,$cnum) eq 'ok') {
2141: return 'ok';
2142: } else {
2143: return 'error: Count not store comment.';
2144: }
2145: } else {
2146: # the key does not exist
2147: return 'error: The key does not exist';
2148: }
2149: }
2150:
1.344 www 2151: # ------------------------------------------------------ Generate a set of keys
2152:
2153: sub generate_access_keys {
1.364 www 2154: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2155: $cdom=
1.620 albertel 2156: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2157: $cnum=
1.620 albertel 2158: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2159: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2160: unless (($cdom) && ($cnum)) { return 0; }
2161: if ($number>10000) { return 0; }
2162: sleep(2); # make sure don't get same seed twice
2163: srand(time()^($$+($$<<15))); # from "Programming Perl"
2164: my $total=0;
2165: for (my $i=1;$i<=$number;$i++) {
2166: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2167: sprintf("%lx",int(100000*rand)).'-'.
2168: sprintf("%lx",int(100000*rand));
2169: $newkey=~s/1/g/g; # folks mix up 1 and l
2170: $newkey=~s/0/h/g; # and also 0 and O
2171: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2172: if ($existing{$newkey}) {
2173: $i--;
2174: } else {
1.364 www 2175: if (&put('accesskeys',
2176: { $newkey => '# generated '.localtime().
1.620 albertel 2177: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2178: '; '.$logentry },
2179: $cdom,$cnum) eq 'ok') {
1.344 www 2180: $total++;
2181: }
2182: }
2183: }
1.620 albertel 2184: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2185: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2186: return $total;
2187: }
2188:
2189: # ------------------------------------------------------- Validate an accesskey
2190:
2191: sub validate_access_key {
2192: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2193: $cdom=
1.620 albertel 2194: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2195: $cnum=
1.620 albertel 2196: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2197: $udom=$env{'user.domain'} unless (defined($udom));
2198: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2199: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2200: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2201: }
2202:
2203: # ------------------------------------- Find the section of student in a course
1.652 albertel 2204: sub devalidate_getsection_cache {
2205: my ($udom,$unam,$courseid)=@_;
2206: my $hashid="$udom:$unam:$courseid";
2207: &devalidate_cache_new('getsection',$hashid);
2208: }
1.298 matthew 2209:
1.815 albertel 2210: sub courseid_to_courseurl {
2211: my ($courseid) = @_;
2212: #already url style courseid
2213: return $courseid if ($courseid =~ m{^/});
2214:
2215: if (exists($env{'course.'.$courseid.'.num'})) {
2216: my $cnum = $env{'course.'.$courseid.'.num'};
2217: my $cdom = $env{'course.'.$courseid.'.domain'};
2218: return "/$cdom/$cnum";
2219: }
2220:
2221: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2222: if (exists($courseinfo{'num'})) {
2223: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2224: }
2225:
2226: return undef;
2227: }
2228:
1.298 matthew 2229: sub getsection {
2230: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2231: my $cachetime=1800;
1.551 albertel 2232:
2233: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2234: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2235: if (defined($cached)) { return $result; }
2236:
1.298 matthew 2237: my %Pending;
2238: my %Expired;
2239: #
2240: # Each role can either have not started yet (pending), be active,
2241: # or have expired.
2242: #
2243: # If there is an active role, we are done.
2244: #
2245: # If there is more than one role which has not started yet,
2246: # choose the one which will start sooner
2247: # If there is one role which has not started yet, return it.
2248: #
2249: # If there is more than one expired role, choose the one which ended last.
2250: # If there is a role which has expired, return it.
2251: #
1.815 albertel 2252: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2253: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2254: foreach my $key (keys(%roleshash)) {
1.479 albertel 2255: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2256: my $section=$1;
2257: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2258: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2259: my $now=time;
1.548 albertel 2260: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2261: $Expired{$end}=$section;
2262: next;
2263: }
1.548 albertel 2264: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2265: $Pending{$start}=$section;
2266: next;
2267: }
1.599 albertel 2268: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2269: }
2270: #
2271: # Presumedly there will be few matching roles from the above
2272: # loop and the sorting time will be negligible.
2273: if (scalar(keys(%Pending))) {
2274: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2275: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2276: }
2277: if (scalar(keys(%Expired))) {
2278: my @sorted = sort {$a <=> $b} keys(%Expired);
2279: my $time = pop(@sorted);
1.599 albertel 2280: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2281: }
1.599 albertel 2282: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2283: }
1.70 www 2284:
1.599 albertel 2285: sub save_cache {
2286: &purge_remembered();
1.722 albertel 2287: #&Apache::loncommon::validate_page();
1.620 albertel 2288: undef(%env);
1.780 albertel 2289: undef($env_loaded);
1.599 albertel 2290: }
1.452 albertel 2291:
1.599 albertel 2292: my $to_remember=-1;
2293: my %remembered;
2294: my %accessed;
2295: my $kicks=0;
2296: my $hits=0;
1.849 albertel 2297: sub make_key {
2298: my ($name,$id) = @_;
1.872 albertel 2299: if (length($id) > 65
2300: && length(&escape($id)) > 200) {
2301: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2302: }
1.849 albertel 2303: return &escape($name.':'.$id);
2304: }
2305:
1.599 albertel 2306: sub devalidate_cache_new {
2307: my ($name,$id,$debug) = @_;
2308: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2309: $id=&make_key($name,$id);
1.599 albertel 2310: $memcache->delete($id);
2311: delete($remembered{$id});
2312: delete($accessed{$id});
2313: }
2314:
2315: sub is_cached_new {
2316: my ($name,$id,$debug) = @_;
1.849 albertel 2317: $id=&make_key($name,$id);
1.599 albertel 2318: if (exists($remembered{$id})) {
1.1133 foxr 2319: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2320: $accessed{$id}=[&gettimeofday()];
2321: $hits++;
2322: return ($remembered{$id},1);
2323: }
2324: my $value = $memcache->get($id);
2325: if (!(defined($value))) {
2326: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2327: return (undef,undef);
1.416 albertel 2328: }
1.599 albertel 2329: if ($value eq '__undef__') {
2330: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2331: $value=undef;
2332: }
2333: &make_room($id,$value,$debug);
2334: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2335: return ($value,1);
2336: }
2337:
2338: sub do_cache_new {
2339: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2340: $id=&make_key($name,$id);
1.599 albertel 2341: my $setvalue=$value;
2342: if (!defined($setvalue)) {
2343: $setvalue='__undef__';
2344: }
1.623 albertel 2345: if (!defined($time) ) {
2346: $time=600;
2347: }
1.599 albertel 2348: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2349: my $result = $memcache->set($id,$setvalue,$time);
2350: if (! $result) {
1.872 albertel 2351: &logthis("caching of id -> $id failed");
1.910 albertel 2352: $memcache->disconnect_all();
1.872 albertel 2353: }
1.600 albertel 2354: # need to make a copy of $value
1.919 albertel 2355: &make_room($id,$value,$debug);
1.599 albertel 2356: return $value;
2357: }
2358:
2359: sub make_room {
2360: my ($id,$value,$debug)=@_;
1.919 albertel 2361:
2362: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2363: : $value;
1.599 albertel 2364: if ($to_remember<0) { return; }
2365: $accessed{$id}=[&gettimeofday()];
2366: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2367: my $to_kick;
2368: my $max_time=0;
2369: foreach my $other (keys(%accessed)) {
2370: if (&tv_interval($accessed{$other}) > $max_time) {
2371: $to_kick=$other;
2372: $max_time=&tv_interval($accessed{$other});
2373: }
2374: }
2375: delete($remembered{$to_kick});
2376: delete($accessed{$to_kick});
2377: $kicks++;
2378: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2379: return;
2380: }
2381:
1.599 albertel 2382: sub purge_remembered {
1.604 albertel 2383: #&logthis("Tossing ".scalar(keys(%remembered)));
2384: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2385: undef(%remembered);
2386: undef(%accessed);
1.428 albertel 2387: }
1.70 www 2388: # ------------------------------------- Read an entry from a user's environment
2389:
2390: sub userenvironment {
2391: my ($udom,$unam,@what)=@_;
1.976 raeburn 2392: my $items;
2393: foreach my $item (@what) {
2394: $items.=&escape($item).'&';
2395: }
2396: $items=~s/\&$//;
1.70 www 2397: my %returnhash=();
1.1009 raeburn 2398: my $uhome = &homeserver($unam,$udom);
2399: unless ($uhome eq 'no_host') {
2400: my @answer=split(/\&/,
2401: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2402: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2403: return %returnhash;
2404: }
1.1009 raeburn 2405: my $i;
2406: for ($i=0;$i<=$#what;$i++) {
2407: $returnhash{$what[$i]}=&unescape($answer[$i]);
2408: }
1.70 www 2409: }
2410: return %returnhash;
1.1 albertel 2411: }
2412:
1.617 albertel 2413: # ---------------------------------------------------------- Get a studentphoto
2414: sub studentphoto {
2415: my ($udom,$unam,$ext) = @_;
2416: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2417: if (defined($env{'request.course.id'})) {
1.708 raeburn 2418: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2419: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2420: return(&retrievestudentphoto($udom,$unam,$ext));
2421: } else {
2422: my ($result,$perm_reqd)=
1.707 albertel 2423: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2424: if ($result eq 'ok') {
2425: if (!($perm_reqd eq 'yes')) {
2426: return(&retrievestudentphoto($udom,$unam,$ext));
2427: }
2428: }
2429: }
2430: }
2431: } else {
2432: my ($result,$perm_reqd) =
1.707 albertel 2433: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2434: if ($result eq 'ok') {
2435: if (!($perm_reqd eq 'yes')) {
2436: return(&retrievestudentphoto($udom,$unam,$ext));
2437: }
2438: }
2439: }
2440: return '/adm/lonKaputt/lonlogo_broken.gif';
2441: }
2442:
2443: sub retrievestudentphoto {
2444: my ($udom,$unam,$ext,$type) = @_;
2445: my $home=&Apache::lonnet::homeserver($unam,$udom);
2446: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2447: if ($ret eq 'ok') {
2448: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2449: if ($type eq 'thumbnail') {
2450: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2451: }
2452: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2453: return $tokenurl;
2454: } else {
2455: if ($type eq 'thumbnail') {
2456: return '/adm/lonKaputt/genericstudent_tn.gif';
2457: } else {
2458: return '/adm/lonKaputt/lonlogo_broken.gif';
2459: }
1.617 albertel 2460: }
2461: }
2462:
1.263 www 2463: # -------------------------------------------------------------------- New chat
2464:
2465: sub chatsend {
1.724 raeburn 2466: my ($newentry,$anon,$group)=@_;
1.620 albertel 2467: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2468: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2469: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2470: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2471: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2472: &escape($newentry)).':'.$group,$chome);
1.292 www 2473: }
2474:
2475: # ------------------------------------------ Find current version of a resource
2476:
2477: sub getversion {
2478: my $fname=&clutter(shift);
1.1189 raeburn 2479: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2480: return ¤tversion(&filelocation('',$fname));
2481: }
2482:
2483: sub currentversion {
2484: my $fname=shift;
2485: my $author=$fname;
2486: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2487: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2488: my $home=&homeserver($uname,$udom);
1.292 www 2489: if ($home eq 'no_host') {
2490: return -1;
2491: }
1.1112 www 2492: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2493: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2494: return -1;
2495: }
1.1112 www 2496: return $answer;
1.263 www 2497: }
2498:
1.1111 www 2499: #
2500: # Return special version number of resource if set by override, empty otherwise
2501: #
2502: sub usedversion {
2503: my $fname=shift;
2504: unless ($fname) { $fname=$env{'request.uri'}; }
2505: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2506: if ($urlversion) { return $urlversion; }
2507: return '';
2508: }
2509:
1.1 albertel 2510: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2511:
1.1 albertel 2512: sub subscribe {
2513: my $fname=shift;
1.761 raeburn 2514: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2515: $fname=~s/[\n\r]//g;
1.1 albertel 2516: my $author=$fname;
2517: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2518: my ($udom,$uname)=split(/\//,$author);
2519: my $home=homeserver($uname,$udom);
1.335 albertel 2520: if ($home eq 'no_host') {
2521: return 'not_found';
1.1 albertel 2522: }
2523: my $answer=reply("sub:$fname",$home);
1.64 www 2524: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2525: $answer.=' by '.$home;
2526: }
1.1 albertel 2527: return $answer;
2528: }
2529:
1.8 www 2530: # -------------------------------------------------------------- Replicate file
2531:
2532: sub repcopy {
2533: my $filename=shift;
1.23 www 2534: $filename=~s/\/+/\//g;
1.1142 raeburn 2535: my $londocroot = $perlvar{'lonDocRoot'};
2536: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2537: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2538: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2539: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2540: return &repcopy_userfile($filename);
2541: }
1.532 albertel 2542: $filename=~s/[\n\r]//g;
1.8 www 2543: my $transname="$filename.in.transfer";
1.828 www 2544: # FIXME: this should flock
1.607 raeburn 2545: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2546: my $remoteurl=subscribe($filename);
1.64 www 2547: if ($remoteurl =~ /^con_lost by/) {
2548: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2549: return 'unavailable';
1.8 www 2550: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2551: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2552: return 'not_found';
1.64 www 2553: } elsif ($remoteurl =~ /^rejected by/) {
2554: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2555: return 'forbidden';
1.20 www 2556: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2557: return 'ok';
1.8 www 2558: } else {
1.290 www 2559: my $author=$filename;
2560: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2561: my ($udom,$uname)=split(/\//,$author);
2562: my $home=homeserver($uname,$udom);
2563: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2564: my @parts=split(/\//,$filename);
2565: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2566: if ($path ne "$londocroot/res") {
1.8 www 2567: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2568: return 'bad_request';
1.8 www 2569: }
2570: my $count;
2571: for ($count=5;$count<$#parts;$count++) {
2572: $path.="/$parts[$count]";
2573: if ((-e $path)!=1) {
2574: mkdir($path,0777);
2575: }
2576: }
2577: my $ua=new LWP::UserAgent;
2578: my $request=new HTTP::Request('GET',"$remoteurl");
2579: my $response=$ua->request($request,$transname);
2580: if ($response->is_error()) {
2581: unlink($transname);
2582: my $message=$response->status_line;
1.672 albertel 2583: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2584: ." LWP get: $message: $filename</font>");
1.607 raeburn 2585: return 'unavailable';
1.8 www 2586: } else {
1.16 www 2587: if ($remoteurl!~/\.meta$/) {
2588: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2589: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2590: if ($mresponse->is_error()) {
2591: unlink($filename.'.meta');
2592: &logthis(
1.672 albertel 2593: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2594: }
2595: }
1.8 www 2596: rename($transname,$filename);
1.607 raeburn 2597: return 'ok';
1.8 www 2598: }
1.290 www 2599: }
1.8 www 2600: }
1.330 www 2601: }
2602:
2603: # ------------------------------------------------ Get server side include body
2604: sub ssi_body {
1.381 albertel 2605: my ($filelink,%form)=@_;
1.606 matthew 2606: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2607: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2608: }
1.953 www 2609: my $output='';
2610: my $response;
1.980 raeburn 2611: if ($filelink=~/^https?\:/) {
1.954 raeburn 2612: ($output,$response)=&externalssi($filelink);
1.953 www 2613: } else {
1.1004 droeschl 2614: $filelink .= $filelink=~/\?/ ? '&' : '?';
2615: $filelink .= 'inhibitmenu=yes';
1.953 www 2616: ($output,$response)=&ssi($filelink,%form);
2617: }
1.778 albertel 2618: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2619: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2620: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2621: if (wantarray) {
2622: return ($output, $response);
2623: } else {
2624: return $output;
2625: }
1.8 www 2626: }
2627:
1.15 www 2628: # --------------------------------------------------------- Server Side Include
2629:
1.782 albertel 2630: sub absolute_url {
2631: my ($host_name) = @_;
2632: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2633: if ($host_name eq '') {
2634: $host_name = $ENV{'SERVER_NAME'};
2635: }
2636: return $protocol.$host_name;
2637: }
2638:
1.942 foxr 2639: #
2640: # Server side include.
2641: # Parameters:
2642: # fn Possibly encrypted resource name/id.
2643: # form Hash that describes how the rendering should be done
2644: # and other things.
1.944 foxr 2645: # Returns:
1.950 raeburn 2646: # Scalar context: The content of the response.
2647: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2648: #
1.15 www 2649: sub ssi {
2650:
1.944 foxr 2651: my ($fn,%form)=@_;
1.15 www 2652: my $ua=new LWP::UserAgent;
1.23 www 2653: my $request;
1.711 albertel 2654:
2655: $form{'no_update_last_known'}=1;
1.895 albertel 2656: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2657: if (%form) {
1.782 albertel 2658: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2659: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2660: } else {
1.782 albertel 2661: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2662: }
2663:
1.15 www 2664: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2665: my $response= $ua->request($request);
1.1182 foxr 2666: my $content = $response->content;
2667:
2668:
1.944 foxr 2669: if (wantarray) {
1.1173 foxr 2670: return ($content, $response);
1.944 foxr 2671: } else {
1.1173 foxr 2672: return $content;
1.942 foxr 2673: }
1.324 www 2674: }
2675:
2676: sub externalssi {
2677: my ($url)=@_;
2678: my $ua=new LWP::UserAgent;
2679: my $request=new HTTP::Request('GET',$url);
2680: my $response=$ua->request($request);
1.954 raeburn 2681: if (wantarray) {
2682: return ($response->content, $response);
2683: } else {
2684: return $response->content;
2685: }
1.15 www 2686: }
1.254 www 2687:
1.492 albertel 2688: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2689:
2690: sub allowuploaded {
2691: my ($srcurl,$url)=@_;
2692: $url=&clutter(&declutter($url));
2693: my $dir=$url;
2694: $dir=~s/\/[^\/]+$//;
2695: my %httpref=();
2696: my $httpurl=&hreflocation('',$url);
2697: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2698: &Apache::lonnet::appenv(\%httpref);
1.254 www 2699: }
1.477 raeburn 2700:
1.1193 raeburn 2701: #
2702: # Determine if the current user should be able to edit a particular resource,
2703: # when viewing in course context.
2704: # (a) When viewing resource used to determine if "Edit" item is included in
2705: # Functions.
2706: # (b) When displaying folder contents in course editor, used to determine if
2707: # "Edit" link will be displayed alongside resource.
2708: #
1.1196 raeburn 2709: # input: six args -- filename (decluttered), course number, course domain,
2710: # url, symb (if registered) and group (if this is a group
2711: # item -- e.g., bulletin board, group page etc.).
2712: # output: array of five scalars --
1.1193 raeburn 2713: # $cfile -- url for file editing if editable on current server
2714: # $home -- homeserver of resource (i.e., for author if published,
2715: # or course if uploaded.).
2716: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 2717: # $forceedit -- 1 if icon/link should be to go to edit mode
2718: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 2719: #
2720:
2721: sub can_edit_resource {
1.1194 raeburn 2722: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2723: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2724: #
2725: # For aboutme pages user can only edit his/her own.
2726: #
1.1199 raeburn 2727: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 2728: my ($sdom,$sname) = ($1,$2);
2729: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2730: $home = $env{'user.home'};
2731: $cfile = $resurl;
2732: if ($env{'form.forceedit'}) {
2733: $forceview = 1;
2734: } else {
2735: $forceedit = 1;
2736: }
2737: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2738: } else {
2739: return;
2740: }
2741: }
2742:
2743: if ($env{'request.course.id'}) {
2744: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2745: if ($group ne '') {
2746: # if this is a group homepage or group bulletin board, check group privs
2747: my $allowed = 0;
1.1197 raeburn 2748: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2749: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 2750: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 2751: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2752: $allowed = 1;
2753: }
1.1197 raeburn 2754: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2755: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2756: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 2757: $allowed = 1;
2758: }
2759: }
2760: if ($allowed) {
2761: $home=&homeserver($cnum,$cdom);
2762: if ($env{'form.forceedit'}) {
2763: $forceview = 1;
2764: } else {
2765: $forceedit = 1;
2766: }
2767: $cfile = $resurl;
2768: } else {
2769: return;
2770: }
2771: } else {
1.1208 raeburn 2772: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2773: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2774: return;
2775: }
2776: } elsif (!$crsedit) {
1.1194 raeburn 2777: #
2778: # No edit allowed where CC has switched to student role.
2779: #
2780: return;
2781: }
2782: }
2783: }
2784:
1.1193 raeburn 2785: if ($file ne '') {
2786: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 2787: if (&is_course_upload($file,$cnum,$cdom)) {
2788: $uploaded = 1;
2789: $incourse = 1;
1.1193 raeburn 2790: if ($file =~/\.(htm|html|css|js|txt)$/) {
2791: $cfile = &hreflocation('',$file);
1.1201 raeburn 2792: if ($env{'form.forceedit'}) {
2793: $forceview = 1;
2794: } else {
2795: $forceedit = 1;
2796: }
1.1194 raeburn 2797: }
2798: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2799: $incourse = 1;
2800: if ($env{'form.forceedit'}) {
2801: $forceview = 1;
2802: } else {
2803: $forceedit = 1;
2804: }
2805: $cfile = $resurl;
2806: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2807: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2808: $incourse = 1;
2809: if ($env{'form.forceedit'}) {
2810: $forceview = 1;
2811: } else {
2812: $forceedit = 1;
2813: }
2814: $cfile = $resurl;
1.1199 raeburn 2815: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 2816: $incourse = 1;
2817: $cfile = $resurl.'/smpedit';
1.1199 raeburn 2818: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 2819: $incourse = 1;
1.1199 raeburn 2820: if ($env{'form.forceedit'}) {
2821: $forceview = 1;
2822: } else {
2823: $forceedit = 1;
2824: }
2825: $cfile = $resurl;
1.1208 raeburn 2826: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2827: $incourse = 1;
2828: if ($env{'form.forceedit'}) {
2829: $forceview = 1;
2830: } else {
2831: $forceedit = 1;
2832: }
2833: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 2834: }
2835: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2836: my $template = '/res/lib/templates/simpleproblem.problem';
2837: if (&is_on_map($template)) {
2838: $incourse = 1;
2839: $forceview = 1;
2840: $cfile = $template;
1.1193 raeburn 2841: }
1.1199 raeburn 2842: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2843: $incourse = 1;
2844: if ($env{'form.forceedit'}) {
2845: $forceview = 1;
2846: } else {
2847: $forceedit = 1;
2848: }
2849: $cfile = $resurl;
2850: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2851: $incourse = 1;
2852: $forceview = 1;
2853: if ($symb) {
2854: my ($map,$id,$res)=&decode_symb($symb);
2855: $env{'request.symb'} = $symb;
2856: $cfile = &clutter($res);
2857: } else {
2858: $cfile = $env{'form.suppurl'};
2859: $cfile =~ s{^http://}{};
2860: $cfile = '/adm/wrapper/ext/'.$cfile;
2861: }
1.1234 raeburn 2862: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2863: if ($env{'form.forceedit'}) {
2864: $forceview = 1;
2865: } else {
2866: $forceedit = 1;
2867: }
2868: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 2869: }
2870: }
1.1194 raeburn 2871: if ($uploaded || $incourse) {
2872: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 2873: } elsif ($file !~ m{/$}) {
1.1193 raeburn 2874: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2875: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2876: # Check that the user has permission to edit this resource
2877: my $setpriv = 1;
2878: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2879: if (defined($cfudom)) {
2880: $home=&homeserver($cfuname,$cfudom);
2881: $cfile=$file;
2882: }
2883: }
1.1194 raeburn 2884: if (($cfile ne '') && (!$incourse || $uploaded) &&
2885: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 2886: my @ids=¤t_machine_ids();
2887: unless (grep(/^\Q$home\E$/,@ids)) {
2888: $switchserver=1;
2889: }
2890: }
2891: }
1.1194 raeburn 2892: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 2893: }
2894:
2895: sub is_course_upload {
2896: my ($file,$cnum,$cdom) = @_;
2897: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2898: $uploadpath =~ s{^\/}{};
1.1201 raeburn 2899: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2900: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 2901: return 1;
2902: }
2903: return;
2904: }
2905:
1.1194 raeburn 2906: sub in_course {
1.1195 raeburn 2907: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2908: if ($hideprivileged) {
2909: my $skipuser;
1.1219 raeburn 2910: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2911: my @possdoms = ($cdom);
2912: if ($coursehash{'checkforpriv'}) {
2913: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2914: }
2915: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 2916: $skipuser = 1;
2917: if ($coursehash{'nothideprivileged'}) {
2918: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2919: my $user;
2920: if ($item =~ /:/) {
2921: $user = $item;
2922: } else {
2923: $user = join(':',split(/[\@]/,$item));
2924: }
2925: if ($user eq $uname.':'.$udom) {
2926: undef($skipuser);
2927: last;
2928: }
2929: }
2930: }
2931: if ($skipuser) {
2932: return 0;
2933: }
2934: }
2935: }
1.1194 raeburn 2936: $type ||= 'any';
2937: if (!defined($cdom) || !defined($cnum)) {
2938: my $cid = $env{'request.course.id'};
2939: $cdom = $env{'course.'.$cid.'.domain'};
2940: $cnum = $env{'course.'.$cid.'.num'};
2941: }
2942: my $typesref;
1.1195 raeburn 2943: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 2944: $typesref = ['active','previous','future'];
2945: } elsif ($type eq 'previous' || $type eq 'future') {
2946: $typesref = [$type];
2947: }
2948: my %roles = &get_my_roles($uname,$udom,'userroles',
2949: $typesref,undef,[$cdom]);
2950: my ($tmp) = keys(%roles);
2951: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
2952: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
2953: if (@course_roles > 0) {
2954: return 1;
2955: }
2956: return 0;
2957: }
2958:
1.478 albertel 2959: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2960: # input: action, courseID, current domain, intended
1.637 raeburn 2961: # path to file, source of file, instruction to parse file for objects,
2962: # ref to hash for embedded objects,
2963: # ref to hash for codebase of java objects.
1.1095 raeburn 2964: # reference to scalar to accommodate mime type determined
2965: # from File::MMagic if $parser = parse.
1.637 raeburn 2966: #
1.485 raeburn 2967: # output: url to file (if action was uploaddoc),
2968: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2969: #
1.478 albertel 2970: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2971: # course.
1.477 raeburn 2972: #
1.478 albertel 2973: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2974: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2975: # course's home server.
1.477 raeburn 2976: #
1.478 albertel 2977: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2978: # be copied from $source (current location) to
2979: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2980: # and will then be copied to
2981: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2982: # course's home server.
1.485 raeburn 2983: #
1.481 raeburn 2984: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2985: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2986: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2987: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2988: # in course's home server.
1.637 raeburn 2989: #
1.477 raeburn 2990:
2991: sub process_coursefile {
1.1095 raeburn 2992: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2993: $mimetype)=@_;
1.477 raeburn 2994: my $fetchresult;
1.638 albertel 2995: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2996: if ($action eq 'propagate') {
1.638 albertel 2997: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2998: $home);
1.481 raeburn 2999: } else {
1.477 raeburn 3000: my $fpath = '';
3001: my $fname = $file;
1.478 albertel 3002: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3003: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3004: my $filepath = &build_filepath($fpath);
1.481 raeburn 3005: if ($action eq 'copy') {
3006: if ($source eq '') {
3007: $fetchresult = 'no source file';
3008: return $fetchresult;
3009: } else {
3010: my $destination = $filepath.'/'.$fname;
3011: rename($source,$destination);
3012: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3013: $home);
1.481 raeburn 3014: }
3015: } elsif ($action eq 'uploaddoc') {
3016: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3017: print $fh $env{'form.'.$source};
1.481 raeburn 3018: close($fh);
1.637 raeburn 3019: if ($parser eq 'parse') {
1.1024 raeburn 3020: my $mm = new File::MMagic;
1.1095 raeburn 3021: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3022: if ($type eq 'text/html') {
1.1024 raeburn 3023: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3024: unless ($parse_result eq 'ok') {
3025: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3026: }
1.637 raeburn 3027: }
1.1095 raeburn 3028: if (ref($mimetype)) {
3029: $$mimetype = $type;
3030: }
1.637 raeburn 3031: }
1.477 raeburn 3032: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3033: $home);
1.481 raeburn 3034: if ($fetchresult eq 'ok') {
3035: return '/uploaded/'.$fpath.'/'.$fname;
3036: } else {
3037: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3038: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3039: return '/adm/notfound.html';
3040: }
1.477 raeburn 3041: }
3042: }
1.485 raeburn 3043: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3044: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3045: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3046: }
3047: return $fetchresult;
3048: }
3049:
1.637 raeburn 3050: sub build_filepath {
3051: my ($fpath) = @_;
3052: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3053: unless ($fpath eq '') {
3054: my @parts=split('/',$fpath);
3055: foreach my $part (@parts) {
3056: $filepath.= '/'.$part;
3057: if ((-e $filepath)!=1) {
3058: mkdir($filepath,0777);
3059: }
3060: }
3061: }
3062: return $filepath;
3063: }
3064:
3065: sub store_edited_file {
1.638 albertel 3066: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3067: my $file = $primary_url;
3068: $file =~ s#^/uploaded/$docudom/$docuname/##;
3069: my $fpath = '';
3070: my $fname = $file;
3071: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3072: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3073: my $filepath = &build_filepath($fpath);
3074: open(my $fh,'>'.$filepath.'/'.$fname);
3075: print $fh $content;
3076: close($fh);
1.638 albertel 3077: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3078: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3079: $home);
1.637 raeburn 3080: if ($$fetchresult eq 'ok') {
3081: return '/uploaded/'.$fpath.'/'.$fname;
3082: } else {
1.638 albertel 3083: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3084: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3085: return '/adm/notfound.html';
3086: }
3087: }
3088:
1.531 albertel 3089: sub clean_filename {
1.831 albertel 3090: my ($fname,$args)=@_;
1.315 www 3091: # Replace Windows backslashes by forward slashes
1.257 www 3092: $fname=~s/\\/\//g;
1.831 albertel 3093: if (!$args->{'keep_path'}) {
3094: # Get rid of everything but the actual filename
3095: $fname=~s/^.*\/([^\/]+)$/$1/;
3096: }
1.315 www 3097: # Replace spaces by underscores
3098: $fname=~s/\s+/\_/g;
3099: # Replace all other weird characters by nothing
1.831 albertel 3100: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3101: # Replace all .\d. sequences with _\d. so they no longer look like version
3102: # numbers
3103: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3104: return $fname;
3105: }
1.1051 raeburn 3106: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3107: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3108: # image with the same aspect ratio as the original, but with dimensions which do
3109: # not exceed $resizewidth and $resizeheight.
3110:
1.984 neumanie 3111: sub resizeImage {
1.1051 raeburn 3112: my ($img_path,$resizewidth,$resizeheight) = @_;
3113: my $ima = Image::Magick->new;
3114: my $resized;
3115: if (-e $img_path) {
3116: $ima->Read($img_path);
3117: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3118: my $width = $ima->Get('width');
3119: my $height = $ima->Get('height');
3120: if ($width > $resizewidth) {
3121: my $factor = $width/$resizewidth;
3122: my $newheight = $height/$factor;
3123: $ima->Scale(width=>$resizewidth,height=>$newheight);
3124: $resized = 1;
3125: }
3126: }
3127: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3128: my $width = $ima->Get('width');
3129: my $height = $ima->Get('height');
3130: if ($height > $resizeheight) {
3131: my $factor = $height/$resizeheight;
3132: my $newwidth = $width/$factor;
3133: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3134: $resized = 1;
3135: }
3136: }
3137: if ($resized) {
3138: $ima->Write($img_path);
3139: }
3140: }
3141: return;
1.977 amueller 3142: }
3143:
1.608 albertel 3144: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3145: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3146: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3147: # $context - possible values: coursedoc, existingfile, overwrite,
3148: # canceloverwrite, or ''.
3149: # if 'coursedoc': upload to the current course
3150: # if 'existingfile': write file to tmp/overwrites directory
3151: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3152: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3153: # $subdir - directory in userfile to store the file into
1.858 raeburn 3154: # $parser - instruction to parse file for objects ($parser = parse)
3155: # $allfiles - reference to hash for embedded objects
3156: # $codebase - reference to hash for codebase of java objects
3157: # $desuname - username for permanent storage of uploaded file
3158: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3159: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3160: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3161: # $resizewidth - width (pixels) to which to resize uploaded image
3162: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3163: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3164: # from File::MMagic.
1.858 raeburn 3165: #
1.686 albertel 3166: # output: url of file in userspace, or error: <message>
3167: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3168:
1.531 albertel 3169: sub userfileupload {
1.1090 raeburn 3170: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3171: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3172: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3173: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3174: $fname=&clean_filename($fname);
1.1090 raeburn 3175: # See if there is anything left
1.257 www 3176: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3177: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3178: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3179: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3180: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3181: my $now = time;
1.1090 raeburn 3182: my $filepath;
1.1095 raeburn 3183: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3184: $filepath = 'tmp/helprequests/'.$now;
3185: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3186: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3187: '_'.$env{'user.domain'}.'/pending';
3188: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3189: my ($docuname,$docudom);
3190: if ($destudom) {
3191: $docudom = $destudom;
3192: } else {
3193: $docudom = $env{'user.domain'};
3194: }
3195: if ($destuname) {
3196: $docuname = $destuname;
3197: } else {
3198: $docuname = $env{'user.name'};
3199: }
3200: if (exists($env{'form.group'})) {
3201: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3202: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3203: }
3204: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3205: if ($context eq 'canceloverwrite') {
3206: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3207: if (-e $tempfile) {
3208: my @info = stat($tempfile);
3209: if ($info[9] eq $env{'form.timestamp'}) {
3210: unlink($tempfile);
3211: }
3212: }
3213: return;
1.523 raeburn 3214: }
3215: }
1.1090 raeburn 3216: # Create the directory if not present
1.741 raeburn 3217: my @parts=split(/\//,$filepath);
3218: my $fullpath = $perlvar{'lonDaemons'};
3219: for (my $i=0;$i<@parts;$i++) {
3220: $fullpath .= '/'.$parts[$i];
3221: if ((-e $fullpath)!=1) {
3222: mkdir($fullpath,0777);
3223: }
3224: }
3225: open(my $fh,'>'.$fullpath.'/'.$fname);
3226: print $fh $env{'form.'.$formname};
3227: close($fh);
1.1090 raeburn 3228: if ($context eq 'existingfile') {
3229: my @info = stat($fullpath.'/'.$fname);
3230: return ($fullpath.'/'.$fname,$info[9]);
3231: } else {
3232: return $fullpath.'/'.$fname;
3233: }
1.523 raeburn 3234: }
1.995 raeburn 3235: if ($subdir eq 'scantron') {
3236: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3237: } else {
1.995 raeburn 3238: $fname="$subdir/$fname";
3239: }
1.1090 raeburn 3240: if ($context eq 'coursedoc') {
1.638 albertel 3241: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3242: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3243: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3244: return &finishuserfileupload($docuname,$docudom,
3245: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3246: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3247: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3248: } else {
1.1218 raeburn 3249: if ($env{'form.folder'}) {
3250: $fname=$env{'form.folder'}.'/'.$fname;
3251: }
1.638 albertel 3252: return &process_coursefile('uploaddoc',$docuname,$docudom,
3253: $fname,$formname,$parser,
1.1095 raeburn 3254: $allfiles,$codebase,$mimetype);
1.481 raeburn 3255: }
1.719 banghart 3256: } elsif (defined($destuname)) {
3257: my $docuname=$destuname;
3258: my $docudom=$destudom;
1.860 raeburn 3259: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3260: $parser,$allfiles,$codebase,
1.1051 raeburn 3261: $thumbwidth,$thumbheight,
1.1095 raeburn 3262: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3263: } else {
1.638 albertel 3264: my $docuname=$env{'user.name'};
3265: my $docudom=$env{'user.domain'};
1.1220 raeburn 3266: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3267: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3268: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3269: }
1.860 raeburn 3270: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3271: $parser,$allfiles,$codebase,
1.1051 raeburn 3272: $thumbwidth,$thumbheight,
1.1095 raeburn 3273: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3274: }
1.271 www 3275: }
3276:
3277: sub finishuserfileupload {
1.860 raeburn 3278: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3279: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3280: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3281: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3282:
1.860 raeburn 3283: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3284: $file=$fname;
3285: if ($fname=~m|/|) {
3286: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3287: $path.=$fnamepath.'/';
3288: }
1.259 www 3289: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3290: my $count;
3291: for ($count=4;$count<=$#parts;$count++) {
3292: $filepath.="/$parts[$count]";
3293: if ((-e $filepath)!=1) {
3294: mkdir($filepath,0777);
3295: }
3296: }
1.984 neumanie 3297:
1.258 www 3298: # Save the file
3299: {
1.701 albertel 3300: if (!open(FH,'>'.$filepath.'/'.$file)) {
3301: &logthis('Failed to create '.$filepath.'/'.$file);
3302: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3303: return '/adm/notfound.html';
3304: }
1.1090 raeburn 3305: if ($context eq 'overwrite') {
1.1117 foxr 3306: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3307: my $target = $filepath.'/'.$file;
3308: if (-e $source) {
3309: my @info = stat($source);
3310: if ($info[9] eq $env{'form.timestamp'}) {
3311: unless (&File::Copy::move($source,$target)) {
3312: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3313: return "Moving from $source failed";
3314: }
3315: } else {
3316: return "Temporary file: $source had unexpected date/time for last modification";
3317: }
3318: } else {
3319: return "Temporary file: $source missing";
3320: }
3321: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3322: &logthis('Failed to write to '.$filepath.'/'.$file);
3323: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3324: return '/adm/notfound.html';
3325: }
1.570 albertel 3326: close(FH);
1.1051 raeburn 3327: if ($resizewidth && $resizeheight) {
3328: my $mm = new File::MMagic;
3329: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3330: if ($mime_type =~ m{^image/}) {
3331: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3332: }
1.977 amueller 3333: }
1.258 www 3334: }
1.1152 raeburn 3335: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3336: if (ref($mimetype)) {
3337: if ($$mimetype eq '') {
3338: my $mm = new File::MMagic;
3339: my $type = $mm->checktype_filename($filepath.'/'.$file);
3340: $$mimetype = $type;
3341: }
3342: }
3343: }
1.637 raeburn 3344: if ($parser eq 'parse') {
1.1152 raeburn 3345: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3346: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3347: $allfiles,$codebase);
3348: unless ($parse_result eq 'ok') {
3349: &logthis('Failed to parse '.$filepath.$file.
3350: ' for embedded media: '.$parse_result);
3351: }
1.637 raeburn 3352: }
3353: }
1.860 raeburn 3354: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3355: my $input = $filepath.'/'.$file;
3356: my $output = $filepath.'/'.'tn-'.$file;
3357: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3358: system("convert -sample $thumbsize $input $output");
3359: if (-e $filepath.'/'.'tn-'.$file) {
3360: $fetchthumb = 1;
3361: }
3362: }
1.858 raeburn 3363:
1.259 www 3364: # Notify homeserver to grep it
3365: #
1.984 neumanie 3366: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3367: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3368: if ($fetchresult eq 'ok') {
1.860 raeburn 3369: if ($fetchthumb) {
3370: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3371: if ($thumbresult ne 'ok') {
3372: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3373: $docuhome.': '.$thumbresult);
3374: }
3375: }
1.259 www 3376: #
1.258 www 3377: # Return the URL to it
1.494 albertel 3378: return '/uploaded/'.$path.$file;
1.263 www 3379: } else {
1.494 albertel 3380: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3381: ': '.$fetchresult);
1.263 www 3382: return '/adm/notfound.html';
1.858 raeburn 3383: }
1.493 albertel 3384: }
3385:
1.637 raeburn 3386: sub extract_embedded_items {
1.961 raeburn 3387: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3388: my @state = ();
1.1164 raeburn 3389: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3390: my %javafiles = (
3391: codebase => '',
3392: code => '',
3393: archive => ''
3394: );
3395: my %mediafiles = (
3396: src => '',
3397: movie => '',
3398: );
1.648 raeburn 3399: my $p;
3400: if ($content) {
3401: $p = HTML::LCParser->new($content);
3402: } else {
1.961 raeburn 3403: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3404: }
1.641 albertel 3405: while (my $t=$p->get_token()) {
1.640 albertel 3406: if ($t->[0] eq 'S') {
3407: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3408: push(@state, $tagname);
1.648 raeburn 3409: if (lc($tagname) eq 'allow') {
3410: &add_filetype($allfiles,$attr->{'src'},'src');
3411: }
1.640 albertel 3412: if (lc($tagname) eq 'img') {
3413: &add_filetype($allfiles,$attr->{'src'},'src');
3414: }
1.886 albertel 3415: if (lc($tagname) eq 'a') {
1.1222 raeburn 3416: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3417: &add_filetype($allfiles,$attr->{'href'},'href');
3418: }
1.886 albertel 3419: }
1.645 raeburn 3420: if (lc($tagname) eq 'script') {
1.1164 raeburn 3421: my $src;
1.645 raeburn 3422: if ($attr->{'archive'} =~ /\.jar$/i) {
3423: &add_filetype($allfiles,$attr->{'archive'},'archive');
3424: } else {
1.1164 raeburn 3425: if ($attr->{'src'} ne '') {
3426: $src = $attr->{'src'};
3427: &add_filetype($allfiles,$src,'src');
3428: }
3429: }
3430: my $text = $p->get_trimmed_text();
3431: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3432: my @swfargs = split(/,/,$1);
3433: foreach my $item (@swfargs) {
3434: $item =~ s/["']//g;
3435: $item =~ s/^\s+//;
3436: $item =~ s/\s+$//;
3437: }
3438: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3439: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3440: push(@{$related{$swfargs[0]}},$swfargs[2]);
3441: } else {
3442: $related{$swfargs[0]} = [$swfargs[2]];
3443: }
3444: }
1.645 raeburn 3445: }
3446: }
3447: if (lc($tagname) eq 'link') {
3448: if (lc($attr->{'rel'}) eq 'stylesheet') {
3449: &add_filetype($allfiles,$attr->{'href'},'href');
3450: }
3451: }
1.640 albertel 3452: if (lc($tagname) eq 'object' ||
3453: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3454: foreach my $item (keys(%javafiles)) {
3455: $javafiles{$item} = '';
3456: }
1.1164 raeburn 3457: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3458: $lastids{lc($tagname)} = $attr->{'id'};
3459: }
1.640 albertel 3460: }
3461: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3462: my $name = lc($attr->{'name'});
3463: foreach my $item (keys(%javafiles)) {
3464: if ($name eq $item) {
3465: $javafiles{$item} = $attr->{'value'};
3466: last;
3467: }
3468: }
1.1164 raeburn 3469: my $pathfrom;
1.640 albertel 3470: foreach my $item (keys(%mediafiles)) {
3471: if ($name eq $item) {
1.1164 raeburn 3472: $pathfrom = $attr->{'value'};
3473: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3474: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3475: last;
3476: }
3477: }
1.1164 raeburn 3478: if ($name eq 'flashvars') {
3479: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3480: }
3481: if ($pathfrom ne '') {
3482: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3483: $pathfrom);
3484: }
1.640 albertel 3485: }
3486: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3487: foreach my $item (keys(%javafiles)) {
3488: if ($attr->{$item}) {
3489: $javafiles{$item} = $attr->{$item};
3490: last;
3491: }
3492: }
3493: foreach my $item (keys(%mediafiles)) {
3494: if ($attr->{$item}) {
3495: &add_filetype($allfiles,$attr->{$item},$item);
3496: last;
3497: }
3498: }
1.1164 raeburn 3499: if (lc($tagname) eq 'embed') {
3500: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3501: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3502: $attr->{'src'});
3503: }
3504: }
1.640 albertel 3505: }
1.1243 raeburn 3506: if (lc($tagname) eq 'iframe') {
3507: my $src = $attr->{'src'} ;
3508: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3509: &add_filetype($allfiles,$src,'src');
3510: } elsif ($src =~ m{^/}) {
3511: if ($env{'request.course.id'}) {
3512: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3513: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3514: my $url = &hreflocation('',$fullpath);
3515: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3516: my $relpath = $1;
3517: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3518: &add_filetype($allfiles,$1,'src');
3519: }
3520: }
3521: }
3522: }
3523: }
1.1164 raeburn 3524: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3525: pop(@state);
1.1164 raeburn 3526: }
1.640 albertel 3527: } elsif ($t->[0] eq 'E') {
3528: my ($tagname) = ($t->[1]);
3529: if ($javafiles{'codebase'} ne '') {
3530: $javafiles{'codebase'} .= '/';
3531: }
3532: if (lc($tagname) eq 'applet' ||
3533: lc($tagname) eq 'object' ||
3534: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3535: ) {
3536: foreach my $item (keys(%javafiles)) {
3537: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3538: my $file=$javafiles{'codebase'}.$javafiles{$item};
3539: &add_filetype($allfiles,$file,$item);
3540: }
3541: }
3542: }
3543: pop @state;
3544: }
3545: }
1.1164 raeburn 3546: foreach my $id (sort(keys(%flashvars))) {
3547: if ($shockwave{$id} ne '') {
3548: my @pairs = split(/\&/,$flashvars{$id});
3549: foreach my $pair (@pairs) {
3550: my ($key,$value) = split(/\=/,$pair);
3551: if ($key eq 'thumb') {
3552: &add_filetype($allfiles,$value,$key);
3553: } elsif ($key eq 'content') {
3554: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3555: my ($ext) = ($value =~ /\.([^.]+)$/);
3556: if ($ext ne '') {
3557: &add_filetype($allfiles,$path.$value,$ext);
3558: }
3559: }
3560: }
3561: }
3562: }
1.637 raeburn 3563: return 'ok';
3564: }
3565:
1.639 albertel 3566: sub add_filetype {
3567: my ($allfiles,$file,$type)=@_;
3568: if (exists($allfiles->{$file})) {
3569: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3570: push(@{$allfiles->{$file}}, &escape($type));
3571: }
3572: } else {
3573: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3574: }
3575: }
3576:
1.1164 raeburn 3577: sub embedded_dependency {
3578: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3579: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3580: if (($identifier ne '') &&
3581: (ref($related->{$identifier}) eq 'ARRAY') &&
3582: ($pathfrom ne '')) {
3583: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3584: foreach my $dep (@{$related->{$identifier}}) {
3585: &add_filetype($allfiles,$path.$dep,'object');
3586: }
3587: }
3588: }
3589: return;
3590: }
3591:
1.493 albertel 3592: sub removeuploadedurl {
1.984 neumanie 3593: my ($url)=@_;
3594: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3595: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3596: }
3597:
3598: sub removeuserfile {
3599: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3600: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3601: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3602: if ($result eq 'ok') {
1.798 raeburn 3603: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3604: my $metafile = $fname.'.meta';
3605: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3606: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3607: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3608: my $sqlresult =
1.823 albertel 3609: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3610: 'portfolio_metadata',$group,
3611: 'delete');
1.798 raeburn 3612: }
3613: }
3614: return $result;
1.257 www 3615: }
1.15 www 3616:
1.530 albertel 3617: sub mkdiruserfile {
3618: my ($docuname,$docudom,$dir)=@_;
3619: my $home=&homeserver($docuname,$docudom);
3620: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3621: }
3622:
1.531 albertel 3623: sub renameuserfile {
3624: my ($docuname,$docudom,$old,$new)=@_;
3625: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3626: my $result = &reply("renameuserfile:$docudom:$docuname:".
3627: &escape("$old").':'.&escape("$new"),$home);
3628: if ($result eq 'ok') {
3629: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3630: my $oldmeta = $old.'.meta';
3631: my $newmeta = $new.'.meta';
3632: my $metaresult =
3633: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3634: my $url = "/uploaded/$docudom/$docuname/$old";
3635: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3636: my $sqlresult =
1.823 albertel 3637: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3638: 'portfolio_metadata',$group,
3639: 'delete');
1.798 raeburn 3640: }
3641: }
3642: return $result;
1.531 albertel 3643: }
3644:
1.14 www 3645: # ------------------------------------------------------------------------- Log
3646:
3647: sub log {
3648: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3649: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3650: }
3651:
3652: # ------------------------------------------------------------------ Course Log
1.352 www 3653: #
3654: # This routine flushes several buffers of non-mission-critical nature
3655: #
1.157 www 3656:
3657: sub flushcourselogs {
1.352 www 3658: &logthis('Flushing log buffers');
3659: #
3660: # course logs
3661: # This is a log of all transactions in a course, which can be used
3662: # for data mining purposes
3663: #
3664: # It also collects the courseid database, which lists last transaction
3665: # times and course titles for all courseids
3666: #
3667: my %courseidbuffer=();
1.921 raeburn 3668: foreach my $crsid (keys(%courselogs)) {
1.352 www 3669: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3670: &escape($courselogs{$crsid}),
3671: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3672: delete $courselogs{$crsid};
3673: } else {
3674: &logthis('Failed to flush log buffer for '.$crsid);
3675: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3676: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3677: " exceeded maximum size, deleting.</font>");
3678: delete $courselogs{$crsid};
3679: }
1.352 www 3680: }
1.920 raeburn 3681: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3682: 'description' => $coursedescrbuf{$crsid},
3683: 'inst_code' => $courseinstcodebuf{$crsid},
3684: 'type' => $coursetypebuf{$crsid},
3685: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3686: };
1.191 harris41 3687: }
1.352 www 3688: #
3689: # Write course id database (reverse lookup) to homeserver of courses
3690: # Is used in pickcourse
3691: #
1.840 albertel 3692: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3693: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3694: $courseidbuffer{$crs_home},
3695: $crs_home,'timeonly');
1.352 www 3696: }
3697: #
3698: # File accesses
3699: # Writes to the dynamic metadata of resources to get hit counts, etc.
3700: #
1.449 matthew 3701: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3702: if ($entry =~ /___count$/) {
3703: my ($dom,$name);
1.807 albertel 3704: ($dom,$name,undef)=
1.811 albertel 3705: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3706: if (! defined($dom) || $dom eq '' ||
3707: ! defined($name) || $name eq '') {
1.620 albertel 3708: my $cid = $env{'request.course.id'};
3709: $dom = $env{'request.'.$cid.'.domain'};
3710: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3711: }
1.450 matthew 3712: my $value = $accesshash{$entry};
3713: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3714: my %temphash=($url => $value);
1.449 matthew 3715: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3716: if ($result eq 'ok') {
3717: delete $accesshash{$entry};
3718: }
3719: } else {
1.811 albertel 3720: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3721: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3722: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3723: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3724: delete $accesshash{$entry};
3725: }
1.185 www 3726: }
1.191 harris41 3727: }
1.352 www 3728: #
3729: # Roles
3730: # Reverse lookup of user roles for course faculty/staff and co-authorship
3731: #
1.800 albertel 3732: foreach my $entry (keys(%userrolehash)) {
1.351 www 3733: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3734: split(/\:/,$entry);
3735: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3736: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3737: $rudom,$runame) eq 'ok') {
3738: delete $userrolehash{$entry};
3739: }
3740: }
1.662 raeburn 3741: #
3742: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3743: #
3744: my %domrolebuffer = ();
1.1000 raeburn 3745: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3746: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3747: if ($domrolebuffer{$rudom}) {
3748: $domrolebuffer{$rudom}.='&'.&escape($entry).
3749: '='.&escape($domainrolehash{$entry});
3750: } else {
3751: $domrolebuffer{$rudom}.=&escape($entry).
3752: '='.&escape($domainrolehash{$entry});
3753: }
3754: delete $domainrolehash{$entry};
3755: }
3756: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3757: my %servers = &get_servers($dom,'library');
3758: foreach my $tryserver (keys(%servers)) {
3759: unless (&reply('domroleput:'.$dom.':'.
3760: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3761: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3762: }
1.662 raeburn 3763: }
3764: }
1.186 www 3765: $dumpcount++;
1.157 www 3766: }
3767:
3768: sub courselog {
3769: my $what=shift;
1.158 www 3770: $what=time.':'.$what;
1.620 albertel 3771: unless ($env{'request.course.id'}) { return ''; }
3772: $coursedombuf{$env{'request.course.id'}}=
3773: $env{'course.'.$env{'request.course.id'}.'.domain'};
3774: $coursenumbuf{$env{'request.course.id'}}=
3775: $env{'course.'.$env{'request.course.id'}.'.num'};
3776: $coursehombuf{$env{'request.course.id'}}=
3777: $env{'course.'.$env{'request.course.id'}.'.home'};
3778: $coursedescrbuf{$env{'request.course.id'}}=
3779: $env{'course.'.$env{'request.course.id'}.'.description'};
3780: $courseinstcodebuf{$env{'request.course.id'}}=
3781: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3782: $courseownerbuf{$env{'request.course.id'}}=
3783: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3784: $coursetypebuf{$env{'request.course.id'}}=
3785: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3786: if (defined $courselogs{$env{'request.course.id'}}) {
3787: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3788: } else {
1.620 albertel 3789: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3790: }
1.620 albertel 3791: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3792: &flushcourselogs();
3793: }
1.158 www 3794: }
3795:
3796: sub courseacclog {
3797: my $fnsymb=shift;
1.620 albertel 3798: unless ($env{'request.course.id'}) { return ''; }
3799: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3800: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3801: $what.=':POST';
1.583 matthew 3802: # FIXME: Probably ought to escape things....
1.800 albertel 3803: foreach my $key (keys(%env)) {
3804: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3805: my $formitem = $1;
3806: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3807: $what.=':'.$formitem.'='.$env{$key};
3808: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3809: $what.=':'.$formitem.'='.$env{$key};
3810: }
1.158 www 3811: }
1.191 harris41 3812: }
1.583 matthew 3813: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3814: # FIXME: We should not be depending on a form parameter that someone
3815: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3816: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3817: $what.= ':POST';
3818: # FIXME: Probably ought to escape things....
3819: foreach my $element ('courseexp','crsfulltext','crsrelated',
3820: 'crsdiscuss') {
1.620 albertel 3821: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3822: }
3823: }
1.158 www 3824: }
3825: &courselog($what);
1.149 www 3826: }
3827:
1.185 www 3828: sub countacc {
3829: my $url=&declutter(shift);
1.458 matthew 3830: return if (! defined($url) || $url eq '');
1.620 albertel 3831: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3832: #
3833: # Mark that this url was used in this course
3834: #
1.620 albertel 3835: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3836: #
3837: # Increase the access count for this resource in this child process
3838: #
1.281 www 3839: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3840: $accesshash{$key}++;
1.185 www 3841: }
1.349 www 3842:
1.361 www 3843: sub linklog {
3844: my ($from,$to)=@_;
3845: $from=&declutter($from);
3846: $to=&declutter($to);
3847: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3848: $accesshash{$to.'___'.$from.'___goto'}=1;
3849: }
1.1160 www 3850:
3851: sub statslog {
3852: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3853: if ($users<2) { return; }
3854: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3855: 'course' => $env{'request.course.id'},
3856: 'sections' => '"all"',
3857: 'num_students' => $users,
3858: 'part' => $part,
3859: 'symb' => $symb,
3860: 'mean_tries' => $av_attempts,
3861: 'deg_of_diff' => $degdiff});
3862: foreach my $key (keys(%dynstore)) {
3863: $accesshash{$key}=$dynstore{$key};
3864: }
3865: }
1.361 www 3866:
1.349 www 3867: sub userrolelog {
3868: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3869: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3870: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3871: $userrolehash
3872: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3873: =$tend.':'.$tstart;
1.662 raeburn 3874: }
1.1169 droeschl 3875: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3876: $userrolehash
3877: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3878: =$tend.':'.$tstart;
3879: }
1.1169 droeschl 3880: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3881: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3882: $domainrolehash
3883: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3884: = $tend.':'.$tstart;
3885: }
1.351 www 3886: }
3887:
1.957 raeburn 3888: sub courserolelog {
3889: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 3890: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3891: my $cdom = $1;
3892: my $cnum = $2;
3893: my $sec = $3;
3894: my $namespace = 'rolelog';
3895: my %storehash = (
3896: role => $trole,
3897: start => $tstart,
3898: end => $tend,
3899: selfenroll => $selfenroll,
3900: context => $context,
3901: );
3902: if ($trole eq 'gr') {
3903: $namespace = 'groupslog';
3904: $storehash{'group'} = $sec;
3905: } else {
3906: $storehash{'section'} = $sec;
3907: }
1.1188 raeburn 3908: &write_log('course',$namespace,\%storehash,$delflag,$username,
3909: $domain,$cnum,$cdom);
1.1184 raeburn 3910: if (($trole ne 'st') || ($sec ne '')) {
3911: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3912: }
3913: }
3914: return;
3915: }
3916:
1.1184 raeburn 3917: sub domainrolelog {
3918: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3919: if ($area =~ m{^/($match_domain)/$}) {
3920: my $cdom = $1;
3921: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3922: my $namespace = 'rolelog';
3923: my %storehash = (
3924: role => $trole,
3925: start => $tstart,
3926: end => $tend,
3927: context => $context,
3928: );
1.1188 raeburn 3929: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3930: $domain,$domconfiguser,$cdom);
1.1184 raeburn 3931: }
3932: return;
3933:
3934: }
3935:
3936: sub coauthorrolelog {
3937: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3938: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3939: my $audom = $1;
3940: my $auname = $2;
3941: my $namespace = 'rolelog';
3942: my %storehash = (
3943: role => $trole,
3944: start => $tstart,
3945: end => $tend,
3946: context => $context,
3947: );
1.1188 raeburn 3948: &write_log('author',$namespace,\%storehash,$delflag,$username,
3949: $domain,$auname,$audom);
1.1184 raeburn 3950: }
3951: return;
3952: }
3953:
1.351 www 3954: sub get_course_adv_roles {
1.948 raeburn 3955: my ($cid,$codes) = @_;
1.620 albertel 3956: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3957: my %coursehash=&coursedescription($cid);
1.988 raeburn 3958: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3959: my %nothide=();
1.800 albertel 3960: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3961: if ($user !~ /:/) {
3962: $nothide{join(':',split(/[\@]/,$user))}=1;
3963: } else {
3964: $nothide{$user}=1;
3965: }
1.470 www 3966: }
1.1219 raeburn 3967: my @possdoms = ($coursehash{'domain'});
3968: if ($coursehash{'checkforpriv'}) {
3969: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3970: }
1.351 www 3971: my %returnhash=();
3972: my %dumphash=
3973: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3974: my $now=time;
1.997 raeburn 3975: my %privileged;
1.1000 raeburn 3976: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3977: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3978: if (($tstart) && ($tstart<0)) { next; }
3979: if (($tend) && ($tend<$now)) { next; }
3980: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3981: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3982: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 3983: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 3984: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3985: if ($role eq 'cr') { next; }
1.948 raeburn 3986: if ($codes) {
3987: if ($section) { $role .= ':'.$section; }
3988: if ($returnhash{$role}) {
3989: $returnhash{$role}.=','.$username.':'.$domain;
3990: } else {
3991: $returnhash{$role}=$username.':'.$domain;
3992: }
1.351 www 3993: } else {
1.988 raeburn 3994: my $key=&plaintext($role,$crstype);
1.973 bisitz 3995: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3996: if ($returnhash{$key}) {
3997: $returnhash{$key}.=','.$username.':'.$domain;
3998: } else {
3999: $returnhash{$key}=$username.':'.$domain;
4000: }
1.351 www 4001: }
1.948 raeburn 4002: }
1.400 www 4003: return %returnhash;
4004: }
4005:
4006: sub get_my_roles {
1.937 raeburn 4007: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4008: unless (defined($uname)) { $uname=$env{'user.name'}; }
4009: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4010: my (%dumphash,%nothide);
1.1086 raeburn 4011: if ($context eq 'userroles') {
1.1166 raeburn 4012: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4013: } else {
1.1219 raeburn 4014: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4015: if ($hidepriv) {
4016: my %coursehash=&coursedescription($udom.'_'.$uname);
4017: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4018: if ($user !~ /:/) {
4019: $nothide{join(':',split(/[\@]/,$user))} = 1;
4020: } else {
4021: $nothide{$user} = 1;
4022: }
4023: }
4024: }
1.858 raeburn 4025: }
1.400 www 4026: my %returnhash=();
4027: my $now=time;
1.999 raeburn 4028: my %privileged;
1.800 albertel 4029: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4030: my ($role,$tend,$tstart);
4031: if ($context eq 'userroles') {
1.1149 raeburn 4032: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4033: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4034: } else {
4035: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4036: }
1.400 www 4037: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4038: my $status = 'active';
1.939 raeburn 4039: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4040: $status = 'previous';
4041: }
4042: if (($tstart) && ($now<$tstart)) {
4043: $status = 'future';
4044: }
4045: if (ref($types) eq 'ARRAY') {
4046: if (!grep(/^\Q$status\E$/,@{$types})) {
4047: next;
4048: }
4049: } else {
4050: if ($status ne 'active') {
4051: next;
4052: }
4053: }
1.867 raeburn 4054: my ($rolecode,$username,$domain,$section,$area);
4055: if ($context eq 'userroles') {
1.1186 raeburn 4056: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4057: (undef,$domain,$username,$section) = split(/\//,$area);
4058: } else {
4059: ($role,$username,$domain,$section) = split(/\:/,$entry);
4060: }
1.832 raeburn 4061: if (ref($roledoms) eq 'ARRAY') {
4062: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4063: next;
4064: }
4065: }
4066: if (ref($roles) eq 'ARRAY') {
4067: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4068: if ($role =~ /^cr\//) {
4069: if (!grep(/^cr$/,@{$roles})) {
4070: next;
4071: }
1.1104 raeburn 4072: } elsif ($role =~ /^gr\//) {
4073: if (!grep(/^gr$/,@{$roles})) {
4074: next;
4075: }
1.922 raeburn 4076: } else {
4077: next;
4078: }
1.832 raeburn 4079: }
1.867 raeburn 4080: }
1.937 raeburn 4081: if ($hidepriv) {
1.1219 raeburn 4082: my @privroles = ('dc','su');
1.999 raeburn 4083: if ($context eq 'userroles') {
1.1219 raeburn 4084: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4085: } else {
1.1219 raeburn 4086: my $possdoms = [$domain];
4087: if (ref($roledoms) eq 'ARRAY') {
4088: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4089: }
1.1219 raeburn 4090: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4091: if (!$nothide{$username.':'.$domain}) {
4092: next;
4093: }
4094: }
1.937 raeburn 4095: }
4096: }
1.933 raeburn 4097: if ($withsec) {
4098: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4099: $tstart.':'.$tend;
4100: } else {
4101: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4102: }
1.832 raeburn 4103: }
1.373 www 4104: return %returnhash;
1.399 www 4105: }
4106:
4107: # ----------------------------------------------------- Frontpage Announcements
4108: #
4109: #
4110:
4111: sub postannounce {
4112: my ($server,$text)=@_;
1.844 albertel 4113: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4114: unless ($text=~/\w/) { $text=''; }
4115: return &reply('setannounce:'.&escape($text),$server);
4116: }
4117:
4118: sub getannounce {
1.448 albertel 4119:
4120: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4121: my $announcement='';
1.800 albertel 4122: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4123: close($fh);
1.399 www 4124: if ($announcement=~/\w/) {
4125: return
4126: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4127: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4128: } else {
4129: return '';
4130: }
4131: } else {
4132: return '';
4133: }
1.351 www 4134: }
1.353 www 4135:
4136: # ---------------------------------------------------------- Course ID routines
4137: # Deal with domain's nohist_courseid.db files
4138: #
4139:
4140: sub courseidput {
1.921 raeburn 4141: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4142: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4143: my $outcome;
4144: if ($caller eq 'timeonly') {
4145: my $cids = '';
4146: foreach my $item (keys(%$storehash)) {
4147: $cids.=&escape($item).'&';
4148: }
4149: $cids=~s/\&$//;
4150: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4151: $coursehome);
4152: } else {
4153: my $items = '';
4154: foreach my $item (keys(%$storehash)) {
4155: $items.= &escape($item).'='.
4156: &freeze_escape($$storehash{$item}).'&';
4157: }
4158: $items=~s/\&$//;
4159: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4160: $coursehome);
1.918 raeburn 4161: }
4162: if ($outcome eq 'unknown_cmd') {
4163: my $what;
4164: foreach my $cid (keys(%$storehash)) {
4165: $what .= &escape($cid).'=';
1.921 raeburn 4166: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4167: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4168: }
4169: $what =~ s/\:$/&/;
4170: }
4171: $what =~ s/\&$//;
4172: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4173: } else {
4174: return $outcome;
4175: }
1.353 www 4176: }
4177:
4178: sub courseiddump {
1.921 raeburn 4179: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4180: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4181: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 4182: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 4183: my $as_hash = 1;
4184: my %returnhash;
4185: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4186: my %libserv = &all_library();
4187: foreach my $tryserver (keys(%libserv)) {
4188: if ( ( $hostidflag == 1
4189: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4190: || (!defined($hostidflag)) ) {
4191:
1.918 raeburn 4192: if (($domfilter eq '') ||
4193: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4194: my $rep;
4195: if (grep { $_ eq $tryserver } current_machine_ids()) {
4196: $rep = LONCAPA::Lond::dump_course_id_handler(
4197: join(":", (&host_domain($tryserver), $sincefilter,
4198: &escape($descfilter), &escape($instcodefilter),
4199: &escape($ownerfilter), &escape($coursefilter),
4200: &escape($typefilter), &escape($regexp_ok),
4201: $as_hash, &escape($selfenrollonly),
4202: &escape($catfilter), $showhidden, $caller,
4203: &escape($cloner), &escape($cc_clone), $cloneonly,
4204: &escape($createdbefore), &escape($createdafter),
4205: &escape($creationcontext), $domcloner)));
4206: } else {
4207: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4208: $sincefilter.':'.&escape($descfilter).':'.
4209: &escape($instcodefilter).':'.&escape($ownerfilter).
4210: ':'.&escape($coursefilter).':'.&escape($typefilter).
4211: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4212: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4213: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4214: &escape($cc_clone).':'.$cloneonly.':'.
4215: &escape($createdbefore).':'.&escape($createdafter).':'.
4216: &escape($creationcontext).':'.$domcloner,
4217: $tryserver);
4218: }
4219:
1.918 raeburn 4220: my @pairs=split(/\&/,$rep);
4221: foreach my $item (@pairs) {
4222: my ($key,$value)=split(/\=/,$item,2);
4223: $key = &unescape($key);
4224: next if ($key =~ /^error: 2 /);
4225: my $result = &thaw_unescape($value);
4226: if (ref($result) eq 'HASH') {
4227: $returnhash{$key}=$result;
4228: } else {
1.921 raeburn 4229: my @responses = split(/:/,$value);
4230: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4231: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4232: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4233: }
1.1008 raeburn 4234: }
1.353 www 4235: }
4236: }
4237: }
4238: }
4239: return %returnhash;
4240: }
4241:
1.1055 raeburn 4242: sub courselastaccess {
4243: my ($cdom,$cnum,$hostidref) = @_;
4244: my %returnhash;
4245: if ($cdom && $cnum) {
4246: my $chome = &homeserver($cnum,$cdom);
4247: if ($chome ne 'no_host') {
4248: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4249: &extract_lastaccess(\%returnhash,$rep);
4250: }
4251: } else {
4252: if (!$cdom) { $cdom=''; }
4253: my %libserv = &all_library();
4254: foreach my $tryserver (keys(%libserv)) {
4255: if (ref($hostidref) eq 'ARRAY') {
4256: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4257: }
4258: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4259: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4260: &extract_lastaccess(\%returnhash,$rep);
4261: }
4262: }
4263: }
4264: return %returnhash;
4265: }
4266:
4267: sub extract_lastaccess {
4268: my ($returnhash,$rep) = @_;
4269: if (ref($returnhash) eq 'HASH') {
4270: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4271: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4272: $rep eq '') {
4273: my @pairs=split(/\&/,$rep);
4274: foreach my $item (@pairs) {
4275: my ($key,$value)=split(/\=/,$item,2);
4276: $key = &unescape($key);
4277: next if ($key =~ /^error: 2 /);
4278: $returnhash->{$key} = &thaw_unescape($value);
4279: }
4280: }
4281: }
4282: return;
4283: }
4284:
1.658 raeburn 4285: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4286:
4287: sub dcmailput {
1.685 raeburn 4288: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4289: my $status = &Apache::lonnet::critical(
1.740 www 4290: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4291: &escape($message),$server);
1.662 raeburn 4292: return $status;
4293: }
4294:
1.658 raeburn 4295: sub dcmaildump {
4296: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4297: my %returnhash=();
1.846 albertel 4298:
4299: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4300: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4301: &escape($enddate).':';
4302: my @esc_senders=map { &escape($_)} @$senders;
4303: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4304: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4305: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4306: if (($key) && ($value)) {
4307: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4308: }
4309: }
4310: }
4311: return %returnhash;
4312: }
1.662 raeburn 4313: # ---------------------------------------------------------- Domain roles
4314:
4315: sub get_domain_roles {
4316: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4317: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4318: $startdate = '.';
4319: }
1.1018 raeburn 4320: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4321: $enddate = '.';
4322: }
1.922 raeburn 4323: my $rolelist;
4324: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4325: $rolelist = join('&',@{$roles});
1.922 raeburn 4326: }
1.662 raeburn 4327: my %personnel = ();
1.841 albertel 4328:
4329: my %servers = &get_servers($dom,'library');
4330: foreach my $tryserver (keys(%servers)) {
4331: %{$personnel{$tryserver}}=();
4332: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4333: &escape($startdate).':'.
4334: &escape($enddate).':'.
4335: &escape($rolelist), $tryserver))) {
4336: my ($key,$value) = split(/\=/,$line,2);
4337: if (($key) && ($value)) {
4338: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4339: }
4340: }
1.662 raeburn 4341: }
4342: return %personnel;
4343: }
1.658 raeburn 4344:
1.1057 www 4345: # ----------------------------------------------------------- Interval timing
1.149 www 4346:
1.1153 www 4347: {
4348: # Caches needed for speedup of navmaps
4349: # We don't want to cache this for very long at all (5 seconds at most)
4350: #
4351: # The user for whom we cache
4352: my $cachedkey='';
4353: # The cached times for this user
4354: my %cachedtimes=();
4355: # When this was last done
4356: my $cachedtime=();
4357:
4358: sub load_all_first_access {
1.1154 raeburn 4359: my ($uname,$udom)=@_;
1.1156 www 4360: if (($cachedkey eq $uname.':'.$udom) &&
1.1174 raeburn 4361: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4362: return;
4363: }
4364: $cachedtime=time;
4365: $cachedkey=$uname.':'.$udom;
4366: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4367: }
4368:
1.504 albertel 4369: sub get_first_access {
1.1162 raeburn 4370: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4371: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4372: if ($argsymb) { $symb=$argsymb; }
4373: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4374: if ($argmap) { $map = $argmap; }
1.926 albertel 4375: if ($type eq 'course') {
4376: $res='course';
4377: } elsif ($type eq 'map') {
1.588 albertel 4378: $res=&symbread($map);
4379: } else {
4380: $res=$symb;
4381: }
1.1153 www 4382: &load_all_first_access($uname,$udom);
4383: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4384: }
4385:
4386: sub set_first_access {
1.1162 raeburn 4387: my ($type,$interval)=@_;
1.790 albertel 4388: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4389: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4390: if ($type eq 'course') {
4391: $res='course';
4392: } elsif ($type eq 'map') {
1.588 albertel 4393: $res=&symbread($map);
4394: } else {
4395: $res=$symb;
4396: }
1.1153 www 4397: $cachedkey='';
1.1162 raeburn 4398: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4399: if (!$firstaccess) {
1.1162 raeburn 4400: my $start = time;
4401: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4402: $udom,$uname);
4403: if ($putres eq 'ok') {
4404: &put('timerinterval',{"$courseid\0$res"=>$interval},
4405: $udom,$uname);
4406: &appenv(
4407: {
4408: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4409: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4410: }
4411: );
4412: }
4413: return $putres;
1.505 albertel 4414: }
4415: return 'already_set';
1.504 albertel 4416: }
1.1153 www 4417: }
1.110 www 4418: # --------------------------------------------- Set Expire Date for Spreadsheet
4419:
4420: sub expirespread {
4421: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4422: my $cid=$env{'request.course.id'};
1.110 www 4423: if ($cid) {
4424: my $now=time;
4425: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4426: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4427: $env{'course.'.$cid.'.num'}.
1.110 www 4428: ':nohist_expirationdates:'.
4429: &escape($key).'='.$now,
1.620 albertel 4430: $env{'course.'.$cid.'.home'})
1.110 www 4431: }
4432: return 'ok';
1.14 www 4433: }
4434:
1.109 www 4435: # ----------------------------------------------------- Devalidate Spreadsheets
4436:
4437: sub devalidate {
1.325 www 4438: my ($symb,$uname,$udom)=@_;
1.620 albertel 4439: my $cid=$env{'request.course.id'};
1.109 www 4440: if ($cid) {
1.391 matthew 4441: # delete the stored spreadsheets for
4442: # - the student level sheet of this user in course's homespace
4443: # - the assessment level sheet for this resource
4444: # for this user in user's homespace
1.553 albertel 4445: # - current conditional state info
1.325 www 4446: my $key=$uname.':'.$udom.':';
1.109 www 4447: my $status=
1.299 matthew 4448: &del('nohist_calculatedsheets',
1.391 matthew 4449: [$key.'studentcalc:'],
1.620 albertel 4450: $env{'course.'.$cid.'.domain'},
4451: $env{'course.'.$cid.'.num'})
1.133 albertel 4452: .' '.
4453: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4454: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4455: unless ($status eq 'ok ok') {
4456: &logthis('Could not devalidate spreadsheet '.
1.325 www 4457: $uname.' at '.$udom.' for '.
1.109 www 4458: $symb.': '.$status);
1.133 albertel 4459: }
1.553 albertel 4460: &delenv('user.state.'.$cid);
1.109 www 4461: }
4462: }
4463:
1.265 albertel 4464: sub get_scalar {
4465: my ($string,$end) = @_;
4466: my $value;
4467: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4468: $value = $1;
4469: } elsif ($$string =~ s/^([^&]*?)&//) {
4470: $value = $1;
4471: }
4472: return &unescape($value);
4473: }
4474:
4475: sub array2str {
4476: my (@array) = @_;
4477: my $result=&arrayref2str(\@array);
4478: $result=~s/^__ARRAY_REF__//;
4479: $result=~s/__END_ARRAY_REF__$//;
4480: return $result;
4481: }
4482:
1.204 albertel 4483: sub arrayref2str {
4484: my ($arrayref) = @_;
1.265 albertel 4485: my $result='__ARRAY_REF__';
1.204 albertel 4486: foreach my $elem (@$arrayref) {
1.265 albertel 4487: if(ref($elem) eq 'ARRAY') {
4488: $result.=&arrayref2str($elem).'&';
4489: } elsif(ref($elem) eq 'HASH') {
4490: $result.=&hashref2str($elem).'&';
4491: } elsif(ref($elem)) {
4492: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4493: } else {
4494: $result.=&escape($elem).'&';
4495: }
4496: }
4497: $result=~s/\&$//;
1.265 albertel 4498: $result .= '__END_ARRAY_REF__';
1.204 albertel 4499: return $result;
4500: }
4501:
1.168 albertel 4502: sub hash2str {
1.204 albertel 4503: my (%hash) = @_;
4504: my $result=&hashref2str(\%hash);
1.265 albertel 4505: $result=~s/^__HASH_REF__//;
4506: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4507: return $result;
4508: }
4509:
4510: sub hashref2str {
4511: my ($hashref)=@_;
1.265 albertel 4512: my $result='__HASH_REF__';
1.800 albertel 4513: foreach my $key (sort(keys(%$hashref))) {
4514: if (ref($key) eq 'ARRAY') {
4515: $result.=&arrayref2str($key).'=';
4516: } elsif (ref($key) eq 'HASH') {
4517: $result.=&hashref2str($key).'=';
4518: } elsif (ref($key)) {
1.265 albertel 4519: $result.='=';
1.800 albertel 4520: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4521: } else {
1.1132 raeburn 4522: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4523: }
4524:
1.800 albertel 4525: if(ref($hashref->{$key}) eq 'ARRAY') {
4526: $result.=&arrayref2str($hashref->{$key}).'&';
4527: } elsif(ref($hashref->{$key}) eq 'HASH') {
4528: $result.=&hashref2str($hashref->{$key}).'&';
4529: } elsif(ref($hashref->{$key})) {
1.265 albertel 4530: $result.='&';
1.800 albertel 4531: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4532: } else {
1.800 albertel 4533: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4534: }
4535: }
1.168 albertel 4536: $result=~s/\&$//;
1.265 albertel 4537: $result .= '__END_HASH_REF__';
1.168 albertel 4538: return $result;
4539: }
4540:
4541: sub str2hash {
1.265 albertel 4542: my ($string)=@_;
4543: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4544: return %$hash;
4545: }
4546:
4547: sub str2hashref {
1.168 albertel 4548: my ($string) = @_;
1.265 albertel 4549:
4550: my %hash;
4551:
4552: if($string !~ /^__HASH_REF__/) {
4553: if (! ($string eq '' || !defined($string))) {
4554: $hash{'error'}='Not hash reference';
4555: }
4556: return (\%hash, $string);
4557: }
4558:
4559: $string =~ s/^__HASH_REF__//;
4560:
4561: while($string !~ /^__END_HASH_REF__/) {
4562: #key
4563: my $key='';
4564: if($string =~ /^__HASH_REF__/) {
4565: ($key, $string)=&str2hashref($string);
4566: if(defined($key->{'error'})) {
4567: $hash{'error'}='Bad data';
4568: return (\%hash, $string);
4569: }
4570: } elsif($string =~ /^__ARRAY_REF__/) {
4571: ($key, $string)=&str2arrayref($string);
4572: if($key->[0] eq 'Array reference error') {
4573: $hash{'error'}='Bad data';
4574: return (\%hash, $string);
4575: }
4576: } else {
4577: $string =~ s/^(.*?)=//;
1.267 albertel 4578: $key=&unescape($1);
1.265 albertel 4579: }
4580: $string =~ s/^=//;
4581:
4582: #value
4583: my $value='';
4584: if($string =~ /^__HASH_REF__/) {
4585: ($value, $string)=&str2hashref($string);
4586: if(defined($value->{'error'})) {
4587: $hash{'error'}='Bad data';
4588: return (\%hash, $string);
4589: }
4590: } elsif($string =~ /^__ARRAY_REF__/) {
4591: ($value, $string)=&str2arrayref($string);
4592: if($value->[0] eq 'Array reference error') {
4593: $hash{'error'}='Bad data';
4594: return (\%hash, $string);
4595: }
4596: } else {
4597: $value=&get_scalar(\$string,'__END_HASH_REF__');
4598: }
4599: $string =~ s/^&//;
4600:
4601: $hash{$key}=$value;
1.204 albertel 4602: }
1.265 albertel 4603:
4604: $string =~ s/^__END_HASH_REF__//;
4605:
4606: return (\%hash, $string);
1.204 albertel 4607: }
4608:
4609: sub str2array {
1.265 albertel 4610: my ($string)=@_;
4611: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4612: return @$array;
4613: }
4614:
4615: sub str2arrayref {
1.204 albertel 4616: my ($string) = @_;
1.265 albertel 4617: my @array;
4618:
4619: if($string !~ /^__ARRAY_REF__/) {
4620: if (! ($string eq '' || !defined($string))) {
4621: $array[0]='Array reference error';
4622: }
4623: return (\@array, $string);
4624: }
4625:
4626: $string =~ s/^__ARRAY_REF__//;
4627:
4628: while($string !~ /^__END_ARRAY_REF__/) {
4629: my $value='';
4630: if($string =~ /^__HASH_REF__/) {
4631: ($value, $string)=&str2hashref($string);
4632: if(defined($value->{'error'})) {
4633: $array[0] ='Array reference error';
4634: return (\@array, $string);
4635: }
4636: } elsif($string =~ /^__ARRAY_REF__/) {
4637: ($value, $string)=&str2arrayref($string);
4638: if($value->[0] eq 'Array reference error') {
4639: $array[0] ='Array reference error';
4640: return (\@array, $string);
4641: }
4642: } else {
4643: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4644: }
4645: $string =~ s/^&//;
4646:
4647: push(@array, $value);
1.191 harris41 4648: }
1.265 albertel 4649:
4650: $string =~ s/^__END_ARRAY_REF__//;
4651:
4652: return (\@array, $string);
1.168 albertel 4653: }
4654:
1.167 albertel 4655: # -------------------------------------------------------------------Temp Store
4656:
1.168 albertel 4657: sub tmpreset {
4658: my ($symb,$namespace,$domain,$stuname) = @_;
4659: if (!$symb) {
4660: $symb=&symbread();
1.620 albertel 4661: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4662: }
4663: $symb=escape($symb);
4664:
1.620 albertel 4665: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4666: $namespace=~s/\//\_/g;
4667: $namespace=~s/\W//g;
4668:
1.620 albertel 4669: if (!$domain) { $domain=$env{'user.domain'}; }
4670: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4671: if ($domain eq 'public' && $stuname eq 'public') {
4672: $stuname=$ENV{'REMOTE_ADDR'};
4673: }
1.1117 foxr 4674: my $path=LONCAPA::tempdir();
1.168 albertel 4675: my %hash;
4676: if (tie(%hash,'GDBM_File',
4677: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4678: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4679: foreach my $key (keys(%hash)) {
1.180 albertel 4680: if ($key=~ /:$symb/) {
1.168 albertel 4681: delete($hash{$key});
4682: }
4683: }
4684: }
4685: }
4686:
1.167 albertel 4687: sub tmpstore {
1.168 albertel 4688: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4689:
4690: if (!$symb) {
4691: $symb=&symbread();
1.620 albertel 4692: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4693: }
4694: $symb=escape($symb);
4695:
4696: if (!$namespace) {
4697: # I don't think we would ever want to store this for a course.
4698: # it seems this will only be used if we don't have a course.
1.620 albertel 4699: #$namespace=$env{'request.course.id'};
1.168 albertel 4700: #if (!$namespace) {
1.620 albertel 4701: $namespace=$env{'request.state'};
1.168 albertel 4702: #}
4703: }
4704: $namespace=~s/\//\_/g;
4705: $namespace=~s/\W//g;
1.620 albertel 4706: if (!$domain) { $domain=$env{'user.domain'}; }
4707: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4708: if ($domain eq 'public' && $stuname eq 'public') {
4709: $stuname=$ENV{'REMOTE_ADDR'};
4710: }
1.168 albertel 4711: my $now=time;
4712: my %hash;
1.1117 foxr 4713: my $path=LONCAPA::tempdir();
1.168 albertel 4714: if (tie(%hash,'GDBM_File',
4715: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4716: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4717: $hash{"version:$symb"}++;
4718: my $version=$hash{"version:$symb"};
4719: my $allkeys='';
4720: foreach my $key (keys(%$storehash)) {
4721: $allkeys.=$key.':';
1.591 albertel 4722: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4723: }
4724: $hash{"$version:$symb:timestamp"}=$now;
4725: $allkeys.='timestamp';
4726: $hash{"$version:keys:$symb"}=$allkeys;
4727: if (untie(%hash)) {
4728: return 'ok';
4729: } else {
4730: return "error:$!";
4731: }
4732: } else {
4733: return "error:$!";
4734: }
4735: }
1.167 albertel 4736:
1.168 albertel 4737: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4738:
1.168 albertel 4739: sub tmprestore {
4740: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4741:
1.168 albertel 4742: if (!$symb) {
4743: $symb=&symbread();
1.620 albertel 4744: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4745: }
4746: $symb=escape($symb);
4747:
1.620 albertel 4748: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4749:
1.620 albertel 4750: if (!$domain) { $domain=$env{'user.domain'}; }
4751: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4752: if ($domain eq 'public' && $stuname eq 'public') {
4753: $stuname=$ENV{'REMOTE_ADDR'};
4754: }
1.168 albertel 4755: my %returnhash;
4756: $namespace=~s/\//\_/g;
4757: $namespace=~s/\W//g;
4758: my %hash;
1.1117 foxr 4759: my $path=LONCAPA::tempdir();
1.168 albertel 4760: if (tie(%hash,'GDBM_File',
4761: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4762: &GDBM_READER(),0640)) {
1.168 albertel 4763: my $version=$hash{"version:$symb"};
4764: $returnhash{'version'}=$version;
4765: my $scope;
4766: for ($scope=1;$scope<=$version;$scope++) {
4767: my $vkeys=$hash{"$scope:keys:$symb"};
4768: my @keys=split(/:/,$vkeys);
4769: my $key;
4770: $returnhash{"$scope:keys"}=$vkeys;
4771: foreach $key (@keys) {
1.591 albertel 4772: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4773: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4774: }
4775: }
1.168 albertel 4776: if (!(untie(%hash))) {
4777: return "error:$!";
4778: }
4779: } else {
4780: return "error:$!";
4781: }
4782: return %returnhash;
1.167 albertel 4783: }
4784:
1.9 www 4785: # ----------------------------------------------------------------------- Store
4786:
4787: sub store {
1.124 www 4788: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4789: my $home='';
4790:
1.168 albertel 4791: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4792:
1.213 www 4793: $symb=&symbclean($symb);
1.122 albertel 4794: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4795:
1.620 albertel 4796: if (!$domain) { $domain=$env{'user.domain'}; }
4797: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4798:
4799: &devalidate($symb,$stuname,$domain);
1.109 www 4800:
4801: $symb=escape($symb);
1.187 www 4802: if (!$namespace) {
1.620 albertel 4803: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4804: return '';
4805: }
4806: }
1.620 albertel 4807: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4808:
4809: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4810: $$storehash{'host'}=$perlvar{'lonHostID'};
4811:
1.12 www 4812: my $namevalue='';
1.800 albertel 4813: foreach my $key (keys(%$storehash)) {
4814: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4815: }
1.12 www 4816: $namevalue=~s/\&$//;
1.187 www 4817: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4818: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4819: }
4820:
1.47 www 4821: # -------------------------------------------------------------- Critical Store
4822:
4823: sub cstore {
1.124 www 4824: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4825: my $home='';
4826:
1.168 albertel 4827: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4828:
1.213 www 4829: $symb=&symbclean($symb);
1.122 albertel 4830: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4831:
1.620 albertel 4832: if (!$domain) { $domain=$env{'user.domain'}; }
4833: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4834:
4835: &devalidate($symb,$stuname,$domain);
1.109 www 4836:
4837: $symb=escape($symb);
1.187 www 4838: if (!$namespace) {
1.620 albertel 4839: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4840: return '';
4841: }
4842: }
1.620 albertel 4843: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4844:
4845: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4846: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4847:
1.47 www 4848: my $namevalue='';
1.800 albertel 4849: foreach my $key (keys(%$storehash)) {
4850: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4851: }
1.47 www 4852: $namevalue=~s/\&$//;
1.187 www 4853: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4854: return critical
4855: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4856: }
4857:
1.9 www 4858: # --------------------------------------------------------------------- Restore
4859:
4860: sub restore {
1.124 www 4861: my ($symb,$namespace,$domain,$stuname) = @_;
4862: my $home='';
4863:
1.168 albertel 4864: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4865:
1.122 albertel 4866: if (!$symb) {
1.1224 raeburn 4867: return if ($namespace eq 'courserequests');
4868: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4869: } else {
1.1224 raeburn 4870: unless ($namespace eq 'courserequests') {
4871: $symb=&escape(&symbclean($symb));
4872: }
1.122 albertel 4873: }
1.188 www 4874: if (!$namespace) {
1.620 albertel 4875: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4876: return '';
4877: }
4878: }
1.620 albertel 4879: if (!$domain) { $domain=$env{'user.domain'}; }
4880: if (!$stuname) { $stuname=$env{'user.name'}; }
4881: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4882: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4883:
1.12 www 4884: my %returnhash=();
1.800 albertel 4885: foreach my $line (split(/\&/,$answer)) {
4886: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4887: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4888: }
1.75 www 4889: my $version;
4890: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4891: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4892: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4893: }
1.75 www 4894: }
1.13 www 4895: return %returnhash;
1.34 www 4896: }
4897:
4898: # ---------------------------------------------------------- Course Description
1.1118 foxr 4899: #
4900: #
1.34 www 4901:
4902: sub coursedescription {
1.731 albertel 4903: my ($courseid,$args)=@_;
1.34 www 4904: $courseid=~s/^\///;
1.49 www 4905: $courseid=~s/\_/\//g;
1.34 www 4906: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4907: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4908: my $normalid=$cdomain.'_'.$cnum;
4909: # need to always cache even if we get errors otherwise we keep
4910: # trying and trying and trying to get the course description.
4911: my %envhash=();
4912: my %returnhash=();
1.731 albertel 4913:
4914: my $expiretime=600;
4915: if ($env{'request.course.id'} eq $normalid) {
4916: $expiretime=120;
4917: }
4918:
4919: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4920: if (!$args->{'freshen_cache'}
4921: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4922: foreach my $key (keys(%env)) {
4923: next if ($key !~ /^\Q$prefix\E(.*)/);
4924: my ($setting) = $1;
4925: $returnhash{$setting} = $env{$key};
4926: }
4927: return %returnhash;
4928: }
4929:
1.1118 foxr 4930: # get the data again
4931:
1.731 albertel 4932: if (!$args->{'one_time'}) {
4933: $envhash{'course.'.$normalid.'.last_cache'}=time;
4934: }
1.811 albertel 4935:
1.34 www 4936: if ($chome ne 'no_host') {
1.302 albertel 4937: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4938: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4939: my $username = $env{'user.name'}; # Defult username
4940: if(defined $args->{'user'}) {
4941: $username = $args->{'user'};
4942: }
1.129 albertel 4943: $returnhash{'home'}= $chome;
4944: $returnhash{'domain'} = $cdomain;
4945: $returnhash{'num'} = $cnum;
1.741 raeburn 4946: if (!defined($returnhash{'type'})) {
4947: $returnhash{'type'} = 'Course';
4948: }
1.130 albertel 4949: while (my ($name,$value) = each %returnhash) {
1.53 www 4950: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4951: }
1.270 www 4952: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4953: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4954: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4955: $envhash{'course.'.$normalid.'.home'}=$chome;
4956: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4957: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4958: }
4959: }
1.731 albertel 4960: if (!$args->{'one_time'}) {
1.949 raeburn 4961: &appenv(\%envhash);
1.731 albertel 4962: }
1.302 albertel 4963: return %returnhash;
1.461 www 4964: }
4965:
1.1080 raeburn 4966: sub update_released_required {
4967: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4968: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4969: $cid = $env{'request.course.id'};
4970: $cdom = $env{'course.'.$cid.'.domain'};
4971: $cnum = $env{'course.'.$cid.'.num'};
4972: $chome = $env{'course.'.$cid.'.home'};
4973: }
4974: if ($needsrelease) {
4975: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4976: my $needsupdate;
4977: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4978: $needsupdate = 1;
4979: } else {
4980: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4981: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4982: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4983: $needsupdate = 1;
4984: }
4985: }
4986: if ($needsupdate) {
4987: my %needshash = (
4988: 'internal.releaserequired' => $needsrelease,
4989: );
4990: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4991: if ($putresult eq 'ok') {
4992: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4993: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4994: if (ref($crsinfo{$cid}) eq 'HASH') {
4995: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4996: &courseidput($cdom,\%crsinfo,$chome,'notime');
4997: }
4998: }
4999: }
5000: }
5001: return;
5002: }
5003:
1.461 www 5004: # -------------------------------------------------See if a user is privileged
5005:
5006: sub privileged {
1.1219 raeburn 5007: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5008: my $now = time;
1.1219 raeburn 5009: my $roles;
5010: if (ref($possroles) eq 'ARRAY') {
5011: $roles = $possroles;
5012: } else {
5013: $roles = ['dc','su'];
5014: }
5015: if (ref($possdomains) eq 'ARRAY') {
5016: my %privileged = &privileged_by_domain($possdomains,$roles);
5017: foreach my $dom (@{$possdomains}) {
5018: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5019: (ref($privileged{$dom}) eq 'HASH')) {
5020: foreach my $role (@{$roles}) {
5021: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5022: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5023: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5024: return 1 unless (($end && $end < $now) ||
5025: ($start && $start > $now));
5026: }
5027: }
5028: }
5029: }
5030: }
5031: } else {
5032: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5033: my $now = time;
1.1170 droeschl 5034:
1.1219 raeburn 5035: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170 droeschl 5036: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5037: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5038: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5039: or ($tstart && $tstart > $now);
1.1170 droeschl 5040: }
1.1219 raeburn 5041: }
5042: }
5043: return 0;
5044: }
1.1170 droeschl 5045:
1.1219 raeburn 5046: sub privileged_by_domain {
5047: my ($domains,$roles) = @_;
5048: my %privileged = ();
5049: my $cachetime = 60*60*24;
5050: my $now = time;
5051: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5052: return %privileged;
5053: }
5054: foreach my $dom (@{$domains}) {
5055: next if (ref($privileged{$dom}) eq 'HASH');
5056: my $needroles;
5057: foreach my $role (@{$roles}) {
5058: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5059: if (defined($cached)) {
5060: if (ref($result) eq 'HASH') {
5061: $privileged{$dom}{$role} = $result;
5062: }
5063: } else {
5064: $needroles = 1;
5065: }
5066: }
5067: if ($needroles) {
5068: my %dompersonnel = &get_domain_roles($dom,$roles);
5069: $privileged{$dom} = {};
5070: foreach my $server (keys(%dompersonnel)) {
5071: if (ref($dompersonnel{$server}) eq 'HASH') {
5072: foreach my $item (keys(%{$dompersonnel{$server}})) {
5073: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5074: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5075: next if ($end && $end < $now);
5076: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5077: $dompersonnel{$server}{$item};
5078: }
5079: }
5080: }
5081: if (ref($privileged{$dom}) eq 'HASH') {
5082: foreach my $role (@{$roles}) {
5083: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5084: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5085: } else {
5086: my %hash = ();
5087: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5088: }
5089: }
5090: }
5091: }
5092: }
5093: return %privileged;
1.9 www 5094: }
1.1 albertel 5095:
1.103 harris41 5096: # -------------------------------------------------------- Get user privileges
1.11 www 5097:
5098: sub rolesinit {
1.1169 droeschl 5099: my ($domain, $username) = @_;
5100: my %userroles = ('user.login.time' => time);
5101: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5102:
5103: # firstaccess and timerinterval are related to timed maps/resources.
5104: # also, blocking can be triggered by an activating timer
5105: # it's saved in the user's %env.
5106: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5107: my %timerinterval = &dump('timerinterval', $domain, $username);
5108: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5109: %timerintchk, %timerintenv);
5110:
1.1162 raeburn 5111: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5112: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5113: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5114: }
1.1169 droeschl 5115:
1.1162 raeburn 5116: foreach my $key (keys(%timerinterval)) {
5117: my ($cid,$rest) = split(/\0/,$key);
5118: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5119: }
1.1169 droeschl 5120:
1.11 www 5121: my %allroles=();
1.1162 raeburn 5122: my %allgroups=();
1.11 www 5123:
1.1169 droeschl 5124: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5125: my $role = $rolesdump{$area};
5126: $area =~ s/\_\w\w$//;
5127:
5128: my ($trole, $tend, $tstart, $group_privs);
5129:
5130: if ($role =~ /^cr/) {
5131: # Custom role, defined by a user
5132: # e.g., user.role.cr/msu/smith/mynewrole
5133: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5134: $trole = $1;
5135: ($tend, $tstart) = split('_', $2);
5136: } else {
5137: $trole = $role;
5138: }
5139: } elsif ($role =~ m|^gr/|) {
5140: # Role of member in a group, defined within a course/community
5141: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5142: ($trole, $tend, $tstart) = split(/_/, $role);
5143: next if $tstart eq '-1';
5144: ($trole, $group_privs) = split(/\//, $trole);
5145: $group_privs = &unescape($group_privs);
5146: } else {
5147: # Just a normal role, defined in roles.tab
5148: ($trole, $tend, $tstart) = split(/_/,$role);
5149: }
5150:
5151: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5152: $username);
5153: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5154:
5155: # role expired or not available yet?
5156: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5157: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5158:
5159: next if $area eq '' or $trole eq '';
5160:
5161: my $spec = "$trole.$area";
5162: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5163:
5164: if ($trole =~ /^cr\//) {
5165: # Custom role, defined by a user
5166: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5167: } elsif ($trole eq 'gr') {
5168: # Role of a member in a group, defined within a course/community
5169: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5170: next;
5171: } else {
5172: # Normal role, defined in roles.tab
5173: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5174: }
5175:
5176: my $cid = $tdomain.'_'.$trest;
5177: unless ($firstaccchk{$cid}) {
5178: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5179: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5180: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5181: $coursetimerstarts{$cid}{$item};
5182: }
5183: }
5184: $firstaccchk{$cid} = 1;
5185: }
5186: unless ($timerintchk{$cid}) {
5187: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5188: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5189: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5190: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5191: }
1.12 www 5192: }
1.1169 droeschl 5193: $timerintchk{$cid} = 1;
1.191 harris41 5194: }
1.11 www 5195: }
1.1169 droeschl 5196:
5197: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5198: \%allroles, \%allgroups);
5199: $env{'user.adv'} = $userroles{'user.adv'};
5200:
1.1162 raeburn 5201: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5202: }
5203:
1.567 raeburn 5204: sub set_arearole {
1.1215 raeburn 5205: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5206: unless ($nolog) {
1.567 raeburn 5207: # log the associated role with the area
1.1215 raeburn 5208: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5209: }
1.743 albertel 5210: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5211: }
5212:
5213: sub custom_roleprivs {
5214: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5215: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
5216: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 5217: if (&hostname($homsvr) ne '') {
1.567 raeburn 5218: my ($rdummy,$roledef)=
5219: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5220: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5221: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5222: if (defined($syspriv)) {
1.1043 raeburn 5223: if ($trest =~ /^$match_community$/) {
5224: $syspriv =~ s/bre\&S//;
5225: }
1.567 raeburn 5226: $$allroles{'cm./'}.=':'.$syspriv;
5227: $$allroles{$spec.'./'}.=':'.$syspriv;
5228: }
5229: if ($tdomain ne '') {
5230: if (defined($dompriv)) {
5231: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5232: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5233: }
5234: if (($trest ne '') && (defined($coursepriv))) {
5235: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5236: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5237: }
5238: }
5239: }
5240: }
5241: }
5242:
1.678 raeburn 5243: sub group_roleprivs {
5244: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5245: my $access = 1;
5246: my $now = time;
5247: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5248: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5249: if ($access) {
1.811 albertel 5250: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5251: $$allgroups{$course}{$group} .=':'.$group_privs;
5252: }
5253: }
1.567 raeburn 5254:
5255: sub standard_roleprivs {
5256: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5257: if (defined($pr{$trole.':s'})) {
5258: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5259: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5260: }
5261: if ($tdomain ne '') {
5262: if (defined($pr{$trole.':d'})) {
5263: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5264: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5265: }
5266: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5267: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5268: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5269: }
5270: }
5271: }
5272:
5273: sub set_userprivs {
1.1064 raeburn 5274: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5275: my $author=0;
5276: my $adv=0;
1.678 raeburn 5277: my %grouproles = ();
5278: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5279: my @groupkeys;
1.1000 raeburn 5280: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5281: push(@groupkeys,$role);
5282: }
5283: if (ref($groups_roles) eq 'HASH') {
5284: foreach my $key (keys(%{$groups_roles})) {
5285: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5286: push(@groupkeys,$key);
5287: }
5288: }
5289: }
5290: if (@groupkeys > 0) {
5291: foreach my $role (@groupkeys) {
5292: my ($trole,$area,$sec,$extendedarea);
5293: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5294: $trole = $1;
5295: $area = $2;
5296: $sec = $3;
5297: $extendedarea = $area.$sec;
5298: if (exists($$allgroups{$area})) {
5299: foreach my $group (keys(%{$$allgroups{$area}})) {
5300: my $spec = $trole.'.'.$extendedarea;
5301: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5302: $$allgroups{$area}{$group};
1.1064 raeburn 5303: }
1.678 raeburn 5304: }
5305: }
5306: }
5307: }
5308: }
1.800 albertel 5309: foreach my $group (keys(%grouproles)) {
5310: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5311: }
1.800 albertel 5312: foreach my $role (keys(%{$allroles})) {
5313: my %thesepriv;
1.941 raeburn 5314: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5315: foreach my $item (split(/:/,$$allroles{$role})) {
5316: if ($item ne '') {
5317: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5318: if ($restrictions eq '') {
5319: $thesepriv{$privilege}='F';
5320: } elsif ($thesepriv{$privilege} ne 'F') {
5321: $thesepriv{$privilege}.=$restrictions;
5322: }
5323: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5324: }
5325: }
5326: my $thesestr='';
1.1104 raeburn 5327: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5328: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5329: }
5330: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5331: }
5332: return ($author,$adv);
5333: }
5334:
1.994 raeburn 5335: sub role_status {
1.1104 raeburn 5336: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5337: my @pwhere = ();
5338: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
5339: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
5340: unless (!defined($$role) || $$role eq '') {
5341: $$where=join('.',@pwhere);
5342: $$trolecode=$$role.'.'.$$where;
5343: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5344: $$tstatus='is';
1.1104 raeburn 5345: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5346: $$tstatus='future';
1.1034 raeburn 5347: if ($$tstart<$now) {
5348: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5349: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5350: my (%allroles,%allgroups,$group_privs,
5351: %groups_roles,@rolecodes);
1.1002 raeburn 5352: my %userroles = (
5353: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5354: );
1.1064 raeburn 5355: @rolecodes = ('cm');
1.1002 raeburn 5356: my $spec=$$role.'.'.$$where;
5357: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5358: if ($$role =~ /^cr\//) {
5359: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5360: push(@rolecodes,'cr');
1.1002 raeburn 5361: } elsif ($$role eq 'gr') {
1.1064 raeburn 5362: push(@rolecodes,$$role);
1.1002 raeburn 5363: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5364: $env{'user.name'});
1.1064 raeburn 5365: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5366: (undef,my $group_privs) = split(/\//,$trole);
5367: $group_privs = &unescape($group_privs);
5368: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5369: 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 5370: &get_groups_roles($tdomain,$trest,
5371: \%course_roles,\@rolecodes,
5372: \%groups_roles);
1.1002 raeburn 5373: } else {
1.1064 raeburn 5374: push(@rolecodes,$$role);
1.1002 raeburn 5375: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5376: }
1.1064 raeburn 5377: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5378: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5379: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5380: }
5381: }
1.1034 raeburn 5382: $$tstatus = 'is';
1.1002 raeburn 5383: }
1.994 raeburn 5384: }
5385: if ($$tend) {
1.1104 raeburn 5386: if ($$tend<$update) {
1.994 raeburn 5387: $$tstatus='expired';
5388: } elsif ($$tend<$now) {
5389: $$tstatus='will_not';
5390: }
5391: }
5392: }
5393: }
5394: }
5395:
1.1104 raeburn 5396: sub get_groups_roles {
5397: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5398: return unless((ref($cdom_courseroles) eq 'HASH') &&
5399: (ref($rolecodes) eq 'ARRAY') &&
5400: (ref($groups_roles) eq 'HASH'));
5401: if (keys(%{$cdom_courseroles}) > 0) {
5402: my ($cnum) = ($rest =~ /^($match_courseid)/);
5403: if ($cdom ne '' && $cnum ne '') {
5404: foreach my $key (keys(%{$cdom_courseroles})) {
5405: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5406: my $crsrole = $1;
5407: my $crssec = $2;
5408: if ($crsrole =~ /^cr/) {
5409: unless (grep(/^cr$/,@{$rolecodes})) {
5410: push(@{$rolecodes},'cr');
5411: }
5412: } else {
5413: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5414: push(@{$rolecodes},$crsrole);
5415: }
5416: }
5417: my $rolekey = "$crsrole./$cdom/$cnum";
5418: if ($crssec ne '') {
5419: $rolekey .= "/$crssec";
5420: }
5421: $rolekey .= './';
5422: $groups_roles->{$rolekey} = $rolecodes;
5423: }
5424: }
5425: }
5426: }
5427: return;
5428: }
5429:
5430: sub delete_env_groupprivs {
5431: my ($where,$courseroles,$possroles) = @_;
5432: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5433: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5434: unless (ref($courseroles->{$udom}) eq 'HASH') {
5435: %{$courseroles->{$udom}} =
5436: &get_my_roles('','','userroles',['active'],
5437: $possroles,[$udom],1);
5438: }
5439: if (ref($courseroles->{$udom}) eq 'HASH') {
5440: foreach my $item (keys(%{$courseroles->{$udom}})) {
5441: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5442: my $area = '/'.$cdom.'/'.$cnum;
5443: my $privkey = "user.priv.$crsrole.$area";
5444: if ($crssec ne '') {
5445: $privkey .= '/'.$crssec;
5446: }
5447: $privkey .= ".$area/$group";
5448: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5449: }
5450: }
5451: return;
5452: }
5453:
1.994 raeburn 5454: sub check_adhoc_privs {
1.1104 raeburn 5455: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5456: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5457: my $setprivs;
1.994 raeburn 5458: if ($env{$cckey}) {
5459: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5460: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5461: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5462: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5463: $setprivs = 1;
1.994 raeburn 5464: }
5465: } else {
1.1088 raeburn 5466: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5467: $setprivs = 1;
1.994 raeburn 5468: }
1.1185 raeburn 5469: return $setprivs;
1.994 raeburn 5470: }
5471:
5472: sub set_adhoc_privileges {
5473: # role can be cc or ca
1.1088 raeburn 5474: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5475: my $area = '/'.$dcdom.'/'.$pickedcourse;
5476: my $spec = $role.'.'.$area;
5477: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5478: $env{'user.name'},1);
1.994 raeburn 5479: my %ccrole = ();
5480: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5481: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5482: &appenv(\%userroles,[$role,'cm']);
5483: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5484: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5485: &appenv( {'request.role' => $spec,
5486: 'request.role.domain' => $dcdom,
5487: 'request.course.sec' => ''
5488: }
5489: );
5490: my $tadv=0;
5491: if (&allowed('adv') eq 'F') { $tadv=1; }
5492: &appenv({'request.role.adv' => $tadv});
5493: }
1.994 raeburn 5494: }
5495:
1.12 www 5496: # --------------------------------------------------------------- get interface
5497:
5498: sub get {
1.131 albertel 5499: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5500: my $items='';
1.800 albertel 5501: foreach my $item (@$storearr) {
5502: $items.=&escape($item).'&';
1.191 harris41 5503: }
1.12 www 5504: $items=~s/\&$//;
1.620 albertel 5505: if (!$udomain) { $udomain=$env{'user.domain'}; }
5506: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5507: my $uhome=&homeserver($uname,$udomain);
5508:
1.133 albertel 5509: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5510: my @pairs=split(/\&/,$rep);
1.273 albertel 5511: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5512: return @pairs;
5513: }
1.15 www 5514: my %returnhash=();
1.42 www 5515: my $i=0;
1.800 albertel 5516: foreach my $item (@$storearr) {
5517: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5518: $i++;
1.191 harris41 5519: }
1.15 www 5520: return %returnhash;
1.27 www 5521: }
5522:
5523: # --------------------------------------------------------------- del interface
5524:
5525: sub del {
1.133 albertel 5526: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5527: my $items='';
1.800 albertel 5528: foreach my $item (@$storearr) {
5529: $items.=&escape($item).'&';
1.191 harris41 5530: }
1.984 neumanie 5531:
1.27 www 5532: $items=~s/\&$//;
1.620 albertel 5533: if (!$udomain) { $udomain=$env{'user.domain'}; }
5534: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5535: my $uhome=&homeserver($uname,$udomain);
5536: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5537: }
5538:
5539: # -------------------------------------------------------------- dump interface
5540:
1.1180 droeschl 5541: sub unserialize {
5542: my ($rep, $escapedkeys) = @_;
5543:
5544: return {} if $rep =~ /^error/;
5545:
5546: my %returnhash=();
5547: foreach my $item (split /\&/, $rep) {
5548: my ($key, $value) = split(/=/, $item, 2);
5549: $key = unescape($key) unless $escapedkeys;
5550: next if $key =~ /^error: 2 /;
5551: $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
5552: }
5553: #return %returnhash;
5554: return \%returnhash;
5555: }
5556:
5557: # see Lond::dump_with_regexp
5558: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5559: sub dump {
1.1180 droeschl 5560: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5561: if (!$udomain) { $udomain=$env{'user.domain'}; }
5562: if (!$uname) { $uname=$env{'user.name'}; }
5563: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5564:
1.1180 droeschl 5565: my $reply;
5566: if (grep { $_ eq $uhome } current_machine_ids()) {
5567: # user is hosted on this machine
5568: $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5569: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5570: return %{unserialize($reply, $escapedkeys)};
5571: }
1.755 albertel 5572: if ($regexp) {
5573: $regexp=&escape($regexp);
5574: } else {
5575: $regexp='.';
5576: }
1.1166 raeburn 5577: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5578: my @pairs=split(/\&/,$rep);
5579: my %returnhash=();
1.1098 foxr 5580: if (!($rep =~ /^error/ )) {
5581: foreach my $item (@pairs) {
5582: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5583: $key = unescape($key) unless $escapedkeys;
5584: #$key = &unescape($key);
1.1098 foxr 5585: next if ($key =~ /^error: 2 /);
5586: $returnhash{$key}=&thaw_unescape($value);
5587: }
1.755 albertel 5588: }
5589: return %returnhash;
1.407 www 5590: }
5591:
1.1098 foxr 5592:
1.717 albertel 5593: # --------------------------------------------------------- dumpstore interface
5594:
5595: sub dumpstore {
5596: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5597: # same as dump but keys must be escaped. They may contain colon separated
5598: # lists of values that may themself contain colons (e.g. symbs).
5599: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5600: }
5601:
1.407 www 5602: # -------------------------------------------------------------- keys interface
5603:
5604: sub getkeys {
5605: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5606: if (!$udomain) { $udomain=$env{'user.domain'}; }
5607: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5608: my $uhome=&homeserver($uname,$udomain);
5609: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5610: my @keyarray=();
1.800 albertel 5611: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5612: next if ($key =~ /^error: 2 /);
1.800 albertel 5613: push(@keyarray,&unescape($key));
1.407 www 5614: }
5615: return @keyarray;
1.318 matthew 5616: }
5617:
1.319 matthew 5618: # --------------------------------------------------------------- currentdump
5619: sub currentdump {
1.328 matthew 5620: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5621: $courseid = $env{'request.course.id'} if (! defined($courseid));
5622: $sdom = $env{'user.domain'} if (! defined($sdom));
5623: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5624: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5625: my $rep;
5626:
5627: if (grep { $_ eq $uhome } current_machine_ids()) {
5628: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5629: $courseid)));
5630: } else {
5631: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5632: }
5633:
1.318 matthew 5634: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5635: #
1.318 matthew 5636: my %returnhash=();
1.319 matthew 5637: #
5638: if ($rep eq "unknown_cmd") {
5639: # an old lond will not know currentdump
5640: # Do a dump and make it look like a currentdump
1.822 albertel 5641: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5642: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5643: my %hash = @tmp;
5644: @tmp=();
1.424 matthew 5645: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5646: } else {
5647: my @pairs=split(/\&/,$rep);
1.800 albertel 5648: foreach my $pair (@pairs) {
5649: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5650: my ($symb,$param) = split(/:/,$key);
5651: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5652: &thaw_unescape($value);
1.319 matthew 5653: }
1.191 harris41 5654: }
1.12 www 5655: return %returnhash;
1.424 matthew 5656: }
5657:
5658: sub convert_dump_to_currentdump{
5659: my %hash = %{shift()};
5660: my %returnhash;
5661: # Code ripped from lond, essentially. The only difference
5662: # here is the unescaping done by lonnet::dump(). Conceivably
5663: # we might run in to problems with parameter names =~ /^v\./
5664: while (my ($key,$value) = each(%hash)) {
5665: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5666: $symb = &unescape($symb);
5667: $param = &unescape($param);
1.424 matthew 5668: next if ($v eq 'version' || $symb eq 'keys');
5669: next if (exists($returnhash{$symb}) &&
5670: exists($returnhash{$symb}->{$param}) &&
5671: $returnhash{$symb}->{'v.'.$param} > $v);
5672: $returnhash{$symb}->{$param}=$value;
5673: $returnhash{$symb}->{'v.'.$param}=$v;
5674: }
5675: #
5676: # Remove all of the keys in the hashes which keep track of
5677: # the version of the parameter.
5678: while (my ($symb,$param_hash) = each(%returnhash)) {
5679: # use a foreach because we are going to delete from the hash.
5680: foreach my $key (keys(%$param_hash)) {
5681: delete($param_hash->{$key}) if ($key =~ /^v\./);
5682: }
5683: }
5684: return \%returnhash;
1.12 www 5685: }
5686:
1.627 albertel 5687: # ------------------------------------------------------ critical inc interface
5688:
5689: sub cinc {
5690: return &inc(@_,'critical');
5691: }
5692:
1.449 matthew 5693: # --------------------------------------------------------------- inc interface
5694:
5695: sub inc {
1.627 albertel 5696: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5697: if (!$udomain) { $udomain=$env{'user.domain'}; }
5698: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5699: my $uhome=&homeserver($uname,$udomain);
5700: my $items='';
5701: if (! ref($store)) {
5702: # got a single value, so use that instead
5703: $items = &escape($store).'=&';
5704: } elsif (ref($store) eq 'SCALAR') {
5705: $items = &escape($$store).'=&';
5706: } elsif (ref($store) eq 'ARRAY') {
5707: $items = join('=&',map {&escape($_);} @{$store});
5708: } elsif (ref($store) eq 'HASH') {
5709: while (my($key,$value) = each(%{$store})) {
5710: $items.= &escape($key).'='.&escape($value).'&';
5711: }
5712: }
5713: $items=~s/\&$//;
1.627 albertel 5714: if ($critical) {
5715: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5716: } else {
5717: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5718: }
1.449 matthew 5719: }
5720:
1.12 www 5721: # --------------------------------------------------------------- put interface
5722:
5723: sub put {
1.134 albertel 5724: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5725: if (!$udomain) { $udomain=$env{'user.domain'}; }
5726: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5727: my $uhome=&homeserver($uname,$udomain);
1.12 www 5728: my $items='';
1.800 albertel 5729: foreach my $item (keys(%$storehash)) {
5730: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5731: }
1.12 www 5732: $items=~s/\&$//;
1.134 albertel 5733: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5734: }
5735:
1.631 albertel 5736: # ------------------------------------------------------------ newput interface
5737:
5738: sub newput {
5739: my ($namespace,$storehash,$udomain,$uname)=@_;
5740: if (!$udomain) { $udomain=$env{'user.domain'}; }
5741: if (!$uname) { $uname=$env{'user.name'}; }
5742: my $uhome=&homeserver($uname,$udomain);
5743: my $items='';
5744: foreach my $key (keys(%$storehash)) {
5745: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5746: }
5747: $items=~s/\&$//;
5748: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5749: }
5750:
5751: # --------------------------------------------------------- putstore interface
5752:
1.524 raeburn 5753: sub putstore {
1.715 albertel 5754: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5755: if (!$udomain) { $udomain=$env{'user.domain'}; }
5756: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5757: my $uhome=&homeserver($uname,$udomain);
5758: my $items='';
1.715 albertel 5759: foreach my $key (keys(%$storehash)) {
5760: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5761: }
1.715 albertel 5762: $items=~s/\&$//;
1.716 albertel 5763: my $esc_symb=&escape($symb);
5764: my $esc_v=&escape($version);
1.715 albertel 5765: my $reply =
1.716 albertel 5766: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5767: $uhome);
5768: if ($reply eq 'unknown_cmd') {
1.716 albertel 5769: # gfall back to way things use to be done
1.715 albertel 5770: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5771: $uname);
1.524 raeburn 5772: }
1.715 albertel 5773: return $reply;
5774: }
5775:
5776: sub old_putstore {
1.716 albertel 5777: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5778: if (!$udomain) { $udomain=$env{'user.domain'}; }
5779: if (!$uname) { $uname=$env{'user.name'}; }
5780: my $uhome=&homeserver($uname,$udomain);
5781: my %newstorehash;
1.800 albertel 5782: foreach my $item (keys(%$storehash)) {
5783: my $key = $version.':'.&escape($symb).':'.$item;
5784: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5785: }
5786: my $items='';
5787: my %allitems = ();
1.800 albertel 5788: foreach my $item (keys(%newstorehash)) {
5789: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5790: my $key = $1.':keys:'.$2;
5791: $allitems{$key} .= $3.':';
5792: }
1.800 albertel 5793: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5794: }
1.800 albertel 5795: foreach my $item (keys(%allitems)) {
5796: $allitems{$item} =~ s/\:$//;
5797: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5798: }
5799: $items=~s/\&$//;
5800: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5801: }
5802:
1.47 www 5803: # ------------------------------------------------------ critical put interface
5804:
5805: sub cput {
1.134 albertel 5806: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5807: if (!$udomain) { $udomain=$env{'user.domain'}; }
5808: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5809: my $uhome=&homeserver($uname,$udomain);
1.47 www 5810: my $items='';
1.800 albertel 5811: foreach my $item (keys(%$storehash)) {
5812: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5813: }
1.47 www 5814: $items=~s/\&$//;
1.134 albertel 5815: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5816: }
5817:
5818: # -------------------------------------------------------------- eget interface
5819:
5820: sub eget {
1.133 albertel 5821: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5822: my $items='';
1.800 albertel 5823: foreach my $item (@$storearr) {
5824: $items.=&escape($item).'&';
1.191 harris41 5825: }
1.12 www 5826: $items=~s/\&$//;
1.620 albertel 5827: if (!$udomain) { $udomain=$env{'user.domain'}; }
5828: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5829: my $uhome=&homeserver($uname,$udomain);
5830: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5831: my @pairs=split(/\&/,$rep);
5832: my %returnhash=();
1.42 www 5833: my $i=0;
1.800 albertel 5834: foreach my $item (@$storearr) {
5835: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5836: $i++;
1.191 harris41 5837: }
1.12 www 5838: return %returnhash;
5839: }
5840:
1.667 albertel 5841: # ------------------------------------------------------------ tmpput interface
5842: sub tmpput {
1.802 raeburn 5843: my ($storehash,$server,$context)=@_;
1.667 albertel 5844: my $items='';
1.800 albertel 5845: foreach my $item (keys(%$storehash)) {
5846: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5847: }
5848: $items=~s/\&$//;
1.802 raeburn 5849: if (defined($context)) {
5850: $items .= ':'.&escape($context);
5851: }
1.667 albertel 5852: return &reply("tmpput:$items",$server);
5853: }
5854:
5855: # ------------------------------------------------------------ tmpget interface
5856: sub tmpget {
1.688 albertel 5857: my ($token,$server)=@_;
5858: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5859: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5860: my %returnhash;
5861: foreach my $item (split(/\&/,$rep)) {
5862: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5863: next if ($key =~ /^error: 2 /);
1.667 albertel 5864: $returnhash{&unescape($key)}=&thaw_unescape($value);
5865: }
5866: return %returnhash;
5867: }
5868:
1.1113 raeburn 5869: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5870: sub tmpdel {
5871: my ($token,$server)=@_;
5872: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5873: return &reply("tmpdel:$token",$server);
5874: }
5875:
1.1198 raeburn 5876: # ------------------------------------------------------------ get_timebased_id
5877:
5878: sub get_timebased_id {
5879: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5880: $maxtries) = @_;
5881: my ($newid,$error,$dellock);
5882: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5883: return ('','ok','invalid call to get suffix');
5884: }
5885:
5886: # set defaults for any optional args for which values were not supplied
5887: if ($who eq '') {
5888: $who = $env{'user.name'}.':'.$env{'user.domain'};
5889: }
5890: if (!$locktries) {
5891: $locktries = 3;
5892: }
5893: if (!$maxtries) {
5894: $maxtries = 10;
5895: }
5896:
5897: if (($cdom eq '') || ($cnum eq '')) {
5898: if ($env{'request.course.id'}) {
5899: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5900: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5901: }
5902: if (($cdom eq '') || ($cnum eq '')) {
5903: return ('','ok','call to get suffix not in course context');
5904: }
5905: }
5906:
5907: # construct locking item
5908: my $lockhash = {
5909: $prefix."\0".'locked_'.$keyid => $who,
5910: };
5911: my $tries = 0;
5912:
5913: # attempt to get lock on nohist_$namespace file
5914: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5915: while (($gotlock ne 'ok') && $tries <$locktries) {
5916: $tries ++;
5917: sleep 1;
5918: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5919: }
5920:
5921: # attempt to get unique identifier, based on current timestamp
5922: if ($gotlock eq 'ok') {
5923: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
5924: my $id = time;
5925: $newid = $id;
5926: my $idtries = 0;
5927: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
5928: if ($idtype eq 'concat') {
5929: $newid = $id.$idtries;
5930: } else {
5931: $newid ++;
5932: }
5933: $idtries ++;
5934: }
5935: if (!exists($inuse{$prefix."\0".$newid})) {
5936: my %new_item = (
5937: $prefix."\0".$newid => $who,
5938: );
5939: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
5940: $cdom,$cnum);
5941: if ($putresult ne 'ok') {
5942: undef($newid);
5943: $error = 'error saving new item: '.$putresult;
5944: }
5945: } else {
5946: $error = ('error: no unique suffix available for the new item ');
5947: }
5948: # remove lock
5949: my @del_lock = ($prefix."\0".'locked_'.$keyid);
5950: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
5951: } else {
5952: $error = "error: could not obtain lockfile\n";
5953: $dellock = 'ok';
5954: }
5955: return ($newid,$dellock,$error);
5956: }
5957:
1.765 albertel 5958: # -------------------------------------------------- portfolio access checking
5959:
5960: sub portfolio_access {
1.766 albertel 5961: my ($requrl) = @_;
1.765 albertel 5962: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5963: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 5964: if ($result) {
5965: my %setters;
5966: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5967: my ($startblock,$endblock) =
5968: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5969: if ($startblock && $endblock) {
5970: return 'B';
5971: }
5972: } else {
5973: my ($startblock,$endblock) =
5974: &Apache::loncommon::blockcheck(\%setters,'port');
5975: if ($startblock && $endblock) {
5976: return 'B';
5977: }
5978: }
5979: }
1.765 albertel 5980: if ($result eq 'ok') {
1.766 albertel 5981: return 'F';
1.765 albertel 5982: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 5983: return 'A';
1.765 albertel 5984: }
1.766 albertel 5985: return '';
1.765 albertel 5986: }
5987:
5988: sub get_portfolio_access {
1.767 albertel 5989: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5990:
5991: if (!ref($access_hash)) {
5992: my $current_perms = &get_portfile_permissions($udom,$unum);
5993: my %access_controls = &get_access_controls($current_perms,$group,
5994: $file_name);
5995: $access_hash = $access_controls{$file_name};
5996: }
5997:
1.765 albertel 5998: my ($public,$guest,@domains,@users,@courses,@groups);
5999: my $now = time;
6000: if (ref($access_hash) eq 'HASH') {
6001: foreach my $key (keys(%{$access_hash})) {
6002: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6003: if ($start > $now) {
6004: next;
6005: }
6006: if ($end && $end<$now) {
6007: next;
6008: }
6009: if ($scope eq 'public') {
6010: $public = $key;
6011: last;
6012: } elsif ($scope eq 'guest') {
6013: $guest = $key;
6014: } elsif ($scope eq 'domains') {
6015: push(@domains,$key);
6016: } elsif ($scope eq 'users') {
6017: push(@users,$key);
6018: } elsif ($scope eq 'course') {
6019: push(@courses,$key);
6020: } elsif ($scope eq 'group') {
6021: push(@groups,$key);
6022: }
6023: }
6024: if ($public) {
6025: return 'ok';
6026: }
6027: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6028: if ($guest) {
6029: return $guest;
6030: }
6031: } else {
6032: if (@domains > 0) {
6033: foreach my $domkey (@domains) {
6034: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6035: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6036: return 'ok';
6037: }
6038: }
6039: }
6040: }
6041: if (@users > 0) {
6042: foreach my $userkey (@users) {
1.865 raeburn 6043: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6044: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6045: if (ref($item) eq 'HASH') {
6046: if (($item->{'uname'} eq $env{'user.name'}) &&
6047: ($item->{'udom'} eq $env{'user.domain'})) {
6048: return 'ok';
6049: }
6050: }
6051: }
6052: }
1.765 albertel 6053: }
6054: }
6055: my %roleshash;
6056: my @courses_and_groups = @courses;
6057: push(@courses_and_groups,@groups);
6058: if (@courses_and_groups > 0) {
6059: my (%allgroups,%allroles);
6060: my ($start,$end,$role,$sec,$group);
6061: foreach my $envkey (%env) {
1.1060 raeburn 6062: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6063: my $cid = $2.'_'.$3;
6064: if ($1 eq 'gr') {
6065: $group = $4;
6066: $allgroups{$cid}{$group} = $env{$envkey};
6067: } else {
6068: if ($4 eq '') {
6069: $sec = 'none';
6070: } else {
6071: $sec = $4;
6072: }
6073: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6074: }
1.811 albertel 6075: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6076: my $cid = $2.'_'.$3;
6077: if ($4 eq '') {
6078: $sec = 'none';
6079: } else {
6080: $sec = $4;
6081: }
6082: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6083: }
6084: }
6085: if (keys(%allroles) == 0) {
6086: return;
6087: }
6088: foreach my $key (@courses_and_groups) {
6089: my %content = %{$$access_hash{$key}};
6090: my $cnum = $content{'number'};
6091: my $cdom = $content{'domain'};
6092: my $cid = $cdom.'_'.$cnum;
6093: if (!exists($allroles{$cid})) {
6094: next;
6095: }
6096: foreach my $role_id (keys(%{$content{'roles'}})) {
6097: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6098: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6099: my @status = @{$content{'roles'}{$role_id}{'access'}};
6100: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6101: foreach my $role (keys(%{$allroles{$cid}})) {
6102: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6103: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6104: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6105: if (grep/^all$/,@sections) {
6106: return 'ok';
6107: } else {
6108: if (grep/^$sec$/,@sections) {
6109: return 'ok';
6110: }
6111: }
6112: }
6113: }
6114: if (keys(%{$allgroups{$cid}}) == 0) {
6115: if (grep/^none$/,@groups) {
6116: return 'ok';
6117: }
6118: } else {
6119: if (grep/^all$/,@groups) {
6120: return 'ok';
6121: }
6122: foreach my $group (keys(%{$allgroups{$cid}})) {
6123: if (grep/^$group$/,@groups) {
6124: return 'ok';
6125: }
6126: }
6127: }
6128: }
6129: }
6130: }
6131: }
6132: }
6133: if ($guest) {
6134: return $guest;
6135: }
6136: }
6137: }
6138: return;
6139: }
6140:
6141: sub course_group_datechecker {
6142: my ($dates,$now,$status) = @_;
6143: my ($start,$end) = split(/\./,$dates);
6144: if (!$start && !$end) {
6145: return 'ok';
6146: }
6147: if (grep/^active$/,@{$status}) {
6148: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6149: return 'ok';
6150: }
6151: }
6152: if (grep/^previous$/,@{$status}) {
6153: if ($end > $now ) {
6154: return 'ok';
6155: }
6156: }
6157: if (grep/^future$/,@{$status}) {
6158: if ($start > $now) {
6159: return 'ok';
6160: }
6161: }
6162: return;
6163: }
6164:
6165: sub parse_portfolio_url {
6166: my ($url) = @_;
6167:
6168: my ($type,$udom,$unum,$group,$file_name);
6169:
1.823 albertel 6170: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6171: $type = 1;
6172: $udom = $1;
6173: $unum = $2;
6174: $file_name = $3;
1.823 albertel 6175: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6176: $type = 2;
6177: $udom = $1;
6178: $unum = $2;
6179: $group = $3;
6180: $file_name = $3.'/'.$4;
6181: }
6182: if (wantarray) {
6183: return ($type,$udom,$unum,$file_name,$group);
6184: }
6185: return $type;
6186: }
6187:
6188: sub is_portfolio_url {
6189: my ($url) = @_;
6190: return scalar(&parse_portfolio_url($url));
6191: }
6192:
1.798 raeburn 6193: sub is_portfolio_file {
6194: my ($file) = @_;
1.820 raeburn 6195: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6196: return 1;
6197: }
6198: return;
6199: }
6200:
1.976 raeburn 6201: sub usertools_access {
1.1084 raeburn 6202: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6203: my ($access,%tools);
6204: if ($context eq '') {
6205: $context = 'tools';
6206: }
6207: if ($context eq 'requestcourses') {
6208: %tools = (
6209: official => 1,
6210: unofficial => 1,
1.1006 raeburn 6211: community => 1,
1.1246 ! raeburn 6212: textbook => 1,
1.985 raeburn 6213: );
1.1183 raeburn 6214: } elsif ($context eq 'requestauthor') {
6215: %tools = (
6216: requestauthor => 1,
6217: );
1.985 raeburn 6218: } else {
6219: %tools = (
6220: aboutme => 1,
6221: blog => 1,
1.1177 raeburn 6222: webdav => 1,
1.985 raeburn 6223: portfolio => 1,
6224: );
6225: }
1.976 raeburn 6226: return if (!defined($tools{$tool}));
6227:
1.1242 raeburn 6228: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6229: $udom = $env{'user.domain'};
6230: $uname = $env{'user.name'};
6231: }
6232:
1.978 raeburn 6233: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6234: if ($action ne 'reload') {
1.985 raeburn 6235: if ($context eq 'requestcourses') {
6236: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6237: } elsif ($context eq 'requestauthor') {
6238: return $env{'environment.canrequest.author'};
1.985 raeburn 6239: } else {
6240: return $env{'environment.availabletools.'.$tool};
6241: }
6242: }
1.976 raeburn 6243: }
6244:
1.1183 raeburn 6245: my ($toolstatus,$inststatus,$envkey);
6246: if ($context eq 'requestauthor') {
6247: $envkey = $context;
6248: } else {
6249: $envkey = $context.'.'.$tool;
6250: }
1.976 raeburn 6251:
1.985 raeburn 6252: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6253: ($action ne 'reload')) {
1.1183 raeburn 6254: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6255: $inststatus = $env{'environment.inststatus'};
6256: } else {
1.1084 raeburn 6257: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6258: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6259: $inststatus = $userenvref->{'inststatus'};
6260: } else {
1.1183 raeburn 6261: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6262: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6263: $inststatus = $userenv{'inststatus'};
6264: }
1.976 raeburn 6265: }
6266:
6267: if ($toolstatus ne '') {
6268: if ($toolstatus) {
6269: $access = 1;
6270: } else {
6271: $access = 0;
6272: }
6273: return $access;
6274: }
6275:
1.1084 raeburn 6276: my ($is_adv,%domdef);
6277: if (ref($is_advref) eq 'HASH') {
6278: $is_adv = $is_advref->{'is_adv'};
6279: } else {
6280: $is_adv = &is_advanced_user($udom,$uname);
6281: }
6282: if (ref($domdefref) eq 'HASH') {
6283: %domdef = %{$domdefref};
6284: } else {
6285: %domdef = &get_domain_defaults($udom);
6286: }
1.976 raeburn 6287: if (ref($domdef{$tool}) eq 'HASH') {
6288: if ($is_adv) {
6289: if ($domdef{$tool}{'_LC_adv'} ne '') {
6290: if ($domdef{$tool}{'_LC_adv'}) {
6291: $access = 1;
6292: } else {
6293: $access = 0;
6294: }
6295: return $access;
6296: }
6297: }
6298: if ($inststatus ne '') {
6299: my ($hasaccess,$hasnoaccess);
6300: foreach my $affiliation (split(/:/,$inststatus)) {
6301: if ($domdef{$tool}{$affiliation} ne '') {
6302: if ($domdef{$tool}{$affiliation}) {
6303: $hasaccess = 1;
6304: } else {
6305: $hasnoaccess = 1;
6306: }
6307: }
6308: }
6309: if ($hasaccess || $hasnoaccess) {
6310: if ($hasaccess) {
6311: $access = 1;
6312: } elsif ($hasnoaccess) {
6313: $access = 0;
6314: }
6315: return $access;
6316: }
6317: } else {
6318: if ($domdef{$tool}{'default'} ne '') {
6319: if ($domdef{$tool}{'default'}) {
6320: $access = 1;
6321: } elsif ($domdef{$tool}{'default'} == 0) {
6322: $access = 0;
6323: }
6324: return $access;
6325: }
6326: }
6327: } else {
1.1177 raeburn 6328: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6329: $access = 1;
6330: } else {
6331: $access = 0;
6332: }
1.976 raeburn 6333: return $access;
6334: }
6335: }
6336:
1.1050 raeburn 6337: sub is_course_owner {
6338: my ($cdom,$cnum,$udom,$uname) = @_;
6339: if (($udom eq '') || ($uname eq '')) {
6340: $udom = $env{'user.domain'};
6341: $uname = $env{'user.name'};
6342: }
6343: unless (($udom eq '') || ($uname eq '')) {
6344: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6345: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6346: return 1;
6347: } else {
6348: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6349: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6350: return 1;
6351: }
6352: }
6353: }
6354: }
6355: return;
6356: }
6357:
1.976 raeburn 6358: sub is_advanced_user {
6359: my ($udom,$uname) = @_;
1.1085 raeburn 6360: if ($udom ne '' && $uname ne '') {
6361: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6362: if (wantarray) {
6363: return ($env{'user.adv'},$env{'user.author'});
6364: } else {
6365: return $env{'user.adv'};
6366: }
1.1085 raeburn 6367: }
6368: }
1.976 raeburn 6369: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6370: my %allroles;
1.1128 raeburn 6371: my ($is_adv,$is_author);
1.976 raeburn 6372: foreach my $role (keys(%roleshash)) {
6373: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6374: my $area = '/'.$tdomain.'/'.$trest;
6375: if ($sec ne '') {
6376: $area .= '/'.$sec;
6377: }
6378: if (($area ne '') && ($trole ne '')) {
6379: my $spec=$trole.'.'.$area;
6380: if ($trole =~ /^cr\//) {
6381: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6382: } elsif ($trole ne 'gr') {
6383: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6384: }
1.1128 raeburn 6385: if ($trole eq 'au') {
6386: $is_author = 1;
6387: }
1.976 raeburn 6388: }
6389: }
6390: foreach my $role (keys(%allroles)) {
6391: last if ($is_adv);
6392: foreach my $item (split(/:/,$allroles{$role})) {
6393: if ($item ne '') {
6394: my ($privilege,$restrictions)=split(/&/,$item);
6395: if ($privilege eq 'adv') {
6396: $is_adv = 1;
6397: last;
6398: }
6399: }
6400: }
6401: }
1.1128 raeburn 6402: if (wantarray) {
6403: return ($is_adv,$is_author);
6404: }
1.976 raeburn 6405: return $is_adv;
6406: }
1.798 raeburn 6407:
1.1035 raeburn 6408: sub check_can_request {
1.1036 raeburn 6409: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6410: my $canreq = 0;
6411: my ($types,$typename) = &Apache::loncommon::course_types();
6412: my @options = ('approval','validate','autolimit');
6413: my $optregex = join('|',@options);
6414: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6415: foreach my $type (@{$types}) {
6416: if (&usertools_access($env{'user.name'},
6417: $env{'user.domain'},
6418: $type,undef,'requestcourses')) {
6419: $canreq ++;
1.1036 raeburn 6420: if (ref($request_domains) eq 'HASH') {
6421: push(@{$request_domains->{$type}},$env{'user.domain'});
6422: }
1.1035 raeburn 6423: if ($dom eq $env{'user.domain'}) {
6424: $can_request->{$type} = 1;
6425: }
6426: }
6427: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6428: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6429: if (@curr > 0) {
1.1036 raeburn 6430: foreach my $item (@curr) {
6431: if (ref($request_domains) eq 'HASH') {
6432: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6433: if ($otherdom ne '') {
6434: if (ref($request_domains->{$type}) eq 'ARRAY') {
6435: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6436: push(@{$request_domains->{$type}},$otherdom);
6437: }
6438: } else {
6439: push(@{$request_domains->{$type}},$otherdom);
6440: }
6441: }
6442: }
6443: }
6444: unless($dom eq $env{'user.domain'}) {
6445: $canreq ++;
1.1035 raeburn 6446: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6447: $can_request->{$type} = 1;
6448: }
6449: }
6450: }
6451: }
6452: }
6453: }
6454: return $canreq;
6455: }
6456:
1.341 www 6457: # ---------------------------------------------- Custom access rule evaluation
6458:
6459: sub customaccess {
6460: my ($priv,$uri)=@_;
1.807 albertel 6461: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6462: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6463: $udom = &LONCAPA::clean_domain($udom);
6464: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6465: my $access=0;
1.800 albertel 6466: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6467: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6468: if ($type eq 'user') {
6469: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6470: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6471: if ($tdom) {
6472: if ($tdom ne $env{'user.domain'}) { next; }
6473: }
1.896 albertel 6474: if ($tuname) {
6475: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6476: }
6477: $access=($effect eq 'allow');
6478: last;
6479: }
6480: } else {
6481: if ($role) {
6482: if ($role ne $urole) { next; }
6483: }
6484: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6485: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6486: if ($tdom) {
6487: if ($tdom ne $udom) { next; }
6488: }
6489: if ($tcrs) {
6490: if ($tcrs ne $ucrs) { next; }
6491: }
6492: if ($tsec) {
6493: if ($tsec ne $usec) { next; }
6494: }
6495: $access=($effect eq 'allow');
6496: last;
6497: }
6498: if ($realm eq '' && $role eq '') {
6499: $access=($effect eq 'allow');
6500: }
1.402 bowersj2 6501: }
1.341 www 6502: }
6503: return $access;
6504: }
6505:
1.103 harris41 6506: # ------------------------------------------------- Check for a user privilege
1.12 www 6507:
6508: sub allowed {
1.810 raeburn 6509: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6510: my $ver_orguri=$uri;
1.439 www 6511: $uri=&deversion($uri);
1.152 www 6512: my $orguri=$uri;
1.52 www 6513: $uri=&declutter($uri);
1.809 raeburn 6514:
1.810 raeburn 6515: if ($priv eq 'evb') {
6516: # Evade communication block restrictions for specified role in a course
6517: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6518: return $1;
6519: } else {
6520: return;
6521: }
6522: }
6523:
1.620 albertel 6524: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6525: # Free bre access to adm and meta resources
1.775 albertel 6526: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6527: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6528: && ($priv eq 'bre')) {
1.14 www 6529: return 'F';
1.159 www 6530: }
6531:
1.545 banghart 6532: # Free bre access to user's own portfolio contents
1.714 raeburn 6533: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6534: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6535: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6536: my %setters;
6537: my ($startblock,$endblock) =
6538: &Apache::loncommon::blockcheck(\%setters,'port');
6539: if ($startblock && $endblock) {
6540: return 'B';
6541: } else {
6542: return 'F';
6543: }
1.545 banghart 6544: }
6545:
1.762 raeburn 6546: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6547: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6548: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6549: if (exists($env{'request.course.id'})) {
6550: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6551: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6552: if (($domain eq $cdom) && ($name eq $cnum)) {
6553: my $courseprivid=$env{'request.course.id'};
6554: $courseprivid=~s/\_/\//;
6555: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6556: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6557: return $1;
1.762 raeburn 6558: } else {
6559: if ($env{'request.course.sec'}) {
6560: $courseprivid.='/'.$env{'request.course.sec'};
6561: }
6562: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6563: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6564: return $2;
6565: }
1.714 raeburn 6566: }
6567: }
6568: }
6569: }
6570:
1.159 www 6571: # Free bre to public access
6572:
6573: if ($priv eq 'bre') {
1.238 www 6574: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6575: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6576: return 'F';
6577: }
1.238 www 6578: if ($copyright eq 'priv') {
6579: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6580: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6581: return '';
6582: }
6583: }
6584: if ($copyright eq 'domain') {
6585: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6586: unless (($env{'user.domain'} eq $1) ||
6587: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6588: return '';
6589: }
1.262 matthew 6590: }
1.620 albertel 6591: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6592: # Library role, so allow browsing of resources in this domain.
6593: return 'F';
1.238 www 6594: }
1.341 www 6595: if ($copyright eq 'custom') {
6596: unless (&customaccess($priv,$uri)) { return ''; }
6597: }
1.14 www 6598: }
1.264 matthew 6599: # Domain coordinator is trying to create a course
1.620 albertel 6600: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6601: # uri is the requested domain in this case.
6602: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6603: # a role of dc for the domain in question.
1.620 albertel 6604: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6605: }
1.29 www 6606:
1.52 www 6607: my $thisallowed='';
6608: my $statecond=0;
6609: my $courseprivid='';
6610:
1.1039 raeburn 6611: my $ownaccess;
1.1043 raeburn 6612: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6613: if (($priv eq 'bro') && ($env{'user.author'})) {
6614: if ($uri eq '') {
6615: $ownaccess = 1;
6616: } else {
6617: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6618: my $udom = $env{'user.domain'};
6619: my $uname = $env{'user.name'};
6620: if ($uri =~ m{^\Q$udom\E/?$}) {
6621: $ownaccess = 1;
1.1040 raeburn 6622: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6623: unless ($uri =~ m{\.\./}) {
6624: $ownaccess = 1;
6625: }
6626: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6627: my $now = time;
6628: if ($uri =~ m{^([^/]+)/?$}) {
6629: my $adom = $1;
6630: foreach my $key (keys(%env)) {
1.1042 raeburn 6631: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6632: my ($start,$end) = split('.',$env{$key});
6633: if (($now >= $start) && (!$end || $end < $now)) {
6634: $ownaccess = 1;
6635: last;
6636: }
6637: }
6638: }
6639: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6640: my $adom = $1;
6641: my $aname = $2;
1.1042 raeburn 6642: foreach my $role ('ca','aa') {
6643: if ($env{"user.role.$role./$adom/$aname"}) {
6644: my ($start,$end) =
6645: split('.',$env{"user.role.$role./$adom/$aname"});
6646: if (($now >= $start) && (!$end || $end < $now)) {
6647: $ownaccess = 1;
6648: last;
6649: }
1.1039 raeburn 6650: }
6651: }
6652: }
6653: }
6654: }
6655: }
6656: }
6657:
1.52 www 6658: # Course
6659:
1.620 albertel 6660: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6661: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6662: $thisallowed.=$1;
6663: }
1.52 www 6664: }
1.29 www 6665:
1.52 www 6666: # Domain
6667:
1.620 albertel 6668: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6669: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6670: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6671: $thisallowed.=$1;
6672: }
1.12 www 6673: }
1.52 www 6674:
1.1141 raeburn 6675: # User who is not author or co-author might still be able to edit
6676: # resource of an author in the domain (e.g., if Domain Coordinator).
6677: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6678: (&allowed('mdc',$env{'request.course.id'}))) {
6679: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6680: $thisallowed.=$1;
6681: }
6682: }
6683:
1.52 www 6684: # Course: uri itself is a course
1.66 www 6685: my $courseuri=$uri;
6686: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6687: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6688:
1.620 albertel 6689: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6690: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6691: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6692: $thisallowed.=$1;
6693: }
1.12 www 6694: }
1.29 www 6695:
1.665 albertel 6696: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6697: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6698: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6699: $thisallowed='';
1.671 raeburn 6700: my ($match)=&is_on_map($uri);
6701: if ($match) {
6702: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6703: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6704: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6705: if (@blockers > 0) {
6706: $thisallowed = 'B';
6707: } else {
6708: $thisallowed.=$1;
6709: }
1.671 raeburn 6710: }
6711: } else {
1.705 albertel 6712: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6713: if ($refuri) {
6714: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6715: $thisallowed='F';
1.671 raeburn 6716: } else {
6717: $refuri=&declutter($refuri);
6718: my ($match) = &is_on_map($refuri);
6719: if ($match) {
1.1162 raeburn 6720: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6721: if (@blockers > 0) {
6722: $thisallowed = 'B';
6723: } else {
6724: $thisallowed='F';
6725: }
1.671 raeburn 6726: }
1.669 raeburn 6727: }
1.671 raeburn 6728: }
6729: }
1.314 www 6730: }
1.492 albertel 6731:
1.766 albertel 6732: if ($priv eq 'bre'
6733: && $thisallowed ne 'F'
6734: && $thisallowed ne '2'
6735: && &is_portfolio_url($uri)) {
6736: $thisallowed = &portfolio_access($uri);
6737: }
6738:
1.52 www 6739: # Full access at system, domain or course-wide level? Exit.
1.29 www 6740: if ($thisallowed=~/F/) {
6741: return 'F';
6742: }
6743:
1.52 www 6744: # If this is generating or modifying users, exit with special codes
1.29 www 6745:
1.643 www 6746: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6747: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6748: my ($audom,$auname)=split('/',$uri);
1.643 www 6749: # no author name given, so this just checks on the general right to make a co-author in this domain
6750: unless ($auname) { return $thisallowed; }
6751: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6752: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6753: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6754: ($audom ne $env{'request.role.domain'}))) { return ''; }
6755: }
1.52 www 6756: return $thisallowed;
6757: }
6758: #
1.103 harris41 6759: # Gathered so far: system, domain and course wide privileges
1.52 www 6760: #
6761: # Course: See if uri or referer is an individual resource that is part of
6762: # the course
6763:
1.620 albertel 6764: if ($env{'request.course.id'}) {
1.232 www 6765:
1.620 albertel 6766: $courseprivid=$env{'request.course.id'};
6767: if ($env{'request.course.sec'}) {
6768: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6769: }
6770: $courseprivid=~s/\_/\//;
6771: my $checkreferer=1;
1.232 www 6772: my ($match,$cond)=&is_on_map($uri);
6773: if ($match) {
6774: $statecond=$cond;
1.620 albertel 6775: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6776: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6777: my $value = $1;
6778: if ($priv eq 'bre') {
6779: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6780: if (@blockers > 0) {
6781: $thisallowed = 'B';
6782: } else {
6783: $thisallowed.=$value;
6784: }
6785: } else {
6786: $thisallowed.=$value;
6787: }
1.52 www 6788: $checkreferer=0;
6789: }
1.29 www 6790: }
1.83 www 6791:
1.148 www 6792: if ($checkreferer) {
1.620 albertel 6793: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6794: unless ($refuri) {
1.800 albertel 6795: foreach my $key (keys(%env)) {
6796: if ($key=~/^httpref\..*\*/) {
6797: my $pattern=$key;
1.156 www 6798: $pattern=~s/^httpref\.\/res\///;
1.148 www 6799: $pattern=~s/\*/\[\^\/\]\+/g;
6800: $pattern=~s/\//\\\//g;
1.152 www 6801: if ($orguri=~/$pattern/) {
1.800 albertel 6802: $refuri=$env{$key};
1.148 www 6803: }
6804: }
1.191 harris41 6805: }
1.148 www 6806: }
1.232 www 6807:
1.148 www 6808: if ($refuri) {
1.152 www 6809: $refuri=&declutter($refuri);
1.232 www 6810: my ($match,$cond)=&is_on_map($refuri);
6811: if ($match) {
6812: my $refstatecond=$cond;
1.620 albertel 6813: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6814: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6815: my $value = $1;
6816: if ($priv eq 'bre') {
6817: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6818: if (@blockers > 0) {
6819: $thisallowed = 'B';
6820: } else {
6821: $thisallowed.=$value;
6822: }
6823: } else {
6824: $thisallowed.=$value;
6825: }
1.53 www 6826: $uri=$refuri;
6827: $statecond=$refstatecond;
1.52 www 6828: }
6829: }
1.148 www 6830: }
1.29 www 6831: }
1.52 www 6832: }
1.29 www 6833:
1.52 www 6834: #
1.103 harris41 6835: # Gathered now: all privileges that could apply, and condition number
1.52 www 6836: #
6837: #
6838: # Full or no access?
6839: #
1.29 www 6840:
1.52 www 6841: if ($thisallowed=~/F/) {
6842: return 'F';
6843: }
1.29 www 6844:
1.52 www 6845: unless ($thisallowed) {
6846: return '';
6847: }
1.29 www 6848:
1.52 www 6849: # Restrictions exist, deal with them
6850: #
6851: # C:according to course preferences
6852: # R:according to resource settings
6853: # L:unless locked
6854: # X:according to user session state
6855: #
6856:
6857: # Possibly locked functionality, check all courses
1.54 www 6858: # Locks might take effect only after 10 minutes cache expiration for other
6859: # courses, and 2 minutes for current course
1.52 www 6860:
6861: my $envkey;
6862: if ($thisallowed=~/L/) {
1.1000 raeburn 6863: foreach $envkey (keys(%env)) {
1.54 www 6864: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6865: my $courseid=$2;
6866: my $roleid=$1.'.'.$2;
1.92 www 6867: $courseid=~s/^\///;
1.54 www 6868: my $expiretime=600;
1.620 albertel 6869: if ($env{'request.role'} eq $roleid) {
1.54 www 6870: $expiretime=120;
6871: }
6872: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6873: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6874: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6875: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6876: }
1.620 albertel 6877: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6878: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6879: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6880: &log($env{'user.domain'},$env{'user.name'},
6881: $env{'user.home'},
1.57 www 6882: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6883: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6884: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6885: return '';
6886: }
6887: }
1.620 albertel 6888: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6889: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6890: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6891: &log($env{'user.domain'},$env{'user.name'},
6892: $env{'user.home'},
1.57 www 6893: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6894: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6895: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6896: return '';
6897: }
6898: }
6899: }
1.29 www 6900: }
1.52 www 6901: }
6902:
6903: #
6904: # Rest of the restrictions depend on selected course
6905: #
6906:
1.620 albertel 6907: unless ($env{'request.course.id'}) {
1.766 albertel 6908: if ($thisallowed eq 'A') {
6909: return 'A';
1.814 raeburn 6910: } elsif ($thisallowed eq 'B') {
6911: return 'B';
1.766 albertel 6912: } else {
6913: return '1';
6914: }
1.52 www 6915: }
1.29 www 6916:
1.52 www 6917: #
6918: # Now user is definitely in a course
6919: #
1.53 www 6920:
6921:
6922: # Course preferences
6923:
6924: if ($thisallowed=~/C/) {
1.620 albertel 6925: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6926: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6927: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6928: =~/\Q$rolecode\E/) {
1.1103 raeburn 6929: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6930: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6931: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6932: $env{'request.course.id'});
6933: }
1.237 www 6934: return '';
6935: }
6936:
1.620 albertel 6937: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6938: =~/\Q$unamedom\E/) {
1.1103 raeburn 6939: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6940: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6941: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6942: $env{'request.course.id'});
6943: }
1.54 www 6944: return '';
6945: }
1.53 www 6946: }
6947:
6948: # Resource preferences
6949:
6950: if ($thisallowed=~/R/) {
1.620 albertel 6951: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6952: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6953: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6954: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6955: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6956: }
6957: return '';
1.54 www 6958: }
1.53 www 6959: }
1.30 www 6960:
1.246 www 6961: # Restricted by state or randomout?
1.30 www 6962:
1.52 www 6963: if ($thisallowed=~/X/) {
1.620 albertel 6964: if ($env{'acc.randomout'}) {
1.579 albertel 6965: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 6966: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 6967: return '';
6968: }
1.247 www 6969: }
6970: if (&condval($statecond)) {
1.52 www 6971: return '2';
6972: } else {
6973: return '';
6974: }
6975: }
1.30 www 6976:
1.766 albertel 6977: if ($thisallowed eq 'A') {
6978: return 'A';
1.814 raeburn 6979: } elsif ($thisallowed eq 'B') {
6980: return 'B';
1.766 albertel 6981: }
1.52 www 6982: return 'F';
1.232 www 6983: }
1.1162 raeburn 6984:
1.1192 raeburn 6985: # ------------------------------------------- Check construction space access
6986:
6987: sub constructaccess {
6988: my ($url,$setpriv)=@_;
6989:
6990: # We do not allow editing of previous versions of files
6991: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
6992:
6993: # Get username and domain from URL
6994: my ($ownername,$ownerdomain,$ownerhome);
6995:
6996: ($ownerdomain,$ownername) =
6997: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
6998:
6999: # The URL does not really point to any authorspace, forget it
7000: unless (($ownername) && ($ownerdomain)) { return ''; }
7001:
7002: # Now we need to see if the user has access to the authorspace of
7003: # $ownername at $ownerdomain
7004:
7005: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7006: # Real author for this?
7007: $ownerhome = $env{'user.home'};
7008: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7009: return ($ownername,$ownerdomain,$ownerhome);
7010: }
7011: } else {
7012: # Co-author for this?
7013: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7014: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7015: $ownerhome = &homeserver($ownername,$ownerdomain);
7016: return ($ownername,$ownerdomain,$ownerhome);
7017: }
7018: }
7019:
7020: # We don't have any access right now. If we are not possibly going to do anything about this,
7021: # we might as well leave
7022: unless ($setpriv) { return ''; }
7023:
7024: # Backdoor access?
7025: my $allowed=&allowed('eco',$ownerdomain);
7026: # Nope
7027: unless ($allowed) { return ''; }
7028: # Looks like we may have access, but could be locked by the owner of the construction space
7029: if ($allowed eq 'U') {
7030: my %blocked=&get('environment',['domcoord.author'],
7031: $ownerdomain,$ownername);
7032: # Is blocked by owner
7033: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7034: }
7035: if (($allowed eq 'F') || ($allowed eq 'U')) {
7036: # Grant temporary access
7037: my $then=$env{'user.login.time'};
1.1209 raeburn 7038: my $update=$env{'user.update.time'};
1.1192 raeburn 7039: if (!$update) { $update = $then; }
7040: my $refresh=$env{'user.refresh.time'};
7041: if (!$refresh) { $refresh = $update; }
7042: my $now = time;
7043: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7044: $now,'ca','constructaccess');
7045: $ownerhome = &homeserver($ownername,$ownerdomain);
7046: return($ownername,$ownerdomain,$ownerhome);
7047: }
7048: # No business here
7049: return '';
7050: }
7051:
1.1162 raeburn 7052: sub get_comm_blocks {
7053: my ($cdom,$cnum) = @_;
7054: if ($cdom eq '' || $cnum eq '') {
7055: return unless ($env{'request.course.id'});
7056: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7057: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7058: }
7059: my %commblocks;
7060: my $hashid=$cdom.'_'.$cnum;
7061: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7062: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7063: %commblocks = %{$blocksref};
7064: } else {
7065: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7066: my $cachetime = 600;
7067: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7068: }
7069: return %commblocks;
7070: }
7071:
7072: sub has_comm_blocking {
7073: my ($priv,$symb,$uri,$blocks) = @_;
7074: return unless ($env{'request.course.id'});
7075: return unless ($priv eq 'bre');
7076: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7077: my %commblocks;
7078: if (ref($blocks) eq 'HASH') {
7079: %commblocks = %{$blocks};
7080: } else {
7081: %commblocks = &get_comm_blocks();
7082: }
7083: return unless (keys(%commblocks) > 0);
7084: if (!$symb) { $symb=&symbread($uri,1); }
7085: my ($map,$resid,undef)=&decode_symb($symb);
7086: my %tocheck = (
7087: maps => $map,
7088: resources => $symb,
7089: );
7090: my @blockers;
7091: my $now = time;
1.1163 raeburn 7092: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7093: foreach my $block (keys(%commblocks)) {
7094: if ($block =~ /^(\d+)____(\d+)$/) {
7095: my ($start,$end) = ($1,$2);
7096: if ($start <= $now && $end >= $now) {
7097: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7098: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7099: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7100: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7101: unless (grep(/^\Q$block\E$/,@blockers)) {
7102: push(@blockers,$block);
7103: }
7104: }
7105: }
7106: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7107: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7108: unless (grep(/^\Q$block\E$/,@blockers)) {
7109: push(@blockers,$block);
7110: }
7111: }
7112: }
7113: }
7114: }
7115: }
7116: } elsif ($block =~ /^firstaccess____(.+)$/) {
7117: my $item = $1;
1.1163 raeburn 7118: my @to_test;
1.1162 raeburn 7119: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7120: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7121: my $check_interval;
7122: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7123: my @interval;
7124: my $type = 'map';
7125: if ($item eq 'course') {
7126: $type = 'course';
7127: @interval=&EXT("resource.0.interval");
7128: } else {
7129: if ($item =~ /___\d+___/) {
7130: $type = 'resource';
7131: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7132: if (ref($navmap)) {
7133: my $res = $navmap->getBySymb($item);
7134: push(@to_test,$res);
7135: }
1.1162 raeburn 7136: } else {
7137: my $mapsymb = &symbread($item,1);
7138: if ($mapsymb) {
7139: if (ref($navmap)) {
7140: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7141: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7142: foreach my $res (@to_test) {
1.1162 raeburn 7143: my $symb = $res->symb();
7144: next if ($symb eq $mapsymb);
7145: if ($symb ne '') {
7146: @interval=&EXT("resource.0.interval",$symb);
7147: last;
7148: }
7149: }
7150: }
7151: }
7152: }
7153: }
7154: if ($interval[0] =~ /\d+/) {
7155: my $first_access;
7156: if ($type eq 'resource') {
7157: $first_access=&get_first_access($interval[1],$item);
7158: } elsif ($type eq 'map') {
7159: $first_access=&get_first_access($interval[1],undef,$item);
7160: } else {
7161: $first_access=&get_first_access($interval[1]);
7162: }
7163: if ($first_access) {
7164: my $timesup = $first_access+$interval[0];
7165: if ($timesup > $now) {
1.1163 raeburn 7166: foreach my $res (@to_test) {
7167: if ($res->is_problem()) {
7168: if ($res->completable()) {
7169: unless (grep(/^\Q$block\E$/,@blockers)) {
7170: push(@blockers,$block);
7171: }
7172: last;
7173: }
7174: }
1.1162 raeburn 7175: }
7176: }
7177: }
7178: }
7179: }
7180: }
7181: }
7182: }
7183: }
7184: return @blockers;
7185: }
7186:
7187: sub check_docs_block {
7188: my ($docsblock,$tocheck) =@_;
7189: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7190: return;
7191: }
7192: if (ref($docsblock->{'maps'}) eq 'HASH') {
7193: if ($tocheck->{'maps'}) {
7194: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7195: return 1;
7196: }
7197: }
7198: }
7199: if (ref($docsblock->{'resources'}) eq 'HASH') {
7200: if ($tocheck->{'resources'}) {
7201: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7202: return 1;
7203: }
7204: }
7205: }
7206: return;
7207: }
7208:
1.1133 foxr 7209: #
7210: # Removes the versino from a URI and
7211: # splits it in to its filename and path to the filename.
7212: # Seems like File::Basename could have done this more clearly.
7213: # Parameters:
7214: # $uri - input URI
7215: # Returns:
7216: # Two element list consisting of
7217: # $pathname - the URI up to and excluding the trailing /
7218: # $filename - The part of the URI following the last /
7219: # NOTE:
7220: # Another realization of this is simply:
7221: # use File::Basename;
7222: # ...
7223: # $uri = shift;
7224: # $filename = basename($uri);
7225: # $path = dirname($uri);
7226: # return ($filename, $path);
7227: #
7228: # The implementation below is probably faster however.
7229: #
1.710 albertel 7230: sub split_uri_for_cond {
7231: my $uri=&deversion(&declutter(shift));
7232: my @uriparts=split(/\//,$uri);
7233: my $filename=pop(@uriparts);
7234: my $pathname=join('/',@uriparts);
7235: return ($pathname,$filename);
7236: }
1.232 www 7237: # --------------------------------------------------- Is a resource on the map?
7238:
7239: sub is_on_map {
1.710 albertel 7240: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7241: #Trying to find the conditional for the file
1.620 albertel 7242: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7243: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7244: if ($match) {
1.289 bowersj2 7245: return (1,$1);
7246: } else {
1.434 www 7247: return (0,0);
1.289 bowersj2 7248: }
1.12 www 7249: }
7250:
1.427 www 7251: # --------------------------------------------------------- Get symb from alias
7252:
7253: sub get_symb_from_alias {
7254: my $symb=shift;
7255: my ($map,$resid,$url)=&decode_symb($symb);
7256: # Already is a symb
7257: if ($url) { return $symb; }
7258: # Must be an alias
7259: my $aliassymb='';
7260: my %bighash;
1.620 albertel 7261: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7262: &GDBM_READER(),0640)) {
7263: my $rid=$bighash{'mapalias_'.$symb};
7264: if ($rid) {
7265: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7266: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7267: $resid,$bighash{'src_'.$rid});
1.427 www 7268: }
7269: untie %bighash;
7270: }
7271: return $aliassymb;
7272: }
7273:
1.12 www 7274: # ----------------------------------------------------------------- Define Role
7275:
7276: sub definerole {
7277: if (allowed('mcr','/')) {
7278: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7279: foreach my $role (split(':',$sysrole)) {
7280: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7281: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7282: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7283: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7284: return "refused:s:$crole&$cqual";
7285: }
7286: }
1.191 harris41 7287: }
1.800 albertel 7288: foreach my $role (split(':',$domrole)) {
7289: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7290: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7291: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7292: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7293: return "refused:d:$crole&$cqual";
7294: }
7295: }
1.191 harris41 7296: }
1.800 albertel 7297: foreach my $role (split(':',$courole)) {
7298: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7299: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7300: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7301: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7302: return "refused:c:$crole&$cqual";
7303: }
7304: }
1.191 harris41 7305: }
1.620 albertel 7306: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7307: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7308: "rolesdef_$rolename=".
7309: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7310: return reply($command,$env{'user.home'});
1.12 www 7311: } else {
7312: return 'refused';
7313: }
1.105 harris41 7314: }
7315:
7316: # ---------------- Make a metadata query against the network of library servers
7317:
7318: sub metadata_query {
1.1237 raeburn 7319: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7320: my %rhash;
1.845 albertel 7321: my %libserv = &all_library();
1.244 matthew 7322: my @server_list = (defined($server_array) ? @$server_array
7323: : keys(%libserv) );
7324: for my $server (@server_list) {
1.1237 raeburn 7325: my $domains = '';
7326: if (ref($domains_hash) eq 'HASH') {
7327: $domains = $domains_hash->{$server};
7328: }
1.118 harris41 7329: unless ($custom or $customshow) {
1.1237 raeburn 7330: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7331: $rhash{$server}=$reply;
7332: }
7333: else {
7334: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7335: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7336: $server);
7337: $rhash{$server}=$reply;
7338: }
1.112 harris41 7339: }
1.118 harris41 7340: return \%rhash;
1.240 www 7341: }
7342:
7343: # ----------------------------------------- Send log queries and wait for reply
7344:
7345: sub log_query {
7346: my ($uname,$udom,$query,%filters)=@_;
7347: my $uhome=&homeserver($uname,$udom);
7348: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7349: my $uhost=&hostname($uhome);
1.800 albertel 7350: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7351: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7352: $uhome);
1.479 albertel 7353: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7354: return get_query_reply($queryid);
7355: }
7356:
1.818 raeburn 7357: # -------------------------- Update MySQL table for portfolio file
7358:
7359: sub update_portfolio_table {
1.821 raeburn 7360: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7361: if ($group ne '') {
7362: $file_name =~s /^\Q$group\E//;
7363: }
1.818 raeburn 7364: my $homeserver = &homeserver($uname,$udom);
7365: my $queryid=
1.821 raeburn 7366: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7367: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7368: my $reply = &get_query_reply($queryid);
7369: return $reply;
7370: }
7371:
1.899 raeburn 7372: # -------------------------- Update MySQL allusers table
7373:
7374: sub update_allusers_table {
7375: my ($uname,$udom,$names) = @_;
7376: my $homeserver = &homeserver($uname,$udom);
7377: my $queryid=
7378: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7379: 'lastname='.&escape($names->{'lastname'}).'%%'.
7380: 'firstname='.&escape($names->{'firstname'}).'%%'.
7381: 'middlename='.&escape($names->{'middlename'}).'%%'.
7382: 'generation='.&escape($names->{'generation'}).'%%'.
7383: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7384: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7385: return;
1.899 raeburn 7386: }
7387:
1.508 raeburn 7388: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7389:
7390: sub fetch_enrollment_query {
1.511 raeburn 7391: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7392: my $homeserver;
1.547 raeburn 7393: my $maxtries = 1;
1.508 raeburn 7394: if ($context eq 'automated') {
7395: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7396: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7397: } else {
7398: $homeserver = &homeserver($cnum,$dom);
7399: }
1.838 albertel 7400: my $host=&hostname($homeserver);
1.506 raeburn 7401: my $cmd = '';
1.1000 raeburn 7402: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7403: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7404: }
7405: $cmd =~ s/%%$//;
7406: $cmd = &escape($cmd);
7407: my $query = 'fetchenrollment';
1.620 albertel 7408: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7409: unless ($queryid=~/^\Q$host\E\_/) {
7410: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7411: return 'error: '.$queryid;
7412: }
1.506 raeburn 7413: my $reply = &get_query_reply($queryid);
1.547 raeburn 7414: my $tries = 1;
7415: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7416: $reply = &get_query_reply($queryid);
7417: $tries ++;
7418: }
1.526 raeburn 7419: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7420: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7421: } else {
1.901 albertel 7422: my @responses = split(/:/,$reply);
1.515 raeburn 7423: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7424: foreach my $line (@responses) {
7425: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7426: $$replyref{$key} = $value;
7427: }
7428: } else {
1.1117 foxr 7429: my $pathname = LONCAPA::tempdir();
1.800 albertel 7430: foreach my $line (@responses) {
7431: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7432: $$replyref{$key} = $value;
7433: if ($value > 0) {
1.800 albertel 7434: foreach my $item (@{$$affiliatesref{$key}}) {
7435: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7436: my $destname = $pathname.'/'.$filename;
7437: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7438: if ($xml_classlist =~ /^error/) {
7439: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7440: } else {
1.506 raeburn 7441: if ( open(FILE,">$destname") ) {
7442: print FILE &unescape($xml_classlist);
7443: close(FILE);
1.526 raeburn 7444: } else {
7445: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7446: }
7447: }
7448: }
7449: }
7450: }
7451: }
7452: return 'ok';
7453: }
7454: return 'error';
7455: }
7456:
1.242 www 7457: sub get_query_reply {
7458: my $queryid=shift;
1.1117 foxr 7459: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7460: my $reply='';
7461: for (1..100) {
7462: sleep 2;
7463: if (-e $replyfile.'.end') {
1.448 albertel 7464: if (open(my $fh,$replyfile)) {
1.904 albertel 7465: $reply = join('',<$fh>);
7466: close($fh);
1.240 www 7467: } else { return 'error: reply_file_error'; }
1.242 www 7468: return &unescape($reply);
7469: }
1.240 www 7470: }
1.242 www 7471: return 'timeout:'.$queryid;
1.240 www 7472: }
7473:
7474: sub courselog_query {
1.241 www 7475: #
7476: # possible filters:
7477: # url: url or symb
7478: # username
7479: # domain
7480: # action: view, submit, grade
7481: # start: timestamp
7482: # end: timestamp
7483: #
1.240 www 7484: my (%filters)=@_;
1.620 albertel 7485: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7486: if ($filters{'url'}) {
7487: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7488: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7489: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7490: }
1.620 albertel 7491: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7492: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7493: return &log_query($cname,$cdom,'courselog',%filters);
7494: }
7495:
7496: sub userlog_query {
1.858 raeburn 7497: #
7498: # possible filters:
7499: # action: log check role
7500: # start: timestamp
7501: # end: timestamp
7502: #
1.240 www 7503: my ($uname,$udom,%filters)=@_;
7504: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7505: }
7506:
1.506 raeburn 7507: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7508:
7509: sub auto_run {
1.508 raeburn 7510: my ($cnum,$cdom) = @_;
1.876 raeburn 7511: my $response = 0;
7512: my $settings;
7513: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7514: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7515: $settings = $domconfig{'autoenroll'};
7516: if ($settings->{'run'} eq '1') {
7517: $response = 1;
7518: }
7519: } else {
1.934 raeburn 7520: my $homeserver;
7521: if (&is_course($cdom,$cnum)) {
7522: $homeserver = &homeserver($cnum,$cdom);
7523: } else {
7524: $homeserver = &domain($cdom,'primary');
7525: }
7526: if ($homeserver ne 'no_host') {
7527: $response = &reply('autorun:'.$cdom,$homeserver);
7528: }
1.876 raeburn 7529: }
1.506 raeburn 7530: return $response;
7531: }
1.776 albertel 7532:
1.506 raeburn 7533: sub auto_get_sections {
1.508 raeburn 7534: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7535: my $homeserver;
7536: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7537: $homeserver = &homeserver($cnum,$cdom);
7538: }
7539: if (!defined($homeserver)) {
7540: if ($cdom =~ /^$match_domain$/) {
7541: $homeserver = &domain($cdom,'primary');
7542: }
7543: }
7544: my @secs;
7545: if (defined($homeserver)) {
7546: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7547: unless ($response eq 'refused') {
7548: @secs = split(/:/,$response);
7549: }
1.506 raeburn 7550: }
7551: return @secs;
7552: }
1.776 albertel 7553:
1.506 raeburn 7554: sub auto_new_course {
1.1099 raeburn 7555: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7556: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7557: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7558: return $response;
7559: }
1.776 albertel 7560:
1.506 raeburn 7561: sub auto_validate_courseID {
1.508 raeburn 7562: my ($cnum,$cdom,$inst_course_id) = @_;
7563: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7564: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7565: return $response;
7566: }
1.776 albertel 7567:
1.1007 raeburn 7568: sub auto_validate_instcode {
1.1020 raeburn 7569: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7570: my ($homeserver,$response);
7571: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7572: $homeserver = &homeserver($cnum,$cdom);
7573: }
7574: if (!defined($homeserver)) {
7575: if ($cdom =~ /^$match_domain$/) {
7576: $homeserver = &domain($cdom,'primary');
7577: }
7578: }
1.1065 raeburn 7579: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7580: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 7581: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7582: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7583: }
7584:
1.506 raeburn 7585: sub auto_create_password {
1.873 raeburn 7586: my ($cnum,$cdom,$authparam,$udom) = @_;
7587: my ($homeserver,$response);
1.506 raeburn 7588: my $create_passwd = 0;
7589: my $authchk = '';
1.873 raeburn 7590: if ($udom =~ /^$match_domain$/) {
7591: $homeserver = &domain($udom,'primary');
7592: }
7593: if ($homeserver eq '') {
7594: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7595: $homeserver = &homeserver($cnum,$cdom);
7596: }
7597: }
7598: if ($homeserver eq '') {
7599: $authchk = 'nodomain';
1.506 raeburn 7600: } else {
1.873 raeburn 7601: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7602: if ($response eq 'refused') {
7603: $authchk = 'refused';
7604: } else {
1.901 albertel 7605: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7606: }
1.506 raeburn 7607: }
7608: return ($authparam,$create_passwd,$authchk);
7609: }
7610:
1.706 raeburn 7611: sub auto_photo_permission {
7612: my ($cnum,$cdom,$students) = @_;
7613: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7614: my ($outcome,$perm_reqd,$conditions) =
7615: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7616: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7617: return (undef,undef);
7618: }
1.706 raeburn 7619: return ($outcome,$perm_reqd,$conditions);
7620: }
7621:
7622: sub auto_checkphotos {
7623: my ($uname,$udom,$pid) = @_;
7624: my $homeserver = &homeserver($uname,$udom);
7625: my ($result,$resulttype);
7626: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7627: &escape($uname).':'.&escape($pid),
7628: $homeserver));
1.709 albertel 7629: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7630: return (undef,undef);
7631: }
1.706 raeburn 7632: if ($outcome) {
7633: ($result,$resulttype) = split(/:/,$outcome);
7634: }
7635: return ($result,$resulttype);
7636: }
7637:
7638: sub auto_photochoice {
7639: my ($cnum,$cdom) = @_;
7640: my $homeserver = &homeserver($cnum,$cdom);
7641: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7642: &escape($cdom),
7643: $homeserver)));
1.709 albertel 7644: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7645: return (undef,undef);
7646: }
1.706 raeburn 7647: return ($update,$comment);
7648: }
7649:
7650: sub auto_photoupdate {
7651: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7652: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7653: my $host=&hostname($homeserver);
1.706 raeburn 7654: my $cmd = '';
7655: my $maxtries = 1;
1.800 albertel 7656: foreach my $affiliate (keys(%{$affiliatesref})) {
7657: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7658: }
7659: $cmd =~ s/%%$//;
7660: $cmd = &escape($cmd);
7661: my $query = 'institutionalphotos';
7662: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7663: unless ($queryid=~/^\Q$host\E\_/) {
7664: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7665: return 'error: '.$queryid;
7666: }
7667: my $reply = &get_query_reply($queryid);
7668: my $tries = 1;
7669: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7670: $reply = &get_query_reply($queryid);
7671: $tries ++;
7672: }
7673: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7674: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7675: } else {
7676: my @responses = split(/:/,$reply);
7677: my $outcome = shift(@responses);
7678: foreach my $item (@responses) {
7679: my ($key,$value) = split(/=/,$item);
7680: $$photo{$key} = $value;
7681: }
7682: return $outcome;
7683: }
7684: return 'error';
7685: }
7686:
1.521 raeburn 7687: sub auto_instcode_format {
1.793 albertel 7688: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7689: $cat_order) = @_;
1.521 raeburn 7690: my $courses = '';
1.772 raeburn 7691: my @homeservers;
1.521 raeburn 7692: if ($caller eq 'global') {
1.841 albertel 7693: my %servers = &get_servers($codedom,'library');
7694: foreach my $tryserver (keys(%servers)) {
7695: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7696: push(@homeservers,$tryserver);
7697: }
1.584 raeburn 7698: }
1.1022 raeburn 7699: } elsif ($caller eq 'requests') {
7700: if ($codedom =~ /^$match_domain$/) {
7701: my $chome = &domain($codedom,'primary');
7702: unless ($chome eq 'no_host') {
7703: push(@homeservers,$chome);
7704: }
7705: }
1.521 raeburn 7706: } else {
1.772 raeburn 7707: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7708: }
1.793 albertel 7709: foreach my $code (keys(%{$instcodes})) {
7710: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7711: }
7712: chop($courses);
1.772 raeburn 7713: my $ok_response = 0;
7714: my $response;
7715: while (@homeservers > 0 && $ok_response == 0) {
7716: my $server = shift(@homeservers);
7717: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7718: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7719: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7720: split(/:/,$response);
1.772 raeburn 7721: %{$codes} = (%{$codes},&str2hash($codes_str));
7722: push(@{$codetitles},&str2array($codetitles_str));
7723: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7724: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7725: $ok_response = 1;
7726: }
7727: }
7728: if ($ok_response) {
1.521 raeburn 7729: return 'ok';
1.772 raeburn 7730: } else {
7731: return $response;
1.521 raeburn 7732: }
7733: }
7734:
1.792 raeburn 7735: sub auto_instcode_defaults {
7736: my ($domain,$returnhash,$code_order) = @_;
7737: my @homeservers;
1.841 albertel 7738:
7739: my %servers = &get_servers($domain,'library');
7740: foreach my $tryserver (keys(%servers)) {
7741: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7742: push(@homeservers,$tryserver);
7743: }
1.792 raeburn 7744: }
1.841 albertel 7745:
1.792 raeburn 7746: my $response;
1.841 albertel 7747: foreach my $server (@homeservers) {
1.792 raeburn 7748: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7749: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7750:
7751: foreach my $pair (split(/\&/,$response)) {
7752: my ($name,$value)=split(/\=/,$pair);
7753: if ($name eq 'code_order') {
7754: @{$code_order} = split(/\&/,&unescape($value));
7755: } else {
7756: $returnhash->{&unescape($name)}=&unescape($value);
7757: }
7758: }
7759: return 'ok';
1.792 raeburn 7760: }
1.841 albertel 7761:
7762: return $response;
1.1003 raeburn 7763: }
7764:
7765: sub auto_possible_instcodes {
1.1007 raeburn 7766: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7767: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7768: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7769: return;
7770: }
1.1003 raeburn 7771: my (@homeservers,$uhome);
7772: if (defined(&domain($domain,'primary'))) {
7773: $uhome=&domain($domain,'primary');
7774: push(@homeservers,&domain($domain,'primary'));
7775: } else {
7776: my %servers = &get_servers($domain,'library');
7777: foreach my $tryserver (keys(%servers)) {
7778: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7779: push(@homeservers,$tryserver);
7780: }
7781: }
7782: }
7783: my $response;
7784: foreach my $server (@homeservers) {
7785: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7786: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7787: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7788: split(':',$response);
7789: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7790: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7791: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7792: my ($name,$value)=split('=',$item);
7793: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7794: }
7795: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7796: my ($name,$value)=split('=',$item);
7797: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7798: }
7799: return 'ok';
7800: }
7801: return $response;
7802: }
1.792 raeburn 7803:
1.1010 raeburn 7804: sub auto_courserequest_checks {
7805: my ($dom) = @_;
1.1020 raeburn 7806: my ($homeserver,%validations);
7807: if ($dom =~ /^$match_domain$/) {
7808: $homeserver = &domain($dom,'primary');
7809: }
7810: unless ($homeserver eq 'no_host') {
7811: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7812: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7813: my @items = split(/&/,$response);
7814: foreach my $item (@items) {
7815: my ($key,$value) = split('=',$item);
7816: $validations{&unescape($key)} = &thaw_unescape($value);
7817: }
7818: }
7819: }
1.1010 raeburn 7820: return %validations;
7821: }
7822:
1.1020 raeburn 7823: sub auto_courserequest_validation {
7824: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7825: my ($homeserver,$response);
7826: if ($dom =~ /^$match_domain$/) {
7827: $homeserver = &domain($dom,'primary');
7828: }
7829: unless ($homeserver eq 'no_host') {
1.1021 raeburn 7830:
1.1020 raeburn 7831: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7832: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 7833: ':'.&escape($instcode).':'.&escape($instseclist),
7834: $homeserver));
7835: }
7836: return $response;
7837: }
7838:
1.777 albertel 7839: sub auto_validate_class_sec {
1.918 raeburn 7840: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7841: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7842: my $ownerlist;
7843: if (ref($owners) eq 'ARRAY') {
7844: $ownerlist = join(',',@{$owners});
7845: } else {
7846: $ownerlist = $owners;
7847: }
1.773 raeburn 7848: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7849: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7850: return $response;
7851: }
7852:
1.679 raeburn 7853: # ------------------------------------------------------- Course Group routines
7854:
7855: sub get_coursegroups {
1.809 raeburn 7856: my ($cdom,$cnum,$group,$namespace) = @_;
7857: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7858: }
7859:
1.679 raeburn 7860: sub modify_coursegroup {
7861: my ($cdom,$cnum,$groupsettings) = @_;
7862: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7863: }
7864:
1.809 raeburn 7865: sub toggle_coursegroup_status {
7866: my ($cdom,$cnum,$group,$action) = @_;
7867: my ($from_namespace,$to_namespace);
7868: if ($action eq 'delete') {
7869: $from_namespace = 'coursegroups';
7870: $to_namespace = 'deleted_groups';
7871: } else {
7872: $from_namespace = 'deleted_groups';
7873: $to_namespace = 'coursegroups';
7874: }
7875: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7876: if (my $tmp = &error(%curr_group)) {
7877: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7878: return ('read error',$tmp);
7879: } else {
7880: my %savedsettings = %curr_group;
1.809 raeburn 7881: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7882: my $deloutcome;
7883: if ($result eq 'ok') {
1.809 raeburn 7884: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7885: } else {
7886: return ('write error',$result);
7887: }
7888: if ($deloutcome eq 'ok') {
7889: return 'ok';
7890: } else {
7891: return ('delete error',$deloutcome);
7892: }
7893: }
7894: }
7895:
1.679 raeburn 7896: sub modify_group_roles {
1.957 raeburn 7897: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7898: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7899: my $role = 'gr/'.&escape($userprivs);
7900: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7901: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7902: if ($result eq 'ok') {
7903: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7904: }
1.679 raeburn 7905: return $result;
7906: }
7907:
7908: sub modify_coursegroup_membership {
7909: my ($cdom,$cnum,$membership) = @_;
7910: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7911: return $result;
7912: }
7913:
1.682 raeburn 7914: sub get_active_groups {
7915: my ($udom,$uname,$cdom,$cnum) = @_;
7916: my $now = time;
7917: my %groups = ();
7918: foreach my $key (keys(%env)) {
1.811 albertel 7919: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7920: my ($start,$end) = split(/\./,$env{$key});
7921: if (($end!=0) && ($end<$now)) { next; }
7922: if (($start!=0) && ($start>$now)) { next; }
7923: if ($1 eq $cdom && $2 eq $cnum) {
7924: $groups{$3} = $env{$key} ;
7925: }
7926: }
7927: }
7928: return %groups;
7929: }
7930:
1.683 raeburn 7931: sub get_group_membership {
7932: my ($cdom,$cnum,$group) = @_;
7933: return(&dump('groupmembership',$cdom,$cnum,$group));
7934: }
7935:
7936: sub get_users_groups {
7937: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 7938: my @usersgroups;
1.683 raeburn 7939: my $cachetime=1800;
7940:
7941: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 7942: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7943: if (defined($cached)) {
1.734 albertel 7944: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 7945: } else {
7946: $grouplist = '';
1.816 raeburn 7947: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 7948: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 7949: my $access_end = $env{'course.'.$courseid.
7950: '.default_enrollment_end_date'};
7951: my $now = time;
7952: foreach my $key (keys(%roleshash)) {
7953: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7954: my $group = $1;
7955: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7956: my $start = $2;
7957: my $end = $1;
7958: if ($start == -1) { next; } # deleted from group
7959: if (($start!=0) && ($start>$now)) { next; }
7960: if (($end!=0) && ($end<$now)) {
7961: if ($access_end && $access_end < $now) {
7962: if ($access_end - $end < 86400) {
7963: push(@usersgroups,$group);
1.733 raeburn 7964: }
7965: }
1.817 raeburn 7966: next;
1.733 raeburn 7967: }
1.817 raeburn 7968: push(@usersgroups,$group);
1.683 raeburn 7969: }
7970: }
7971: }
1.817 raeburn 7972: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7973: $grouplist = join(':',@usersgroups);
7974: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 7975: }
1.733 raeburn 7976: return @usersgroups;
1.683 raeburn 7977: }
7978:
7979: sub devalidate_getgroups_cache {
7980: my ($udom,$uname,$cdom,$cnum)=@_;
7981: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 7982:
1.683 raeburn 7983: my $hashid="$udom:$uname:$courseid";
7984: &devalidate_cache_new('getgroups',$hashid);
7985: }
7986:
1.12 www 7987: # ------------------------------------------------------------------ Plain Text
7988:
7989: sub plaintext {
1.988 raeburn 7990: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 7991: if ($short =~ m{^cr/}) {
1.758 albertel 7992: return (split('/',$short))[-1];
7993: }
1.742 raeburn 7994: if (!defined($cid)) {
7995: $cid = $env{'request.course.id'};
7996: }
7997: my %rolenames = (
1.1008 raeburn 7998: Course => 'std',
7999: Community => 'alt1',
1.742 raeburn 8000: );
1.1037 raeburn 8001: if ($cid ne '') {
8002: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8003: unless ($forcedefault) {
8004: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8005: &Apache::lonlocal::mt_escape(\$roletext);
8006: return &Apache::lonlocal::mt($roletext);
8007: }
8008: }
8009: }
8010: if ((defined($type)) && (defined($rolenames{$type})) &&
8011: (defined($rolenames{$type})) &&
8012: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8013: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8014: } elsif ($cid ne '') {
8015: my $crstype = $env{'course.'.$cid.'.type'};
8016: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8017: (defined($prp{$short}{$rolenames{$crstype}}))) {
8018: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8019: }
1.742 raeburn 8020: }
1.1037 raeburn 8021: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8022: }
8023:
8024: # ----------------------------------------------------------------- Assign Role
8025:
8026: sub assignrole {
1.957 raeburn 8027: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8028: $context)=@_;
1.21 www 8029: my $mrole;
8030: if ($role =~ /^cr\//) {
1.393 www 8031: my $cwosec=$url;
1.811 albertel 8032: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8033: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8034: my $refused = 1;
8035: if ($context eq 'requestcourses') {
8036: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8037: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8038: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8039: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8040: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8041: if ($crsenv{'internal.courseowner'} eq
8042: $env{'user.name'}.':'.$env{'user.domain'}) {
8043: $refused = '';
8044: }
8045: }
8046: }
8047: }
8048: }
8049: if ($refused) {
8050: &logthis('Refused custom assignrole: '.
8051: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8052: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8053: return 'refused';
8054: }
1.104 www 8055: }
1.21 www 8056: $mrole='cr';
1.678 raeburn 8057: } elsif ($role =~ /^gr\//) {
8058: my $cwogrp=$url;
1.811 albertel 8059: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8060: unless (&allowed('mdg',$cwogrp)) {
8061: &logthis('Refused group assignrole: '.
8062: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8063: $env{'user.name'}.' at '.$env{'user.domain'});
8064: return 'refused';
8065: }
8066: $mrole='gr';
1.21 www 8067: } else {
1.82 www 8068: my $cwosec=$url;
1.811 albertel 8069: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8070: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8071: my $refused;
8072: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8073: if (!(&allowed('c'.$role,$url))) {
8074: $refused = 1;
8075: }
8076: } else {
8077: $refused = 1;
8078: }
1.947 raeburn 8079: if ($refused) {
1.1045 raeburn 8080: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8081: if (!$selfenroll && $context eq 'course') {
8082: my %crsenv;
8083: if ($role eq 'cc' || $role eq 'co') {
8084: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8085: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8086: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8087: if ($crsenv{'internal.courseowner'} eq
8088: $env{'user.name'}.':'.$env{'user.domain'}) {
8089: $refused = '';
8090: }
8091: }
8092: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8093: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8094: if ($crsenv{'internal.courseowner'} eq
8095: $env{'user.name'}.':'.$env{'user.domain'}) {
8096: $refused = '';
8097: }
8098: }
8099: }
8100: }
8101: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8102: $refused = '';
1.1017 raeburn 8103: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8104: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8105: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8106: my $wrongcc;
8107: if ($cnum =~ /^$match_community$/) {
8108: $wrongcc = 1 if ($role eq 'cc');
8109: } else {
8110: $wrongcc = 1 if ($role eq 'co');
8111: }
8112: unless ($wrongcc) {
8113: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8114: if ($crsenv{'internal.courseowner'} eq
8115: $env{'user.name'}.':'.$env{'user.domain'}) {
8116: $refused = '';
8117: }
1.1017 raeburn 8118: }
8119: }
1.1183 raeburn 8120: } elsif ($context eq 'requestauthor') {
8121: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8122: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8123: if ($env{'environment.requestauthor'} eq 'automatic') {
8124: $refused = '';
8125: } else {
8126: my %domdefaults = &get_domain_defaults($udom);
8127: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8128: my $checkbystatus;
8129: if ($env{'user.adv'}) {
8130: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8131: if ($disposition eq 'automatic') {
8132: $refused = '';
8133: } elsif ($disposition eq '') {
8134: $checkbystatus = 1;
8135: }
8136: } else {
8137: $checkbystatus = 1;
8138: }
8139: if ($checkbystatus) {
8140: if ($env{'environment.inststatus'}) {
8141: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8142: foreach my $type (@inststatuses) {
8143: if (($type ne '') &&
8144: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8145: $refused = '';
8146: }
8147: }
8148: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8149: $refused = '';
8150: }
8151: }
8152: }
8153: }
8154: }
1.1017 raeburn 8155: }
8156: if ($refused) {
1.947 raeburn 8157: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8158: ' '.$role.' '.$end.' '.$start.' by '.
8159: $env{'user.name'}.' at '.$env{'user.domain'});
8160: return 'refused';
8161: }
1.932 raeburn 8162: }
1.1131 raeburn 8163: } elsif ($role eq 'au') {
8164: if ($url ne '/'.$udom.'/') {
8165: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8166: ' to assign author role for '.$uname.':'.$udom.
8167: ' in domain: '.$url.' refused (wrong domain).');
8168: return 'refused';
8169: }
1.104 www 8170: }
1.21 www 8171: $mrole=$role;
8172: }
1.620 albertel 8173: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8174: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8175: if ($end) { $command.='_'.$end; }
1.21 www 8176: if ($start) {
8177: if ($end) {
1.81 www 8178: $command.='_'.$start;
1.21 www 8179: } else {
1.81 www 8180: $command.='_0_'.$start;
1.21 www 8181: }
8182: }
1.739 raeburn 8183: my $origstart = $start;
8184: my $origend = $end;
1.957 raeburn 8185: my $delflag;
1.357 www 8186: # actually delete
8187: if ($deleteflag) {
1.373 www 8188: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8189: # modify command to delete the role
1.620 albertel 8190: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8191: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8192: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8193: # set start and finish to negative values for userrolelog
8194: $start=-1;
8195: $end=-1;
1.957 raeburn 8196: $delflag = 1;
1.357 www 8197: }
8198: }
8199: # send command
1.349 www 8200: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8201: # log new user role if status is ok
1.349 www 8202: if ($answer eq 'ok') {
1.663 raeburn 8203: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8204: if (($role eq 'cc') || ($role eq 'in') ||
8205: ($role eq 'ep') || ($role eq 'ad') ||
8206: ($role eq 'ta') || ($role eq 'st') ||
8207: ($role=~/^cr/) || ($role eq 'gr') ||
8208: ($role eq 'co')) {
1.1200 raeburn 8209: # for course roles, perform group memberships changes triggered by role change.
8210: unless ($role =~ /^gr/) {
8211: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8212: $origstart,$selfenroll,$context);
8213: }
1.1184 raeburn 8214: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8215: $selfenroll,$context);
8216: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8217: ($role eq 'au') || ($role eq 'dc')) {
8218: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8219: $context);
8220: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8221: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8222: $context);
8223: }
1.1053 raeburn 8224: if ($role eq 'cc') {
8225: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8226: }
1.349 www 8227: }
8228: return $answer;
1.169 harris41 8229: }
8230:
1.1053 raeburn 8231: sub autoupdate_coowners {
8232: my ($url,$end,$start,$uname,$udom) = @_;
8233: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8234: if (($cdom ne '') && ($cnum ne '')) {
8235: my $now = time;
8236: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8237: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8238: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8239: my $instcode = $coursehash{'internal.coursecode'};
8240: if ($instcode ne '') {
1.1056 raeburn 8241: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8242: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8243: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8244: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8245: if ($result eq 'valid') {
8246: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8247: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8248: push(@newcoowners,$coowner);
8249: }
8250: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8251: push(@newcoowners,$uname.':'.$udom);
8252: }
8253: @newcoowners = sort(@newcoowners);
8254: } else {
8255: push(@newcoowners,$uname.':'.$udom);
8256: }
8257: } else {
8258: if ($coursehash{'internal.co-owners'}) {
8259: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8260: unless ($coowner eq $uname.':'.$udom) {
8261: push(@newcoowners,$coowner);
8262: }
8263: }
8264: unless (@newcoowners > 0) {
8265: $delcoowners = 1;
8266: $coowners = '';
8267: }
8268: }
8269: }
8270: if (@newcoowners || $delcoowners) {
8271: &store_coowners($cdom,$cnum,$coursehash{'home'},
8272: $delcoowners,@newcoowners);
8273: }
8274: }
8275: }
8276: }
8277: }
8278: }
8279: }
8280:
8281: sub store_coowners {
8282: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8283: my $cid = $cdom.'_'.$cnum;
8284: my ($coowners,$delresult,$putresult);
8285: if (@newcoowners) {
8286: $coowners = join(',',@newcoowners);
8287: my %coownershash = (
8288: 'internal.co-owners' => $coowners,
8289: );
8290: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8291: if ($putresult eq 'ok') {
8292: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8293: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8294: }
8295: }
8296: }
8297: if ($delcoowners) {
8298: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8299: if ($delresult eq 'ok') {
8300: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8301: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8302: }
8303: }
8304: }
8305: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8306: my %crsinfo =
8307: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8308: if (ref($crsinfo{$cid}) eq 'HASH') {
8309: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8310: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8311: }
8312: }
8313: }
8314:
1.169 harris41 8315: # -------------------------------------------------- Modify user authentication
1.197 www 8316: # Overrides without validation
8317:
1.169 harris41 8318: sub modifyuserauth {
8319: my ($udom,$uname,$umode,$upass)=@_;
8320: my $uhome=&homeserver($uname,$udom);
1.197 www 8321: unless (&allowed('mau',$udom)) { return 'refused'; }
8322: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8323: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8324: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8325: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8326: &escape($upass),$uhome);
1.620 albertel 8327: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8328: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8329: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8330: &log($udom,,$uname,$uhome,
1.620 albertel 8331: 'Authentication changed by '.$env{'user.domain'}.', '.
8332: $env{'user.name'}.', '.$umode.
1.197 www 8333: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8334: unless ($reply eq 'ok') {
1.197 www 8335: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8336: return 'error: '.$reply;
8337: }
1.170 harris41 8338: return 'ok';
1.80 www 8339: }
8340:
1.81 www 8341: # --------------------------------------------------------------- Modify a user
1.80 www 8342:
1.81 www 8343: sub modifyuser {
1.206 matthew 8344: my ($udom, $uname, $uid,
8345: $umode, $upass, $first,
8346: $middle, $last, $gene,
1.1058 raeburn 8347: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8348: $udom= &LONCAPA::clean_domain($udom);
8349: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8350: my $showcandelete = 'none';
8351: if (ref($candelete) eq 'ARRAY') {
8352: if (@{$candelete} > 0) {
8353: $showcandelete = join(', ',@{$candelete});
8354: }
8355: }
1.81 www 8356: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8357: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8358: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8359: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8360: ' desiredhome not specified').
1.620 albertel 8361: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8362: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8363: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8364: my $newuser;
8365: if ($uhome eq 'no_host') {
8366: $newuser = 1;
8367: }
1.80 www 8368: # ----------------------------------------------------------------- Create User
1.406 albertel 8369: if (($uhome eq 'no_host') &&
8370: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8371: my $unhome='';
1.844 albertel 8372: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8373: $unhome = $desiredhome;
1.620 albertel 8374: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8375: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8376: } else { # load balancing routine for determining $unhome
1.81 www 8377: my $loadm=10000000;
1.841 albertel 8378: my %servers = &get_servers($udom,'library');
8379: foreach my $tryserver (keys(%servers)) {
8380: my $answer=reply('load',$tryserver);
8381: if (($answer=~/\d+/) && ($answer<$loadm)) {
8382: $loadm=$answer;
8383: $unhome=$tryserver;
8384: }
1.80 www 8385: }
8386: }
8387: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8388: return 'error: unable to find a home server for '.$uname.
8389: ' in domain '.$udom;
1.80 www 8390: }
8391: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8392: &escape($upass),$unhome);
8393: unless ($reply eq 'ok') {
8394: return 'error: '.$reply;
8395: }
1.230 stredwic 8396: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8397: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8398: return 'error: unable verify users home machine.';
1.80 www 8399: }
1.209 matthew 8400: } # End of creation of new user
1.80 www 8401: # ---------------------------------------------------------------------- Add ID
8402: if ($uid) {
8403: $uid=~tr/A-Z/a-z/;
8404: my %uidhash=&idrget($udom,$uname);
1.196 www 8405: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8406: && (!$forceid)) {
1.80 www 8407: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8408: return 'error: user id "'.$uid.'" does not match '.
8409: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8410: }
8411: } else {
8412: &idput($udom,($uname => $uid));
8413: }
8414: }
8415: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8416: my @tmp=&get('environment',
1.899 raeburn 8417: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8418: 'permanentemail','inststatus'],
1.134 albertel 8419: $udom,$uname);
1.1075 raeburn 8420: my (%names,%oldnames);
1.313 matthew 8421: if ($tmp[0] =~ m/^error:.*/) {
8422: %names=();
8423: } else {
8424: %names = @tmp;
1.1075 raeburn 8425: %oldnames = %names;
1.313 matthew 8426: }
1.388 www 8427: #
1.1058 raeburn 8428: # If name, email and/or uid are blank (e.g., because an uploaded file
8429: # of users did not contain them), do not overwrite existing values
8430: # unless field is in $candelete array ref.
8431: #
8432:
8433: my @fields = ('firstname','middlename','lastname','generation',
8434: 'permanentemail','id');
8435: my %newvalues;
8436: if (ref($candelete) eq 'ARRAY') {
8437: foreach my $field (@fields) {
8438: if (grep(/^\Q$field\E$/,@{$candelete})) {
8439: if ($field eq 'firstname') {
8440: $names{$field} = $first;
8441: } elsif ($field eq 'middlename') {
8442: $names{$field} = $middle;
8443: } elsif ($field eq 'lastname') {
8444: $names{$field} = $last;
8445: } elsif ($field eq 'generation') {
8446: $names{$field} = $gene;
8447: } elsif ($field eq 'permanentemail') {
8448: $names{$field} = $email;
8449: } elsif ($field eq 'id') {
8450: $names{$field} = $uid;
8451: }
8452: }
8453: }
8454: }
1.388 www 8455: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8456: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8457: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8458: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8459: if ($email) {
8460: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8461: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8462: }
1.899 raeburn 8463: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8464: if (defined($inststatus)) {
8465: $names{'inststatus'} = '';
8466: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8467: if (ref($usertypes) eq 'HASH') {
8468: my @okstatuses;
8469: foreach my $item (split(/:/,$inststatus)) {
8470: if (defined($usertypes->{$item})) {
8471: push(@okstatuses,$item);
8472: }
8473: }
8474: if (@okstatuses) {
8475: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8476: }
8477: }
8478: }
1.1075 raeburn 8479: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8480: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8481: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8482: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8483: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8484: } else {
8485: $logmsg .= ' during self creation';
8486: }
1.1075 raeburn 8487: my $changed;
8488: if ($newuser) {
8489: $changed = 1;
8490: } else {
8491: foreach my $field (@fields) {
8492: if ($names{$field} ne $oldnames{$field}) {
8493: $changed = 1;
8494: last;
8495: }
8496: }
8497: }
8498: unless ($changed) {
8499: $logmsg = 'No changes in user information needed for: '.$logmsg;
8500: &logthis($logmsg);
8501: return 'ok';
8502: }
8503: my $reply = &put('environment', \%names, $udom,$uname);
8504: if ($reply ne 'ok') {
8505: return 'error: '.$reply;
8506: }
1.1087 raeburn 8507: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8508: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8509: }
1.1075 raeburn 8510: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8511: &devalidate_cache_new('namescache',$uname.':'.$udom);
8512: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8513: &logthis($logmsg);
1.134 albertel 8514: return 'ok';
1.80 www 8515: }
8516:
1.81 www 8517: # -------------------------------------------------------------- Modify student
1.80 www 8518:
1.81 www 8519: sub modifystudent {
8520: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8521: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216 raeburn 8522: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8523: if (!$cid) {
1.620 albertel 8524: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8525: return 'not_in_class';
8526: }
1.80 www 8527: }
8528: # --------------------------------------------------------------- Make the user
1.81 www 8529: my $reply=&modifyuser
1.209 matthew 8530: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8531: $desiredhome,$email,$inststatus);
1.80 www 8532: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8533: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 8534: # student's environment
1.297 matthew 8535: $uid = undef if (!$forceid);
1.455 albertel 8536: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 8537: $gene,$usec,$end,$start,$type,$locktype,
8538: $cid,$selfenroll,$context,$credits);
1.297 matthew 8539: return $reply;
8540: }
8541:
8542: sub modify_student_enrollment {
1.1216 raeburn 8543: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8544: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8545: my ($cdom,$cnum,$chome);
8546: if (!$cid) {
1.620 albertel 8547: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8548: return 'not_in_class';
8549: }
1.620 albertel 8550: $cdom=$env{'course.'.$cid.'.domain'};
8551: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8552: } else {
8553: ($cdom,$cnum)=split(/_/,$cid);
8554: }
1.620 albertel 8555: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8556: if (!$chome) {
1.457 raeburn 8557: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8558: }
1.455 albertel 8559: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8560: # Make sure the user exists
1.81 www 8561: my $uhome=&homeserver($uname,$udom);
8562: if (($uhome eq '') || ($uhome eq 'no_host')) {
8563: return 'error: no such user';
8564: }
1.297 matthew 8565: # Get student data if we were not given enough information
8566: if (!defined($first) || $first eq '' ||
8567: !defined($last) || $last eq '' ||
8568: !defined($uid) || $uid eq '' ||
8569: !defined($middle) || $middle eq '' ||
8570: !defined($gene) || $gene eq '') {
1.294 matthew 8571: # They did not supply us with enough data to enroll the student, so
8572: # we need to pick up more information.
1.297 matthew 8573: my %tmp = &get('environment',
1.294 matthew 8574: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8575: ,$udom,$uname);
8576:
1.800 albertel 8577: #foreach my $key (keys(%tmp)) {
8578: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8579: #}
1.294 matthew 8580: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8581: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8582: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8583: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8584: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8585: }
1.556 albertel 8586: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8587: my $user = "$uname:$udom";
8588: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8589: my $reply=cput('classlist',
1.1148 raeburn 8590: {$user =>
1.1216 raeburn 8591: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8592: $cdom,$cnum);
1.1148 raeburn 8593: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8594: &devalidate_getsection_cache($udom,$uname,$cid);
8595: } else {
1.81 www 8596: return 'error: '.$reply;
8597: }
1.297 matthew 8598: # Add student role to user
1.83 www 8599: my $uurl='/'.$cid;
1.81 www 8600: $uurl=~s/\_/\//g;
8601: if ($usec) {
8602: $uurl.='/'.$usec;
8603: }
1.1148 raeburn 8604: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8605: $selfenroll,$context);
8606: if ($result ne 'ok') {
8607: if ($old_entry{$user} ne '') {
8608: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8609: } else {
8610: $reply = &del('classlist',[$user],$cdom,$cnum);
8611: }
8612: }
8613: return $result;
1.21 www 8614: }
8615:
1.556 albertel 8616: sub format_name {
8617: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8618: my $name;
8619: if ($first ne 'lastname') {
8620: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8621: } else {
8622: if ($lastname=~/\S/) {
8623: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8624: $name=~s/\s+,/,/;
8625: } else {
8626: $name.= $firstname.' '.$middlename.' '.$generation;
8627: }
8628: }
8629: $name=~s/^\s+//;
8630: $name=~s/\s+$//;
8631: $name=~s/\s+/ /g;
8632: return $name;
8633: }
8634:
1.84 www 8635: # ------------------------------------------------- Write to course preferences
8636:
8637: sub writecoursepref {
8638: my ($courseid,%prefs)=@_;
8639: $courseid=~s/^\///;
8640: $courseid=~s/\_/\//g;
8641: my ($cdomain,$cnum)=split(/\//,$courseid);
8642: my $chome=homeserver($cnum,$cdomain);
8643: if (($chome eq '') || ($chome eq 'no_host')) {
8644: return 'error: no such course';
8645: }
8646: my $cstring='';
1.800 albertel 8647: foreach my $pref (keys(%prefs)) {
8648: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8649: }
1.84 www 8650: $cstring=~s/\&$//;
8651: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8652: }
8653:
8654: # ---------------------------------------------------------- Make/modify course
8655:
8656: sub createcourse {
1.741 raeburn 8657: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8658: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8659: $url=&declutter($url);
8660: my $cid='';
1.1028 raeburn 8661: if ($context eq 'requestcourses') {
8662: my $can_create = 0;
8663: my ($ownername,$ownerdom) = split(':',$course_owner);
8664: if ($udom eq $ownerdom) {
8665: if (&usertools_access($ownername,$ownerdom,$category,undef,
8666: $context)) {
8667: $can_create = 1;
8668: }
8669: } else {
8670: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8671: $category);
8672: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8673: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8674: if (@curr > 0) {
8675: my @options = qw(approval validate autolimit);
8676: my $optregex = join('|',@options);
8677: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8678: $can_create = 1;
8679: }
8680: }
8681: }
8682: }
8683: if ($can_create) {
8684: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8685: unless (&allowed('ccc',$udom)) {
8686: return 'refused';
8687: }
1.1017 raeburn 8688: }
8689: } else {
8690: return 'refused';
8691: }
1.1028 raeburn 8692: } elsif (!&allowed('ccc',$udom)) {
8693: return 'refused';
1.84 www 8694: }
1.1011 raeburn 8695: # --------------------------------------------------------------- Get Unique ID
8696: my $uname;
8697: if ($cnum =~ /^$match_courseid$/) {
8698: my $chome=&homeserver($cnum,$udom,'true');
8699: if (($chome eq '') || ($chome eq 'no_host')) {
8700: $uname = $cnum;
8701: } else {
1.1038 raeburn 8702: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8703: }
8704: } else {
1.1038 raeburn 8705: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8706: }
8707: return $uname if ($uname =~ /^error/);
8708: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8709: if (!defined($course_server)) {
8710: if (defined(&domain($udom,'primary'))) {
8711: $course_server = &domain($udom,'primary');
8712: } else {
8713: $course_server = $env{'user.home'};
8714: }
8715: }
8716: my %host_servers =
8717: &Apache::lonnet::get_servers($udom,'library');
8718: unless ($host_servers{$course_server}) {
8719: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8720: }
1.84 www 8721: # ------------------------------------------------------------- Make the course
8722: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8723: $course_server);
1.84 www 8724: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8725: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8726: if (($uhome eq '') || ($uhome eq 'no_host')) {
8727: return 'error: no such course';
8728: }
1.271 www 8729: # ----------------------------------------------------------------- Course made
1.516 raeburn 8730: # log existence
1.1029 raeburn 8731: my $now = time;
1.918 raeburn 8732: my $newcourse = {
8733: $udom.'_'.$uname => {
1.921 raeburn 8734: description => $description,
8735: inst_code => $inst_code,
8736: owner => $course_owner,
8737: type => $crstype,
1.1029 raeburn 8738: creator => $env{'user.name'}.':'.
8739: $env{'user.domain'},
8740: created => $now,
8741: context => $context,
1.918 raeburn 8742: },
8743: };
1.921 raeburn 8744: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8745: # set toplevel url
1.271 www 8746: my $topurl=$url;
8747: unless ($nonstandard) {
8748: # ------------------------------------------ For standard courses, make top url
8749: my $mapurl=&clutter($url);
1.278 www 8750: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8751: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8752: <map>
8753: <resource id="1" type="start"></resource>
8754: <resource id="2" src="$mapurl"></resource>
8755: <resource id="3" type="finish"></resource>
8756: <link index="1" from="1" to="2"></link>
8757: <link index="2" from="2" to="3"></link>
8758: </map>
8759: ENDINITMAP
8760: $topurl=&declutter(
1.638 albertel 8761: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8762: );
8763: }
8764: # ----------------------------------------------------------- Write preferences
1.84 www 8765: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8766: ('description' => $description,
8767: 'url' => $topurl,
8768: 'internal.creator' => $env{'user.name'}.':'.
8769: $env{'user.domain'},
8770: 'internal.created' => $now,
8771: 'internal.creationcontext' => $context)
8772: );
1.84 www 8773: return '/'.$udom.'/'.$uname;
8774: }
8775:
1.1011 raeburn 8776: # ------------------------------------------------------------------- Create ID
8777: sub generate_coursenum {
1.1038 raeburn 8778: my ($udom,$crstype) = @_;
1.1011 raeburn 8779: my $domdesc = &domain($udom);
8780: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8781: my $first;
8782: if ($crstype eq 'Community') {
8783: $first = '0';
8784: } else {
8785: $first = int(1+rand(9));
8786: }
8787: my $uname=$first.
1.1011 raeburn 8788: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8789: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8790: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8791: # ----------------------------------------------- Make sure that does not exist
8792: my $uhome=&homeserver($uname,$udom,'true');
8793: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8794: if ($crstype eq 'Community') {
8795: $first = '0';
8796: } else {
8797: $first = int(1+rand(9));
8798: }
8799: $uname=$first.
1.1011 raeburn 8800: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8801: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8802: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8803: $uhome=&homeserver($uname,$udom,'true');
8804: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8805: return 'error: unable to generate unique course-ID';
8806: }
8807: }
8808: return $uname;
8809: }
8810:
1.813 albertel 8811: sub is_course {
1.1167 droeschl 8812: my ($cdom, $cnum) = scalar(@_) == 1 ?
8813: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8814:
8815: return unless $cdom and $cnum;
8816:
8817: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8818: '.');
8819:
1.1219 raeburn 8820: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8821: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8822: }
8823:
1.1015 raeburn 8824: sub store_userdata {
8825: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8826: my $result;
1.1016 raeburn 8827: if ($datakey ne '') {
1.1013 raeburn 8828: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8829: if ($udom eq '' || $uname eq '') {
8830: $udom = $env{'user.domain'};
8831: $uname = $env{'user.name'};
8832: }
8833: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8834: if (($uhome eq '') || ($uhome eq 'no_host')) {
8835: $result = 'error: no_host';
8836: } else {
8837: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8838: $storehash->{'host'} = $perlvar{'lonHostID'};
8839:
8840: my $namevalue='';
8841: foreach my $key (keys(%{$storehash})) {
8842: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8843: }
8844: $namevalue=~s/\&$//;
1.1224 raeburn 8845: unless ($namespace eq 'courserequests') {
8846: $datakey = &escape($datakey);
8847: }
1.1105 raeburn 8848: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8849: $namevalue,$uhome);
1.1013 raeburn 8850: }
8851: } else {
8852: $result = 'error: data to store was not a hash reference';
8853: }
8854: } else {
8855: $result= 'error: invalid requestkey';
8856: }
8857: return $result;
8858: }
8859:
1.21 www 8860: # ---------------------------------------------------------- Assign Custom Role
8861:
8862: sub assigncustomrole {
1.957 raeburn 8863: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8864: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8865: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8866: }
8867:
8868: # ----------------------------------------------------------------- Revoke Role
8869:
8870: sub revokerole {
1.957 raeburn 8871: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8872: my $now=time;
1.965 raeburn 8873: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8874: }
8875:
8876: # ---------------------------------------------------------- Revoke Custom Role
8877:
8878: sub revokecustomrole {
1.957 raeburn 8879: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8880: my $now=time;
1.357 www 8881: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8882: $deleteflag,$selfenroll,$context);
1.17 www 8883: }
8884:
1.533 banghart 8885: # ------------------------------------------------------------ Disk usage
1.535 albertel 8886: sub diskusage {
1.955 raeburn 8887: my ($udom,$uname,$directorypath,$getpropath)=@_;
8888: $directorypath =~ s/\/$//;
8889: my $listing=&reply('du2:'.&escape($directorypath).':'
8890: .&escape($getpropath).':'.&escape($uname).':'
8891: .&escape($udom),homeserver($uname,$udom));
8892: if ($listing eq 'unknown_cmd') {
8893: if ($getpropath) {
8894: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8895: }
8896: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8897: }
1.514 albertel 8898: return $listing;
1.512 banghart 8899: }
8900:
1.566 banghart 8901: sub is_locked {
1.1096 raeburn 8902: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8903: my @check;
8904: my $is_locked;
1.1093 raeburn 8905: push (@check,$file_name);
1.613 albertel 8906: my %locked = &get('file_permissions',\@check,
1.620 albertel 8907: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8908: my ($tmp)=keys(%locked);
8909: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8910:
1.566 banghart 8911: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8912: $is_locked = 'false';
8913: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8914: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8915: $is_locked = 'true';
1.1096 raeburn 8916: if (ref($which) eq 'ARRAY') {
8917: push(@{$which},$entry);
8918: } else {
8919: last;
8920: }
1.745 raeburn 8921: }
8922: }
1.566 banghart 8923: } else {
8924: $is_locked = 'false';
8925: }
1.1093 raeburn 8926: return $is_locked;
1.566 banghart 8927: }
8928:
1.759 albertel 8929: sub declutter_portfile {
8930: my ($file) = @_;
1.833 albertel 8931: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 8932: return $file;
8933: }
8934:
1.559 banghart 8935: # ------------------------------------------------------------- Mark as Read Only
8936:
8937: sub mark_as_readonly {
8938: my ($domain,$user,$files,$what) = @_;
1.613 albertel 8939: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8940: my ($tmp)=keys(%current_permissions);
8941: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 8942: foreach my $file (@{$files}) {
1.759 albertel 8943: $file = &declutter_portfile($file);
1.561 banghart 8944: push(@{$current_permissions{$file}},$what);
1.559 banghart 8945: }
1.613 albertel 8946: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8947: return;
8948: }
8949:
1.572 banghart 8950: # ------------------------------------------------------------Save Selected Files
8951:
8952: sub save_selected_files {
8953: my ($user, $path, @files) = @_;
8954: my $filename = $user."savedfiles";
1.573 banghart 8955: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 8956: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 8957: foreach my $file (@files) {
1.620 albertel 8958: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 8959: }
8960: foreach my $file (@other_files) {
1.574 banghart 8961: print (OUT $file."\n");
1.572 banghart 8962: }
1.574 banghart 8963: close (OUT);
1.572 banghart 8964: return 'ok';
8965: }
8966:
1.574 banghart 8967: sub clear_selected_files {
8968: my ($user) = @_;
8969: my $filename = $user."savedfiles";
1.1117 foxr 8970: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 8971: print (OUT undef);
8972: close (OUT);
8973: return ("ok");
8974: }
8975:
1.572 banghart 8976: sub files_in_path {
8977: my ($user, $path) = @_;
8978: my $filename = $user."savedfiles";
8979: my %return_files;
1.1117 foxr 8980: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 8981: while (my $line_in = <IN>) {
1.574 banghart 8982: chomp ($line_in);
8983: my @paths_and_file = split (m!/!, $line_in);
8984: my $file_part = pop (@paths_and_file);
8985: my $path_part = join ('/', @paths_and_file);
1.573 banghart 8986: $path_part.='/';
8987: my $path_and_file = $path_part.$file_part;
8988: if ($path_part eq $path) {
8989: $return_files{$file_part}= 'selected';
8990: }
8991: }
1.574 banghart 8992: close (IN);
8993: return (\%return_files);
1.572 banghart 8994: }
8995:
8996: # called in portfolio select mode, to show files selected NOT in current directory
8997: sub files_not_in_path {
8998: my ($user, $path) = @_;
8999: my $filename = $user."savedfiles";
9000: my @return_files;
9001: my $path_part;
1.1117 foxr 9002: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9003: while (my $line = <IN>) {
1.572 banghart 9004: #ok, I know it's clunky, but I want it to work
1.800 albertel 9005: my @paths_and_file = split(m|/|, $line);
9006: my $file_part = pop(@paths_and_file);
9007: chomp($file_part);
9008: my $path_part = join('/', @paths_and_file);
1.572 banghart 9009: $path_part .= '/';
9010: my $path_and_file = $path_part.$file_part;
9011: if ($path_part ne $path) {
1.800 albertel 9012: push(@return_files, ($path_and_file));
1.572 banghart 9013: }
9014: }
1.800 albertel 9015: close(OUT);
1.574 banghart 9016: return (@return_files);
1.572 banghart 9017: }
9018:
1.745 raeburn 9019: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9020:
1.745 raeburn 9021: sub get_portfile_permissions {
9022: my ($domain,$user) = @_;
1.613 albertel 9023: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9024: my ($tmp)=keys(%current_permissions);
9025: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9026: return \%current_permissions;
9027: }
9028:
9029: #---------------------------------------------Get portfolio file access controls
9030:
1.749 raeburn 9031: sub get_access_controls {
1.745 raeburn 9032: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9033: my %access;
9034: my $real_file = $file;
9035: $file =~ s/\.meta$//;
1.745 raeburn 9036: if (defined($file)) {
1.749 raeburn 9037: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9038: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9039: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9040: }
9041: }
1.745 raeburn 9042: } else {
1.749 raeburn 9043: foreach my $key (keys(%{$current_permissions})) {
9044: if ($key =~ /\0accesscontrol$/) {
9045: if (defined($group)) {
9046: if ($key !~ m-^\Q$group\E/-) {
9047: next;
9048: }
9049: }
9050: my ($fullpath) = split(/\0/,$key);
9051: if (ref($$current_permissions{$key}) eq 'HASH') {
9052: foreach my $control (keys(%{$$current_permissions{$key}})) {
9053: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9054: }
9055: }
9056: }
9057: }
9058: }
9059: return %access;
9060: }
9061:
9062: sub modify_access_controls {
9063: my ($file_name,$changes,$domain,$user)=@_;
9064: my ($outcome,$deloutcome);
9065: my %store_permissions;
9066: my %new_values;
9067: my %new_control;
9068: my %translation;
9069: my @deletions = ();
9070: my $now = time;
9071: if (exists($$changes{'activate'})) {
9072: if (ref($$changes{'activate'}) eq 'HASH') {
9073: my @newitems = sort(keys(%{$$changes{'activate'}}));
9074: my $numnew = scalar(@newitems);
9075: for (my $i=0; $i<$numnew; $i++) {
9076: my $newkey = $newitems[$i];
9077: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9078: if ($newkey =~ /^\d+:/) {
9079: $newkey =~ s/^(\d+)/$newid/;
9080: $translation{$1} = $newid;
9081: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9082: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9083: $translation{$1} = $newid;
9084: }
1.749 raeburn 9085: $new_values{$file_name."\0".$newkey} =
9086: $$changes{'activate'}{$newitems[$i]};
9087: $new_control{$newkey} = $now;
9088: }
9089: }
9090: }
9091: my %todelete;
9092: my %changed_items;
9093: foreach my $action ('delete','update') {
9094: if (exists($$changes{$action})) {
9095: if (ref($$changes{$action}) eq 'HASH') {
9096: foreach my $key (keys(%{$$changes{$action}})) {
9097: my ($itemnum) = ($key =~ /^([^:]+):/);
9098: if ($action eq 'delete') {
9099: $todelete{$itemnum} = 1;
9100: } else {
9101: $changed_items{$itemnum} = $key;
9102: }
9103: }
1.745 raeburn 9104: }
9105: }
1.749 raeburn 9106: }
9107: # get lock on access controls for file.
9108: my $lockhash = {
9109: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9110: ':'.$env{'user.domain'},
9111: };
9112: my $tries = 0;
9113: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9114:
9115: while (($gotlock ne 'ok') && $tries <3) {
9116: $tries ++;
9117: sleep 1;
9118: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9119: }
9120: if ($gotlock eq 'ok') {
9121: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9122: my ($tmp)=keys(%curr_permissions);
9123: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9124: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9125: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9126: if (ref($curr_controls) eq 'HASH') {
9127: foreach my $control_item (keys(%{$curr_controls})) {
9128: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9129: if (defined($todelete{$itemnum})) {
9130: push(@deletions,$file_name."\0".$control_item);
9131: } else {
9132: if (defined($changed_items{$itemnum})) {
9133: $new_control{$changed_items{$itemnum}} = $now;
9134: push(@deletions,$file_name."\0".$control_item);
9135: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9136: } else {
9137: $new_control{$control_item} = $$curr_controls{$control_item};
9138: }
9139: }
1.745 raeburn 9140: }
9141: }
9142: }
1.970 raeburn 9143: my ($group);
9144: if (&is_course($domain,$user)) {
9145: ($group,my $file) = split(/\//,$file_name,2);
9146: }
1.749 raeburn 9147: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9148: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9149: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9150: # remove lock
9151: my @del_lock = ($file_name."\0".'locked_access_records');
9152: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9153: my $sqlresult =
1.970 raeburn 9154: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9155: $group);
1.749 raeburn 9156: } else {
9157: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9158: }
1.749 raeburn 9159: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9160: }
9161:
1.827 raeburn 9162: sub make_public_indefinitely {
9163: my ($requrl) = @_;
9164: my $now = time;
9165: my $action = 'activate';
9166: my $aclnum = 0;
9167: if (&is_portfolio_url($requrl)) {
9168: my (undef,$udom,$unum,$file_name,$group) =
9169: &parse_portfolio_url($requrl);
9170: my $current_perms = &get_portfile_permissions($udom,$unum);
9171: my %access_controls = &get_access_controls($current_perms,
9172: $group,$file_name);
9173: foreach my $key (keys(%{$access_controls{$file_name}})) {
9174: my ($num,$scope,$end,$start) =
9175: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9176: if ($scope eq 'public') {
9177: if ($start <= $now && $end == 0) {
9178: $action = 'none';
9179: } else {
9180: $action = 'update';
9181: $aclnum = $num;
9182: }
9183: last;
9184: }
9185: }
9186: if ($action eq 'none') {
9187: return 'ok';
9188: } else {
9189: my %changes;
9190: my $newend = 0;
9191: my $newstart = $now;
9192: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9193: $changes{$action}{$newkey} = {
9194: type => 'public',
9195: time => {
9196: start => $newstart,
9197: end => $newend,
9198: },
9199: };
9200: my ($outcome,$deloutcome,$new_values,$translation) =
9201: &modify_access_controls($file_name,\%changes,$udom,$unum);
9202: return $outcome;
9203: }
9204: } else {
9205: return 'invalid';
9206: }
9207: }
9208:
1.745 raeburn 9209: #------------------------------------------------------Get Marked as Read Only
9210:
9211: sub get_marked_as_readonly {
9212: my ($domain,$user,$what,$group) = @_;
9213: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9214: my @readonly_files;
1.629 banghart 9215: my $cmp1=$what;
9216: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9217: while (my ($file_name,$value) = each(%{$current_permissions})) {
9218: if (defined($group)) {
9219: if ($file_name !~ m-^\Q$group\E/-) {
9220: next;
9221: }
9222: }
1.561 banghart 9223: if (ref($value) eq "ARRAY"){
9224: foreach my $stored_what (@{$value}) {
1.629 banghart 9225: my $cmp2=$stored_what;
1.759 albertel 9226: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9227: $cmp2=join('',@{$stored_what});
1.745 raeburn 9228: }
1.629 banghart 9229: if ($cmp1 eq $cmp2) {
1.561 banghart 9230: push(@readonly_files, $file_name);
1.745 raeburn 9231: last;
1.563 banghart 9232: } elsif (!defined($what)) {
9233: push(@readonly_files, $file_name);
1.745 raeburn 9234: last;
1.561 banghart 9235: }
9236: }
1.745 raeburn 9237: }
1.561 banghart 9238: }
9239: return @readonly_files;
9240: }
1.577 banghart 9241: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9242:
1.577 banghart 9243: sub get_marked_as_readonly_hash {
1.745 raeburn 9244: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9245: my %readonly_files;
1.745 raeburn 9246: while (my ($file_name,$value) = each(%{$current_permissions})) {
9247: if (defined($group)) {
9248: if ($file_name !~ m-^\Q$group\E/-) {
9249: next;
9250: }
9251: }
1.577 banghart 9252: if (ref($value) eq "ARRAY"){
9253: foreach my $stored_what (@{$value}) {
1.745 raeburn 9254: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9255: foreach my $lock_descriptor(@{$stored_what}) {
9256: if ($lock_descriptor eq 'graded') {
9257: $readonly_files{$file_name} = 'graded';
9258: } elsif ($lock_descriptor eq 'handback') {
9259: $readonly_files{$file_name} = 'handback';
9260: } else {
9261: if (!exists($readonly_files{$file_name})) {
9262: $readonly_files{$file_name} = 'locked';
9263: }
9264: }
1.745 raeburn 9265: }
1.750 banghart 9266: }
1.577 banghart 9267: }
9268: }
9269: }
9270: return %readonly_files;
9271: }
1.559 banghart 9272: # ------------------------------------------------------------ Unmark as Read Only
9273:
9274: sub unmark_as_readonly {
1.629 banghart 9275: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9276: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9277: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9278: $file_name = &declutter_portfile($file_name);
1.634 albertel 9279: my $symb_crs = $what;
9280: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9281: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9282: my ($tmp)=keys(%current_permissions);
9283: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9284: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9285: foreach my $file (@readonly_files) {
1.759 albertel 9286: my $clean_file = &declutter_portfile($file);
9287: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9288: my $current_locks = $current_permissions{$file};
1.563 banghart 9289: my @new_locks;
9290: my @del_keys;
9291: if (ref($current_locks) eq "ARRAY"){
9292: foreach my $locker (@{$current_locks}) {
1.632 albertel 9293: my $compare=$locker;
1.749 raeburn 9294: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9295: $compare=join('',@{$locker});
1.746 raeburn 9296: if ($compare ne $symb_crs) {
9297: push(@new_locks, $locker);
9298: }
1.563 banghart 9299: }
9300: }
1.650 albertel 9301: if (scalar(@new_locks) > 0) {
1.563 banghart 9302: $current_permissions{$file} = \@new_locks;
9303: } else {
9304: push(@del_keys, $file);
1.613 albertel 9305: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9306: delete($current_permissions{$file});
1.563 banghart 9307: }
9308: }
1.561 banghart 9309: }
1.613 albertel 9310: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9311: return;
9312: }
1.512 banghart 9313:
1.17 www 9314: # ------------------------------------------------------------ Directory lister
9315:
9316: sub dirlist {
1.955 raeburn 9317: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9318: $uri=~s/^\///;
9319: $uri=~s/\/$//;
1.253 stredwic 9320: my ($udom, $uname);
1.955 raeburn 9321: if ($getuserdir) {
1.253 stredwic 9322: $udom = $userdomain;
9323: $uname = $username;
1.955 raeburn 9324: } else {
9325: (undef,$udom,$uname)=split(/\//,$uri);
9326: if(defined($userdomain)) {
9327: $udom = $userdomain;
9328: }
9329: if(defined($username)) {
9330: $uname = $username;
9331: }
1.253 stredwic 9332: }
1.955 raeburn 9333: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9334:
1.955 raeburn 9335: $dirRoot = $perlvar{'lonDocRoot'};
9336: if (defined($getpropath)) {
9337: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9338: $dirRoot =~ s/\/$//;
1.955 raeburn 9339: } elsif (defined($getuserdir)) {
9340: my $subdir=$uname.'__';
9341: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9342: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9343: ."/$udom/$subdir/$uname";
9344: } elsif (defined($alternateRoot)) {
9345: $dirRoot = $alternateRoot;
1.751 banghart 9346: }
1.253 stredwic 9347:
9348: if($udom) {
9349: if($uname) {
1.1135 raeburn 9350: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9351: if ($uhome eq 'no_host') {
9352: return ([],'no_host');
9353: }
1.955 raeburn 9354: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9355: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9356: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9357: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9358: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9359: } else {
9360: @listing_results = map { &unescape($_); } split(/:/,$listing);
9361: }
1.605 matthew 9362: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9363: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9364: @listing_results = split(/:/,$listing);
9365: } else {
9366: @listing_results = map { &unescape($_); } split(/:/,$listing);
9367: }
1.1135 raeburn 9368: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9369: ($listing eq 'rejected') || ($listing eq 'refused') ||
9370: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9371: return ([],$listing);
9372: } else {
9373: return (\@listing_results);
1.1135 raeburn 9374: }
1.955 raeburn 9375: } elsif(!$alternateRoot) {
1.1136 raeburn 9376: my (%allusers,%listerror);
1.841 albertel 9377: my %servers = &get_servers($udom,'library');
1.955 raeburn 9378: foreach my $tryserver (keys(%servers)) {
9379: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9380: &escape($udom),$tryserver);
9381: if ($listing eq 'unknown_cmd') {
9382: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9383: $udom, $tryserver);
9384: } else {
9385: @listing_results = map { &unescape($_); } split(/:/,$listing);
9386: }
1.841 albertel 9387: if ($listing eq 'unknown_cmd') {
9388: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9389: $udom, $tryserver);
9390: @listing_results = split(/:/,$listing);
9391: } else {
9392: @listing_results =
9393: map { &unescape($_); } split(/:/,$listing);
9394: }
1.1136 raeburn 9395: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9396: ($listing eq 'rejected') || ($listing eq 'refused') ||
9397: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9398: $listerror{$tryserver} = $listing;
9399: } else {
1.841 albertel 9400: foreach my $line (@listing_results) {
9401: my ($entry) = split(/&/,$line,2);
9402: $allusers{$entry} = 1;
9403: }
9404: }
1.253 stredwic 9405: }
1.1136 raeburn 9406: my @alluserslist=();
1.800 albertel 9407: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9408: push(@alluserslist,$user.'&user');
1.253 stredwic 9409: }
1.1136 raeburn 9410: return (\@alluserslist);
1.253 stredwic 9411: } else {
1.1136 raeburn 9412: return ([],'missing username');
1.253 stredwic 9413: }
1.955 raeburn 9414: } elsif(!defined($getpropath)) {
1.1136 raeburn 9415: my $path = $perlvar{'lonDocRoot'}.'/res/';
9416: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9417: return (\@all_domains);
1.955 raeburn 9418: } else {
1.1136 raeburn 9419: return ([],'missing domain');
1.275 stredwic 9420: }
9421: }
9422:
9423: # --------------------------------------------- GetFileTimestamp
9424: # This function utilizes dirlist and returns the date stamp for
9425: # when it was last modified. It will also return an error of -1
9426: # if an error occurs
9427:
9428: sub GetFileTimestamp {
1.955 raeburn 9429: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9430: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9431: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9432: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9433: undef,$getuserdir);
9434: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9435: return -1;
9436: }
9437: if (ref($fileref) eq 'ARRAY') {
9438: my @stats = split('&',$fileref->[0]);
1.375 matthew 9439: # @stats contains first the filename, then the stat output
9440: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9441: } else {
9442: return -1;
1.253 stredwic 9443: }
1.26 www 9444: }
9445:
1.712 albertel 9446: sub stat_file {
9447: my ($uri) = @_;
1.787 albertel 9448: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9449:
1.955 raeburn 9450: my ($udom,$uname,$file);
1.712 albertel 9451: if ($uri =~ m-^/(uploaded|editupload)/-) {
9452: ($udom,$uname,$file) =
1.811 albertel 9453: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9454: $file = 'userfiles/'.$file;
9455: }
9456: if ($uri =~ m-^/res/-) {
9457: ($udom,$uname) =
1.807 albertel 9458: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9459: $file = $uri;
9460: }
9461:
9462: if (!$udom || !$uname || !$file) {
9463: # unable to handle the uri
9464: return ();
9465: }
1.956 raeburn 9466: my $getpropath;
9467: if ($file =~ /^userfiles\//) {
9468: $getpropath = 1;
9469: }
1.1136 raeburn 9470: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9471: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9472: return ();
9473: } else {
9474: if (ref($listref) eq 'ARRAY') {
9475: my @stats = split('&',$listref->[0]);
9476: shift(@stats); #filename is first
9477: return @stats;
9478: }
1.712 albertel 9479: }
9480: return ();
9481: }
9482:
1.26 www 9483: # -------------------------------------------------------- Value of a Condition
9484:
1.713 albertel 9485: # gets the value of a specific preevaluated condition
9486: # stored in the string $env{user.state.<cid>}
9487: # or looks up a condition reference in the bighash and if if hasn't
9488: # already been evaluated recurses into docondval to get the value of
9489: # the condition, then memoizing it to
9490: # $env{user.state.<cid>.<condition>}
1.40 www 9491: sub directcondval {
9492: my $number=shift;
1.620 albertel 9493: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9494: &Apache::lonuserstate::evalstate();
9495: }
1.713 albertel 9496: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9497: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9498: } elsif ($number =~ /^_/) {
9499: my $sub_condition;
9500: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9501: &GDBM_READER(),0640)) {
9502: $sub_condition=$bighash{'conditions'.$number};
9503: untie(%bighash);
9504: }
9505: my $value = &docondval($sub_condition);
1.949 raeburn 9506: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9507: return $value;
9508: }
1.620 albertel 9509: if ($env{'user.state.'.$env{'request.course.id'}}) {
9510: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9511: } else {
9512: return 2;
9513: }
9514: }
9515:
1.713 albertel 9516: # get the collection of conditions for this resource
1.26 www 9517: sub condval {
9518: my $condidx=shift;
1.54 www 9519: my $allpathcond='';
1.713 albertel 9520: foreach my $cond (split(/\|/,$condidx)) {
9521: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9522: $allpathcond.=
9523: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9524: }
1.191 harris41 9525: }
1.54 www 9526: $allpathcond=~s/\|$//;
1.713 albertel 9527: return &docondval($allpathcond);
9528: }
9529:
9530: #evaluates an expression of conditions
9531: sub docondval {
9532: my ($allpathcond) = @_;
9533: my $result=0;
9534: if ($env{'request.course.id'}
9535: && defined($allpathcond)) {
9536: my $operand='|';
9537: my @stack;
9538: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9539: if ($chunk eq '(') {
9540: push @stack,($operand,$result);
9541: } elsif ($chunk eq ')') {
9542: my $before=pop @stack;
9543: if (pop @stack eq '&') {
9544: $result=$result>$before?$before:$result;
9545: } else {
9546: $result=$result>$before?$result:$before;
9547: }
9548: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9549: $operand=$chunk;
9550: } else {
9551: my $new=directcondval($chunk);
9552: if ($operand eq '&') {
9553: $result=$result>$new?$new:$result;
9554: } else {
9555: $result=$result>$new?$result:$new;
9556: }
9557: }
9558: }
1.26 www 9559: }
9560: return $result;
1.421 albertel 9561: }
9562:
9563: # ---------------------------------------------------- Devalidate courseresdata
9564:
9565: sub devalidatecourseresdata {
9566: my ($coursenum,$coursedomain)=@_;
9567: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9568: &devalidate_cache_new('courseres',$hashid);
1.28 www 9569: }
9570:
1.763 www 9571:
1.200 www 9572: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9573: #
9574: # Parameters:
9575: # $coursenum - Number of the course.
9576: # $coursedomain - Domain at which the course was created.
9577: # Returns:
9578: # A hash of the course parameters along (I think) with timestamps
9579: # and version info.
1.877 foxr 9580:
1.624 albertel 9581: sub get_courseresdata {
9582: my ($coursenum,$coursedomain)=@_;
1.200 www 9583: my $coursehom=&homeserver($coursenum,$coursedomain);
9584: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9585: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9586: my %dumpreply;
1.417 albertel 9587: unless (defined($cached)) {
1.624 albertel 9588: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9589: $result=\%dumpreply;
1.251 albertel 9590: my ($tmp) = keys(%dumpreply);
9591: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9592: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9593: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9594: return $tmp;
1.416 albertel 9595: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9596: $result=undef;
1.599 albertel 9597: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9598: }
9599: }
1.624 albertel 9600: return $result;
9601: }
9602:
1.633 albertel 9603: sub devalidateuserresdata {
9604: my ($uname,$udom)=@_;
9605: my $hashid="$udom:$uname";
9606: &devalidate_cache_new('userres',$hashid);
9607: }
9608:
1.624 albertel 9609: sub get_userresdata {
9610: my ($uname,$udom)=@_;
9611: #most student don\'t have any data set, check if there is some data
9612: if (&EXT_cache_status($udom,$uname)) { return undef; }
9613:
9614: my $hashid="$udom:$uname";
9615: my ($result,$cached)=&is_cached_new('userres',$hashid);
9616: if (!defined($cached)) {
9617: my %resourcedata=&dump('resourcedata',$udom,$uname);
9618: $result=\%resourcedata;
9619: &do_cache_new('userres',$hashid,$result,600);
9620: }
9621: my ($tmp)=keys(%$result);
9622: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9623: return $result;
9624: }
9625: #error 2 occurs when the .db doesn't exist
9626: if ($tmp!~/error: 2 /) {
1.672 albertel 9627: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9628: " Trying to get resource data for ".
9629: $uname." at ".$udom.": ".
9630: $tmp."</font>");
9631: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9632: #&EXT_cache_set($udom,$uname);
9633: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9634: undef($tmp); # not really an error so don't send it back
1.624 albertel 9635: }
9636: return $tmp;
9637: }
1.879 foxr 9638: #----------------------------------------------- resdata - return resource data
9639: # Purpose:
9640: # Return resource data for either users or for a course.
9641: # Parameters:
9642: # $name - Course/user name.
9643: # $domain - Name of the domain the user/course is registered on.
9644: # $type - Type of thing $name is (must be 'course' or 'user'
9645: # @which - Array of names of resources desired.
9646: # Returns:
9647: # The value of the first reasource in @which that is found in the
9648: # resource hash.
9649: # Exceptional Conditions:
9650: # If the $type passed in is not valid (not the string 'course' or
9651: # 'user', an undefined reference is returned.
9652: # If none of the resources are found, an undef is returned
1.624 albertel 9653: sub resdata {
9654: my ($name,$domain,$type,@which)=@_;
9655: my $result;
9656: if ($type eq 'course') {
9657: $result=&get_courseresdata($name,$domain);
9658: } elsif ($type eq 'user') {
9659: $result=&get_userresdata($name,$domain);
9660: }
9661: if (!ref($result)) { return $result; }
1.251 albertel 9662: foreach my $item (@which) {
1.927 albertel 9663: if (defined($result->{$item->[0]})) {
9664: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9665: }
1.250 albertel 9666: }
1.291 albertel 9667: return undef;
1.200 www 9668: }
9669:
1.1236 raeburn 9670: sub get_numsuppfiles {
9671: my ($cnum,$cdom,$ignorecache)=@_;
9672: my $hashid=$cnum.':'.$cdom;
9673: my ($suppcount,$cached);
9674: unless ($ignorecache) {
9675: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9676: }
9677: unless (defined($cached)) {
9678: my $chome=&homeserver($cnum,$cdom);
9679: unless ($chome eq 'no_host') {
9680: ($suppcount,my $errors) = (0,0);
9681: my $suppmap = 'supplemental.sequence';
9682: ($suppcount,$errors) =
9683: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9684: }
9685: &do_cache_new('suppcount',$hashid,$suppcount,600);
9686: }
9687: return $suppcount;
9688: }
9689:
1.379 matthew 9690: #
9691: # EXT resource caching routines
9692: #
9693:
9694: sub clear_EXT_cache_status {
1.383 albertel 9695: &delenv('cache.EXT.');
1.379 matthew 9696: }
9697:
9698: sub EXT_cache_status {
9699: my ($target_domain,$target_user) = @_;
1.383 albertel 9700: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9701: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9702: # We know already the user has no data
9703: return 1;
9704: } else {
9705: return 0;
9706: }
9707: }
9708:
9709: sub EXT_cache_set {
9710: my ($target_domain,$target_user) = @_;
1.383 albertel 9711: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9712: #&appenv({$cachename => time});
1.379 matthew 9713: }
9714:
1.28 www 9715: # --------------------------------------------------------- Value of a Variable
1.58 www 9716: sub EXT {
1.715 albertel 9717:
1.1228 raeburn 9718: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9719: unless ($varname) { return ''; }
1.218 albertel 9720: #get real user name/domain, courseid and symb
9721: my $courseid;
1.359 albertel 9722: my $publicuser;
1.427 www 9723: if ($symbparm) {
9724: $symbparm=&get_symb_from_alias($symbparm);
9725: }
1.218 albertel 9726: if (!($uname && $udom)) {
1.790 albertel 9727: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9728: if (!$symbparm) { $symbparm=$cursymb; }
9729: } else {
1.620 albertel 9730: $courseid=$env{'request.course.id'};
1.218 albertel 9731: }
1.48 www 9732: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9733: my $rest;
1.320 albertel 9734: if (defined($therest[0])) {
1.48 www 9735: $rest=join('.',@therest);
9736: } else {
9737: $rest='';
9738: }
1.320 albertel 9739:
1.57 www 9740: my $qualifierrest=$qualifier;
9741: if ($rest) { $qualifierrest.='.'.$rest; }
9742: my $spacequalifierrest=$space;
9743: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9744: if ($realm eq 'user') {
1.48 www 9745: # --------------------------------------------------------------- user.resource
9746: if ($space eq 'resource') {
1.651 albertel 9747: if ( (defined($Apache::lonhomework::parsing_a_problem)
9748: || defined($Apache::lonhomework::parsing_a_task))
9749: &&
1.744 albertel 9750: ($symbparm eq &symbread()) ) {
9751: # if we are in the middle of processing the resource the
9752: # get the value we are planning on committing
9753: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9754: return $Apache::lonhomework::results{$qualifierrest};
9755: } else {
9756: return $Apache::lonhomework::history{$qualifierrest};
9757: }
1.335 albertel 9758: } else {
1.359 albertel 9759: my %restored;
1.620 albertel 9760: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9761: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9762: } else {
9763: %restored=&restore($symbparm,$courseid,$udom,$uname);
9764: }
1.335 albertel 9765: return $restored{$qualifierrest};
9766: }
1.48 www 9767: # ----------------------------------------------------------------- user.access
9768: } elsif ($space eq 'access') {
1.218 albertel 9769: # FIXME - not supporting calls for a specific user
1.48 www 9770: return &allowed($qualifier,$rest);
9771: # ------------------------------------------ user.preferences, user.environment
9772: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9773: if (($uname eq $env{'user.name'}) &&
9774: ($udom eq $env{'user.domain'})) {
9775: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9776: } else {
1.359 albertel 9777: my %returnhash;
9778: if (!$publicuser) {
9779: %returnhash=&userenvironment($udom,$uname,
9780: $qualifierrest);
9781: }
1.218 albertel 9782: return $returnhash{$qualifierrest};
9783: }
1.48 www 9784: # ----------------------------------------------------------------- user.course
9785: } elsif ($space eq 'course') {
1.218 albertel 9786: # FIXME - not supporting calls for a specific user
1.620 albertel 9787: return $env{join('.',('request.course',$qualifier))};
1.48 www 9788: # ------------------------------------------------------------------- user.role
9789: } elsif ($space eq 'role') {
1.218 albertel 9790: # FIXME - not supporting calls for a specific user
1.620 albertel 9791: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9792: if ($qualifier eq 'value') {
9793: return $role;
9794: } elsif ($qualifier eq 'extent') {
9795: return $where;
9796: }
9797: # ----------------------------------------------------------------- user.domain
9798: } elsif ($space eq 'domain') {
1.218 albertel 9799: return $udom;
1.48 www 9800: # ------------------------------------------------------------------- user.name
9801: } elsif ($space eq 'name') {
1.218 albertel 9802: return $uname;
1.48 www 9803: # ---------------------------------------------------- Any other user namespace
1.29 www 9804: } else {
1.359 albertel 9805: my %reply;
9806: if (!$publicuser) {
9807: %reply=&get($space,[$qualifierrest],$udom,$uname);
9808: }
9809: return $reply{$qualifierrest};
1.48 www 9810: }
1.236 www 9811: } elsif ($realm eq 'query') {
9812: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9813: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9814: [$spacequalifierrest]);
1.620 albertel 9815: return $env{'form.'.$spacequalifierrest};
1.236 www 9816: } elsif ($realm eq 'request') {
1.48 www 9817: # ------------------------------------------------------------- request.browser
9818: if ($space eq 'browser') {
1.1145 bisitz 9819: return $env{'browser.'.$qualifier};
1.57 www 9820: # ------------------------------------------------------------ request.filename
9821: } else {
1.620 albertel 9822: return $env{'request.'.$spacequalifierrest};
1.29 www 9823: }
1.28 www 9824: } elsif ($realm eq 'course') {
1.48 www 9825: # ---------------------------------------------------------- course.description
1.620 albertel 9826: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9827: } elsif ($realm eq 'resource') {
1.165 www 9828:
1.620 albertel 9829: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9830: if (!$symbparm) { $symbparm=&symbread(); }
9831: }
1.693 albertel 9832:
1.1232 raeburn 9833: if ($qualifier eq '') {
9834: if ($space eq 'title') {
9835: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9836: return &gettitle($symbparm);
9837: }
1.693 albertel 9838:
1.1232 raeburn 9839: if ($space eq 'map') {
9840: my ($map) = &decode_symb($symbparm);
9841: return &symbread($map);
9842: }
9843: if ($space eq 'maptitle') {
9844: my ($map) = &decode_symb($symbparm);
9845: return &gettitle($map);
9846: }
9847: if ($space eq 'filename') {
9848: if ($symbparm) {
9849: return &clutter((&decode_symb($symbparm))[2]);
9850: }
9851: return &hreflocation('',$env{'request.filename'});
1.905 albertel 9852: }
1.1232 raeburn 9853:
1.1233 raeburn 9854: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
9855: if ($space eq 'visibleparts') {
9856: my $navmap = Apache::lonnavmaps::navmap->new();
9857: my $item;
9858: if (ref($navmap)) {
9859: my $res = $navmap->getBySymb($symbparm);
9860: my $parts = $res->parts();
9861: if (ref($parts) eq 'ARRAY') {
9862: $item = join(',',@{$parts});
9863: }
9864: undef($navmap);
1.1232 raeburn 9865: }
1.1233 raeburn 9866: return $item;
1.1232 raeburn 9867: }
9868: }
9869: }
1.693 albertel 9870:
9871: my ($section, $group, @groups);
1.593 albertel 9872: my ($courselevelm,$courselevel);
1.1228 raeburn 9873: if (($courseid eq '') && ($cid)) {
9874: $courseid = $cid;
9875: }
9876: if (($symbparm && $courseid) &&
9877: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 9878:
1.218 albertel 9879: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9880:
1.60 www 9881: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9882: my $symbp=$symbparm;
1.735 albertel 9883: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9884:
9885: my $symbparm=$symbp.'.'.$spacequalifierrest;
9886: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9887:
1.620 albertel 9888: if (($env{'user.name'} eq $uname) &&
9889: ($env{'user.domain'} eq $udom)) {
9890: $section=$env{'request.course.sec'};
1.733 raeburn 9891: @groups = split(/:/,$env{'request.course.groups'});
9892: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9893: } else {
1.539 albertel 9894: if (! defined($usection)) {
1.551 albertel 9895: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9896: } else {
9897: $section = $usection;
9898: }
1.733 raeburn 9899: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9900: }
9901:
9902: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9903: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9904: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9905:
1.593 albertel 9906: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9907: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9908: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9909:
1.60 www 9910: # ----------------------------------------------------------- first, check user
1.624 albertel 9911:
9912: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9913: ([$courselevelr,'resource'],
9914: [$courselevelm,'map' ],
9915: [$courselevel, 'course' ]));
1.931 albertel 9916: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9917:
1.594 albertel 9918: # ------------------------------------------------ second, check some of course
1.684 raeburn 9919: my $coursereply;
1.691 raeburn 9920: if (@groups > 0) {
9921: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9922: $mapparm,$spacequalifierrest);
1.927 albertel 9923: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9924: }
1.96 www 9925:
1.684 raeburn 9926: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9927: $env{'course.'.$courseid.'.domain'},
9928: 'course',
9929: ([$seclevelr, 'resource'],
9930: [$seclevelm, 'map' ],
9931: [$seclevel, 'course' ],
9932: [$courselevelr,'resource']));
9933: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 9934:
1.60 www 9935: # ------------------------------------------------------ third, check map parms
1.218 albertel 9936: my %parmhash=();
9937: my $thisparm='';
9938: if (tie(%parmhash,'GDBM_File',
1.620 albertel 9939: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 9940: &GDBM_READER(),0640)) {
1.218 albertel 9941: $thisparm=$parmhash{$symbparm};
9942: untie(%parmhash);
9943: }
1.927 albertel 9944: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 9945: }
1.594 albertel 9946: # ------------------------------------------ fourth, look in resource metadata
1.71 www 9947:
1.218 albertel 9948: $spacequalifierrest=~s/\./\_/;
1.282 albertel 9949: my $filename;
9950: if (!$symbparm) { $symbparm=&symbread(); }
9951: if ($symbparm) {
1.409 www 9952: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 9953: } else {
1.620 albertel 9954: $filename=$env{'request.filename'};
1.282 albertel 9955: }
9956: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 9957: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 9958: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 9959: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 9960:
1.927 albertel 9961: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 9962: if ($symbparm && defined($courseid) &&
1.620 albertel 9963: $courseid eq $env{'request.course.id'}) {
1.624 albertel 9964: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9965: $env{'course.'.$courseid.'.domain'},
9966: 'course',
1.927 albertel 9967: ([$courselevelm,'map' ],
9968: [$courselevel, 'course']));
9969: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 9970: }
1.145 www 9971: # ------------------------------------------------------------------ Cascade up
1.218 albertel 9972: unless ($space eq '0') {
1.336 albertel 9973: my @parts=split(/_/,$space);
9974: my $id=pop(@parts);
9975: my $part=join('_',@parts);
9976: if ($part eq '') { $part='0'; }
1.927 albertel 9977: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 9978: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 9979: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 9980: }
1.395 albertel 9981: if ($recurse) { return undef; }
9982: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 9983: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 9984: # ---------------------------------------------------- Any other user namespace
9985: } elsif ($realm eq 'environment') {
9986: # ----------------------------------------------------------------- environment
1.620 albertel 9987: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9988: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 9989: } else {
1.770 albertel 9990: if ($uname eq 'anonymous' && $udom eq '') {
9991: return '';
9992: }
1.219 albertel 9993: my %returnhash=&userenvironment($udom,$uname,
9994: $spacequalifierrest);
9995: return $returnhash{$spacequalifierrest};
9996: }
1.28 www 9997: } elsif ($realm eq 'system') {
1.48 www 9998: # ----------------------------------------------------------------- system.time
9999: if ($space eq 'time') {
10000: return time;
10001: }
1.696 albertel 10002: } elsif ($realm eq 'server') {
10003: # ----------------------------------------------------------------- system.time
10004: if ($space eq 'name') {
10005: return $ENV{'SERVER_NAME'};
10006: }
1.28 www 10007: }
1.48 www 10008: return '';
1.61 www 10009: }
10010:
1.927 albertel 10011: sub get_reply {
10012: my ($reply_value) = @_;
1.940 raeburn 10013: if (ref($reply_value) eq 'ARRAY') {
10014: if (wantarray) {
10015: return @$reply_value;
10016: }
10017: return $reply_value->[0];
10018: } else {
10019: return $reply_value;
1.927 albertel 10020: }
10021: }
10022:
1.691 raeburn 10023: sub check_group_parms {
10024: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10025: my @groupitems = ();
10026: my $resultitem;
1.927 albertel 10027: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10028: foreach my $group (@{$groups}) {
10029: foreach my $level (@levels) {
1.927 albertel 10030: my $item = $courseid.'.['.$group.'].'.$level->[0];
10031: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10032: }
10033: }
10034: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10035: $env{'course.'.$courseid.'.domain'},
10036: 'course',@groupitems);
10037: return $coursereply;
10038: }
10039:
10040: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10041: my ($courseid,@groups) = @_;
10042: @groups = sort(@groups);
1.691 raeburn 10043: return @groups;
10044: }
10045:
1.395 albertel 10046: sub packages_tab_default {
10047: my ($uri,$varname)=@_;
10048: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10049:
10050: my (@extension,@specifics,$do_default);
10051: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10052: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10053: if ($pack_type eq 'default') {
10054: $do_default=1;
10055: } elsif ($pack_type eq 'extension') {
10056: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10057: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10058: # only look at packages defaults for packages that this id is
1.738 albertel 10059: push(@specifics,[$package,$pack_type,$pack_part]);
10060: }
10061: }
10062: # first look for a package that matches the requested part id
10063: foreach my $package (@specifics) {
10064: my (undef,$pack_type,$pack_part)=@{$package};
10065: next if ($pack_part ne $part);
10066: if (defined($packagetab{"$pack_type&$name&default"})) {
10067: return $packagetab{"$pack_type&$name&default"};
10068: }
10069: }
10070: # look for any possible matching non extension_ package
10071: foreach my $package (@specifics) {
10072: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10073: if (defined($packagetab{"$pack_type&$name&default"})) {
10074: return $packagetab{"$pack_type&$name&default"};
10075: }
1.585 albertel 10076: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10077: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10078: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10079: }
10080: }
1.738 albertel 10081: # look for any posible extension_ match
10082: foreach my $package (@extension) {
10083: my ($package,$pack_type)=@{$package};
10084: if (defined($packagetab{"$pack_type&$name&default"})) {
10085: return $packagetab{"$pack_type&$name&default"};
10086: }
10087: if (defined($packagetab{$package."&$name&default"})) {
10088: return $packagetab{$package."&$name&default"};
10089: }
10090: }
10091: # look for a global default setting
10092: if ($do_default && defined($packagetab{"default&$name&default"})) {
10093: return $packagetab{"default&$name&default"};
10094: }
1.395 albertel 10095: return undef;
10096: }
10097:
1.334 albertel 10098: sub add_prefix_and_part {
10099: my ($prefix,$part)=@_;
10100: my $keyroot;
10101: if (defined($prefix) && $prefix !~ /^__/) {
10102: # prefix that has a part already
10103: $keyroot=$prefix;
10104: } elsif (defined($prefix)) {
10105: # prefix that is missing a part
10106: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10107: } else {
10108: # no prefix at all
10109: if (defined($part)) { $keyroot='_'.$part; }
10110: }
10111: return $keyroot;
10112: }
10113:
1.71 www 10114: # ---------------------------------------------------------------- Get metadata
10115:
1.599 albertel 10116: my %metaentry;
1.1070 www 10117: my %importedpartids;
1.71 www 10118: sub metadata {
1.176 www 10119: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10120: $uri=&declutter($uri);
1.288 albertel 10121: # if it is a non metadata possible uri return quickly
1.529 albertel 10122: if (($uri eq '') ||
10123: (($uri =~ m|^/*adm/|) &&
1.1217 raeburn 10124: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10125: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10126: return undef;
10127: }
1.1140 www 10128: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 10129: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10130: return undef;
1.288 albertel 10131: }
1.73 www 10132: my $filename=$uri;
10133: $uri=~s/\.meta$//;
1.172 www 10134: #
10135: # Is the metadata already cached?
1.177 www 10136: # Look at timestamp of caching
1.172 www 10137: # Everything is cached by the main uri, libraries are never directly cached
10138: #
1.428 albertel 10139: if (!defined($liburi)) {
1.599 albertel 10140: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10141: if (defined($cached)) { return $result->{':'.$what}; }
10142: }
10143: {
1.1069 www 10144: # Imported parts would go here
1.1070 www 10145: my %importedids=();
10146: my @origfileimportpartids=();
1.1069 www 10147: my $importedparts=0;
1.172 www 10148: #
10149: # Is this a recursive call for a library?
10150: #
1.599 albertel 10151: # if (! exists($metacache{$uri})) {
10152: # $metacache{$uri}={};
10153: # }
1.924 albertel 10154: my $cachetime = 60*60;
1.171 www 10155: if ($liburi) {
10156: $liburi=&declutter($liburi);
10157: $filename=$liburi;
1.401 bowersj2 10158: } else {
1.599 albertel 10159: &devalidate_cache_new('meta',$uri);
10160: undef(%metaentry);
1.401 bowersj2 10161: }
1.140 www 10162: my %metathesekeys=();
1.73 www 10163: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10164: my $metastring;
1.1140 www 10165: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10166: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10167: $metastring =
1.929 albertel 10168: &Apache::lonnet::ssi_body($which,
1.924 albertel 10169: ('grade_target' => 'meta'));
10170: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10171: } elsif (($uri !~ m -^(editupload)/-) &&
10172: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10173: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10174: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10175: $metastring=&getfile($file);
1.489 albertel 10176: }
1.208 albertel 10177: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10178: my $token;
1.140 www 10179: undef %metathesekeys;
1.71 www 10180: while ($token=$parser->get_token) {
1.339 albertel 10181: if ($token->[0] eq 'S') {
10182: if (defined($token->[2]->{'package'})) {
1.172 www 10183: #
10184: # This is a package - get package info
10185: #
1.339 albertel 10186: my $package=$token->[2]->{'package'};
10187: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10188: if (defined($token->[2]->{'id'})) {
10189: $keyroot.='_'.$token->[2]->{'id'};
10190: }
1.599 albertel 10191: if ($metaentry{':packages'}) {
10192: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10193: } else {
1.599 albertel 10194: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10195: }
1.736 albertel 10196: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10197: my $part=$keyroot;
10198: $part=~s/^\_//;
1.736 albertel 10199: if ($pack_entry=~/^\Q$package\E\&/ ||
10200: $pack_entry=~/^\Q$package\E_0\&/) {
10201: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10202: # ignore package.tab specified default values
10203: # here &package_tab_default() will fetch those
10204: if ($subp eq 'default') { next; }
1.736 albertel 10205: my $value=$packagetab{$pack_entry};
1.432 albertel 10206: my $unikey;
10207: if ($pack =~ /_0$/) {
10208: $unikey='parameter_0_'.$name;
10209: $part=0;
10210: } else {
10211: $unikey='parameter'.$keyroot.'_'.$name;
10212: }
1.339 albertel 10213: if ($subp eq 'display') {
10214: $value.=' [Part: '.$part.']';
10215: }
1.599 albertel 10216: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10217: $metathesekeys{$unikey}=1;
1.599 albertel 10218: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10219: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10220: }
1.599 albertel 10221: if (defined($metaentry{':'.$unikey.'.default'})) {
10222: $metaentry{':'.$unikey}=
10223: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10224: }
1.339 albertel 10225: }
10226: }
10227: } else {
1.172 www 10228: #
10229: # This is not a package - some other kind of start tag
1.339 albertel 10230: #
10231: my $entry=$token->[1];
1.1068 www 10232: my $unikey='';
1.175 www 10233:
1.339 albertel 10234: if ($entry eq 'import') {
1.175 www 10235: #
10236: # Importing a library here
1.339 albertel 10237: #
1.1067 www 10238: my $location=$parser->get_text('/import');
10239: my $dir=$filename;
10240: $dir=~s|[^/]*$||;
10241: $location=&filelocation($dir,$location);
1.1069 www 10242:
1.1068 www 10243: my $importmode=$token->[2]->{'importmode'};
10244: if ($importmode eq 'problem') {
1.1069 www 10245: # Import as problem/response
1.1068 www 10246: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10247: } elsif ($importmode eq 'part') {
10248: # Import as part(s)
1.1069 www 10249: $importedparts=1;
10250: # We need to get the original file and the imported file to get the part order correct
10251: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10252: # Load and inspect original file
1.1070 www 10253: if ($#origfileimportpartids<0) {
10254: undef(%importedpartids);
10255: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10256: my $origfile=&getfile($origfilelocation);
10257: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10258: }
10259:
1.1069 www 10260: # Load and inspect imported file
10261: my $impfile=&getfile($location);
10262: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10263: if ($#impfilepartids>=0) {
10264: # This problem had parts
1.1070 www 10265: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10266: } else {
10267: # Importing by turning a single problem into a problem part
10268: # It gets the import-tags ID as part-ID
10269: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10270: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10271: }
1.1068 www 10272: } else {
10273: # Normal import
10274: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10275: if (defined($token->[2]->{'id'})) {
10276: $unikey.='_'.$token->[2]->{'id'};
10277: }
1.1067 www 10278: }
10279:
1.339 albertel 10280: if ($depthcount<20) {
1.736 albertel 10281: my $metadata =
10282: &metadata($uri,'keys', $location,$unikey,
10283: $depthcount+1);
10284: foreach my $meta (split(',',$metadata)) {
10285: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10286: $metathesekeys{$meta}=1;
1.339 albertel 10287: }
1.1068 www 10288:
10289: }
1.1067 www 10290: } else {
10291: #
10292: # Not importing, some other kind of non-package, non-library start tag
10293: #
10294: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10295: if (defined($token->[2]->{'id'})) {
10296: $unikey.='_'.$token->[2]->{'id'};
10297: }
1.339 albertel 10298: if (defined($token->[2]->{'name'})) {
10299: $unikey.='_'.$token->[2]->{'name'};
10300: }
10301: $metathesekeys{$unikey}=1;
1.736 albertel 10302: foreach my $param (@{$token->[3]}) {
10303: $metaentry{':'.$unikey.'.'.$param} =
10304: $token->[2]->{$param};
1.339 albertel 10305: }
10306: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10307: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10308: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10309: # only ws inside the tag, and not in default, so use default
10310: # as value
1.599 albertel 10311: $metaentry{':'.$unikey}=$default;
1.908 albertel 10312: } elsif ( $internaltext =~ /\S/ ) {
10313: # something interesting inside the tag
10314: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10315: } else {
1.908 albertel 10316: # no interesting values, don't set a default
1.339 albertel 10317: }
1.172 www 10318: # end of not-a-package not-a-library import
1.339 albertel 10319: }
1.172 www 10320: # end of not-a-package start tag
1.339 albertel 10321: }
1.172 www 10322: # the next is the end of "start tag"
1.339 albertel 10323: }
10324: }
1.483 albertel 10325: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10326: $extension = lc($extension);
10327: if ($extension eq 'htm') { $extension='html'; }
10328:
1.737 albertel 10329: foreach my $key (keys(%packagetab)) {
1.483 albertel 10330: #no specific packages #how's our extension
10331: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10332: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10333: \%metathesekeys);
10334: }
1.883 albertel 10335:
10336: if (!exists($metaentry{':packages'})
10337: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10338: foreach my $key (keys(%packagetab)) {
1.483 albertel 10339: #no specific packages well let's get default then
10340: if ($key!~/^default&/) { next; }
1.488 albertel 10341: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10342: \%metathesekeys);
10343: }
10344: }
1.338 www 10345: # are there custom rights to evaluate
1.599 albertel 10346: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10347:
1.338 www 10348: #
10349: # Importing a rights file here
1.339 albertel 10350: #
10351: unless ($depthcount) {
1.599 albertel 10352: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10353: my $dir=$filename;
10354: $dir=~s|[^/]*$||;
10355: $location=&filelocation($dir,$location);
1.736 albertel 10356: my $rights_metadata =
10357: &metadata($uri,'keys',$location,'_rights',
10358: $depthcount+1);
10359: foreach my $rights (split(',',$rights_metadata)) {
10360: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10361: $metathesekeys{$rights}=1;
1.339 albertel 10362: }
10363: }
10364: }
1.737 albertel 10365: # uniqifiy package listing
10366: my %seen;
10367: my @uniq_packages =
10368: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10369: $metaentry{':packages'} = join(',',@uniq_packages);
10370:
1.1070 www 10371: if ($importedparts) {
10372: # We had imported parts and need to rebuild partorder
10373: $metaentry{':partorder'}='';
10374: $metathesekeys{'partorder'}=1;
10375: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10376: if ($origfileimportpartids[$index] eq 'part') {
10377: # original part, part of the problem
10378: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10379: } else {
10380: # we have imported parts at this position
10381: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10382: }
10383: }
10384: $metaentry{':partorder'}=~s/^\,//;
10385: }
10386:
1.737 albertel 10387: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10388: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10389: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 10390: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10391: # this is the end of "was not already recently cached
1.71 www 10392: }
1.599 albertel 10393: return $metaentry{':'.$what};
1.261 albertel 10394: }
10395:
1.488 albertel 10396: sub metadata_create_package_def {
1.483 albertel 10397: my ($uri,$key,$package,$metathesekeys)=@_;
10398: my ($pack,$name,$subp)=split(/\&/,$key);
10399: if ($subp eq 'default') { next; }
10400:
1.599 albertel 10401: if (defined($metaentry{':packages'})) {
10402: $metaentry{':packages'}.=','.$package;
1.483 albertel 10403: } else {
1.599 albertel 10404: $metaentry{':packages'}=$package;
1.483 albertel 10405: }
10406: my $value=$packagetab{$key};
10407: my $unikey;
10408: $unikey='parameter_0_'.$name;
1.599 albertel 10409: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10410: $$metathesekeys{$unikey}=1;
1.599 albertel 10411: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10412: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10413: }
1.599 albertel 10414: if (defined($metaentry{':'.$unikey.'.default'})) {
10415: $metaentry{':'.$unikey}=
10416: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10417: }
10418: }
10419:
1.261 albertel 10420: sub metadata_generate_part0 {
10421: my ($metadata,$metacache,$uri) = @_;
10422: my %allnames;
1.737 albertel 10423: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10424: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10425: my $part=$$metacache{':'.$metakey.'.part'};
10426: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10427: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10428: $allnames{$name}=$part;
10429: }
10430: }
10431: }
10432: foreach my $name (keys(%allnames)) {
10433: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10434: my $key=":parameter_0_$name";
1.261 albertel 10435: $$metacache{"$key.part"}='0';
10436: $$metacache{"$key.name"}=$name;
1.428 albertel 10437: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10438: $allnames{$name}.'_'.$name.
10439: '.type'};
1.428 albertel 10440: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10441: '.display'};
1.644 www 10442: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10443: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10444: $$metacache{"$key.display"}=$olddis;
10445: }
1.71 www 10446: }
10447:
1.764 albertel 10448: # ------------------------------------------------------ Devalidate title cache
10449:
10450: sub devalidate_title_cache {
10451: my ($url)=@_;
10452: if (!$env{'request.course.id'}) { return; }
10453: my $symb=&symbread($url);
10454: if (!$symb) { return; }
10455: my $key=$env{'request.course.id'}."\0".$symb;
10456: &devalidate_cache_new('title',$key);
10457: }
10458:
1.1014 droeschl 10459: # ------------------------------------------------- Get the title of a course
10460:
10461: sub current_course_title {
10462: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10463: }
1.301 www 10464: # ------------------------------------------------- Get the title of a resource
10465:
10466: sub gettitle {
10467: my $urlsymb=shift;
10468: my $symb=&symbread($urlsymb);
1.534 albertel 10469: if ($symb) {
1.620 albertel 10470: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10471: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10472: if (defined($cached)) {
10473: return $result;
10474: }
1.534 albertel 10475: my ($map,$resid,$url)=&decode_symb($symb);
10476: my $title='';
1.907 albertel 10477: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10478: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10479: } else {
10480: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10481: &GDBM_READER(),0640)) {
10482: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10483: $title=$bighash{'title_'.$mapid.'.'.$resid};
10484: untie(%bighash);
10485: }
1.534 albertel 10486: }
10487: $title=~s/\&colon\;/\:/gs;
10488: if ($title) {
1.1159 www 10489: # Remember both $symb and $title for dynamic metadata
10490: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10491: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10492: # Cache this title and then return it
1.599 albertel 10493: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10494: }
10495: $urlsymb=$url;
10496: }
10497: my $title=&metadata($urlsymb,'title');
10498: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10499: return $title;
1.301 www 10500: }
1.613 albertel 10501:
1.614 albertel 10502: sub get_slot {
10503: my ($which,$cnum,$cdom)=@_;
10504: if (!$cnum || !$cdom) {
1.790 albertel 10505: (undef,my $courseid)=&whichuser();
1.620 albertel 10506: $cdom=$env{'course.'.$courseid.'.domain'};
10507: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10508: }
1.703 albertel 10509: my $key=join("\0",'slots',$cdom,$cnum,$which);
10510: my %slotinfo;
10511: if (exists($remembered{$key})) {
10512: $slotinfo{$which} = $remembered{$key};
10513: } else {
10514: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10515: &Apache::lonhomework::showhash(%slotinfo);
10516: my ($tmp)=keys(%slotinfo);
10517: if ($tmp=~/^error:/) { return (); }
10518: $remembered{$key} = $slotinfo{$which};
10519: }
1.616 albertel 10520: if (ref($slotinfo{$which}) eq 'HASH') {
10521: return %{$slotinfo{$which}};
10522: }
10523: return $slotinfo{$which};
1.614 albertel 10524: }
1.1150 raeburn 10525:
10526: sub get_reservable_slots {
10527: my ($cnum,$cdom,$uname,$udom) = @_;
10528: my $now = time;
10529: my $reservable_info;
10530: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10531: if (exists($remembered{$key})) {
10532: $reservable_info = $remembered{$key};
10533: } else {
10534: my %resv;
10535: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10536: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10537: $reservable_info = \%resv;
10538: $remembered{$key} = $reservable_info;
10539: }
10540: return $reservable_info;
10541: }
10542:
10543: sub get_course_slots {
10544: my ($cnum,$cdom) = @_;
10545: my $hashid=$cnum.':'.$cdom;
10546: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10547: if (defined($cached)) {
10548: if (ref($result) eq 'HASH') {
10549: return %{$result};
10550: }
10551: } else {
10552: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10553: my ($tmp) = keys(%slots);
10554: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 10555: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10556: return %slots;
10557: }
10558: }
10559: return;
10560: }
10561:
10562: sub devalidate_slots_cache {
10563: my ($cnum,$cdom)=@_;
10564: my $hashid=$cnum.':'.$cdom;
10565: &devalidate_cache_new('allslots',$hashid);
10566: }
10567:
1.1181 raeburn 10568: sub get_coursechange {
10569: my ($cdom,$cnum) = @_;
10570: if ($cdom eq '' || $cnum eq '') {
10571: return unless ($env{'request.course.id'});
10572: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10573: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10574: }
10575: my $hashid=$cdom.'_'.$cnum;
10576: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10577: if ((defined($cached)) && ($change ne '')) {
10578: return $change;
10579: } else {
10580: my %crshash;
10581: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10582: if ($crshash{'internal.contentchange'} eq '') {
10583: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10584: if ($change eq '') {
10585: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10586: $change = $crshash{'internal.created'};
10587: }
10588: } else {
10589: $change = $crshash{'internal.contentchange'};
10590: }
10591: my $cachetime = 600;
10592: &do_cache_new('crschange',$hashid,$change,$cachetime);
10593: }
10594: return $change;
10595: }
10596:
10597: sub devalidate_coursechange_cache {
10598: my ($cnum,$cdom)=@_;
10599: my $hashid=$cnum.':'.$cdom;
10600: &devalidate_cache_new('crschange',$hashid);
10601: }
10602:
1.31 www 10603: # ------------------------------------------------- Update symbolic store links
10604:
10605: sub symblist {
10606: my ($mapname,%newhash)=@_;
1.438 www 10607: $mapname=&deversion(&declutter($mapname));
1.31 www 10608: my %hash;
1.620 albertel 10609: if (($env{'request.course.fn'}) && (%newhash)) {
10610: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10611: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10612: foreach my $url (keys(%newhash)) {
1.711 albertel 10613: next if ($url eq 'last_known'
10614: && $env{'form.no_update_last_known'});
10615: $hash{declutter($url)}=&encode_symb($mapname,
10616: $newhash{$url}->[1],
10617: $newhash{$url}->[0]);
1.191 harris41 10618: }
1.31 www 10619: if (untie(%hash)) {
10620: return 'ok';
10621: }
10622: }
10623: }
10624: return 'error';
1.212 www 10625: }
10626:
10627: # --------------------------------------------------------------- Verify a symb
10628:
10629: sub symbverify {
1.1190 raeburn 10630: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10631: my $thisfn=$thisurl;
1.439 www 10632: $thisfn=&declutter($thisfn);
1.215 www 10633: # direct jump to resource in page or to a sequence - will construct own symbs
10634: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10635: # check URL part
1.409 www 10636: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10637:
1.431 www 10638: unless ($url eq $thisfn) { return 0; }
1.213 www 10639:
1.216 www 10640: $symb=&symbclean($symb);
1.510 www 10641: $thisurl=&deversion($thisurl);
1.439 www 10642: $thisfn=&deversion($thisfn);
1.213 www 10643:
10644: my %bighash;
10645: my $okay=0;
1.431 www 10646:
1.620 albertel 10647: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10648: &GDBM_READER(),0640)) {
1.1204 raeburn 10649: my $noclutter;
1.1032 raeburn 10650: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10651: $thisurl =~ s/\?.+$//;
1.1204 raeburn 10652: if ($map =~ m{^uploaded/.+\.page$}) {
10653: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10654: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10655: $noclutter = 1;
10656: }
10657: }
10658: my $ids;
10659: if ($noclutter) {
10660: $ids=$bighash{'ids_'.$thisurl};
10661: } else {
10662: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10663: }
1.1102 raeburn 10664: unless ($ids) {
10665: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10666: $ids=$bighash{$idkey};
1.216 www 10667: }
10668: if ($ids) {
10669: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 10670: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 10671: $symb =~ s/\?.+$//;
1.1202 raeburn 10672: }
1.800 albertel 10673: foreach my $id (split(/\,/,$ids)) {
10674: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10675: if (
10676: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 10677: eq $symb) {
10678: if (ref($encstate)) {
10679: $$encstate = $bighash{'encrypted_'.$id};
10680: }
1.620 albertel 10681: if (($env{'request.role.adv'}) ||
1.1101 raeburn 10682: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10683: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 10684: $okay=1;
1.1202 raeburn 10685: last;
1.582 albertel 10686: }
10687: }
1.216 www 10688: }
10689: }
1.213 www 10690: untie(%bighash);
10691: }
10692: return $okay;
1.31 www 10693: }
10694:
1.210 www 10695: # --------------------------------------------------------------- Clean-up symb
10696:
10697: sub symbclean {
10698: my $symb=shift;
1.568 albertel 10699: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10700: # remove version from map
10701: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10702:
1.210 www 10703: # remove version from URL
10704: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10705:
1.507 www 10706: # remove wrapper
10707:
1.510 www 10708: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10709: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10710: return $symb;
1.409 www 10711: }
10712:
10713: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10714:
10715: sub encode_symb {
10716: my ($map,$resid,$url)=@_;
10717: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10718: }
1.409 www 10719:
10720: sub decode_symb {
1.568 albertel 10721: my $symb=shift;
10722: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10723: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10724: return (&fixversion($map),$resid,&fixversion($url));
10725: }
10726:
10727: sub fixversion {
10728: my $fn=shift;
1.609 banghart 10729: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10730: my %bighash;
10731: my $uri=&clutter($fn);
1.620 albertel 10732: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10733: # is this cached?
1.599 albertel 10734: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10735: if (defined($cached)) { return $result; }
10736: # unfortunately not cached, or expired
1.620 albertel 10737: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10738: &GDBM_READER(),0640)) {
10739: if ($bighash{'version_'.$uri}) {
10740: my $version=$bighash{'version_'.$uri};
1.444 www 10741: unless (($version eq 'mostrecent') ||
10742: ($version==&getversion($uri))) {
1.440 www 10743: $uri=~s/\.(\w+)$/\.$version\.$1/;
10744: }
10745: }
10746: untie %bighash;
1.413 www 10747: }
1.599 albertel 10748: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10749: }
10750:
10751: sub deversion {
10752: my $url=shift;
10753: $url=~s/\.\d+\.(\w+)$/\.$1/;
10754: return $url;
1.210 www 10755: }
10756:
1.31 www 10757: # ------------------------------------------------------ Return symb list entry
10758:
10759: sub symbread {
1.249 www 10760: my ($thisfn,$donotrecurse)=@_;
1.1206 raeburn 10761: my $cache_str;
10762: if ($thisfn ne '') {
10763: $cache_str='request.symbread.cached.'.$thisfn;
10764: if ($env{$cache_str} ne '') {
1.1179 raeburn 10765: return $env{$cache_str};
10766: }
1.1206 raeburn 10767: } else {
1.242 www 10768: # no filename provided? try from environment
1.620 albertel 10769: if ($env{'request.symb'}) {
10770: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 10771: }
1.620 albertel 10772: $thisfn=$env{'request.filename'};
1.44 www 10773: }
1.569 albertel 10774: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10775: # is that filename actually a symb? Verify, clean, and return
10776: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10777: if (&symbverify($thisfn,$1)) {
1.620 albertel 10778: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10779: }
1.242 www 10780: }
1.44 www 10781: $thisfn=declutter($thisfn);
1.31 www 10782: my %hash;
1.37 www 10783: my %bighash;
10784: my $syval='';
1.620 albertel 10785: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10786: my $targetfn = $thisfn;
1.609 banghart 10787: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10788: $targetfn = 'adm/wrapper/'.$thisfn;
10789: }
1.687 albertel 10790: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10791: $targetfn=$1;
10792: }
1.620 albertel 10793: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10794: &GDBM_READER(),0640)) {
1.481 raeburn 10795: $syval=$hash{$targetfn};
1.37 www 10796: untie(%hash);
10797: }
10798: # ---------------------------------------------------------- There was an entry
10799: if ($syval) {
1.601 albertel 10800: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10801: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10802: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10803: #return $env{$cache_str}='';
1.601 albertel 10804: #}
10805: #$syval.=$1;
10806: #}
1.37 www 10807: } else {
10808: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10809: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10810: &GDBM_READER(),0640)) {
1.37 www 10811: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10812: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10813: unless ($ids) {
10814: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10815: }
10816: unless ($ids) {
10817: # alias?
10818: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10819: }
1.37 www 10820: if ($ids) {
10821: # ------------------------------------------------------------------- Has ID(s)
10822: my @possibilities=split(/\,/,$ids);
1.39 www 10823: if ($#possibilities==0) {
10824: # ----------------------------------------------- There is only one possibility
1.37 www 10825: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10826: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10827: $resid,$thisfn);
1.249 www 10828: } elsif (!$donotrecurse) {
1.39 www 10829: # ------------------------------------------ There is more than one possibility
10830: my $realpossible=0;
1.800 albertel 10831: foreach my $id (@possibilities) {
10832: my $file=$bighash{'src_'.$id};
1.39 www 10833: if (&allowed('bre',$file)) {
1.800 albertel 10834: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10835: if ($bighash{'map_type_'.$mapid} ne 'page') {
10836: $realpossible++;
1.626 albertel 10837: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10838: $resid,$thisfn);
1.39 www 10839: }
10840: }
1.191 harris41 10841: }
1.39 www 10842: if ($realpossible!=1) { $syval=''; }
1.249 www 10843: } else {
10844: $syval='';
1.37 www 10845: }
10846: }
10847: untie(%bighash)
1.481 raeburn 10848: }
1.31 www 10849: }
1.62 www 10850: if ($syval) {
1.620 albertel 10851: return $env{$cache_str}=$syval;
1.62 www 10852: }
1.31 www 10853: }
1.949 raeburn 10854: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10855: return $env{$cache_str}='';
1.31 www 10856: }
10857:
10858: # ---------------------------------------------------------- Return random seed
10859:
1.32 www 10860: sub numval {
10861: my $txt=shift;
10862: $txt=~tr/A-J/0-9/;
10863: $txt=~tr/a-j/0-9/;
10864: $txt=~tr/K-T/0-9/;
10865: $txt=~tr/k-t/0-9/;
10866: $txt=~tr/U-Z/0-5/;
10867: $txt=~tr/u-z/0-5/;
10868: $txt=~s/\D//g;
1.564 albertel 10869: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10870: return int($txt);
1.368 albertel 10871: }
10872:
1.484 albertel 10873: sub numval2 {
10874: my $txt=shift;
10875: $txt=~tr/A-J/0-9/;
10876: $txt=~tr/a-j/0-9/;
10877: $txt=~tr/K-T/0-9/;
10878: $txt=~tr/k-t/0-9/;
10879: $txt=~tr/U-Z/0-5/;
10880: $txt=~tr/u-z/0-5/;
10881: $txt=~s/\D//g;
10882: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10883: my $total;
10884: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10885: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10886: return int($total);
10887: }
10888:
1.575 albertel 10889: sub numval3 {
10890: use integer;
10891: my $txt=shift;
10892: $txt=~tr/A-J/0-9/;
10893: $txt=~tr/a-j/0-9/;
10894: $txt=~tr/K-T/0-9/;
10895: $txt=~tr/k-t/0-9/;
10896: $txt=~tr/U-Z/0-5/;
10897: $txt=~tr/u-z/0-5/;
10898: $txt=~s/\D//g;
10899: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10900: my $total;
10901: foreach my $val (@txts) { $total+=$val; }
10902: if ($_64bit) { $total=(($total<<32)>>32); }
10903: return $total;
10904: }
10905:
1.675 albertel 10906: sub digest {
10907: my ($data)=@_;
10908: my $digest=&Digest::MD5::md5($data);
10909: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10910: my ($e,$f);
10911: {
10912: use integer;
10913: $e=($a+$b);
10914: $f=($c+$d);
10915: if ($_64bit) {
10916: $e=(($e<<32)>>32);
10917: $f=(($f<<32)>>32);
10918: }
10919: }
10920: if (wantarray) {
10921: return ($e,$f);
10922: } else {
10923: my $g;
10924: {
10925: use integer;
10926: $g=($e+$f);
10927: if ($_64bit) {
10928: $g=(($g<<32)>>32);
10929: }
10930: }
10931: return $g;
10932: }
10933: }
10934:
1.368 albertel 10935: sub latest_rnd_algorithm_id {
1.675 albertel 10936: return '64bit5';
1.366 albertel 10937: }
1.32 www 10938:
1.503 albertel 10939: sub get_rand_alg {
10940: my ($courseid)=@_;
1.790 albertel 10941: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 10942: if ($courseid) {
1.620 albertel 10943: return $env{"course.$courseid.rndseed"};
1.503 albertel 10944: }
10945: return &latest_rnd_algorithm_id();
10946: }
10947:
1.562 albertel 10948: sub validCODE {
10949: my ($CODE)=@_;
10950: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10951: return 0;
10952: }
10953:
1.491 albertel 10954: sub getCODE {
1.620 albertel 10955: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 10956: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10957: defined($Apache::lonhomework::parsing_a_task) ) &&
10958: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 10959: return $Apache::lonhomework::history{'resource.CODE'};
10960: }
10961: return undef;
10962: }
1.1133 foxr 10963: #
10964: # Determines the random seed for a specific context:
10965: #
10966: # parameters:
10967: # symb - in course context the symb for the seed.
10968: # course_id - The course id of the form domain_coursenum.
10969: # domain - Domain for the user.
10970: # course - Course for the user.
10971: # cenv - environment of the course.
10972: #
10973: # NOTE:
10974: # All parameters are picked out of the environment if missing
10975: # or not defined.
10976: # If a symb cannot be determined the current time is used instead.
10977: #
10978: # For a given well defined symb, courside, domain, username,
10979: # and course environment, the seed is reproducible.
10980: #
1.31 www 10981: sub rndseed {
1.1133 foxr 10982: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 10983: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 10984: if (!defined($symb)) {
1.366 albertel 10985: unless ($symb=$wsymb) { return time; }
10986: }
1.1146 foxr 10987: if (!defined $courseid) {
10988: $courseid=$wcourseid;
10989: }
10990: if (!defined $domain) { $domain=$wdomain; }
10991: if (!defined $username) { $username=$wusername }
1.1133 foxr 10992:
10993: my $which;
10994: if (defined($cenv->{'rndseed'})) {
10995: $which = $cenv->{'rndseed'};
10996: } else {
10997: $which =&get_rand_alg($courseid);
10998: }
1.491 albertel 10999: if (defined(&getCODE())) {
1.1133 foxr 11000:
1.675 albertel 11001: if ($which eq '64bit5') {
11002: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11003: } elsif ($which eq '64bit4') {
1.575 albertel 11004: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11005: } else {
11006: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11007: }
1.675 albertel 11008: } elsif ($which eq '64bit5') {
11009: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11010: } elsif ($which eq '64bit4') {
11011: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11012: } elsif ($which eq '64bit3') {
11013: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11014: } elsif ($which eq '64bit2') {
11015: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11016: } elsif ($which eq '64bit') {
11017: return &rndseed_64bit($symb,$courseid,$domain,$username);
11018: }
11019: return &rndseed_32bit($symb,$courseid,$domain,$username);
11020: }
11021:
11022: sub rndseed_32bit {
11023: my ($symb,$courseid,$domain,$username)=@_;
11024: {
11025: use integer;
11026: my $symbchck=unpack("%32C*",$symb) << 27;
11027: my $symbseed=numval($symb) << 22;
11028: my $namechck=unpack("%32C*",$username) << 17;
11029: my $nameseed=numval($username) << 12;
11030: my $domainseed=unpack("%32C*",$domain) << 7;
11031: my $courseseed=unpack("%32C*",$courseid);
11032: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11033: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11034: #&logthis("rndseed :$num:$symb");
1.564 albertel 11035: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11036: return $num;
11037: }
11038: }
11039:
11040: sub rndseed_64bit {
11041: my ($symb,$courseid,$domain,$username)=@_;
11042: {
11043: use integer;
11044: my $symbchck=unpack("%32S*",$symb) << 21;
11045: my $symbseed=numval($symb) << 10;
11046: my $namechck=unpack("%32S*",$username);
11047:
11048: my $nameseed=numval($username) << 21;
11049: my $domainseed=unpack("%32S*",$domain) << 10;
11050: my $courseseed=unpack("%32S*",$courseid);
11051:
11052: my $num1=$symbchck+$symbseed+$namechck;
11053: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11054: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11055: #&logthis("rndseed :$num:$symb");
1.564 albertel 11056: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11057: return "$num1,$num2";
1.155 albertel 11058: }
1.366 albertel 11059: }
11060:
1.443 albertel 11061: sub rndseed_64bit2 {
11062: my ($symb,$courseid,$domain,$username)=@_;
11063: {
11064: use integer;
11065: # strings need to be an even # of cahracters long, it it is odd the
11066: # last characters gets thrown away
11067: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11068: my $symbseed=numval($symb) << 10;
11069: my $namechck=unpack("%32S*",$username.' ');
11070:
11071: my $nameseed=numval($username) << 21;
1.501 albertel 11072: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11073: my $courseseed=unpack("%32S*",$courseid.' ');
11074:
11075: my $num1=$symbchck+$symbseed+$namechck;
11076: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11077: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11078: #&logthis("rndseed :$num:$symb");
1.803 albertel 11079: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11080: return "$num1,$num2";
11081: }
11082: }
11083:
11084: sub rndseed_64bit3 {
11085: my ($symb,$courseid,$domain,$username)=@_;
11086: {
11087: use integer;
11088: # strings need to be an even # of cahracters long, it it is odd the
11089: # last characters gets thrown away
11090: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11091: my $symbseed=numval2($symb) << 10;
11092: my $namechck=unpack("%32S*",$username.' ');
11093:
11094: my $nameseed=numval2($username) << 21;
1.443 albertel 11095: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11096: my $courseseed=unpack("%32S*",$courseid.' ');
11097:
11098: my $num1=$symbchck+$symbseed+$namechck;
11099: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11100: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11101: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11102: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11103:
1.503 albertel 11104: return "$num1:$num2";
1.443 albertel 11105: }
11106: }
11107:
1.575 albertel 11108: sub rndseed_64bit4 {
11109: my ($symb,$courseid,$domain,$username)=@_;
11110: {
11111: use integer;
11112: # strings need to be an even # of cahracters long, it it is odd the
11113: # last characters gets thrown away
11114: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11115: my $symbseed=numval3($symb) << 10;
11116: my $namechck=unpack("%32S*",$username.' ');
11117:
11118: my $nameseed=numval3($username) << 21;
11119: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11120: my $courseseed=unpack("%32S*",$courseid.' ');
11121:
11122: my $num1=$symbchck+$symbseed+$namechck;
11123: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11124: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11125: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11126: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11127:
1.575 albertel 11128: return "$num1:$num2";
11129: }
11130: }
11131:
1.675 albertel 11132: sub rndseed_64bit5 {
11133: my ($symb,$courseid,$domain,$username)=@_;
11134: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11135: return "$num1:$num2";
11136: }
11137:
1.366 albertel 11138: sub rndseed_CODE_64bit {
11139: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11140: {
1.366 albertel 11141: use integer;
1.443 albertel 11142: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11143: my $symbseed=numval2($symb);
1.491 albertel 11144: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11145: my $CODEseed=numval(&getCODE());
1.443 albertel 11146: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11147: my $num1=$symbseed+$CODEchck;
11148: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11149: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11150: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11151: if ($_64bit) { $num1=(($num1<<32)>>32); }
11152: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11153: return "$num1:$num2";
1.366 albertel 11154: }
11155: }
11156:
1.575 albertel 11157: sub rndseed_CODE_64bit4 {
11158: my ($symb,$courseid,$domain,$username)=@_;
11159: {
11160: use integer;
11161: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11162: my $symbseed=numval3($symb);
11163: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11164: my $CODEseed=numval3(&getCODE());
11165: my $courseseed=unpack("%32S*",$courseid.' ');
11166: my $num1=$symbseed+$CODEchck;
11167: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11168: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11169: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11170: if ($_64bit) { $num1=(($num1<<32)>>32); }
11171: if ($_64bit) { $num2=(($num2<<32)>>32); }
11172: return "$num1:$num2";
11173: }
11174: }
11175:
1.675 albertel 11176: sub rndseed_CODE_64bit5 {
11177: my ($symb,$courseid,$domain,$username)=@_;
11178: my $code = &getCODE();
11179: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11180: return "$num1:$num2";
11181: }
11182:
1.366 albertel 11183: sub setup_random_from_rndseed {
11184: my ($rndseed)=@_;
1.503 albertel 11185: if ($rndseed =~/([,:])/) {
11186: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 11187: &Math::Random::random_set_seed(abs($num1),abs($num2));
11188: } else {
11189: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11190: }
1.36 albertel 11191: }
11192:
1.474 albertel 11193: sub latest_receipt_algorithm_id {
1.835 albertel 11194: return 'receipt3';
1.474 albertel 11195: }
11196:
1.480 www 11197: sub recunique {
11198: my $fucourseid=shift;
11199: my $unique;
1.835 albertel 11200: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11201: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11202: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11203: } else {
11204: $unique=$perlvar{'lonReceipt'};
11205: }
11206: return unpack("%32C*",$unique);
11207: }
11208:
11209: sub recprefix {
11210: my $fucourseid=shift;
11211: my $prefix;
1.835 albertel 11212: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11213: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11214: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11215: } else {
11216: $prefix=$perlvar{'lonHostID'};
11217: }
11218: return unpack("%32C*",$prefix);
11219: }
11220:
1.76 www 11221: sub ireceipt {
1.474 albertel 11222: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11223:
11224: my $return =&recprefix($fucourseid).'-';
11225:
11226: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11227: $env{'request.state'} eq 'construct') {
11228: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11229: return $return;
11230: }
11231:
1.76 www 11232: my $cuname=unpack("%32C*",$funame);
11233: my $cudom=unpack("%32C*",$fudom);
11234: my $cucourseid=unpack("%32C*",$fucourseid);
11235: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11236: my $cunique=&recunique($fucourseid);
1.474 albertel 11237: my $cpart=unpack("%32S*",$part);
1.835 albertel 11238: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11239:
1.790 albertel 11240: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11241:
11242: $return.= ($cunique%$cuname+
11243: $cunique%$cudom+
11244: $cusymb%$cuname+
11245: $cusymb%$cudom+
11246: $cucourseid%$cuname+
11247: $cucourseid%$cudom+
11248: $cpart%$cuname+
11249: $cpart%$cudom);
11250: } else {
11251: $return.= ($cunique%$cuname+
11252: $cunique%$cudom+
11253: $cusymb%$cuname+
11254: $cusymb%$cudom+
11255: $cucourseid%$cuname+
11256: $cucourseid%$cudom);
11257: }
11258: return $return;
1.76 www 11259: }
11260:
11261: sub receipt {
1.474 albertel 11262: my ($part)=@_;
1.790 albertel 11263: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11264: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11265: }
1.260 ng 11266:
1.790 albertel 11267: sub whichuser {
11268: my ($passedsymb)=@_;
11269: my ($symb,$courseid,$domain,$name,$publicuser);
11270: if (defined($env{'form.grade_symb'})) {
11271: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11272: my $allowed=&allowed('vgr',$tmp_courseid);
11273: if (!$allowed &&
11274: exists($env{'request.course.sec'}) &&
11275: $env{'request.course.sec'} !~ /^\s*$/) {
11276: $allowed=&allowed('vgr',$tmp_courseid.
11277: '/'.$env{'request.course.sec'});
11278: }
11279: if ($allowed) {
11280: ($symb)=&get_env_multiple('form.grade_symb');
11281: $courseid=$tmp_courseid;
11282: ($domain)=&get_env_multiple('form.grade_domain');
11283: ($name)=&get_env_multiple('form.grade_username');
11284: return ($symb,$courseid,$domain,$name,$publicuser);
11285: }
11286: }
11287: if (!$passedsymb) {
11288: $symb=&symbread();
11289: } else {
11290: $symb=$passedsymb;
11291: }
11292: $courseid=$env{'request.course.id'};
11293: $domain=$env{'user.domain'};
11294: $name=$env{'user.name'};
11295: if ($name eq 'public' && $domain eq 'public') {
11296: if (!defined($env{'form.username'})) {
11297: $env{'form.username'}.=time.rand(10000000);
11298: }
11299: $name.=$env{'form.username'};
11300: }
11301: return ($symb,$courseid,$domain,$name,$publicuser);
11302:
11303: }
11304:
1.36 albertel 11305: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11306: # returns either the contents of the file or
11307: # -1 if the file doesn't exist
1.481 raeburn 11308: #
11309: # if the target is a file that was uploaded via DOCS,
11310: # a check will be made to see if a current copy exists on the local server,
11311: # if it does this will be served, otherwise a copy will be retrieved from
11312: # the home server for the course and stored in /home/httpd/html/userfiles on
11313: # the local server.
1.472 albertel 11314:
1.36 albertel 11315: sub getfile {
1.538 albertel 11316: my ($file) = @_;
1.609 banghart 11317: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11318: &repcopy($file);
11319: return &readfile($file);
11320: }
11321:
11322: sub repcopy_userfile {
11323: my ($file)=@_;
1.1142 raeburn 11324: my $londocroot = $perlvar{'lonDocRoot'};
11325: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11326: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11327: my ($cdom,$cnum,$filename) =
1.811 albertel 11328: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11329: my $uri="/uploaded/$cdom/$cnum/$filename";
11330: if (-e "$file") {
1.828 www 11331: # we already have a local copy, check it out
1.538 albertel 11332: my @fileinfo = stat($file);
1.828 www 11333: my $rtncode;
11334: my $info;
1.538 albertel 11335: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11336: if ($lwpresp ne 'ok') {
1.828 www 11337: # there is no such file anymore, even though we had a local copy
1.482 albertel 11338: if ($rtncode eq '404') {
1.538 albertel 11339: unlink($file);
1.482 albertel 11340: }
11341: return -1;
11342: }
11343: if ($info < $fileinfo[9]) {
1.828 www 11344: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11345: return 'ok';
1.828 www 11346: } else {
11347: # the file is outdated, get rid of it
11348: unlink($file);
1.482 albertel 11349: }
1.828 www 11350: }
11351: # one way or the other, at this point, we don't have the file
11352: # construct the correct path for the file
11353: my @parts = ($cdom,$cnum);
11354: if ($filename =~ m|^(.+)/[^/]+$|) {
11355: push @parts, split(/\//,$1);
11356: }
11357: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11358: foreach my $part (@parts) {
11359: $path .= '/'.$part;
11360: if (!-e $path) {
11361: mkdir($path,0770);
1.482 albertel 11362: }
11363: }
1.828 www 11364: # now the path exists for sure
11365: # get a user agent
11366: my $ua=new LWP::UserAgent;
11367: my $transferfile=$file.'.in.transfer';
11368: # FIXME: this should flock
11369: if (-e $transferfile) { return 'ok'; }
11370: my $request;
11371: $uri=~s/^\///;
1.980 raeburn 11372: my $homeserver = &homeserver($cnum,$cdom);
11373: my $protocol = $protocol{$homeserver};
11374: $protocol = 'http' if ($protocol ne 'https');
11375: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11376: my $response=$ua->request($request,$transferfile);
11377: # did it work?
11378: if ($response->is_error()) {
11379: unlink($transferfile);
11380: &logthis("Userfile repcopy failed for $uri");
11381: return -1;
11382: }
11383: # worked, rename the transfer file
11384: rename($transferfile,$file);
1.607 raeburn 11385: return 'ok';
1.481 raeburn 11386: }
11387:
1.517 albertel 11388: sub tokenwrapper {
11389: my $uri=shift;
1.980 raeburn 11390: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11391: $uri=~s|^/||;
1.620 albertel 11392: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11393: my $token=$1;
1.552 albertel 11394: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11395: if ($udom && $uname && $file) {
11396: $file=~s|(\?\.*)*$||;
1.949 raeburn 11397: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11398: my $homeserver = &homeserver($uname,$udom);
11399: my $protocol = $protocol{$homeserver};
11400: $protocol = 'http' if ($protocol ne 'https');
11401: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11402: (($uri=~/\?/)?'&':'?').'token='.$token.
11403: '&tokenissued='.$perlvar{'lonHostID'};
11404: } else {
11405: return '/adm/notfound.html';
11406: }
11407: }
11408:
1.828 www 11409: # call with reqtype HEAD: get last modification time
11410: # call with reqtype GET: get the file contents
11411: # Do not call this with reqtype GET for large files! It loads everything into memory
11412: #
1.481 raeburn 11413: sub getuploaded {
11414: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11415: $uri=~s/^\///;
1.980 raeburn 11416: my $homeserver = &homeserver($cnum,$cdom);
11417: my $protocol = $protocol{$homeserver};
11418: $protocol = 'http' if ($protocol ne 'https');
11419: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11420: my $ua=new LWP::UserAgent;
11421: my $request=new HTTP::Request($reqtype,$uri);
11422: my $response=$ua->request($request);
11423: $$rtncode = $response->code;
1.482 albertel 11424: if (! $response->is_success()) {
11425: return 'failed';
11426: }
11427: if ($reqtype eq 'HEAD') {
1.486 www 11428: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11429: } elsif ($reqtype eq 'GET') {
11430: $$info = $response->content;
1.472 albertel 11431: }
1.482 albertel 11432: return 'ok';
1.36 albertel 11433: }
11434:
1.481 raeburn 11435: sub readfile {
11436: my $file = shift;
11437: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11438: my $fh;
11439: open($fh,"<$file");
11440: my $a='';
1.800 albertel 11441: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11442: return $a;
11443: }
11444:
1.36 albertel 11445: sub filelocation {
1.590 banghart 11446: my ($dir,$file) = @_;
11447: my $location;
11448: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11449:
11450: if ($file =~ m-^/adm/-) {
11451: $file=~s-^/adm/wrapper/-/-;
11452: $file=~s-^/adm/coursedocs/showdoc/-/-;
11453: }
1.882 albertel 11454:
1.1139 www 11455: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11456: $location = $file;
1.609 banghart 11457: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11458: my ($udom,$uname,$filename)=
1.811 albertel 11459: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11460: my $home=&homeserver($uname,$udom);
11461: my $is_me=0;
11462: my @ids=¤t_machine_ids();
11463: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11464: if ($is_me) {
1.1117 foxr 11465: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11466: } else {
11467: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11468: $udom.'/'.$uname.'/'.$filename;
11469: }
1.882 albertel 11470: } elsif ($file =~ m-^/adm/-) {
11471: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11472: } else {
11473: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11474: $file=~s:^/(res|priv)/:/:;
11475: my $space=$1;
1.590 banghart 11476: if ( !( $file =~ m:^/:) ) {
11477: $location = $dir. '/'.$file;
11478: } else {
1.1142 raeburn 11479: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11480: }
1.59 albertel 11481: }
1.590 banghart 11482: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11483: while ($location=~m{/\.\./}) {
11484: if ($location =~ m{/[^/]+/\.\./}) {
11485: $location=~ s{/[^/]+/\.\./}{/}g;
11486: } else {
11487: $location=~ s{/\.\./}{/}g;
11488: }
11489: } #remove dir/..
1.590 banghart 11490: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11491: return $location;
1.46 www 11492: }
1.36 albertel 11493:
1.46 www 11494: sub hreflocation {
11495: my ($dir,$file)=@_;
1.980 raeburn 11496: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11497: $file=filelocation($dir,$file);
1.700 albertel 11498: } elsif ($file=~m-^/adm/-) {
11499: $file=~s-^/adm/wrapper/-/-;
11500: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11501: }
11502: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11503: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11504: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11505: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11506: {/uploaded/$1/$2/}x;
1.46 www 11507: }
1.913 albertel 11508: if ($file=~ m{^/userfiles/}) {
11509: $file =~ s{^/userfiles/}{/uploaded/};
11510: }
1.462 albertel 11511: return $file;
1.465 albertel 11512: }
11513:
1.1139 www 11514:
11515:
11516:
11517:
1.465 albertel 11518: sub current_machine_domains {
1.853 albertel 11519: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11520: }
11521:
11522: sub machine_domains {
11523: my ($hostname) = @_;
1.465 albertel 11524: my @domains;
1.838 albertel 11525: my %hostname = &all_hostnames();
1.465 albertel 11526: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11527: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11528: if ($hostname eq $name) {
1.844 albertel 11529: push(@domains,&host_domain($id));
1.465 albertel 11530: }
11531: }
11532: return @domains;
11533: }
11534:
11535: sub current_machine_ids {
1.853 albertel 11536: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11537: }
11538:
11539: sub machine_ids {
11540: my ($hostname) = @_;
11541: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11542: my @ids;
1.888 albertel 11543: my %name_to_host = &all_names();
1.889 albertel 11544: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11545: return @{ $name_to_host{$hostname} };
11546: }
11547: return;
1.31 www 11548: }
11549:
1.824 raeburn 11550: sub additional_machine_domains {
11551: my @domains;
11552: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11553: while( my $line = <$fh>) {
11554: $line =~ s/\s//g;
11555: push(@domains,$line);
11556: }
11557: return @domains;
11558: }
11559:
11560: sub default_login_domain {
11561: my $domain = $perlvar{'lonDefDomain'};
11562: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11563: foreach my $posdom (¤t_machine_domains(),
11564: &additional_machine_domains()) {
11565: if (lc($posdom) eq lc($testdomain)) {
11566: $domain=$posdom;
11567: last;
11568: }
11569: }
11570: return $domain;
11571: }
11572:
1.31 www 11573: # ------------------------------------------------------------- Declutters URLs
11574:
11575: sub declutter {
11576: my $thisfn=shift;
1.569 albertel 11577: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 11578: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 11579: $thisfn=~s/^\///;
1.697 albertel 11580: $thisfn=~s|^adm/wrapper/||;
11581: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11582: $thisfn=~s/^res\///;
1.1172 bisitz 11583: $thisfn=~s/^priv\///;
1.1032 raeburn 11584: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11585: $thisfn=~s/\?.+$//;
11586: }
1.268 www 11587: return $thisfn;
11588: }
11589:
11590: # ------------------------------------------------------------- Clutter up URLs
11591:
11592: sub clutter {
11593: my $thisfn='/'.&declutter(shift);
1.887 albertel 11594: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11595: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11596: $thisfn='/res'.$thisfn;
11597: }
1.1031 raeburn 11598: if ($thisfn !~m|^/adm|) {
11599: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11600: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11601: } else {
11602: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11603: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11604: if ($embstyle eq 'ssi'
11605: || ($embstyle eq 'hdn')
11606: || ($embstyle eq 'rat')
11607: || ($embstyle eq 'prv')
11608: || ($embstyle eq 'ign')) {
11609: #do nothing with these
11610: } elsif (($embstyle eq 'img')
1.695 albertel 11611: || ($embstyle eq 'emb')
11612: || ($embstyle eq 'wrp')) {
11613: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11614: } elsif ($embstyle eq 'unk'
11615: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11616: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11617: } else {
1.718 www 11618: # &logthis("Got a blank emb style");
1.695 albertel 11619: }
1.694 albertel 11620: }
11621: }
1.31 www 11622: return $thisfn;
1.12 www 11623: }
11624:
1.787 albertel 11625: sub clutter_with_no_wrapper {
11626: my $uri = &clutter(shift);
11627: if ($uri =~ m-^/adm/-) {
11628: $uri =~ s-^/adm/wrapper/-/-;
11629: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11630: }
11631: return $uri;
11632: }
11633:
1.557 albertel 11634: sub freeze_escape {
11635: my ($value)=@_;
11636: if (ref($value)) {
11637: $value=&nfreeze($value);
11638: return '__FROZEN__'.&escape($value);
11639: }
11640: return &escape($value);
11641: }
11642:
1.11 www 11643:
1.557 albertel 11644: sub thaw_unescape {
11645: my ($value)=@_;
11646: if ($value =~ /^__FROZEN__/) {
11647: substr($value,0,10,undef);
11648: $value=&unescape($value);
11649: return &thaw($value);
11650: }
11651: return &unescape($value);
11652: }
11653:
1.436 albertel 11654: sub correct_line_ends {
11655: my ($result)=@_;
11656: $$result =~s/\r\n/\n/mg;
11657: $$result =~s/\r/\n/mg;
1.415 albertel 11658: }
1.1 albertel 11659: # ================================================================ Main Program
11660:
1.184 www 11661: sub goodbye {
1.204 albertel 11662: &logthis("Starting Shut down");
1.443 albertel 11663: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11664: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11665: #converted
1.599 albertel 11666: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11667: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11668: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11669: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11670: #1.1 only
1.870 albertel 11671: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11672: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11673: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11674: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11675: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11676: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11677: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11678: &flushcourselogs();
11679: &logthis("Shutting down");
11680: }
11681:
1.852 albertel 11682: sub get_dns {
1.1210 raeburn 11683: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11684: if (!$ignore_cache) {
11685: my ($content,$cached)=
11686: &Apache::lonnet::is_cached_new('dns',$url);
11687: if ($cached) {
1.1210 raeburn 11688: &$func($content,$hashref);
1.869 albertel 11689: return;
11690: }
11691: }
11692:
11693: my %alldns;
1.852 albertel 11694: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11695: foreach my $dns (<$config>) {
11696: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11697: my $line = $1;
11698: my ($host,$protocol) = split(/:/,$line);
11699: if ($protocol ne 'https') {
11700: $protocol = 'http';
11701: }
11702: $alldns{$host} = $protocol;
1.869 albertel 11703: }
11704: while (%alldns) {
11705: my ($dns) = keys(%alldns);
1.852 albertel 11706: my $ua=new LWP::UserAgent;
1.1134 raeburn 11707: $ua->timeout(30);
1.979 raeburn 11708: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11709: my $response=$ua->request($request);
1.979 raeburn 11710: delete($alldns{$dns});
1.852 albertel 11711: next if ($response->is_error());
11712: my @content = split("\n",$response->content);
1.1210 raeburn 11713: unless ($nocache) {
1.1219 raeburn 11714: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 11715: }
11716: &$func(\@content,$hashref);
1.869 albertel 11717: return;
1.852 albertel 11718: }
11719: close($config);
1.871 albertel 11720: my $which = (split('/',$url))[3];
11721: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11722: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11723: my @content = <$config>;
1.1210 raeburn 11724: &$func(\@content,$hashref);
11725: return;
11726: }
11727:
11728: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 11729: sub parse_dns_checksums_tab {
1.1210 raeburn 11730: my ($lines,$hashref) = @_;
11731: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11732: my $loncaparev = &get_server_loncaparev($machine_dom);
11733: my ($release,$timestamp) = split(/\-/,$loncaparev);
11734: my (%chksum,%revnum);
11735: if (ref($lines) eq 'ARRAY') {
11736: chomp(@{$lines});
1.1238 raeburn 11737: my $version = shift(@{$lines});
11738: if ($version eq $release) {
1.1210 raeburn 11739: foreach my $line (@{$lines}) {
1.1238 raeburn 11740: my ($file,$version,$shasum) = split(/,/,$line);
11741: $chksum{$file} = $shasum;
11742: $revnum{$file} = $version;
1.1210 raeburn 11743: }
11744: if (ref($hashref) eq 'HASH') {
11745: %{$hashref} = (
11746: sums => \%chksum,
11747: versions => \%revnum,
11748: );
11749: }
11750: }
11751: }
1.869 albertel 11752: return;
1.852 albertel 11753: }
1.1210 raeburn 11754:
11755: sub fetch_dns_checksums {
1.1238 raeburn 11756: my %checksums;
11757: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11758: my $loncaparev = &get_server_loncaparev($machine_dom);
11759: my ($release,$timestamp) = split(/\-/,$loncaparev);
11760: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 11761: \%checksums);
1.1210 raeburn 11762: return \%checksums;
11763: }
11764:
1.327 albertel 11765: # ------------------------------------------------------------ Read domain file
11766: {
1.852 albertel 11767: my $loaded;
1.846 albertel 11768: my %domain;
11769:
1.852 albertel 11770: sub parse_domain_tab {
11771: my ($lines) = @_;
11772: foreach my $line (@$lines) {
11773: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11774:
1.846 albertel 11775: chomp($line);
1.852 albertel 11776: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11777: my %this_domain;
11778: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11779: 'lang_def', 'city', 'longi', 'lati',
11780: 'primary') {
11781: $this_domain{$field} = shift(@elements);
11782: }
11783: $domain{$name} = \%this_domain;
1.852 albertel 11784: }
11785: }
1.864 albertel 11786:
11787: sub reset_domain_info {
11788: undef($loaded);
11789: undef(%domain);
11790: }
11791:
1.852 albertel 11792: sub load_domain_tab {
1.869 albertel 11793: my ($ignore_cache) = @_;
11794: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11795: my $fh;
11796: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11797: my @lines = <$fh>;
11798: &parse_domain_tab(\@lines);
1.448 albertel 11799: }
1.852 albertel 11800: close($fh);
11801: $loaded = 1;
1.327 albertel 11802: }
1.846 albertel 11803:
11804: sub domain {
1.852 albertel 11805: &load_domain_tab() if (!$loaded);
11806:
1.846 albertel 11807: my ($name,$what) = @_;
11808: return if ( !exists($domain{$name}) );
11809:
11810: if (!$what) {
11811: return $domain{$name}{'description'};
11812: }
11813: return $domain{$name}{$what};
11814: }
1.974 raeburn 11815:
11816: sub domain_info {
11817: &load_domain_tab() if (!$loaded);
11818: return %domain;
11819: }
11820:
1.327 albertel 11821: }
11822:
11823:
1.1 albertel 11824: # ------------------------------------------------------------- Read hosts file
11825: {
1.838 albertel 11826: my %hostname;
1.844 albertel 11827: my %hostdom;
1.845 albertel 11828: my %libserv;
1.852 albertel 11829: my $loaded;
1.888 albertel 11830: my %name_to_host;
1.1074 raeburn 11831: my %internetdom;
1.1107 raeburn 11832: my %LC_dns_serv;
1.852 albertel 11833:
11834: sub parse_hosts_tab {
11835: my ($file) = @_;
11836: foreach my $configline (@$file) {
11837: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11838: chomp($configline);
11839: if ($configline =~ /^\^/) {
11840: if ($configline =~ /^\^([\w.\-]+)/) {
11841: $LC_dns_serv{$1} = 1;
11842: }
11843: next;
11844: }
1.1074 raeburn 11845: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11846: $name=~s/\s//g;
11847: if ($id && $domain && $role && $name) {
11848: $hostname{$id}=$name;
1.888 albertel 11849: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11850: $hostdom{$id}=$domain;
11851: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11852: if (defined($protocol)) {
11853: if ($protocol eq 'https') {
11854: $protocol{$id} = $protocol;
11855: } else {
11856: $protocol{$id} = 'http';
11857: }
1.968 raeburn 11858: } else {
1.969 raeburn 11859: $protocol{$id} = 'http';
1.968 raeburn 11860: }
1.1074 raeburn 11861: if (defined($intdom)) {
11862: $internetdom{$id} = $intdom;
11863: }
1.852 albertel 11864: }
11865: }
11866: }
1.864 albertel 11867:
11868: sub reset_hosts_info {
1.897 albertel 11869: &purge_remembered();
1.864 albertel 11870: &reset_domain_info();
11871: &reset_hosts_ip_info();
1.892 albertel 11872: undef(%name_to_host);
1.864 albertel 11873: undef(%hostname);
11874: undef(%hostdom);
11875: undef(%libserv);
11876: undef($loaded);
11877: }
1.1 albertel 11878:
1.852 albertel 11879: sub load_hosts_tab {
1.869 albertel 11880: my ($ignore_cache) = @_;
11881: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11882: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11883: my @config = <$config>;
11884: &parse_hosts_tab(\@config);
11885: close($config);
11886: $loaded=1;
1.1 albertel 11887: }
1.852 albertel 11888:
1.838 albertel 11889: sub hostname {
1.852 albertel 11890: &load_hosts_tab() if (!$loaded);
11891:
1.838 albertel 11892: my ($lonid) = @_;
11893: return $hostname{$lonid};
11894: }
1.845 albertel 11895:
1.838 albertel 11896: sub all_hostnames {
1.852 albertel 11897: &load_hosts_tab() if (!$loaded);
11898:
1.838 albertel 11899: return %hostname;
11900: }
1.845 albertel 11901:
1.888 albertel 11902: sub all_names {
11903: &load_hosts_tab() if (!$loaded);
11904:
11905: return %name_to_host;
11906: }
11907:
1.974 raeburn 11908: sub all_host_domain {
11909: &load_hosts_tab() if (!$loaded);
11910: return %hostdom;
11911: }
11912:
1.845 albertel 11913: sub is_library {
1.852 albertel 11914: &load_hosts_tab() if (!$loaded);
11915:
1.845 albertel 11916: return exists($libserv{$_[0]});
11917: }
11918:
11919: sub all_library {
1.852 albertel 11920: &load_hosts_tab() if (!$loaded);
11921:
1.845 albertel 11922: return %libserv;
11923: }
11924:
1.1062 droeschl 11925: sub unique_library {
11926: #2x reverse removes all hostnames that appear more than once
11927: my %unique = reverse &all_library();
11928: return reverse %unique;
11929: }
11930:
1.841 albertel 11931: sub get_servers {
1.852 albertel 11932: &load_hosts_tab() if (!$loaded);
11933:
1.841 albertel 11934: my ($domain,$type) = @_;
11935: my %possible_hosts = ($type eq 'library') ? %libserv
11936: : %hostname;
11937: my %result;
1.842 albertel 11938: if (ref($domain) eq 'ARRAY') {
11939: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 11940: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 11941: $result{$host} = $hostname;
11942: }
11943: }
11944: } else {
11945: while ( my ($host,$hostname) = each(%possible_hosts)) {
11946: if ($hostdom{$host} eq $domain) {
11947: $result{$host} = $hostname;
11948: }
1.841 albertel 11949: }
11950: }
11951: return %result;
11952: }
1.845 albertel 11953:
1.1062 droeschl 11954: sub get_unique_servers {
11955: my %unique = reverse &get_servers(@_);
11956: return reverse %unique;
11957: }
11958:
1.844 albertel 11959: sub host_domain {
1.852 albertel 11960: &load_hosts_tab() if (!$loaded);
11961:
1.844 albertel 11962: my ($lonid) = @_;
11963: return $hostdom{$lonid};
11964: }
11965:
1.841 albertel 11966: sub all_domains {
1.852 albertel 11967: &load_hosts_tab() if (!$loaded);
11968:
1.841 albertel 11969: my %seen;
11970: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11971: return @uniq;
11972: }
1.1074 raeburn 11973:
11974: sub internet_dom {
11975: &load_hosts_tab() if (!$loaded);
11976:
11977: my ($lonid) = @_;
11978: return $internetdom{$lonid};
11979: }
1.1107 raeburn 11980:
11981: sub is_LC_dns {
11982: &load_hosts_tab() if (!$loaded);
11983:
11984: my ($hostname) = @_;
11985: return exists($LC_dns_serv{$hostname});
11986: }
11987:
1.1 albertel 11988: }
11989:
1.847 albertel 11990: {
11991: my %iphost;
1.856 albertel 11992: my %name_to_ip;
11993: my %lonid_to_ip;
1.869 albertel 11994:
1.847 albertel 11995: sub get_hosts_from_ip {
11996: my ($ip) = @_;
11997: my %iphosts = &get_iphost();
11998: if (ref($iphosts{$ip})) {
11999: return @{$iphosts{$ip}};
12000: }
12001: return;
1.839 albertel 12002: }
1.864 albertel 12003:
12004: sub reset_hosts_ip_info {
12005: undef(%iphost);
12006: undef(%name_to_ip);
12007: undef(%lonid_to_ip);
12008: }
1.856 albertel 12009:
12010: sub get_host_ip {
12011: my ($lonid) = @_;
12012: if (exists($lonid_to_ip{$lonid})) {
12013: return $lonid_to_ip{$lonid};
12014: }
12015: my $name=&hostname($lonid);
12016: my $ip = gethostbyname($name);
12017: return if (!$ip || length($ip) ne 4);
12018: $ip=inet_ntoa($ip);
12019: $name_to_ip{$name} = $ip;
12020: $lonid_to_ip{$lonid} = $ip;
12021: return $ip;
12022: }
1.847 albertel 12023:
12024: sub get_iphost {
1.869 albertel 12025: my ($ignore_cache) = @_;
1.894 albertel 12026:
1.869 albertel 12027: if (!$ignore_cache) {
12028: if (%iphost) {
12029: return %iphost;
12030: }
12031: my ($ip_info,$cached)=
12032: &Apache::lonnet::is_cached_new('iphost','iphost');
12033: if ($cached) {
12034: %iphost = %{$ip_info->[0]};
12035: %name_to_ip = %{$ip_info->[1]};
12036: %lonid_to_ip = %{$ip_info->[2]};
12037: return %iphost;
12038: }
12039: }
1.894 albertel 12040:
12041: # get yesterday's info for fallback
12042: my %old_name_to_ip;
12043: my ($ip_info,$cached)=
12044: &Apache::lonnet::is_cached_new('iphost','iphost');
12045: if ($cached) {
12046: %old_name_to_ip = %{$ip_info->[1]};
12047: }
12048:
1.888 albertel 12049: my %name_to_host = &all_names();
12050: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12051: my $ip;
12052: if (!exists($name_to_ip{$name})) {
12053: $ip = gethostbyname($name);
12054: if (!$ip || length($ip) ne 4) {
1.894 albertel 12055: if (defined($old_name_to_ip{$name})) {
12056: $ip = $old_name_to_ip{$name};
12057: &logthis("Can't find $name defaulting to old $ip");
12058: } else {
12059: &logthis("Name $name no IP found");
12060: next;
12061: }
12062: } else {
12063: $ip=inet_ntoa($ip);
1.847 albertel 12064: }
12065: $name_to_ip{$name} = $ip;
12066: } else {
12067: $ip = $name_to_ip{$name};
1.653 albertel 12068: }
1.888 albertel 12069: foreach my $id (@{ $name_to_host{$name} }) {
12070: $lonid_to_ip{$id} = $ip;
12071: }
12072: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12073: }
1.1219 raeburn 12074: &do_cache_new('iphost','iphost',
12075: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12076: 48*60*60);
1.869 albertel 12077:
1.847 albertel 12078: return %iphost;
1.598 albertel 12079: }
12080:
1.992 raeburn 12081: #
12082: # Given a DNS returns the loncapa host name for that DNS
12083: #
12084: sub host_from_dns {
12085: my ($dns) = @_;
12086: my @hosts;
12087: my $ip;
12088:
1.993 raeburn 12089: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12090: $ip = $name_to_ip{$dns};
12091: }
12092: if (!$ip) {
12093: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12094: if (length($ip) == 4) {
12095: $ip = &IO::Socket::inet_ntoa($ip);
12096: }
12097: }
12098: if ($ip) {
12099: @hosts = get_hosts_from_ip($ip);
12100: return $hosts[0];
12101: }
12102: return undef;
1.986 foxr 12103: }
1.992 raeburn 12104:
1.1074 raeburn 12105: sub get_internet_names {
12106: my ($lonid) = @_;
12107: return if ($lonid eq '');
12108: my ($idnref,$cached)=
12109: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12110: if ($cached) {
12111: return $idnref;
12112: }
12113: my $ip = &get_host_ip($lonid);
12114: my @hosts = &get_hosts_from_ip($ip);
12115: my %iphost = &get_iphost();
12116: my (@idns,%seen);
12117: foreach my $id (@hosts) {
12118: my $dom = &host_domain($id);
12119: my $prim_id = &domain($dom,'primary');
12120: my $prim_ip = &get_host_ip($prim_id);
12121: next if ($seen{$prim_ip});
12122: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12123: foreach my $id (@{$iphost{$prim_ip}}) {
12124: my $intdom = &internet_dom($id);
12125: unless (grep(/^\Q$intdom\E$/,@idns)) {
12126: push(@idns,$intdom);
12127: }
12128: }
12129: }
12130: $seen{$prim_ip} = 1;
12131: }
1.1219 raeburn 12132: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12133: }
12134:
1.986 foxr 12135: }
12136:
1.1079 raeburn 12137: sub all_loncaparevs {
12138: 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);
12139: }
12140:
1.1227 raeburn 12141: # ---------------------------------------------------------- Read loncaparev table
12142: {
12143: sub load_loncaparevs {
12144: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12145: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12146: while (my $configline=<$config>) {
12147: chomp($configline);
12148: my ($hostid,$loncaparev)=split(/:/,$configline);
12149: $loncaparevs{$hostid}=$loncaparev;
12150: }
12151: close($config);
12152: }
12153: }
12154: }
12155: }
12156:
12157: # ---------------------------------------------------------- Read serverhostID table
12158: {
12159: sub load_serverhomeIDs {
12160: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12161: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12162: while (my $configline=<$config>) {
12163: chomp($configline);
12164: my ($name,$id)=split(/:/,$configline);
12165: $serverhomeIDs{$name}=$id;
12166: }
12167: close($config);
12168: }
12169: }
12170: }
12171: }
12172:
12173:
1.862 albertel 12174: BEGIN {
12175:
12176: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12177: unless ($readit) {
12178: {
12179: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12180: %perlvar = (%perlvar,%{$configvars});
12181: }
12182:
12183:
1.1 albertel 12184: # ------------------------------------------------------ Read spare server file
12185: {
1.448 albertel 12186: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12187:
12188: while (my $configline=<$config>) {
12189: chomp($configline);
1.284 matthew 12190: if ($configline) {
1.784 albertel 12191: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12192: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12193: push(@{ $spareid{$type} }, $host);
1.1 albertel 12194: }
12195: }
1.448 albertel 12196: close($config);
1.1 albertel 12197: }
1.11 www 12198: # ------------------------------------------------------------ Read permissions
12199: {
1.448 albertel 12200: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12201:
12202: while (my $configline=<$config>) {
1.448 albertel 12203: chomp($configline);
12204: if ($configline) {
12205: my ($role,$perm)=split(/ /,$configline);
12206: if ($perm ne '') { $pr{$role}=$perm; }
12207: }
1.11 www 12208: }
1.448 albertel 12209: close($config);
1.11 www 12210: }
12211:
12212: # -------------------------------------------- Read plain texts for permissions
12213: {
1.448 albertel 12214: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12215:
12216: while (my $configline=<$config>) {
1.448 albertel 12217: chomp($configline);
12218: if ($configline) {
1.742 raeburn 12219: my ($short,@plain)=split(/:/,$configline);
12220: %{$prp{$short}} = ();
12221: if (@plain > 0) {
12222: $prp{$short}{'std'} = $plain[0];
12223: for (my $i=1; $i<@plain; $i++) {
12224: $prp{$short}{'alt'.$i} = $plain[$i];
12225: }
12226: }
1.448 albertel 12227: }
1.135 www 12228: }
1.448 albertel 12229: close($config);
1.135 www 12230: }
12231:
12232: # ---------------------------------------------------------- Read package table
12233: {
1.448 albertel 12234: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12235:
12236: while (my $configline=<$config>) {
1.483 albertel 12237: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12238: chomp($configline);
12239: my ($short,$plain)=split(/:/,$configline);
12240: my ($pack,$name)=split(/\&/,$short);
12241: if ($plain ne '') {
12242: $packagetab{$pack.'&'.$name.'&name'}=$name;
12243: $packagetab{$short}=$plain;
12244: }
1.11 www 12245: }
1.448 albertel 12246: close($config);
1.329 matthew 12247: }
12248:
1.1073 raeburn 12249: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 12250:
12251: &load_loncaparevs();
1.1073 raeburn 12252:
1.1074 raeburn 12253: # ---------------------------------------------------------- Read serverhostID table
12254:
1.1227 raeburn 12255: &load_serverhomeIDs();
12256:
12257: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12258: {
12259: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12260: if (-e $file) {
12261: my $parser = HTML::LCParser->new($file);
12262: while (my $token = $parser->get_token()) {
12263: if ($token->[0] eq 'S') {
12264: my $item = $token->[1];
12265: my $name = $token->[2]{'name'};
12266: my $value = $token->[2]{'value'};
12267: if ($item ne '' && $name ne '' && $value ne '') {
12268: my $release = $parser->get_text();
12269: $release =~ s/(^\s*|\s*$ )//gx;
12270: $needsrelease{$item.':'.$name.':'.$value} = $release;
12271: }
12272: }
12273: }
12274: }
1.1073 raeburn 12275: }
12276:
1.1138 raeburn 12277: # ---------------------------------------------------------- Read managers table
12278: {
12279: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12280: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12281: while (my $configline=<$config>) {
12282: chomp($configline);
12283: next if ($configline =~ /^\#/);
12284: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12285: $managerstab{$configline} = 1;
12286: }
12287: }
12288: close($config);
12289: }
12290: }
12291: }
12292:
1.329 matthew 12293: # ------------- set up temporary directory
12294: {
1.1117 foxr 12295: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12296:
1.11 www 12297: }
12298:
1.794 albertel 12299: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12300: 'compress_threshold'=> 20_000,
12301: });
1.185 www 12302:
1.281 www 12303: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12304: $dumpcount=0;
1.958 www 12305: $locknum=0;
1.22 www 12306:
1.163 harris41 12307: &logtouch();
1.672 albertel 12308: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12309: $readit=1;
1.564 albertel 12310: {
12311: use integer;
12312: my $test=(2**32)+1;
1.568 albertel 12313: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12314: &logthis(" Detected 64bit platform ($_64bit)");
12315: }
1.195 www 12316: }
1.1 albertel 12317: }
1.179 www 12318:
1.1 albertel 12319: 1;
1.191 harris41 12320: __END__
12321:
1.243 albertel 12322: =pod
12323:
1.191 harris41 12324: =head1 NAME
12325:
1.243 albertel 12326: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12327:
12328: =head1 SYNOPSIS
12329:
1.243 albertel 12330: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12331:
12332: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12333:
1.243 albertel 12334: Common parameters:
12335:
12336: =over 4
12337:
12338: =item *
12339:
12340: $uname : an internal username (if $cname expecting a course Id specifically)
12341:
12342: =item *
12343:
12344: $udom : a domain (if $cdom expecting a course's domain specifically)
12345:
12346: =item *
12347:
12348: $symb : a resource instance identifier
12349:
12350: =item *
12351:
12352: $namespace : the name of a .db file that contains the data needed or
12353: being set.
12354:
12355: =back
12356:
1.394 bowersj2 12357: =head1 OVERVIEW
1.191 harris41 12358:
1.394 bowersj2 12359: lonnet provides subroutines which interact with the
12360: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12361: about classes, users, and resources.
1.243 albertel 12362:
12363: For many of these objects you can also use this to store data about
12364: them or modify them in various ways.
1.191 harris41 12365:
1.394 bowersj2 12366: =head2 Symbs
1.191 harris41 12367:
1.394 bowersj2 12368: To identify a specific instance of a resource, LON-CAPA uses symbols
12369: or "symbs"X<symb>. These identifiers are built from the URL of the
12370: map, the resource number of the resource in the map, and the URL of
12371: the resource itself. The latter is somewhat redundant, but might help
12372: if maps change.
12373:
12374: An example is
12375:
12376: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12377:
12378: The respective map entry is
12379:
12380: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12381: title="Problem 2">
12382: </resource>
12383:
12384: Symbs are used by the random number generator, as well as to store and
12385: restore data specific to a certain instance of for example a problem.
12386:
12387: =head2 Storing And Retrieving Data
12388:
12389: X<store()>X<cstore()>X<restore()>Three of the most important functions
12390: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12391: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12392: is is the non-critical message twin of cstore. These functions are for
12393: handlers to store a perl hash to a user's permanent data space in an
12394: easy manner, and to retrieve it again on another call. It is expected
12395: that a handler would use this once at the beginning to retrieve data,
12396: and then again once at the end to send only the new data back.
12397:
12398: The data is stored in the user's data directory on the user's
12399: homeserver under the ID of the course.
12400:
12401: The hash that is returned by restore will have all of the previous
12402: value for all of the elements of the hash.
12403:
12404: Example:
12405:
12406: #creating a hash
12407: my %hash;
12408: $hash{'foo'}='bar';
12409:
12410: #storing it
12411: &Apache::lonnet::cstore(\%hash);
12412:
12413: #changing a value
12414: $hash{'foo'}='notbar';
12415:
12416: #adding a new value
12417: $hash{'bar'}='foo';
12418: &Apache::lonnet::cstore(\%hash);
12419:
12420: #retrieving the hash
12421: my %history=&Apache::lonnet::restore();
12422:
12423: #print the hash
12424: foreach my $key (sort(keys(%history))) {
12425: print("\%history{$key} = $history{$key}");
12426: }
12427:
12428: Will print out:
1.191 harris41 12429:
1.394 bowersj2 12430: %history{1:foo} = bar
12431: %history{1:keys} = foo:timestamp
12432: %history{1:timestamp} = 990455579
12433: %history{2:bar} = foo
12434: %history{2:foo} = notbar
12435: %history{2:keys} = foo:bar:timestamp
12436: %history{2:timestamp} = 990455580
12437: %history{bar} = foo
12438: %history{foo} = notbar
12439: %history{timestamp} = 990455580
12440: %history{version} = 2
12441:
12442: Note that the special hash entries C<keys>, C<version> and
12443: C<timestamp> were added to the hash. C<version> will be equal to the
12444: total number of versions of the data that have been stored. The
12445: C<timestamp> attribute will be the UNIX time the hash was
12446: stored. C<keys> is available in every historical section to list which
12447: keys were added or changed at a specific historical revision of a
12448: hash.
12449:
12450: B<Warning>: do not store the hash that restore returns directly. This
12451: will cause a mess since it will restore the historical keys as if the
12452: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12453:
1.394 bowersj2 12454: Calling convention:
1.191 harris41 12455:
1.1225 raeburn 12456: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12457: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12458:
1.394 bowersj2 12459: For more detailed information, see lonnet specific documentation.
1.191 harris41 12460:
1.394 bowersj2 12461: =head1 RETURN MESSAGES
1.191 harris41 12462:
1.394 bowersj2 12463: =over 4
1.191 harris41 12464:
1.394 bowersj2 12465: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12466:
1.394 bowersj2 12467: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12468: when the connection is brought back up
1.191 harris41 12469:
1.394 bowersj2 12470: =item * B<con_failed>: unable to contact remote host and unable to save message
12471: for later delivery
1.191 harris41 12472:
1.967 bisitz 12473: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12474:
1.394 bowersj2 12475: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12476: that was requested
1.191 harris41 12477:
1.243 albertel 12478: =back
1.191 harris41 12479:
1.243 albertel 12480: =head1 PUBLIC SUBROUTINES
1.191 harris41 12481:
1.243 albertel 12482: =head2 Session Environment Functions
1.191 harris41 12483:
1.243 albertel 12484: =over 4
1.191 harris41 12485:
1.394 bowersj2 12486: =item *
12487: X<appenv()>
1.949 raeburn 12488: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12489: the user envirnoment file, and will be restored for each access this
1.620 albertel 12490: user makes during this session, also modifies the %env for the current
1.949 raeburn 12491: process. Optional rolesarrayref - if defined contains a reference to an array
12492: of roles which are exempt from the restriction on modifying user.role entries
12493: in the user's environment.db and in %env.
1.191 harris41 12494:
12495: =item *
1.394 bowersj2 12496: X<delenv()>
1.987 raeburn 12497: B<delenv($delthis,$regexp)>: removes all items from the session
12498: environment file that begin with $delthis. If the
12499: optional second arg - $regexp - is true, $delthis is treated as a
12500: regular expression, otherwise \Q$delthis\E is used.
12501: The values are also deleted from the current processes %env.
1.191 harris41 12502:
1.795 albertel 12503: =item * get_env_multiple($name)
12504:
12505: gets $name from the %env hash, it seemlessly handles the cases where multiple
12506: values may be defined and end up as an array ref.
12507:
12508: returns an array of values
12509:
1.243 albertel 12510: =back
12511:
12512: =head2 User Information
1.191 harris41 12513:
1.243 albertel 12514: =over 4
1.191 harris41 12515:
12516: =item *
1.394 bowersj2 12517: X<queryauthenticate()>
12518: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12519: authentication scheme
12520:
12521: =item *
1.394 bowersj2 12522: X<authenticate()>
1.1073 raeburn 12523: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12524: authenticate user from domain's lib servers (first use the current
12525: one). C<$upass> should be the users password.
1.1073 raeburn 12526: $checkdefauth is optional (value is 1 if a check should be made to
12527: authenticate user using default authentication method, and allow
12528: account creation if username does not have account in the domain).
12529: $clientcancheckhost is optional (value is 1 if checking whether the
12530: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12531:
12532: =item *
1.394 bowersj2 12533: X<homeserver()>
12534: B<homeserver($uname,$udom)>: find the server which has
12535: the user's directory and files (there must be only one), this caches
12536: the answer, and also caches if there is a borken connection.
1.191 harris41 12537:
12538: =item *
1.394 bowersj2 12539: X<idget()>
12540: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12541: (IDs are a unique resource in a domain, there must be only 1 ID per
12542: username, and only 1 username per ID in a specific domain) (returns
12543: hash: id=>name,id=>name)
1.191 harris41 12544:
12545: =item *
1.394 bowersj2 12546: X<idrget()>
12547: B<idrget($udom,@unames)>: find the IDs behind a list of
12548: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12549:
12550: =item *
1.394 bowersj2 12551: X<idput()>
12552: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12553:
12554: =item *
1.394 bowersj2 12555: X<rolesinit()>
1.1169 droeschl 12556: B<rolesinit($udom,$username)>: get user privileges.
12557: returns user role, first access and timer interval hashes
1.243 albertel 12558:
12559: =item *
1.1171 droeschl 12560: X<privileged()>
12561: B<privileged($username,$domain)>: returns a true if user has a
12562: privileged and active role (i.e. su or dc), false otherwise.
12563:
12564: =item *
1.551 albertel 12565: X<getsection()>
12566: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12567: course $cname, return section name/number or '' for "not in course"
12568: and '-1' for "no section"
12569:
12570: =item *
1.394 bowersj2 12571: X<userenvironment()>
12572: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12573: passed in @what from the requested user's environment, returns a hash
12574:
1.858 raeburn 12575: =item *
12576: X<userlog_query()>
1.859 albertel 12577: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12578: activity.log file. %filters defines filters applied when parsing the
12579: log file. These can be start or end timestamps, or the type of action
12580: - log to look for Login or Logout events, check for Checkin or
12581: Checkout, role for role selection. The response is in the form
12582: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12583: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12584:
1.243 albertel 12585: =back
12586:
12587: =head2 User Roles
12588:
12589: =over 4
12590:
12591: =item *
12592:
1.810 raeburn 12593: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12594: F: full access
12595: U,I,K: authentication modes (cxx only)
12596: '': forbidden
12597: 1: user needs to choose course
12598: 2: browse allowed
1.766 albertel 12599: A: passphrase authentication needed
1.243 albertel 12600:
12601: =item *
12602:
1.1192 raeburn 12603: constructaccess($url,$setpriv) : check for access to construction space URL
12604:
12605: See if the owner domain and name in the URL match those in the
12606: expected environment. If so, return three element list
12607: ($ownername,$ownerdomain,$ownerhome).
12608:
12609: Otherwise return the null string.
12610:
12611: If second argument 'setpriv' is true, it assigns the privileges,
12612: and returns the same three element list, unless the owner has
12613: blocked "ad hoc" Domain Coordinator access to the Author Space,
12614: in which case the null string is returned.
12615:
12616: =item *
12617:
1.243 albertel 12618: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12619: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12620: and course level
12621:
12622: =item *
12623:
1.988 raeburn 12624: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12625: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12626: $type is Course (default) or Community.
1.988 raeburn 12627: If $forcedefault evaluates to true, text returned will be default
12628: text for $type. Otherwise, if this is a course, the text returned
12629: will be a custom name for the role (if defined in the course's
12630: environment). If no custom name is defined the default is returned.
12631:
1.832 raeburn 12632: =item *
12633:
1.1219 raeburn 12634: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12635: All arguments are optional. Returns a hash of a roles, either for
12636: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12637: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12638: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12639: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12640: For each key, value is set to colon-separated start and end times for
12641: the role. If no username and domain are specified, will default to
1.934 raeburn 12642: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12643: of role statuses (active, future or previous), roles
12644: (e.g., cc,in, st etc.) and domains of the roles which can be used
12645: to restrict the list of roles reported. If no array ref is
12646: provided for types, will default to return only active roles.
1.834 albertel 12647:
1.1195 raeburn 12648: =item *
12649:
12650: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 12651: user: $uname:$udom has a role in the course: $cdom_$cnum.
12652:
12653: Additional optional arguments are: $type (if role checking is to be restricted
12654: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 12655: available roles) or future (roles available in the future), and
12656: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 12657: have active Domain Coordinator role in course's domain or in additional
12658: domains (specified in 'Domains to check for privileged users' in course
12659: environment -- set via: Course Settings -> Classlists and staff listing).
12660:
12661: =item *
12662:
12663: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12664: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12665: $possdomains and $possroles are optional array refs -- to domains to check and
12666: roles to check. If $possdomains is not specified, a dump will be done of the
12667: users' roles.db to check for a dc or su role in any domain. This can be
12668: time consuming if &privileged is called repeatedly (e.g., when displaying a
12669: classlist), so in such cases, supplying a $possdomains array is preferred, as
12670: this then allows &privileged_by_domain() to be used, which caches the identity
12671: of privileged users, eliminating the need for repeated calls to &dump().
12672:
12673: =item *
12674:
12675: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12676: where the outer hash keys are domains specified in the $possdomains array ref,
12677: next inner hash keys are privileged roles specified in the $roles array ref,
12678: and the innermost hash contains key = value pairs for username:domain = end:start
12679: for active or future "privileged" users with that role in that domain. To avoid
12680: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12681: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 12682:
1.243 albertel 12683: =back
12684:
12685: =head2 User Modification
12686:
12687: =over 4
12688:
12689: =item *
12690:
1.957 raeburn 12691: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12692: user for the level given by URL. Optional start and end dates (leave empty
12693: string or zero for "no date")
1.191 harris41 12694:
12695: =item *
12696:
1.243 albertel 12697: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12698: change a users, password, possible return values are: ok,
12699: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12700: refused
1.191 harris41 12701:
12702: =item *
12703:
1.243 albertel 12704: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12705:
12706: =item *
12707:
1.1058 raeburn 12708: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12709: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12710:
12711: will update user information (firstname,middlename,lastname,generation,
12712: permanentemail), and if forceid is true, student/employee ID also.
12713: A user's institutional affiliation(s) can also be updated.
12714: User information fields will not be overwritten with empty entries
12715: unless the field is included in the $candelete array reference.
12716: This array is included when a single user is modified via "Manage Users",
12717: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12718:
12719: =item *
12720:
1.286 matthew 12721: modifystudent
12722:
1.957 raeburn 12723: modify a student's enrollment and identification information.
1.1235 raeburn 12724: The course id is resolved based on the current user's environment.
12725: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12726: associated with a course.
12727:
1.297 matthew 12728: This call is essentially a wrapper for lonnet::modifyuser and
12729: lonnet::modify_student_enrollment
1.286 matthew 12730:
12731: Inputs:
12732:
12733: =over 4
12734:
1.957 raeburn 12735: =item B<$udom> Student's loncapa domain
1.286 matthew 12736:
1.957 raeburn 12737: =item B<$uname> Student's loncapa login name
1.286 matthew 12738:
1.964 bisitz 12739: =item B<$uid> Student/Employee ID
1.286 matthew 12740:
1.957 raeburn 12741: =item B<$umode> Student's authentication mode
1.286 matthew 12742:
1.957 raeburn 12743: =item B<$upass> Student's password
1.286 matthew 12744:
1.957 raeburn 12745: =item B<$first> Student's first name
1.286 matthew 12746:
1.957 raeburn 12747: =item B<$middle> Student's middle name
1.286 matthew 12748:
1.957 raeburn 12749: =item B<$last> Student's last name
1.286 matthew 12750:
1.957 raeburn 12751: =item B<$gene> Student's generation
1.286 matthew 12752:
1.957 raeburn 12753: =item B<$usec> Student's section in course
1.286 matthew 12754:
12755: =item B<$end> Unix time of the roles expiration
12756:
12757: =item B<$start> Unix time of the roles start date
12758:
12759: =item B<$forceid> If defined, allow $uid to be changed
12760:
12761: =item B<$desiredhome> server to use as home server for student
12762:
1.957 raeburn 12763: =item B<$email> Student's permanent e-mail address
12764:
12765: =item B<$type> Type of enrollment (auto or manual)
12766:
1.963 raeburn 12767: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12768:
12769: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12770:
1.963 raeburn 12771: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12772:
1.963 raeburn 12773: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12774:
1.1216 raeburn 12775: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12776:
12777: =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 12778:
1.286 matthew 12779: =back
1.297 matthew 12780:
12781: =item *
12782:
12783: modify_student_enrollment
12784:
1.1235 raeburn 12785: Change a student's enrollment status in a class. The environment variable
1.297 matthew 12786: 'role.request.course' must be defined for this function to proceed.
12787:
12788: Inputs:
12789:
12790: =over 4
12791:
1.1235 raeburn 12792: =item $udom, student's domain
1.297 matthew 12793:
1.1235 raeburn 12794: =item $uname, student's name
1.297 matthew 12795:
1.1235 raeburn 12796: =item $uid, student's user id
1.297 matthew 12797:
1.1235 raeburn 12798: =item $first, student's first name
1.297 matthew 12799:
12800: =item $middle
12801:
12802: =item $last
12803:
12804: =item $gene
12805:
12806: =item $usec
12807:
12808: =item $end
12809:
12810: =item $start
12811:
1.957 raeburn 12812: =item $type
12813:
12814: =item $locktype
12815:
12816: =item $cid
12817:
12818: =item $selfenroll
12819:
12820: =item $context
12821:
1.1216 raeburn 12822: =item $credits, number of credits student will earn from this class
12823:
1.297 matthew 12824: =back
12825:
1.191 harris41 12826:
12827: =item *
12828:
1.243 albertel 12829: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12830: custom role; give a custom role to a user for the level given by URL. Specify
12831: name and domain of role author, and role name
1.191 harris41 12832:
12833: =item *
12834:
1.243 albertel 12835: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12836:
12837: =item *
12838:
1.243 albertel 12839: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12840:
12841: =back
12842:
12843: =head2 Course Infomation
12844:
12845: =over 4
1.191 harris41 12846:
12847: =item *
12848:
1.1118 foxr 12849: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12850: specified course id, including all environment settings for the
12851: course, the description of the course will be in the hash under the
12852: key 'description'
1.191 harris41 12853:
1.1118 foxr 12854: $options is an optional parameter that if supplied is a hash reference that controls
12855: what how this function works. It has the following key/values:
12856:
12857: =over 4
12858:
12859: =item freshen_cache
12860:
12861: If defined, and the environment cache for the course is valid, it is
12862: returned in the returned hash.
12863:
12864: =item one_time
12865:
12866: If defined, the last cache time is set to _now_
12867:
12868: =item user
12869:
12870: If defined, the supplied username is used instead of the current user.
12871:
12872:
12873: =back
12874:
1.191 harris41 12875: =item *
12876:
1.624 albertel 12877: resdata($name,$domain,$type,@which) : request for current parameter
12878: setting for a specific $type, where $type is either 'course' or 'user',
12879: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 12880: answers for 10 minutes.
1.243 albertel 12881:
1.877 foxr 12882: =item *
12883:
12884: get_courseresdata($courseid, $domain) : dump the entire course resource
12885: data base, returning a hash that is keyed by the resource name and has
12886: values that are the resource value. I believe that the timestamps and
12887: versions are also returned.
12888:
1.1236 raeburn 12889: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12890: supplemental content area. This routine caches the number of files for
12891: 10 minutes.
12892:
1.243 albertel 12893: =back
12894:
12895: =head2 Course Modification
12896:
12897: =over 4
1.191 harris41 12898:
12899: =item *
12900:
1.243 albertel 12901: writecoursepref($courseid,%prefs) : write preferences (environment
12902: database) for a course
1.191 harris41 12903:
12904: =item *
12905:
1.1011 raeburn 12906: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12907:
12908: =item *
12909:
1.1038 raeburn 12910: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 12911:
1.1167 droeschl 12912: =item *
12913:
12914: is_course($courseid), is_course($cdom, $cnum)
12915:
12916: Accepts either a combined $courseid (in the form of domain_courseid) or the
12917: two component version $cdom, $cnum. It checks if the specified course exists.
12918:
12919: Returns:
12920: undef if the course doesn't exist, otherwise
12921: in scalar context the combined courseid.
12922: in list context the two components of the course identifier, domain and
12923: courseid.
12924:
1.243 albertel 12925: =back
12926:
12927: =head2 Resource Subroutines
12928:
12929: =over 4
1.191 harris41 12930:
12931: =item *
12932:
1.243 albertel 12933: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 12934:
12935: =item *
12936:
1.243 albertel 12937: repcopy($filename) : subscribes to the requested file, and attempts to
12938: replicate from the owning library server, Might return
1.607 raeburn 12939: 'unavailable', 'not_found', 'forbidden', 'ok', or
12940: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 12941: resource. Expects the local filesystem pathname
12942: (/home/httpd/html/res/....)
12943:
12944: =back
12945:
12946: =head2 Resource Information
12947:
12948: =over 4
1.191 harris41 12949:
12950: =item *
12951:
1.1228 raeburn 12952: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
12953: and returns the value of a variety of different possible values,
12954: $varname should be a request string, and the other parameters can be
12955: used to specify who and what one is asking about. Ordinarily, $cid
12956: does not need to be specified, as it is retrived from
12957: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
12958: within lonuserstate::loadmap() when initializing a course, before
12959: $env{'request.course.id'} has been set, so it needs to be provided
12960: in that one case.
1.243 albertel 12961:
12962: Possible values for $varname are environment.lastname (or other item
12963: from the envirnment hash), user.name (or someother aspect about the
12964: user), resource.0.maxtries (or some other part and parameter of a
12965: resource)
1.204 albertel 12966:
12967: =item *
12968:
1.243 albertel 12969: directcondval($number) : get current value of a condition; reads from a state
12970: string
1.204 albertel 12971:
12972: =item *
12973:
1.243 albertel 12974: condval($condidx) : value of condition index based on state
1.204 albertel 12975:
12976: =item *
12977:
1.243 albertel 12978: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12979: resource's metadata, $what should be either a specific key, or either
12980: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12981: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12982:
12983: this function automatically caches all requests
1.191 harris41 12984:
12985: =item *
12986:
1.243 albertel 12987: metadata_query($query,$custom,$customshow) : make a metadata query against the
12988: network of library servers; returns file handle of where SQL and regex results
12989: will be stored for query
1.191 harris41 12990:
12991: =item *
12992:
1.243 albertel 12993: symbread($filename) : return symbolic list entry (filename argument optional);
12994: returns the data handle
1.191 harris41 12995:
12996: =item *
12997:
1.1190 raeburn 12998: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
12999: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13000: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 13001: on failure, user must be in a course, as it assumes the existence of
13002: the course initial hash, and uses $env('request.course.id'}. The third
13003: arg is an optional reference to a scalar. If this arg is passed in the
13004: call to symbverify, it will be set to 1 if the symb has been set to be
13005: encrypted; otherwise it will be null.
1.191 harris41 13006:
13007: =item *
13008:
1.243 albertel 13009: symbclean($symb) : removes versions numbers from a symb, returns the
13010: cleaned symb
1.191 harris41 13011:
13012: =item *
13013:
1.243 albertel 13014: is_on_map($uri) : checks if the $uri is somewhere on the current
13015: course map, user must be in a course for it to work.
1.191 harris41 13016:
13017: =item *
13018:
1.243 albertel 13019: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13020:
13021: =item *
13022:
1.243 albertel 13023: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13024: a random seed, all arguments are optional, if they aren't sent it uses the
13025: environment to derive them. Note: if symb isn't sent and it can't get one
13026: from &symbread it will use the current time as its return value
1.191 harris41 13027:
13028: =item *
13029:
1.243 albertel 13030: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13031: unfakeable, receipt
1.191 harris41 13032:
13033: =item *
13034:
1.620 albertel 13035: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13036:
13037: =item *
13038:
1.243 albertel 13039: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13040:
13041: =item *
13042:
1.243 albertel 13043: 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 13044:
13045: =item *
13046:
1.243 albertel 13047: 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 13048:
13049: =item *
13050:
1.243 albertel 13051: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13052:
13053: =item *
13054:
1.243 albertel 13055: devalidate($symb) : devalidate temporary spreadsheet calculations,
13056: forcing spreadsheet to reevaluate the resource scores next time.
13057:
1.1195 raeburn 13058: =item *
13059:
1.1196 raeburn 13060: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13061: when viewing in course context.
1.1195 raeburn 13062:
1.1196 raeburn 13063: input: six args -- filename (decluttered), course number, course domain,
13064: url, symb (if registered) and group (if this is a
13065: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 13066:
1.1196 raeburn 13067: output: array of five scalars --
1.1195 raeburn 13068: $cfile -- url for file editing if editable on current server
13069: $home -- homeserver of resource (i.e., for author if published,
13070: or course if uploaded.).
13071: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 13072: $forceedit -- 1 if icon/link should be to go to edit mode
13073: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 13074:
13075: =item *
13076:
13077: is_course_upload($file,$cnum,$cdom)
13078:
13079: Used in course context to determine if current file was uploaded to
13080: the course (i.e., would be found in /userfiles/docs on the course's
13081: homeserver.
13082:
13083: input: 3 args -- filename (decluttered), course number and course domain.
13084: output: boolean -- 1 if file was uploaded.
13085:
1.243 albertel 13086: =back
13087:
13088: =head2 Storing/Retreiving Data
13089:
13090: =over 4
1.191 harris41 13091:
13092: =item *
13093:
1.243 albertel 13094: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13095: for this url; hashref needs to be given and should be a \%hashname; the
13096: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13097: be derived from the env
1.191 harris41 13098:
13099: =item *
13100:
1.243 albertel 13101: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13102: uses critical subroutine
1.191 harris41 13103:
13104: =item *
13105:
1.243 albertel 13106: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13107: all args are optional
1.191 harris41 13108:
13109: =item *
13110:
1.717 albertel 13111: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13112: dumps the complete (or key matching regexp) namespace into a hash
13113: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13114: normally &store()ed into
13115:
13116: $range should be either an integer '100' (give me the first 100
13117: matching records)
13118: or be two integers sperated by a - with no spaces
13119: '30-50' (give me the 30th through the 50th matching
13120: records)
13121:
13122:
13123: =item *
13124:
13125: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13126: replaces a &store() version of data with a replacement set of data
13127: for a particular resource in a namespace passed in the $storehash hash
13128: reference
13129:
13130: =item *
13131:
1.243 albertel 13132: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13133: works very similar to store/cstore, but all data is stored in a
13134: temporary location and can be reset using tmpreset, $storehash should
13135: be a hash reference, returns nothing on success
1.191 harris41 13136:
13137: =item *
13138:
1.243 albertel 13139: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13140: similar to restore, but all data is stored in a temporary location and
13141: can be reset using tmpreset. Returns a hash of values on success,
13142: error string otherwise.
1.191 harris41 13143:
13144: =item *
13145:
1.243 albertel 13146: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13147: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13148:
13149: =item *
13150:
1.243 albertel 13151: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13152: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13153:
13154: =item *
13155:
1.243 albertel 13156: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13157: namesp ($udom and $uname are optional)
1.191 harris41 13158:
13159: =item *
13160:
1.702 albertel 13161: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13162: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13163: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13164:
1.702 albertel 13165: $range should be either an integer '100' (give me the first 100
13166: matching records)
13167: or be two integers sperated by a - with no spaces
13168: '30-50' (give me the 30th through the 50th matching
13169: records)
1.449 matthew 13170: =item *
13171:
13172: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13173: $store can be a scalar, an array reference, or if the amount to be
13174: incremented is > 1, a hash reference.
13175:
13176: ($udom and $uname are optional)
1.191 harris41 13177:
13178: =item *
13179:
1.243 albertel 13180: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13181: ($udom and $uname are optional)
1.191 harris41 13182:
13183: =item *
13184:
1.243 albertel 13185: cput($namespace,$storehash,$udom,$uname) : critical put
13186: ($udom and $uname are optional)
1.191 harris41 13187:
13188: =item *
13189:
1.748 albertel 13190: newput($namespace,$storehash,$udom,$uname) :
13191:
13192: Attempts to store the items in the $storehash, but only if they don't
13193: currently exist, if this succeeds you can be certain that you have
13194: successfully created a new key value pair in the $namespace db.
13195:
13196:
13197: Args:
13198: $namespace: name of database to store values to
13199: $storehash: hashref to store to the db
13200: $udom: (optional) domain of user containing the db
13201: $uname: (optional) name of user caontaining the db
13202:
13203: Returns:
13204: 'ok' -> succeeded in storing all keys of $storehash
13205: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13206: least <key> already existed in the db (other
13207: requested keys may also already exist)
1.967 bisitz 13208: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13209: 'con_lost' -> unable to contact request server
13210: 'refused' -> action was not allowed by remote machine
13211:
13212:
13213: =item *
13214:
1.243 albertel 13215: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13216: reference filled in from namesp (encrypts the return communication)
13217: ($udom and $uname are optional)
1.191 harris41 13218:
13219: =item *
13220:
1.243 albertel 13221: log($udom,$name,$home,$message) : write to permanent log for user; use
13222: critical subroutine
13223:
1.806 raeburn 13224: =item *
13225:
1.860 raeburn 13226: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13227: array reference filled in from namespace found in domain level on either
13228: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13229:
13230: =item *
13231:
1.860 raeburn 13232: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13233: domain level either on specified domain server ($uhome) or primary domain
13234: server ($udom and $uhome are optional)
1.806 raeburn 13235:
1.943 raeburn 13236: =item *
13237:
1.1240 raeburn 13238: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13239: for: authentication, language, quotas, timezone, date locale, and portal URL in
13240: the target domain.
13241:
13242: May also include additional key => value pairs for the following groups:
13243:
13244: =over
13245:
13246: =item
13247: disk quotas (MB allocated by default to portfolios and authoring spaces).
13248:
13249: =over
13250:
13251: =item defaultquota, authorquota
13252:
13253: =back
13254:
13255: =item
13256: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13257: portfolio for users).
13258:
13259: =over
13260:
13261: =item
13262: aboutme, blog, webdav, portfolio
13263:
13264: =back
13265:
13266: =item
13267: requestcourses: ability to request courses, and how requests are processed.
13268:
13269: =over
13270:
13271: =item
1.1246 ! raeburn 13272: official, unofficial, community, textbook
1.1240 raeburn 13273:
13274: =back
13275:
13276: =item
13277: inststatus: types of institutional affiliation, and order in which they are displayed.
13278:
13279: =over
13280:
13281: =item
13282: inststatustypes, inststatusorder
13283:
13284: =back
13285:
13286: =item
13287: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13288: for course's uploaded content.
13289:
13290: =over
13291:
13292: =item
1.1246 ! raeburn 13293: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
! 13294: communityquota, textbookquota
1.1240 raeburn 13295:
13296: =back
13297:
13298: =item
13299: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13300: on your servers.
13301:
13302: =over
13303:
13304: =item
13305: remotesessions, hostedsessions
13306:
13307: =back
13308:
13309: =back
13310:
13311: In cases where a domain coordinator has never used the "Set Domain Configuration"
13312: utility to create a configuration.db file on a domain's primary library server
13313: only the following domain defaults: auth_def, auth_arg_def, lang_def
13314: -- corresponding values are authentication type (internal, krb4, krb5,
13315: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13316: will be available. Values are retrieved from cache (if current), unless the
13317: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13318: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13319:
13320: Typical usage:
1.943 raeburn 13321:
1.1240 raeburn 13322: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13323:
1.243 albertel 13324: =back
13325:
13326: =head2 Network Status Functions
13327:
13328: =over 4
1.191 harris41 13329:
13330: =item *
13331:
1.1137 raeburn 13332: dirlist() : return directory list based on URI (first arg).
13333:
13334: Inputs: 1 required, 5 optional.
13335:
13336: =over
13337:
13338: =item
13339: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13340:
13341: =item
13342: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13343:
13344: =item
13345: $username - username of user/course to be listed. Extracted from $uri if absent.
13346:
13347: =item
13348: $getpropath - boolean: 1 if prepend path using &propath().
13349:
13350: =item
13351: $getuserdir - boolean: 1 if prepend path for "userfiles".
13352:
13353: =item
13354: $alternateRoot - path to prepend in place of path from $uri.
13355:
13356: =back
13357:
13358: Returns: Array of up to two items.
13359:
13360: =over
13361:
13362: a reference to an array of files/subdirectories
13363:
13364: =over
13365:
13366: Each element in the array of files/subdirectories is a & separated list of
13367: item name and the result of running stat on the item. If dirlist was requested
13368: for a file instead of a directory, the item name will be ''. For a directory
13369: listing, if the item is a metadata file, the element will end &N&M
13370: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13371: default copyright set (1).
13372:
13373: =back
13374:
13375: a scalar containing error condition (if encountered).
13376:
13377: =over
13378:
13379: =item
13380: no_host (no homeserver identified for $username:$domain).
13381:
13382: =item
13383: no_such_host (server contacted for listing not identified as valid host).
13384:
13385: =item
13386: con_lost (connection to remote server failed).
13387:
13388: =item
13389: refused (invalid $username:$domain received on lond side).
13390:
13391: =item
13392: no_such_dir (directory at specified path on lond side does not exist).
13393:
13394: =item
13395: empty (directory at specified path on lond side is empty).
13396:
13397: =over
13398:
13399: This is currently not encountered because the &ls3, &ls2,
13400: &ls (_handler) routines on the lond side do not filter out
13401: . and .. from a directory listing.
13402:
13403: =back
13404:
13405: =back
13406:
13407: =back
1.191 harris41 13408:
13409: =item *
13410:
1.243 albertel 13411: spareserver() : find server with least workload from spare.tab
13412:
1.986 foxr 13413:
13414: =item *
13415:
13416: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13417: if there is no corresponding loncapa host.
13418:
1.243 albertel 13419: =back
13420:
1.986 foxr 13421:
1.243 albertel 13422: =head2 Apache Request
13423:
13424: =over 4
1.191 harris41 13425:
13426: =item *
13427:
1.243 albertel 13428: ssi($url,%hash) : server side include, does a complete request cycle on url to
13429: localhost, posts hash
13430:
13431: =back
13432:
13433: =head2 Data to String to Data
13434:
13435: =over 4
1.191 harris41 13436:
13437: =item *
13438:
1.243 albertel 13439: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13440: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13441:
13442: =item *
13443:
1.243 albertel 13444: hashref2str($hashref) : convert a hashref into a string complete with
13445: escaping and '=' and '&' separators, supports elements that are
13446: arrayrefs and hashrefs
1.191 harris41 13447:
13448: =item *
13449:
1.243 albertel 13450: arrayref2str($arrayref) : convert an arrayref into a string complete
13451: with escaping and '&' separators, supports elements that are arrayrefs
13452: and hashrefs
1.191 harris41 13453:
13454: =item *
13455:
1.243 albertel 13456: str2hash($string) : convert string to hash using unescaping and
13457: splitting on '=' and '&', supports elements that are arrayrefs and
13458: hashrefs
1.191 harris41 13459:
13460: =item *
13461:
1.243 albertel 13462: str2array($string) : convert string to hash using unescaping and
13463: splitting on '&', supports elements that are arrayrefs and hashrefs
13464:
13465: =back
13466:
13467: =head2 Logging Routines
13468:
13469:
13470: These routines allow one to make log messages in the lonnet.log and
13471: lonnet.perm logfiles.
1.191 harris41 13472:
1.1119 foxr 13473: =over 4
13474:
1.191 harris41 13475: =item *
13476:
1.243 albertel 13477: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13478:
13479: =item *
13480:
1.243 albertel 13481: logthis() : append message to the normal lonnet.log file, it gets
13482: preiodically rolled over and deleted.
1.191 harris41 13483:
13484: =item *
13485:
1.243 albertel 13486: logperm() : append a permanent message to lonnet.perm.log, this log
13487: file never gets deleted by any automated portion of the system, only
13488: messages of critical importance should go in here.
13489:
1.1119 foxr 13490:
1.243 albertel 13491: =back
13492:
13493: =head2 General File Helper Routines
13494:
13495: =over 4
1.191 harris41 13496:
13497: =item *
13498:
1.481 raeburn 13499: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13500: (a) files in /uploaded
13501: (i) If a local copy of the file exists -
13502: compares modification date of local copy with last-modified date for
13503: definitive version stored on home server for course. If local copy is
13504: stale, requests a new version from the home server and stores it.
13505: If the original has been removed from the home server, then local copy
13506: is unlinked.
13507: (ii) If local copy does not exist -
13508: requests the file from the home server and stores it.
13509:
13510: If $caller is 'uploadrep':
13511: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13512: for request for files originally uploaded via DOCS.
13513: - returns 'ok' if fresh local copy now available, -1 otherwise.
13514:
13515: Otherwise:
13516: This indicates a call from the content generation phase of the request.
13517: - returns the entire contents of the file or -1.
13518:
13519: (b) files in /res
13520: - returns the entire contents of a file or -1;
13521: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13522:
1.712 albertel 13523:
13524: =item *
13525:
13526: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13527: reference
13528:
13529: returns either a stat() list of data about the file or an empty list
13530: if the file doesn't exist or couldn't find out about it (connection
13531: problems or user unknown)
13532:
1.191 harris41 13533: =item *
13534:
1.243 albertel 13535: filelocation($dir,$file) : returns file system location of a file
13536: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13537: directory that relative $file lookups are to looked in ($dir of /a/dir
13538: and a file of ../bob will become /a/bob)
1.191 harris41 13539:
13540: =item *
13541:
13542: hreflocation($dir,$file) : returns file system location or a URL; same as
13543: filelocation except for hrefs
13544:
13545: =item *
13546:
13547: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13548:
1.243 albertel 13549: =back
13550:
1.608 albertel 13551: =head2 Usererfile file routines (/uploaded*)
13552:
13553: =over 4
13554:
13555: =item *
13556:
13557: userfileupload(): main rotine for putting a file in a user or course's
13558: filespace, arguments are,
13559:
1.620 albertel 13560: formname - required - this is the name of the element in $env where the
1.608 albertel 13561: filename, and the contents of the file to create/modifed exist
1.620 albertel 13562: the filename is in $env{'form.'.$formname.'.filename'} and the
13563: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13564: context - if coursedoc, store the file in the course of the active role
13565: of the current user;
13566: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13567: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13568: subdir - required - subdirectory to put the file in under ../userfiles/
13569: if undefined, it will be placed in "unknown"
13570:
13571: (This routine calls clean_filename() to remove any dangerous
13572: characters from the filename, and then calls finuserfileupload() to
13573: complete the transaction)
13574:
13575: returns either the url of the uploaded file (/uploaded/....) if successful
13576: and /adm/notfound.html if unsuccessful
13577:
13578: =item *
13579:
13580: clean_filename(): routine for cleaing a filename up for storage in
13581: userfile space, argument is:
13582:
13583: filename - proposed filename
13584:
13585: returns: the new clean filename
13586:
13587: =item *
13588:
1.1090 raeburn 13589: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13590: userspace, probably shouldn't be called directly
13591:
13592: docuname: username or courseid of destination for the file
13593: docudom: domain of user/course of destination for the file
13594: formname: same as for userfileupload()
1.1090 raeburn 13595: fname: filename (including subdirectories) for the file
13596: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13597: allfiles: reference to hash used to store objects found by parser
13598: codebase: reference to hash used for codebases of java objects found by parser
13599: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13600: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13601: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13602: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13603: context: if 'overwrite', will move the uploaded file from its temporary location to
13604: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13605: mimetype: reference to scalar to accommodate mime type determined
13606: from File::MMagic if $parser = parse.
1.608 albertel 13607:
13608: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13609: and /adm/notfound.html if unsuccessful (or an error message if context
13610: was 'overwrite').
13611:
1.608 albertel 13612:
13613: =item *
13614:
13615: renameuserfile(): renames an existing userfile to a new name
13616:
13617: Args:
13618: docuname: username or courseid of destination for the file
13619: docudom: domain of user/course of destination for the file
13620: old: current file name (including any subdirs under userfiles)
13621: new: desired file name (including any subdirs under userfiles)
13622:
13623: =item *
13624:
13625: mkdiruserfile(): creates a directory is a userfiles dir
13626:
13627: Args:
13628: docuname: username or courseid of destination for the file
13629: docudom: domain of user/course of destination for the file
13630: dir: dir to create (including any subdirs under userfiles)
13631:
13632: =item *
13633:
13634: removeuserfile(): removes a file that exists in userfiles
13635:
13636: Args:
13637: docuname: username or courseid of destination for the file
13638: docudom: domain of user/course of destination for the file
13639: fname: filname to delete (including any subdirs under userfiles)
13640:
13641: =item *
13642:
13643: removeuploadedurl(): convience function for removeuserfile()
13644:
13645: Args:
13646: url: a full /uploaded/... url to delete
13647:
1.747 albertel 13648: =item *
13649:
13650: get_portfile_permissions():
13651: Args:
13652: domain: domain of user or course contain the portfolio files
13653: user: name of user or num of course contain the portfolio files
13654: Returns:
13655: hashref of a dump of the proper file_permissions.db
13656:
13657:
13658: =item *
13659:
13660: get_access_controls():
13661:
13662: Args:
13663: current_permissions: the hash ref returned from get_portfile_permissions()
13664: group: (optional) the group you want the files associated with
13665: file: (optional) the file you want access info on
13666:
13667: Returns:
1.749 raeburn 13668: a hash (keys are file names) of hashes containing
13669: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13670: values are XML containing access control settings (see below)
1.747 albertel 13671:
13672: Internal notes:
13673:
1.749 raeburn 13674: access controls are stored in file_permissions.db as key=value pairs.
13675: key -> path to file/file_name\0uniqueID:scope_end_start
13676: where scope -> public,guest,course,group,domains or users.
13677: end -> UNIX time for end of access (0 -> no end date)
13678: start -> UNIX time for start of access
13679:
13680: value -> XML description of access control
13681: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13682: <start></start>
13683: <end></end>
13684:
13685: <password></password> for scope type = guest
13686:
13687: <domain></domain> for scope type = course or group
13688: <number></number>
13689: <roles id="">
13690: <role></role>
13691: <access></access>
13692: <section></section>
13693: <group></group>
13694: </roles>
13695:
13696: <dom></dom> for scope type = domains
13697:
13698: <users> for scope type = users
13699: <user>
13700: <uname></uname>
13701: <udom></udom>
13702: </user>
13703: </users>
13704: </scope>
13705:
13706: Access data is also aggregated for each file in an additional key=value pair:
13707: key -> path to file/file_name\0accesscontrol
13708: value -> reference to hash
13709: hash contains key = value pairs
13710: where key = uniqueID:scope_end_start
13711: value = UNIX time record was last updated
13712:
13713: Used to improve speed of look-ups of access controls for each file.
13714:
13715: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13716:
1.1198 raeburn 13717: =item *
13718:
1.749 raeburn 13719: modify_access_controls():
13720:
13721: Modifies access controls for a portfolio file
13722: Args
13723: 1. file name
13724: 2. reference to hash of required changes,
13725: 3. domain
13726: 4. username
13727: where domain,username are the domain of the portfolio owner
13728: (either a user or a course)
13729:
13730: Returns:
13731: 1. result of additions or updates ('ok' or 'error', with error message).
13732: 2. result of deletions ('ok' or 'error', with error message).
13733: 3. reference to hash of any new or updated access controls.
13734: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13735: key = integer (inbound ID)
1.1198 raeburn 13736: value = uniqueID
13737:
13738: =item *
13739:
13740: get_timebased_id():
13741:
13742: Attempts to get a unique timestamp-based suffix for use with items added to a
13743: course via the Course Editor (e.g., folders, composite pages,
13744: group bulletin boards).
13745:
13746: Args: (first three required; six others optional)
13747:
13748: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13749: docssequence, or name of group
13750:
13751: 2. keyid (alphanumeric): name of temporary locking key in hash,
13752: e.g., num, boardids
13753:
13754: 3. namespace: name of gdbm file used to store suffixes already assigned;
13755: file will be named nohist_namespace.db
13756:
13757: 4. cdom: domain of course; default is current course domain from %env
13758:
13759: 5. cnum: course number; default is current course number from %env
13760:
13761: 6. idtype: set to concat if an additional digit is to be appended to the
13762: unix timestamp to form the suffix, if the plain timestamp is already
13763: in use. Default is to not do this, but simply increment the unix
13764: timestamp by 1 until a unique key is obtained.
13765:
13766: 7. who: holder of locking key; defaults to user:domain for user.
13767:
13768: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13769: retrying); default is 3.
13770:
13771: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13772:
13773: Returns:
13774:
13775: 1. suffix obtained (numeric)
13776:
13777: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13778:
13779: 3. error: contains (localized) error message if an error occurred.
13780:
1.747 albertel 13781:
1.608 albertel 13782: =back
13783:
1.243 albertel 13784: =head2 HTTP Helper Routines
13785:
13786: =over 4
13787:
1.191 harris41 13788: =item *
13789:
13790: escape() : unpack non-word characters into CGI-compatible hex codes
13791:
13792: =item *
13793:
13794: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13795:
1.243 albertel 13796: =back
13797:
13798: =head1 PRIVATE SUBROUTINES
13799:
13800: =head2 Underlying communication routines (Shouldn't call)
13801:
13802: =over 4
13803:
13804: =item *
13805:
13806: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13807:
13808: =item *
13809:
13810: reply() : uses subreply to send a message to remote machine, logs all failures
13811:
13812: =item *
13813:
13814: critical() : passes a critical message to another server; if cannot
13815: get through then place message in connection buffer directory and
13816: returns con_delayed, if incapable of saving message, returns
13817: con_failed
13818:
13819: =item *
13820:
13821: reconlonc() : tries to reconnect lonc client processes.
13822:
13823: =back
13824:
13825: =head2 Resource Access Logging
13826:
13827: =over 4
13828:
13829: =item *
13830:
13831: flushcourselogs() : flush (save) buffer logs and access logs
13832:
13833: =item *
13834:
13835: courselog($what) : save message for course in hash
13836:
13837: =item *
13838:
13839: courseacclog($what) : save message for course using &courselog(). Perform
13840: special processing for specific resource types (problems, exams, quizzes, etc).
13841:
1.191 harris41 13842: =item *
13843:
13844: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13845: as a PerlChildExitHandler
1.243 albertel 13846:
13847: =back
13848:
13849: =head2 Other
13850:
13851: =over 4
13852:
13853: =item *
13854:
13855: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 13856:
13857: =back
13858:
13859: =cut
1.877 foxr 13860:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>