Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1257
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1257 ! raeburn 4: # $Id: lonnet.pm,v 1.1256 2014/04/23 10:11:34 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') {
1.1250 raeburn 679: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949 raeburn 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 {
1.1253 raeburn 893: my ($try_server, $spare_server, $lowest_load, $required) = @_;
894:
895: if ($required) {
896: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
897: my $remoterev = &get_server_loncaparev(undef,$try_server);
898: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
899: if (($major eq '' && $minor eq '') ||
900: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
901: return ($spare_server,$lowest_load);
902: }
903: }
1.784 albertel 904:
905: my $loadans = &reply('load', $try_server);
906: my $userloadans = &reply('userload',$try_server);
907:
908: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 909: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 910: }
911:
912: my $load;
913: if ($loadans =~ /\d/) {
914: if ($userloadans =~ /\d/) {
915: #both are numbers, pick the bigger one
916: $load = ($loadans > $userloadans) ? $loadans
917: : $userloadans;
1.411 albertel 918: } else {
1.784 albertel 919: $load = $loadans;
1.411 albertel 920: }
1.784 albertel 921: } else {
922: $load = $userloadans;
923: }
924:
925: if (($load =~ /\d/) && ($load < $lowest_load)) {
926: $spare_server = $try_server;
927: $lowest_load = $load;
1.370 albertel 928: }
1.784 albertel 929: return ($spare_server,$lowest_load);
1.202 matthew 930: }
1.914 albertel 931:
932: # --------------------------- ask offload servers if user already has a session
933: sub find_existing_session {
934: my ($udom,$uname) = @_;
1.1123 raeburn 935: my $spareshash = &this_host_spares($udom);
936: if (ref($spareshash) eq 'HASH') {
937: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
938: foreach my $try_server (@{ $spareshash->{'primary'} }) {
939: return $try_server if (&has_user_session($try_server, $udom, $uname));
940: }
941: }
942: if (ref($spareshash->{'default'}) eq 'ARRAY') {
943: foreach my $try_server (@{ $spareshash->{'default'} }) {
944: return $try_server if (&has_user_session($try_server, $udom, $uname));
945: }
946: }
1.914 albertel 947: }
948: return;
949: }
950:
951: # -------------------------------- ask if server already has a session for user
952: sub has_user_session {
953: my ($lonid,$udom,$uname) = @_;
954: my $result = &reply(join(':','userhassession',
955: map {&escape($_)} ($udom,$uname)),$lonid);
956: return 1 if ($result eq 'ok');
957:
958: return 0;
959: }
960:
1.1076 raeburn 961: # --------- determine least loaded server in a user's domain which allows login
962:
963: sub choose_server {
1.1253 raeburn 964: my ($udom,$checkloginvia,$required) = @_;
1.1076 raeburn 965: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 966: my %servers = &get_servers($udom);
1.1076 raeburn 967: my $lowest_load = 30000;
1.1151 raeburn 968: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 969: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 970: my $loginvia;
971: if ($checkloginvia) {
972: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 973: if ($loginvia) {
974: my ($server,$path) = split(/:/,$loginvia);
975: ($login_host, $lowest_load) =
1.1253 raeburn 976: &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116 raeburn 977: if ($login_host eq $server) {
978: $portal_path = $path;
1.1151 raeburn 979: $isredirect = 1;
1.1116 raeburn 980: }
981: } else {
982: ($login_host, $lowest_load) =
1.1253 raeburn 983: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116 raeburn 984: if ($login_host eq $lonhost) {
985: $portal_path = '';
1.1151 raeburn 986: $isredirect = '';
1.1116 raeburn 987: }
988: }
989: } else {
1.1076 raeburn 990: ($login_host, $lowest_load) =
1.1253 raeburn 991: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076 raeburn 992: }
993: }
994: if ($login_host ne '') {
1.1116 raeburn 995: $hostname = &hostname($login_host);
1.1076 raeburn 996: }
1.1151 raeburn 997: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 998: }
999:
1.202 matthew 1000: # --------------------------------------------- Try to change a user's password
1001:
1002: sub changepass {
1.799 raeburn 1003: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 1004: $currentpass = &escape($currentpass);
1005: $newpass = &escape($newpass);
1.1030 raeburn 1006: my $lonhost = $perlvar{'lonHostID'};
1007: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 1008: $server);
1009: if (! $answer) {
1010: &logthis("No reply on password change request to $server ".
1011: "by $uname in domain $udom.");
1012: } elsif ($answer =~ "^ok") {
1013: &logthis("$uname in $udom successfully changed their password ".
1014: "on $server.");
1015: } elsif ($answer =~ "^pwchange_failure") {
1016: &logthis("$uname in $udom was unable to change their password ".
1017: "on $server. The action was blocked by either lcpasswd ".
1018: "or pwchange");
1019: } elsif ($answer =~ "^non_authorized") {
1020: &logthis("$uname in $udom did not get their password correct when ".
1021: "attempting to change it on $server.");
1022: } elsif ($answer =~ "^auth_mode_error") {
1023: &logthis("$uname in $udom attempted to change their password despite ".
1024: "not being locally or internally authenticated on $server.");
1025: } elsif ($answer =~ "^unknown_user") {
1026: &logthis("$uname in $udom attempted to change their password ".
1027: "on $server but were unable to because $server is not ".
1028: "their home server.");
1029: } elsif ($answer =~ "^refused") {
1030: &logthis("$server refused to change $uname in $udom password because ".
1031: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1032: } elsif ($answer =~ "invalid_client") {
1033: &logthis("$server refused to change $uname in $udom password because ".
1034: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1035: }
1036: return $answer;
1.1 albertel 1037: }
1038:
1.169 harris41 1039: # ----------------------- Try to determine user's current authentication scheme
1040:
1041: sub queryauthenticate {
1042: my ($uname,$udom)=@_;
1.456 albertel 1043: my $uhome=&homeserver($uname,$udom);
1044: if (!$uhome) {
1045: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1046: return 'no_host';
1047: }
1048: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1049: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1050: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1051: }
1.456 albertel 1052: return $answer;
1.169 harris41 1053: }
1054:
1.1 albertel 1055: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1056:
1.1 albertel 1057: sub authenticate {
1.1073 raeburn 1058: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1059: $upass=&escape($upass);
1060: $uname= &LONCAPA::clean_username($uname);
1.836 www 1061: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1062: my $newhome;
1.836 www 1063: if ((!$uhome) || ($uhome eq 'no_host')) {
1064: # Maybe the machine was offline and only re-appeared again recently?
1065: &reconlonc();
1066: # One more
1.952 raeburn 1067: $uhome=&homeserver($uname,$udom,1);
1068: if (($uhome eq 'no_host') && $checkdefauth) {
1069: if (defined(&domain($udom,'primary'))) {
1070: $newhome=&domain($udom,'primary');
1071: }
1072: if ($newhome ne '') {
1073: $uhome = $newhome;
1074: }
1075: }
1.836 www 1076: if ((!$uhome) || ($uhome eq 'no_host')) {
1077: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1078: return 'no_host';
1079: }
1.1 albertel 1080: }
1.1073 raeburn 1081: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1082: if ($answer eq 'authorized') {
1.952 raeburn 1083: if ($newhome) {
1084: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1085: return 'no_account_on_host';
1086: } else {
1087: &logthis("User $uname at $udom authorized by $uhome");
1088: return $uhome;
1089: }
1.471 albertel 1090: }
1091: if ($answer eq 'non_authorized') {
1092: &logthis("User $uname at $udom rejected by $uhome");
1093: return 'no_host';
1.9 www 1094: }
1.471 albertel 1095: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1096: return 'no_host';
1097: }
1098:
1.1073 raeburn 1099: sub can_host_session {
1.1074 raeburn 1100: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1101: my $canhost = 1;
1.1074 raeburn 1102: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1103: if (ref($remotesessions) eq 'HASH') {
1104: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1105: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1106: $canhost = 0;
1107: } else {
1108: $canhost = 1;
1109: }
1110: }
1111: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1112: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1113: $canhost = 1;
1114: } else {
1115: $canhost = 0;
1116: }
1117: }
1118: if ($canhost) {
1119: if ($remotesessions->{'version'} ne '') {
1120: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1121: if ($reqmajor ne '' && $reqminor ne '') {
1122: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1123: my $major = $1;
1124: my $minor = $2;
1125: if (($major < $reqmajor ) ||
1126: (($major == $reqmajor) && ($minor < $reqminor))) {
1127: $canhost = 0;
1128: }
1129: } else {
1130: $canhost = 0;
1131: }
1132: }
1133: }
1134: }
1135: }
1136: if ($canhost) {
1137: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1138: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1139: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1140: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1141: if (($uint_dom ne '') &&
1142: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1143: $canhost = 0;
1144: } else {
1145: $canhost = 1;
1146: }
1147: }
1148: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1149: if (($uint_dom ne '') &&
1150: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1151: $canhost = 1;
1152: } else {
1153: $canhost = 0;
1154: }
1155: }
1156: }
1157: }
1158: return $canhost;
1159: }
1160:
1.1083 raeburn 1161: sub spare_can_host {
1162: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1163: my $canhost=1;
1164: my @intdoms;
1165: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1166: if (ref($internet_names) eq 'ARRAY') {
1167: @intdoms = @{$internet_names};
1168: }
1169: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1170: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1171: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1172: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1173: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1174: $canhost = &can_host_session($udom,$try_server,$remoterev,
1175: $remotesessions,
1176: $defdomdefaults{'hostedsessions'});
1177: }
1178: return $canhost;
1179: }
1180:
1.1123 raeburn 1181: sub this_host_spares {
1182: my ($dom) = @_;
1.1126 raeburn 1183: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1184: my @hosts = ¤t_machine_ids();
1185: foreach my $lonhost (@hosts) {
1186: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1187: $dom_in_use = $dom;
1188: $lonhost_in_use = $lonhost;
1.1123 raeburn 1189: last;
1190: }
1191: }
1.1126 raeburn 1192: if ($dom_in_use ne '') {
1193: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1194: }
1195: if (ref($result) ne 'HASH') {
1196: $lonhost_in_use = $perlvar{'lonHostID'};
1197: $dom_in_use = &host_domain($lonhost_in_use);
1198: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1199: if (ref($result) ne 'HASH') {
1200: $result = \%spareid;
1201: }
1202: }
1203: return $result;
1204: }
1205:
1206: sub spares_for_offload {
1207: my ($dom_in_use,$lonhost_in_use) = @_;
1208: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1209: if (defined($cached)) {
1210: return $result;
1211: } else {
1.1126 raeburn 1212: my $cachetime = 60*60*24;
1213: my %domconfig =
1214: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1215: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1216: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1217: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1218: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1219: }
1220: }
1221: }
1222: }
1.1126 raeburn 1223: return;
1.1123 raeburn 1224: }
1225:
1.1129 raeburn 1226: sub get_lonbalancer_config {
1227: my ($servers) = @_;
1228: my ($currbalancer,$currtargets);
1229: if (ref($servers) eq 'HASH') {
1230: foreach my $server (keys(%{$servers})) {
1231: my %what = (
1232: spareid => 1,
1233: perlvar => 1,
1234: );
1235: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1236: if ($result eq 'ok') {
1237: if (ref($returnhash) eq 'HASH') {
1238: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1239: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1240: $currbalancer = $server;
1241: $currtargets = {};
1242: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1243: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1244: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1245: }
1246: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1247: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1248: }
1249: }
1250: last;
1251: }
1252: }
1253: }
1254: }
1255: }
1256: }
1257: return ($currbalancer,$currtargets);
1258: }
1259:
1260: sub check_loadbalancing {
1261: my ($uname,$udom) = @_;
1.1191 raeburn 1262: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1263: $rule_in_effect,$offloadto,$otherserver);
1.1129 raeburn 1264: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1265: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1266: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1267: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1268: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1269: my $serverhomedom = &host_domain($lonhost);
1270:
1271: my $cachetime = 60*60*24;
1272:
1273: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1274: $dom_in_use = $udom;
1275: $homeintdom = 1;
1276: } else {
1277: $dom_in_use = $serverhomedom;
1278: }
1279: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1280: unless (defined($cached)) {
1281: my %domconfig =
1282: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1283: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1284: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1285: }
1286: }
1287: if (ref($result) eq 'HASH') {
1.1191 raeburn 1288: ($is_balancer,$currtargets,$currrules) =
1289: &check_balancer_result($result,@hosts);
1.1129 raeburn 1290: if ($is_balancer) {
1291: if (ref($currrules) eq 'HASH') {
1292: if ($homeintdom) {
1293: if ($uname ne '') {
1294: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1295: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1296: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1297: $rule_in_effect = $currrules->{'_LC_author'};
1298: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1299: $rule_in_effect = $currrules->{'_LC_adv'}
1300: }
1301: }
1302: if ($rule_in_effect eq '') {
1303: my %userenv = &userenvironment($udom,$uname,'inststatus');
1304: if ($userenv{'inststatus'} ne '') {
1305: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1306: my ($othertitle,$usertypes,$types) =
1307: &Apache::loncommon::sorted_inst_types($udom);
1308: if (ref($types) eq 'ARRAY') {
1309: foreach my $type (@{$types}) {
1310: if (grep(/^\Q$type\E$/,@statuses)) {
1311: if (exists($currrules->{$type})) {
1312: $rule_in_effect = $currrules->{$type};
1313: }
1314: }
1315: }
1316: }
1317: } else {
1318: if (exists($currrules->{'default'})) {
1319: $rule_in_effect = $currrules->{'default'};
1320: }
1321: }
1322: }
1323: } else {
1324: if (exists($currrules->{'default'})) {
1325: $rule_in_effect = $currrules->{'default'};
1326: }
1327: }
1328: } else {
1329: if ($currrules->{'_LC_external'} ne '') {
1330: $rule_in_effect = $currrules->{'_LC_external'};
1331: }
1332: }
1333: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1334: $uname,$udom);
1335: }
1336: }
1337: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239 raeburn 1338: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129 raeburn 1339: unless (defined($cached)) {
1340: my %domconfig =
1341: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1342: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1343: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1344: }
1345: }
1346: if (ref($result) eq 'HASH') {
1.1191 raeburn 1347: ($is_balancer,$currtargets,$currrules) =
1348: &check_balancer_result($result,@hosts);
1349: if ($is_balancer) {
1.1129 raeburn 1350: if (ref($currrules) eq 'HASH') {
1351: if ($currrules->{'_LC_internetdom'} ne '') {
1352: $rule_in_effect = $currrules->{'_LC_internetdom'};
1353: }
1354: }
1355: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1356: $uname,$udom);
1357: }
1358: } else {
1359: if ($perlvar{'lonBalancer'} eq 'yes') {
1360: $is_balancer = 1;
1361: $offloadto = &this_host_spares($dom_in_use);
1362: }
1363: }
1364: } else {
1365: if ($perlvar{'lonBalancer'} eq 'yes') {
1366: $is_balancer = 1;
1367: $offloadto = &this_host_spares($dom_in_use);
1368: }
1369: }
1.1176 raeburn 1370: if ($is_balancer) {
1371: my $lowest_load = 30000;
1372: if (ref($offloadto) eq 'HASH') {
1373: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1374: foreach my $try_server (@{$offloadto->{'primary'}}) {
1375: ($otherserver,$lowest_load) =
1376: &compare_server_load($try_server,$otherserver,$lowest_load);
1377: }
1.1129 raeburn 1378: }
1.1176 raeburn 1379: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1380:
1.1176 raeburn 1381: if (!$found_server) {
1382: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1383: foreach my $try_server (@{$offloadto->{'default'}}) {
1384: ($otherserver,$lowest_load) =
1385: &compare_server_load($try_server,$otherserver,$lowest_load);
1386: }
1387: }
1388: }
1389: } elsif (ref($offloadto) eq 'ARRAY') {
1390: if (@{$offloadto} == 1) {
1391: $otherserver = $offloadto->[0];
1392: } elsif (@{$offloadto} > 1) {
1393: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1394: ($otherserver,$lowest_load) =
1395: &compare_server_load($try_server,$otherserver,$lowest_load);
1396: }
1397: }
1398: }
1.1176 raeburn 1399: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1400: $is_balancer = 0;
1401: if ($uname ne '' && $udom ne '') {
1402: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1403:
1404: &appenv({'user.loadbalexempt' => $lonhost,
1405: 'user.loadbalcheck.time' => time});
1406: }
1.1129 raeburn 1407: }
1408: }
1409: }
1410: return ($is_balancer,$otherserver);
1411: }
1412:
1.1191 raeburn 1413: sub check_balancer_result {
1414: my ($result,@hosts) = @_;
1415: my ($is_balancer,$currtargets,$currrules);
1416: if (ref($result) eq 'HASH') {
1417: if ($result->{'lonhost'} ne '') {
1418: my $currbalancer = $result->{'lonhost'};
1419: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1420: $is_balancer = 1;
1421: $currtargets = $result->{'targets'};
1422: $currrules = $result->{'rules'};
1423: }
1424: } else {
1425: foreach my $key (keys(%{$result})) {
1426: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1427: (ref($result->{$key}) eq 'HASH')) {
1428: $is_balancer = 1;
1429: $currrules = $result->{$key}{'rules'};
1430: $currtargets = $result->{$key}{'targets'};
1431: last;
1432: }
1433: }
1434: }
1435: }
1436: return ($is_balancer,$currtargets,$currrules);
1437: }
1438:
1.1129 raeburn 1439: sub get_loadbalancer_targets {
1440: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1441: my $offloadto;
1.1175 raeburn 1442: if ($rule_in_effect eq 'none') {
1443: return [$perlvar{'lonHostID'}];
1444: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1445: $offloadto = $currtargets;
1446: } else {
1447: if ($rule_in_effect eq 'homeserver') {
1448: my $homeserver = &homeserver($uname,$udom);
1449: if ($homeserver ne 'no_host') {
1450: $offloadto = [$homeserver];
1451: }
1452: } elsif ($rule_in_effect eq 'externalbalancer') {
1453: my %domconfig =
1454: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1455: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1456: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1457: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1458: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1459: }
1460: }
1461: } else {
1.1178 raeburn 1462: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1463: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1464: if (&hostname($remotebalancer) ne '') {
1465: $offloadto = [$remotebalancer];
1466: }
1467: }
1468: } elsif (&hostname($rule_in_effect) ne '') {
1469: $offloadto = [$rule_in_effect];
1470: }
1471: }
1472: return $offloadto;
1473: }
1474:
1.1127 raeburn 1475: sub internet_dom_servers {
1476: my ($dom) = @_;
1477: my (%uniqservers,%servers);
1478: my $primaryserver = &hostname(&domain($dom,'primary'));
1479: my @machinedoms = &machine_domains($primaryserver);
1480: foreach my $mdom (@machinedoms) {
1481: my %currservers = %servers;
1482: my %server = &get_servers($mdom);
1483: %servers = (%currservers,%server);
1484: }
1485: my %by_hostname;
1486: foreach my $id (keys(%servers)) {
1487: push(@{$by_hostname{$servers{$id}}},$id);
1488: }
1489: foreach my $hostname (sort(keys(%by_hostname))) {
1490: if (@{$by_hostname{$hostname}} > 1) {
1491: my $match = 0;
1492: foreach my $id (@{$by_hostname{$hostname}}) {
1493: if (&host_domain($id) eq $dom) {
1494: $uniqservers{$id} = $hostname;
1495: $match = 1;
1496: }
1497: }
1498: unless ($match) {
1499: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1500: }
1501: } else {
1502: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1503: }
1504: }
1505: return %uniqservers;
1506: }
1507:
1.1 albertel 1508: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1509:
1.599 albertel 1510: my %homecache;
1.1 albertel 1511: sub homeserver {
1.230 stredwic 1512: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1513: my $index="$uname:$udom";
1.426 albertel 1514:
1.599 albertel 1515: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1516:
1517: my %servers = &get_servers($udom,'library');
1518: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1519: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1520: exists($badServerCache{$tryserver}));
1.841 albertel 1521:
1522: my $answer=reply("home:$udom:$uname",$tryserver);
1523: if ($answer eq 'found') {
1524: delete($badServerCache{$tryserver});
1525: return $homecache{$index}=$tryserver;
1526: } elsif ($answer eq 'no_host') {
1527: $badServerCache{$tryserver}=1;
1528: }
1.1 albertel 1529: }
1530: return 'no_host';
1.70 www 1531: }
1532:
1533: # ------------------------------------- Find the usernames behind a list of IDs
1534:
1535: sub idget {
1536: my ($udom,@ids)=@_;
1537: my %returnhash=();
1538:
1.841 albertel 1539: my %servers = &get_servers($udom,'library');
1540: foreach my $tryserver (keys(%servers)) {
1541: my $idlist=join('&',@ids);
1542: $idlist=~tr/A-Z/a-z/;
1543: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1544: my @answer=();
1545: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1546: @answer=split(/\&/,$reply);
1547: } ;
1548: my $i;
1549: for ($i=0;$i<=$#ids;$i++) {
1550: if ($answer[$i]) {
1551: $returnhash{$ids[$i]}=$answer[$i];
1552: }
1553: }
1554: }
1.70 www 1555: return %returnhash;
1556: }
1557:
1558: # ------------------------------------- Find the IDs behind a list of usernames
1559:
1560: sub idrget {
1561: my ($udom,@unames)=@_;
1562: my %returnhash=();
1.800 albertel 1563: foreach my $uname (@unames) {
1564: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1565: }
1.70 www 1566: return %returnhash;
1567: }
1568:
1569: # ------------------------------- Store away a list of names and associated IDs
1570:
1571: sub idput {
1572: my ($udom,%ids)=@_;
1573: my %servers=();
1.800 albertel 1574: foreach my $uname (keys(%ids)) {
1575: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1576: my $uhom=&homeserver($uname,$udom);
1.70 www 1577: if ($uhom ne 'no_host') {
1.800 albertel 1578: my $id=&escape($ids{$uname});
1.70 www 1579: $id=~tr/A-Z/a-z/;
1.800 albertel 1580: my $esc_unam=&escape($uname);
1.70 www 1581: if ($servers{$uhom}) {
1.800 albertel 1582: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1583: } else {
1.800 albertel 1584: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1585: }
1586: }
1.191 harris41 1587: }
1.800 albertel 1588: foreach my $server (keys(%servers)) {
1589: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1590: }
1.344 www 1591: }
1592:
1.1231 raeburn 1593: # ---------------------------------------- Delete unwanted IDs from ids.db file
1594:
1595: sub iddel {
1596: my ($udom,$idshashref,$uhome)=@_;
1597: my %result=();
1598: unless (ref($idshashref) eq 'HASH') {
1599: return %result;
1600: }
1601: my %servers=();
1602: while (my ($id,$uname) = each(%{$idshashref})) {
1603: my $uhom;
1604: if ($uhome) {
1605: $uhom = $uhome;
1606: } else {
1607: $uhom=&homeserver($uname,$udom);
1608: }
1609: if ($uhom ne 'no_host') {
1610: if ($servers{$uhom}) {
1611: $servers{$uhom}.='&'.&escape($id);
1612: } else {
1613: $servers{$uhom}=&escape($id);
1614: }
1615: }
1616: }
1617: foreach my $server (keys(%servers)) {
1618: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1619: }
1620: return %result;
1621: }
1622:
1.1023 raeburn 1623: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1624: sub dump_dom {
1.1165 droeschl 1625: my ($namespace, $udom, $regexp) = @_;
1626:
1627: $udom ||= $env{'user.domain'};
1628:
1629: return () unless $udom;
1630:
1631: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1632: }
1633:
1.1023 raeburn 1634: # ------------------------------------------ get items from domain db files
1.806 raeburn 1635:
1636: sub get_dom {
1.860 raeburn 1637: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1638: my $items='';
1639: foreach my $item (@$storearr) {
1640: $items.=&escape($item).'&';
1641: }
1642: $items=~s/\&$//;
1.860 raeburn 1643: if (!$udom) {
1644: $udom=$env{'user.domain'};
1645: if (defined(&domain($udom,'primary'))) {
1646: $uhome=&domain($udom,'primary');
1647: } else {
1.874 albertel 1648: undef($uhome);
1.860 raeburn 1649: }
1650: } else {
1651: if (!$uhome) {
1652: if (defined(&domain($udom,'primary'))) {
1653: $uhome=&domain($udom,'primary');
1654: }
1655: }
1656: }
1657: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1658: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1659: my %returnhash;
1.875 albertel 1660: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1661: return %returnhash;
1662: }
1.806 raeburn 1663: my @pairs=split(/\&/,$rep);
1664: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1665: return @pairs;
1666: }
1667: my $i=0;
1668: foreach my $item (@$storearr) {
1669: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1670: $i++;
1671: }
1672: return %returnhash;
1673: } else {
1.880 banghart 1674: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1675: }
1676: }
1677:
1678: # -------------------------------------------- put items in domain db files
1679:
1680: sub put_dom {
1.860 raeburn 1681: my ($namespace,$storehash,$udom,$uhome)=@_;
1682: if (!$udom) {
1683: $udom=$env{'user.domain'};
1684: if (defined(&domain($udom,'primary'))) {
1685: $uhome=&domain($udom,'primary');
1686: } else {
1.874 albertel 1687: undef($uhome);
1.860 raeburn 1688: }
1689: } else {
1690: if (!$uhome) {
1691: if (defined(&domain($udom,'primary'))) {
1692: $uhome=&domain($udom,'primary');
1693: }
1694: }
1695: }
1696: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1697: my $items='';
1698: foreach my $item (keys(%$storehash)) {
1699: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1700: }
1701: $items=~s/\&$//;
1702: return &reply("putdom:$udom:$namespace:$items",$uhome);
1703: } else {
1.860 raeburn 1704: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1705: }
1706: }
1707:
1.1023 raeburn 1708: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1709: sub newput_dom {
1.1023 raeburn 1710: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1711: my $result;
1712: if (!$udom) {
1713: $udom=$env{'user.domain'};
1714: }
1.1023 raeburn 1715: if ($udom) {
1716: my $uname = &get_domainconfiguser($udom);
1717: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1718: }
1719: return $result;
1720: }
1721:
1.1023 raeburn 1722: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1723: sub del_dom {
1.1023 raeburn 1724: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1725: if (ref($storearr) eq 'ARRAY') {
1726: if (!$udom) {
1727: $udom=$env{'user.domain'};
1728: }
1.1023 raeburn 1729: if ($udom) {
1730: my $uname = &get_domainconfiguser($udom);
1731: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1732: }
1733: }
1734: }
1735:
1.1023 raeburn 1736: # ----------------------------------construct domainconfig user for a domain
1737: sub get_domainconfiguser {
1738: my ($udom) = @_;
1739: return $udom.'-domainconfig';
1740: }
1741:
1.837 raeburn 1742: sub retrieve_inst_usertypes {
1743: my ($udom) = @_;
1744: my (%returnhash,@order);
1.989 raeburn 1745: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1746: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1747: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256 raeburn 1748: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989 raeburn 1749: } else {
1750: if (defined(&domain($udom,'primary'))) {
1751: my $uhome=&domain($udom,'primary');
1752: my $rep=&reply("inst_usertypes:$udom",$uhome);
1753: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256 raeburn 1754: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989 raeburn 1755: return (\%returnhash,\@order);
1756: }
1757: my ($hashitems,$orderitems) = split(/:/,$rep);
1758: my @pairs=split(/\&/,$hashitems);
1759: foreach my $item (@pairs) {
1760: my ($key,$value)=split(/=/,$item,2);
1761: $key = &unescape($key);
1762: next if ($key =~ /^error: 2 /);
1763: $returnhash{$key}=&thaw_unescape($value);
1764: }
1765: my @esc_order = split(/\&/,$orderitems);
1766: foreach my $item (@esc_order) {
1767: push(@order,&unescape($item));
1768: }
1769: } else {
1.1256 raeburn 1770: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837 raeburn 1771: }
1.1256 raeburn 1772: return (\%returnhash,\@order);
1.837 raeburn 1773: }
1774: }
1775:
1.868 raeburn 1776: sub is_domainimage {
1777: my ($url) = @_;
1778: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1779: if (&domain($1) ne '') {
1780: return '1';
1781: }
1782: }
1783: return;
1784: }
1785:
1.899 raeburn 1786: sub inst_directory_query {
1787: my ($srch) = @_;
1788: my $udom = $srch->{'srchdomain'};
1789: my %results;
1790: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1791: my $outcome;
1.899 raeburn 1792: if ($homeserver ne '') {
1.904 albertel 1793: my $queryid=&reply("querysend:instdirsearch:".
1794: &escape($srch->{'srchby'}).':'.
1795: &escape($srch->{'srchterm'}).':'.
1796: &escape($srch->{'srchtype'}),$homeserver);
1797: my $host=&hostname($homeserver);
1798: if ($queryid !~/^\Q$host\E\_/) {
1799: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1800: return;
1801: }
1802: my $response = &get_query_reply($queryid);
1803: my $maxtries = 5;
1804: my $tries = 1;
1805: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1806: $response = &get_query_reply($queryid);
1807: $tries ++;
1808: }
1809:
1810: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1811: if ($response eq 'unavailable') {
1812: $outcome = $response;
1813: } else {
1814: $outcome = 'ok';
1815: my @matches = split(/\n/,$response);
1816: foreach my $match (@matches) {
1817: my ($key,$value) = split(/=/,$match);
1818: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1819: }
1.899 raeburn 1820: }
1821: }
1822: }
1.909 raeburn 1823: return ($outcome,%results);
1.899 raeburn 1824: }
1825:
1826: sub usersearch {
1827: my ($srch) = @_;
1828: my $dom = $srch->{'srchdomain'};
1829: my %results;
1830: my %libserv = &all_library();
1831: my $query = 'usersearch';
1832: foreach my $tryserver (keys(%libserv)) {
1833: if (&host_domain($tryserver) eq $dom) {
1834: my $host=&hostname($tryserver);
1835: my $queryid=
1.911 raeburn 1836: &reply("querysend:".&escape($query).':'.
1837: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1838: &escape($srch->{'srchtype'}).':'.
1839: &escape($srch->{'srchterm'}),$tryserver);
1840: if ($queryid !~/^\Q$host\E\_/) {
1841: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1842: next;
1.899 raeburn 1843: }
1844: my $reply = &get_query_reply($queryid);
1845: my $maxtries = 1;
1846: my $tries = 1;
1847: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1848: $reply = &get_query_reply($queryid);
1849: $tries ++;
1850: }
1851: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1852: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1853: } else {
1.911 raeburn 1854: my @matches;
1855: if ($reply =~ /\n/) {
1856: @matches = split(/\n/,$reply);
1857: } else {
1858: @matches = split(/\&/,$reply);
1859: }
1.899 raeburn 1860: foreach my $match (@matches) {
1861: my ($uname,$udom,%userhash);
1.911 raeburn 1862: foreach my $entry (split(/:/,$match)) {
1863: my ($key,$value) =
1864: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1865: $userhash{$key} = $value;
1866: if ($key eq 'username') {
1867: $uname = $value;
1868: } elsif ($key eq 'domain') {
1869: $udom = $value;
1.911 raeburn 1870: }
1.899 raeburn 1871: }
1872: $results{$uname.':'.$udom} = \%userhash;
1873: }
1874: }
1875: }
1876: }
1877: return %results;
1878: }
1879:
1.912 raeburn 1880: sub get_instuser {
1881: my ($udom,$uname,$id) = @_;
1882: my $homeserver = &domain($udom,'primary');
1883: my ($outcome,%results);
1884: if ($homeserver ne '') {
1885: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1886: &escape($id).':'.&escape($udom),$homeserver);
1887: my $host=&hostname($homeserver);
1888: if ($queryid !~/^\Q$host\E\_/) {
1889: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1890: return;
1891: }
1892: my $response = &get_query_reply($queryid);
1893: my $maxtries = 5;
1894: my $tries = 1;
1895: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1896: $response = &get_query_reply($queryid);
1897: $tries ++;
1898: }
1899: if (!&error($response) && $response ne 'refused') {
1900: if ($response eq 'unavailable') {
1901: $outcome = $response;
1902: } else {
1903: $outcome = 'ok';
1904: my @matches = split(/\n/,$response);
1905: foreach my $match (@matches) {
1906: my ($key,$value) = split(/=/,$match);
1907: $results{&unescape($key)} = &thaw_unescape($value);
1908: }
1909: }
1910: }
1911: }
1912: my %userinfo;
1913: if (ref($results{$uname}) eq 'HASH') {
1914: %userinfo = %{$results{$uname}};
1915: }
1916: return ($outcome,%userinfo);
1917: }
1918:
1919: sub inst_rulecheck {
1.923 raeburn 1920: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1921: my %returnhash;
1922: if ($udom ne '') {
1923: if (ref($rules) eq 'ARRAY') {
1924: @{$rules} = map {&escape($_);} (@{$rules});
1925: my $rulestr = join(':',@{$rules});
1926: my $homeserver=&domain($udom,'primary');
1927: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1928: my $response;
1929: if ($item eq 'username') {
1930: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1931: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1932: $homeserver));
1.923 raeburn 1933: } elsif ($item eq 'id') {
1934: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1935: ':'.&escape($id).':'.$rulestr,
1936: $homeserver));
1.945 raeburn 1937: } elsif ($item eq 'selfcreate') {
1938: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1939: &escape($udom).':'.&escape($uname).
1940: ':'.$rulestr,$homeserver));
1.923 raeburn 1941: }
1.912 raeburn 1942: if ($response ne 'refused') {
1943: my @pairs=split(/\&/,$response);
1944: foreach my $item (@pairs) {
1945: my ($key,$value)=split(/=/,$item,2);
1946: $key = &unescape($key);
1947: next if ($key =~ /^error: 2 /);
1948: $returnhash{$key}=&thaw_unescape($value);
1949: }
1950: }
1951: }
1952: }
1953: }
1954: return %returnhash;
1955: }
1956:
1957: sub inst_userrules {
1.923 raeburn 1958: my ($udom,$check) = @_;
1.912 raeburn 1959: my (%ruleshash,@ruleorder);
1960: if ($udom ne '') {
1961: my $homeserver=&domain($udom,'primary');
1962: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1963: my $response;
1964: if ($check eq 'id') {
1965: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1966: $homeserver);
1.943 raeburn 1967: } elsif ($check eq 'email') {
1968: $response=&reply('instemailrules:'.&escape($udom),
1969: $homeserver);
1.923 raeburn 1970: } else {
1971: $response=&reply('instuserrules:'.&escape($udom),
1972: $homeserver);
1973: }
1.912 raeburn 1974: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1975: ($response ne 'unknown_cmd') &&
1.912 raeburn 1976: ($response ne 'no_such_host')) {
1977: my ($hashitems,$orderitems) = split(/:/,$response);
1978: my @pairs=split(/\&/,$hashitems);
1979: foreach my $item (@pairs) {
1980: my ($key,$value)=split(/=/,$item,2);
1981: $key = &unescape($key);
1982: next if ($key =~ /^error: 2 /);
1983: $ruleshash{$key}=&thaw_unescape($value);
1984: }
1985: my @esc_order = split(/\&/,$orderitems);
1986: foreach my $item (@esc_order) {
1987: push(@ruleorder,&unescape($item));
1988: }
1989: }
1990: }
1991: }
1992: return (\%ruleshash,\@ruleorder);
1993: }
1994:
1.976 raeburn 1995: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1996:
1997: sub get_domain_defaults {
1.1240 raeburn 1998: my ($domain,$ignore_cache) = @_;
1.1242 raeburn 1999: return if (($domain eq '') || ($domain eq 'public'));
1.943 raeburn 2000: my $cachetime = 60*60*24;
1.1240 raeburn 2001: unless ($ignore_cache) {
2002: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2003: if (defined($cached)) {
2004: if (ref($result) eq 'HASH') {
2005: return %{$result};
2006: }
1.943 raeburn 2007: }
2008: }
2009: my %domdefaults;
2010: my %domconfig =
1.989 raeburn 2011: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 2012: 'requestcourses','inststatus',
1.1183 raeburn 2013: 'coursedefaults','usersessions',
1.1254 raeburn 2014: 'requestauthor','selfenrollment'],$domain);
2015: my @coursetypes = ('official','unofficial','community','textbook');
1.943 raeburn 2016: if (ref($domconfig{'defaults'}) eq 'HASH') {
2017: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2018: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2019: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 2020: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 2021: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 2022: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 2023: } else {
2024: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2025: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2026: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2027: }
1.976 raeburn 2028: if (ref($domconfig{'quotas'}) eq 'HASH') {
2029: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2030: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2031: } else {
2032: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229 raeburn 2033: }
1.1177 raeburn 2034: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 2035: foreach my $item (@usertools) {
2036: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2037: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2038: }
2039: }
1.1229 raeburn 2040: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2041: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2042: }
1.976 raeburn 2043: }
1.985 raeburn 2044: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1246 raeburn 2045: foreach my $item ('official','unofficial','community','textbook') {
1.985 raeburn 2046: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2047: }
2048: }
1.1183 raeburn 2049: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2050: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2051: }
1.989 raeburn 2052: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256 raeburn 2053: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989 raeburn 2054: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2055: }
2056: }
1.1047 raeburn 2057: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230 raeburn 2058: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1254 raeburn 2059: foreach my $type (@coursetypes) {
2060: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2061: unless ($type eq 'community') {
2062: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2063: }
2064: }
2065: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2066: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2067: }
1.1230 raeburn 2068: }
1.1047 raeburn 2069: }
1.1073 raeburn 2070: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2071: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2072: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2073: }
2074: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2075: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2076: }
2077: }
1.1254 raeburn 2078: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2079: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2080: my @settings = ('types','registered','enroll_dates','access_dates','section',
2081: 'approval','limit');
2082: foreach my $type (@coursetypes) {
2083: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2084: my @mgrdc = ();
2085: foreach my $item (@settings) {
2086: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2087: push(@mgrdc,$item);
2088: }
2089: }
2090: if (@mgrdc) {
2091: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2092: }
2093: }
2094: }
2095: }
2096: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2097: foreach my $type (@coursetypes) {
2098: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2099: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2100: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2101: }
2102: }
2103: }
2104: }
2105: }
1.1219 raeburn 2106: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943 raeburn 2107: return %domdefaults;
2108: }
2109:
1.344 www 2110: # --------------------------------------------------- Assign a key to a student
2111:
2112: sub assign_access_key {
1.364 www 2113: #
2114: # a valid key looks like uname:udom#comments
2115: # comments are being appended
2116: #
1.498 www 2117: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2118: $kdom=
1.620 albertel 2119: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2120: $knum=
1.620 albertel 2121: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2122: $cdom=
1.620 albertel 2123: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2124: $cnum=
1.620 albertel 2125: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2126: $udom=$env{'user.name'} unless (defined($udom));
2127: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2128: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2129: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2130: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2131: # assigned to this person
2132: # - this should not happen,
1.345 www 2133: # unless something went wrong
2134: # the first time around
2135: # ready to assign
1.364 www 2136: $logentry=$1.'; '.$logentry;
1.496 www 2137: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2138: $kdom,$knum) eq 'ok') {
1.345 www 2139: # key now belongs to user
1.346 www 2140: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2141: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2142: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2143: return 'ok';
2144: } else {
2145: return
2146: 'error: Count not permanently assign key, will need to be re-entered later.';
2147: }
2148: } else {
2149: return 'error: Could not assign key, try again later.';
2150: }
1.364 www 2151: } elsif (!$existing{$ckey}) {
1.345 www 2152: # the key does not exist
2153: return 'error: The key does not exist';
2154: } else {
2155: # the key is somebody else's
2156: return 'error: The key is already in use';
2157: }
1.344 www 2158: }
2159:
1.364 www 2160: # ------------------------------------------ put an additional comment on a key
2161:
2162: sub comment_access_key {
2163: #
2164: # a valid key looks like uname:udom#comments
2165: # comments are being appended
2166: #
2167: my ($ckey,$cdom,$cnum,$logentry)=@_;
2168: $cdom=
1.620 albertel 2169: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2170: $cnum=
1.620 albertel 2171: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2172: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2173: if ($existing{$ckey}) {
2174: $existing{$ckey}.='; '.$logentry;
2175: # ready to assign
1.367 www 2176: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2177: $cdom,$cnum) eq 'ok') {
2178: return 'ok';
2179: } else {
2180: return 'error: Count not store comment.';
2181: }
2182: } else {
2183: # the key does not exist
2184: return 'error: The key does not exist';
2185: }
2186: }
2187:
1.344 www 2188: # ------------------------------------------------------ Generate a set of keys
2189:
2190: sub generate_access_keys {
1.364 www 2191: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2192: $cdom=
1.620 albertel 2193: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2194: $cnum=
1.620 albertel 2195: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2196: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2197: unless (($cdom) && ($cnum)) { return 0; }
2198: if ($number>10000) { return 0; }
2199: sleep(2); # make sure don't get same seed twice
2200: srand(time()^($$+($$<<15))); # from "Programming Perl"
2201: my $total=0;
2202: for (my $i=1;$i<=$number;$i++) {
2203: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2204: sprintf("%lx",int(100000*rand)).'-'.
2205: sprintf("%lx",int(100000*rand));
2206: $newkey=~s/1/g/g; # folks mix up 1 and l
2207: $newkey=~s/0/h/g; # and also 0 and O
2208: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2209: if ($existing{$newkey}) {
2210: $i--;
2211: } else {
1.364 www 2212: if (&put('accesskeys',
2213: { $newkey => '# generated '.localtime().
1.620 albertel 2214: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2215: '; '.$logentry },
2216: $cdom,$cnum) eq 'ok') {
1.344 www 2217: $total++;
2218: }
2219: }
2220: }
1.620 albertel 2221: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2222: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2223: return $total;
2224: }
2225:
2226: # ------------------------------------------------------- Validate an accesskey
2227:
2228: sub validate_access_key {
2229: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2230: $cdom=
1.620 albertel 2231: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2232: $cnum=
1.620 albertel 2233: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2234: $udom=$env{'user.domain'} unless (defined($udom));
2235: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2236: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2237: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2238: }
2239:
2240: # ------------------------------------- Find the section of student in a course
1.652 albertel 2241: sub devalidate_getsection_cache {
2242: my ($udom,$unam,$courseid)=@_;
2243: my $hashid="$udom:$unam:$courseid";
2244: &devalidate_cache_new('getsection',$hashid);
2245: }
1.298 matthew 2246:
1.815 albertel 2247: sub courseid_to_courseurl {
2248: my ($courseid) = @_;
2249: #already url style courseid
2250: return $courseid if ($courseid =~ m{^/});
2251:
2252: if (exists($env{'course.'.$courseid.'.num'})) {
2253: my $cnum = $env{'course.'.$courseid.'.num'};
2254: my $cdom = $env{'course.'.$courseid.'.domain'};
2255: return "/$cdom/$cnum";
2256: }
2257:
2258: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2259: if (exists($courseinfo{'num'})) {
2260: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2261: }
2262:
2263: return undef;
2264: }
2265:
1.298 matthew 2266: sub getsection {
2267: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2268: my $cachetime=1800;
1.551 albertel 2269:
2270: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2271: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2272: if (defined($cached)) { return $result; }
2273:
1.298 matthew 2274: my %Pending;
2275: my %Expired;
2276: #
2277: # Each role can either have not started yet (pending), be active,
2278: # or have expired.
2279: #
2280: # If there is an active role, we are done.
2281: #
2282: # If there is more than one role which has not started yet,
2283: # choose the one which will start sooner
2284: # If there is one role which has not started yet, return it.
2285: #
2286: # If there is more than one expired role, choose the one which ended last.
2287: # If there is a role which has expired, return it.
2288: #
1.815 albertel 2289: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2290: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2291: foreach my $key (keys(%roleshash)) {
1.479 albertel 2292: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2293: my $section=$1;
2294: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2295: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2296: my $now=time;
1.548 albertel 2297: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2298: $Expired{$end}=$section;
2299: next;
2300: }
1.548 albertel 2301: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2302: $Pending{$start}=$section;
2303: next;
2304: }
1.599 albertel 2305: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2306: }
2307: #
2308: # Presumedly there will be few matching roles from the above
2309: # loop and the sorting time will be negligible.
2310: if (scalar(keys(%Pending))) {
2311: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2312: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2313: }
2314: if (scalar(keys(%Expired))) {
2315: my @sorted = sort {$a <=> $b} keys(%Expired);
2316: my $time = pop(@sorted);
1.599 albertel 2317: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2318: }
1.599 albertel 2319: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2320: }
1.70 www 2321:
1.599 albertel 2322: sub save_cache {
2323: &purge_remembered();
1.722 albertel 2324: #&Apache::loncommon::validate_page();
1.620 albertel 2325: undef(%env);
1.780 albertel 2326: undef($env_loaded);
1.599 albertel 2327: }
1.452 albertel 2328:
1.599 albertel 2329: my $to_remember=-1;
2330: my %remembered;
2331: my %accessed;
2332: my $kicks=0;
2333: my $hits=0;
1.849 albertel 2334: sub make_key {
2335: my ($name,$id) = @_;
1.872 albertel 2336: if (length($id) > 65
2337: && length(&escape($id)) > 200) {
2338: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2339: }
1.849 albertel 2340: return &escape($name.':'.$id);
2341: }
2342:
1.599 albertel 2343: sub devalidate_cache_new {
2344: my ($name,$id,$debug) = @_;
2345: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2346: $id=&make_key($name,$id);
1.599 albertel 2347: $memcache->delete($id);
2348: delete($remembered{$id});
2349: delete($accessed{$id});
2350: }
2351:
2352: sub is_cached_new {
2353: my ($name,$id,$debug) = @_;
1.849 albertel 2354: $id=&make_key($name,$id);
1.599 albertel 2355: if (exists($remembered{$id})) {
1.1133 foxr 2356: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2357: $accessed{$id}=[&gettimeofday()];
2358: $hits++;
2359: return ($remembered{$id},1);
2360: }
2361: my $value = $memcache->get($id);
2362: if (!(defined($value))) {
2363: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2364: return (undef,undef);
1.416 albertel 2365: }
1.599 albertel 2366: if ($value eq '__undef__') {
2367: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2368: $value=undef;
2369: }
2370: &make_room($id,$value,$debug);
2371: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2372: return ($value,1);
2373: }
2374:
2375: sub do_cache_new {
2376: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2377: $id=&make_key($name,$id);
1.599 albertel 2378: my $setvalue=$value;
2379: if (!defined($setvalue)) {
2380: $setvalue='__undef__';
2381: }
1.623 albertel 2382: if (!defined($time) ) {
2383: $time=600;
2384: }
1.599 albertel 2385: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2386: my $result = $memcache->set($id,$setvalue,$time);
2387: if (! $result) {
1.872 albertel 2388: &logthis("caching of id -> $id failed");
1.910 albertel 2389: $memcache->disconnect_all();
1.872 albertel 2390: }
1.600 albertel 2391: # need to make a copy of $value
1.919 albertel 2392: &make_room($id,$value,$debug);
1.599 albertel 2393: return $value;
2394: }
2395:
2396: sub make_room {
2397: my ($id,$value,$debug)=@_;
1.919 albertel 2398:
2399: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2400: : $value;
1.599 albertel 2401: if ($to_remember<0) { return; }
2402: $accessed{$id}=[&gettimeofday()];
2403: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2404: my $to_kick;
2405: my $max_time=0;
2406: foreach my $other (keys(%accessed)) {
2407: if (&tv_interval($accessed{$other}) > $max_time) {
2408: $to_kick=$other;
2409: $max_time=&tv_interval($accessed{$other});
2410: }
2411: }
2412: delete($remembered{$to_kick});
2413: delete($accessed{$to_kick});
2414: $kicks++;
2415: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2416: return;
2417: }
2418:
1.599 albertel 2419: sub purge_remembered {
1.604 albertel 2420: #&logthis("Tossing ".scalar(keys(%remembered)));
2421: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2422: undef(%remembered);
2423: undef(%accessed);
1.428 albertel 2424: }
1.70 www 2425: # ------------------------------------- Read an entry from a user's environment
2426:
2427: sub userenvironment {
2428: my ($udom,$unam,@what)=@_;
1.976 raeburn 2429: my $items;
2430: foreach my $item (@what) {
2431: $items.=&escape($item).'&';
2432: }
2433: $items=~s/\&$//;
1.70 www 2434: my %returnhash=();
1.1009 raeburn 2435: my $uhome = &homeserver($unam,$udom);
2436: unless ($uhome eq 'no_host') {
2437: my @answer=split(/\&/,
2438: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2439: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2440: return %returnhash;
2441: }
1.1009 raeburn 2442: my $i;
2443: for ($i=0;$i<=$#what;$i++) {
2444: $returnhash{$what[$i]}=&unescape($answer[$i]);
2445: }
1.70 www 2446: }
2447: return %returnhash;
1.1 albertel 2448: }
2449:
1.617 albertel 2450: # ---------------------------------------------------------- Get a studentphoto
2451: sub studentphoto {
2452: my ($udom,$unam,$ext) = @_;
2453: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2454: if (defined($env{'request.course.id'})) {
1.708 raeburn 2455: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2456: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2457: return(&retrievestudentphoto($udom,$unam,$ext));
2458: } else {
2459: my ($result,$perm_reqd)=
1.707 albertel 2460: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2461: if ($result eq 'ok') {
2462: if (!($perm_reqd eq 'yes')) {
2463: return(&retrievestudentphoto($udom,$unam,$ext));
2464: }
2465: }
2466: }
2467: }
2468: } else {
2469: my ($result,$perm_reqd) =
1.707 albertel 2470: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2471: if ($result eq 'ok') {
2472: if (!($perm_reqd eq 'yes')) {
2473: return(&retrievestudentphoto($udom,$unam,$ext));
2474: }
2475: }
2476: }
2477: return '/adm/lonKaputt/lonlogo_broken.gif';
2478: }
2479:
2480: sub retrievestudentphoto {
2481: my ($udom,$unam,$ext,$type) = @_;
2482: my $home=&Apache::lonnet::homeserver($unam,$udom);
2483: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2484: if ($ret eq 'ok') {
2485: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2486: if ($type eq 'thumbnail') {
2487: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2488: }
2489: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2490: return $tokenurl;
2491: } else {
2492: if ($type eq 'thumbnail') {
2493: return '/adm/lonKaputt/genericstudent_tn.gif';
2494: } else {
2495: return '/adm/lonKaputt/lonlogo_broken.gif';
2496: }
1.617 albertel 2497: }
2498: }
2499:
1.263 www 2500: # -------------------------------------------------------------------- New chat
2501:
2502: sub chatsend {
1.724 raeburn 2503: my ($newentry,$anon,$group)=@_;
1.620 albertel 2504: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2505: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2506: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2507: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2508: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2509: &escape($newentry)).':'.$group,$chome);
1.292 www 2510: }
2511:
2512: # ------------------------------------------ Find current version of a resource
2513:
2514: sub getversion {
2515: my $fname=&clutter(shift);
1.1189 raeburn 2516: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2517: return ¤tversion(&filelocation('',$fname));
2518: }
2519:
2520: sub currentversion {
2521: my $fname=shift;
2522: my $author=$fname;
2523: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2524: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2525: my $home=&homeserver($uname,$udom);
1.292 www 2526: if ($home eq 'no_host') {
2527: return -1;
2528: }
1.1112 www 2529: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2530: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2531: return -1;
2532: }
1.1112 www 2533: return $answer;
1.263 www 2534: }
2535:
1.1111 www 2536: #
2537: # Return special version number of resource if set by override, empty otherwise
2538: #
2539: sub usedversion {
2540: my $fname=shift;
2541: unless ($fname) { $fname=$env{'request.uri'}; }
2542: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2543: if ($urlversion) { return $urlversion; }
2544: return '';
2545: }
2546:
1.1 albertel 2547: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2548:
1.1 albertel 2549: sub subscribe {
2550: my $fname=shift;
1.761 raeburn 2551: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2552: $fname=~s/[\n\r]//g;
1.1 albertel 2553: my $author=$fname;
2554: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2555: my ($udom,$uname)=split(/\//,$author);
2556: my $home=homeserver($uname,$udom);
1.335 albertel 2557: if ($home eq 'no_host') {
2558: return 'not_found';
1.1 albertel 2559: }
2560: my $answer=reply("sub:$fname",$home);
1.64 www 2561: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2562: $answer.=' by '.$home;
2563: }
1.1 albertel 2564: return $answer;
2565: }
2566:
1.8 www 2567: # -------------------------------------------------------------- Replicate file
2568:
2569: sub repcopy {
2570: my $filename=shift;
1.23 www 2571: $filename=~s/\/+/\//g;
1.1142 raeburn 2572: my $londocroot = $perlvar{'lonDocRoot'};
2573: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2574: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2575: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2576: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2577: return &repcopy_userfile($filename);
2578: }
1.532 albertel 2579: $filename=~s/[\n\r]//g;
1.8 www 2580: my $transname="$filename.in.transfer";
1.828 www 2581: # FIXME: this should flock
1.607 raeburn 2582: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2583: my $remoteurl=subscribe($filename);
1.64 www 2584: if ($remoteurl =~ /^con_lost by/) {
2585: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2586: return 'unavailable';
1.8 www 2587: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2588: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2589: return 'not_found';
1.64 www 2590: } elsif ($remoteurl =~ /^rejected by/) {
2591: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2592: return 'forbidden';
1.20 www 2593: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2594: return 'ok';
1.8 www 2595: } else {
1.290 www 2596: my $author=$filename;
2597: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2598: my ($udom,$uname)=split(/\//,$author);
2599: my $home=homeserver($uname,$udom);
2600: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2601: my @parts=split(/\//,$filename);
2602: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2603: if ($path ne "$londocroot/res") {
1.8 www 2604: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2605: return 'bad_request';
1.8 www 2606: }
2607: my $count;
2608: for ($count=5;$count<$#parts;$count++) {
2609: $path.="/$parts[$count]";
2610: if ((-e $path)!=1) {
2611: mkdir($path,0777);
2612: }
2613: }
2614: my $ua=new LWP::UserAgent;
2615: my $request=new HTTP::Request('GET',"$remoteurl");
2616: my $response=$ua->request($request,$transname);
2617: if ($response->is_error()) {
2618: unlink($transname);
2619: my $message=$response->status_line;
1.672 albertel 2620: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2621: ." LWP get: $message: $filename</font>");
1.607 raeburn 2622: return 'unavailable';
1.8 www 2623: } else {
1.16 www 2624: if ($remoteurl!~/\.meta$/) {
2625: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2626: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2627: if ($mresponse->is_error()) {
2628: unlink($filename.'.meta');
2629: &logthis(
1.672 albertel 2630: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2631: }
2632: }
1.8 www 2633: rename($transname,$filename);
1.607 raeburn 2634: return 'ok';
1.8 www 2635: }
1.290 www 2636: }
1.8 www 2637: }
1.330 www 2638: }
2639:
2640: # ------------------------------------------------ Get server side include body
2641: sub ssi_body {
1.381 albertel 2642: my ($filelink,%form)=@_;
1.606 matthew 2643: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2644: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2645: }
1.953 www 2646: my $output='';
2647: my $response;
1.980 raeburn 2648: if ($filelink=~/^https?\:/) {
1.954 raeburn 2649: ($output,$response)=&externalssi($filelink);
1.953 www 2650: } else {
1.1004 droeschl 2651: $filelink .= $filelink=~/\?/ ? '&' : '?';
2652: $filelink .= 'inhibitmenu=yes';
1.953 www 2653: ($output,$response)=&ssi($filelink,%form);
2654: }
1.778 albertel 2655: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2656: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2657: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2658: if (wantarray) {
2659: return ($output, $response);
2660: } else {
2661: return $output;
2662: }
1.8 www 2663: }
2664:
1.15 www 2665: # --------------------------------------------------------- Server Side Include
2666:
1.782 albertel 2667: sub absolute_url {
2668: my ($host_name) = @_;
2669: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2670: if ($host_name eq '') {
2671: $host_name = $ENV{'SERVER_NAME'};
2672: }
2673: return $protocol.$host_name;
2674: }
2675:
1.942 foxr 2676: #
2677: # Server side include.
2678: # Parameters:
2679: # fn Possibly encrypted resource name/id.
2680: # form Hash that describes how the rendering should be done
2681: # and other things.
1.944 foxr 2682: # Returns:
1.950 raeburn 2683: # Scalar context: The content of the response.
2684: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2685: #
1.15 www 2686: sub ssi {
2687:
1.944 foxr 2688: my ($fn,%form)=@_;
1.15 www 2689: my $ua=new LWP::UserAgent;
1.23 www 2690: my $request;
1.711 albertel 2691:
2692: $form{'no_update_last_known'}=1;
1.895 albertel 2693: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2694: if (%form) {
1.782 albertel 2695: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2696: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2697: } else {
1.782 albertel 2698: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2699: }
2700:
1.15 www 2701: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2702: my $response= $ua->request($request);
1.1182 foxr 2703: my $content = $response->content;
2704:
2705:
1.944 foxr 2706: if (wantarray) {
1.1173 foxr 2707: return ($content, $response);
1.944 foxr 2708: } else {
1.1173 foxr 2709: return $content;
1.942 foxr 2710: }
1.324 www 2711: }
2712:
2713: sub externalssi {
2714: my ($url)=@_;
2715: my $ua=new LWP::UserAgent;
2716: my $request=new HTTP::Request('GET',$url);
2717: my $response=$ua->request($request);
1.954 raeburn 2718: if (wantarray) {
2719: return ($response->content, $response);
2720: } else {
2721: return $response->content;
2722: }
1.15 www 2723: }
1.254 www 2724:
1.492 albertel 2725: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2726:
2727: sub allowuploaded {
2728: my ($srcurl,$url)=@_;
2729: $url=&clutter(&declutter($url));
2730: my $dir=$url;
2731: $dir=~s/\/[^\/]+$//;
2732: my %httpref=();
2733: my $httpurl=&hreflocation('',$url);
2734: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2735: &Apache::lonnet::appenv(\%httpref);
1.254 www 2736: }
1.477 raeburn 2737:
1.1193 raeburn 2738: #
2739: # Determine if the current user should be able to edit a particular resource,
2740: # when viewing in course context.
2741: # (a) When viewing resource used to determine if "Edit" item is included in
2742: # Functions.
2743: # (b) When displaying folder contents in course editor, used to determine if
2744: # "Edit" link will be displayed alongside resource.
2745: #
1.1196 raeburn 2746: # input: six args -- filename (decluttered), course number, course domain,
2747: # url, symb (if registered) and group (if this is a group
2748: # item -- e.g., bulletin board, group page etc.).
2749: # output: array of five scalars --
1.1193 raeburn 2750: # $cfile -- url for file editing if editable on current server
2751: # $home -- homeserver of resource (i.e., for author if published,
2752: # or course if uploaded.).
2753: # $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 2754: # $forceedit -- 1 if icon/link should be to go to edit mode
2755: # $forceview -- 1 if icon/link should be to go to view mode
1.1193 raeburn 2756: #
2757:
2758: sub can_edit_resource {
1.1194 raeburn 2759: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2760: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2761: #
2762: # For aboutme pages user can only edit his/her own.
2763: #
1.1199 raeburn 2764: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194 raeburn 2765: my ($sdom,$sname) = ($1,$2);
2766: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2767: $home = $env{'user.home'};
2768: $cfile = $resurl;
2769: if ($env{'form.forceedit'}) {
2770: $forceview = 1;
2771: } else {
2772: $forceedit = 1;
2773: }
2774: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2775: } else {
2776: return;
2777: }
2778: }
2779:
2780: if ($env{'request.course.id'}) {
2781: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2782: if ($group ne '') {
2783: # if this is a group homepage or group bulletin board, check group privs
2784: my $allowed = 0;
1.1197 raeburn 2785: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2786: if ((&allowed('mdg',$env{'request.course.id'}.
1.1198 raeburn 2787: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194 raeburn 2788: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2789: $allowed = 1;
2790: }
1.1197 raeburn 2791: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2792: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2793: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194 raeburn 2794: $allowed = 1;
2795: }
2796: }
2797: if ($allowed) {
2798: $home=&homeserver($cnum,$cdom);
2799: if ($env{'form.forceedit'}) {
2800: $forceview = 1;
2801: } else {
2802: $forceedit = 1;
2803: }
2804: $cfile = $resurl;
2805: } else {
2806: return;
2807: }
2808: } else {
1.1208 raeburn 2809: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2810: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2811: return;
2812: }
2813: } elsif (!$crsedit) {
1.1194 raeburn 2814: #
2815: # No edit allowed where CC has switched to student role.
2816: #
2817: return;
2818: }
2819: }
2820: }
2821:
1.1193 raeburn 2822: if ($file ne '') {
2823: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194 raeburn 2824: if (&is_course_upload($file,$cnum,$cdom)) {
2825: $uploaded = 1;
2826: $incourse = 1;
1.1193 raeburn 2827: if ($file =~/\.(htm|html|css|js|txt)$/) {
2828: $cfile = &hreflocation('',$file);
1.1201 raeburn 2829: if ($env{'form.forceedit'}) {
2830: $forceview = 1;
2831: } else {
2832: $forceedit = 1;
2833: }
1.1194 raeburn 2834: }
2835: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2836: $incourse = 1;
2837: if ($env{'form.forceedit'}) {
2838: $forceview = 1;
2839: } else {
2840: $forceedit = 1;
2841: }
2842: $cfile = $resurl;
2843: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2844: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2845: $incourse = 1;
2846: if ($env{'form.forceedit'}) {
2847: $forceview = 1;
2848: } else {
2849: $forceedit = 1;
2850: }
2851: $cfile = $resurl;
1.1199 raeburn 2852: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194 raeburn 2853: $incourse = 1;
2854: $cfile = $resurl.'/smpedit';
1.1199 raeburn 2855: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194 raeburn 2856: $incourse = 1;
1.1199 raeburn 2857: if ($env{'form.forceedit'}) {
2858: $forceview = 1;
2859: } else {
2860: $forceedit = 1;
2861: }
2862: $cfile = $resurl;
1.1208 raeburn 2863: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2864: $incourse = 1;
2865: if ($env{'form.forceedit'}) {
2866: $forceview = 1;
2867: } else {
2868: $forceedit = 1;
2869: }
2870: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194 raeburn 2871: }
2872: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2873: my $template = '/res/lib/templates/simpleproblem.problem';
2874: if (&is_on_map($template)) {
2875: $incourse = 1;
2876: $forceview = 1;
2877: $cfile = $template;
1.1193 raeburn 2878: }
1.1199 raeburn 2879: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2880: $incourse = 1;
2881: if ($env{'form.forceedit'}) {
2882: $forceview = 1;
2883: } else {
2884: $forceedit = 1;
2885: }
2886: $cfile = $resurl;
2887: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2888: $incourse = 1;
2889: $forceview = 1;
2890: if ($symb) {
2891: my ($map,$id,$res)=&decode_symb($symb);
2892: $env{'request.symb'} = $symb;
2893: $cfile = &clutter($res);
2894: } else {
2895: $cfile = $env{'form.suppurl'};
2896: $cfile =~ s{^http://}{};
2897: $cfile = '/adm/wrapper/ext/'.$cfile;
2898: }
1.1234 raeburn 2899: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2900: if ($env{'form.forceedit'}) {
2901: $forceview = 1;
2902: } else {
2903: $forceedit = 1;
2904: }
2905: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193 raeburn 2906: }
2907: }
1.1194 raeburn 2908: if ($uploaded || $incourse) {
2909: $home=&homeserver($cnum,$cdom);
1.1207 raeburn 2910: } elsif ($file !~ m{/$}) {
1.1193 raeburn 2911: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2912: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2913: # Check that the user has permission to edit this resource
2914: my $setpriv = 1;
2915: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2916: if (defined($cfudom)) {
2917: $home=&homeserver($cfuname,$cfudom);
2918: $cfile=$file;
2919: }
2920: }
1.1194 raeburn 2921: if (($cfile ne '') && (!$incourse || $uploaded) &&
2922: (($home ne '') && ($home ne 'no_host'))) {
1.1193 raeburn 2923: my @ids=¤t_machine_ids();
2924: unless (grep(/^\Q$home\E$/,@ids)) {
2925: $switchserver=1;
2926: }
2927: }
2928: }
1.1194 raeburn 2929: return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193 raeburn 2930: }
2931:
2932: sub is_course_upload {
2933: my ($file,$cnum,$cdom) = @_;
2934: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2935: $uploadpath =~ s{^\/}{};
1.1201 raeburn 2936: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2937: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193 raeburn 2938: return 1;
2939: }
2940: return;
2941: }
2942:
1.1194 raeburn 2943: sub in_course {
1.1195 raeburn 2944: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2945: if ($hideprivileged) {
2946: my $skipuser;
1.1219 raeburn 2947: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2948: my @possdoms = ($cdom);
2949: if ($coursehash{'checkforpriv'}) {
2950: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2951: }
2952: if (&privileged($uname,$udom,\@possdoms)) {
1.1195 raeburn 2953: $skipuser = 1;
2954: if ($coursehash{'nothideprivileged'}) {
2955: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2956: my $user;
2957: if ($item =~ /:/) {
2958: $user = $item;
2959: } else {
2960: $user = join(':',split(/[\@]/,$item));
2961: }
2962: if ($user eq $uname.':'.$udom) {
2963: undef($skipuser);
2964: last;
2965: }
2966: }
2967: }
2968: if ($skipuser) {
2969: return 0;
2970: }
2971: }
2972: }
1.1194 raeburn 2973: $type ||= 'any';
2974: if (!defined($cdom) || !defined($cnum)) {
2975: my $cid = $env{'request.course.id'};
2976: $cdom = $env{'course.'.$cid.'.domain'};
2977: $cnum = $env{'course.'.$cid.'.num'};
2978: }
2979: my $typesref;
1.1195 raeburn 2980: if (($type eq 'any') || ($type eq 'all')) {
1.1194 raeburn 2981: $typesref = ['active','previous','future'];
2982: } elsif ($type eq 'previous' || $type eq 'future') {
2983: $typesref = [$type];
2984: }
2985: my %roles = &get_my_roles($uname,$udom,'userroles',
2986: $typesref,undef,[$cdom]);
2987: my ($tmp) = keys(%roles);
2988: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
2989: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
2990: if (@course_roles > 0) {
2991: return 1;
2992: }
2993: return 0;
2994: }
2995:
1.478 albertel 2996: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2997: # input: action, courseID, current domain, intended
1.637 raeburn 2998: # path to file, source of file, instruction to parse file for objects,
2999: # ref to hash for embedded objects,
3000: # ref to hash for codebase of java objects.
1.1095 raeburn 3001: # reference to scalar to accommodate mime type determined
3002: # from File::MMagic if $parser = parse.
1.637 raeburn 3003: #
1.485 raeburn 3004: # output: url to file (if action was uploaddoc),
3005: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 3006: #
1.478 albertel 3007: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3008: # course.
1.477 raeburn 3009: #
1.478 albertel 3010: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3011: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3012: # course's home server.
1.477 raeburn 3013: #
1.478 albertel 3014: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3015: # be copied from $source (current location) to
3016: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3017: # and will then be copied to
3018: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3019: # course's home server.
1.485 raeburn 3020: #
1.481 raeburn 3021: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 3022: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 3023: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3024: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3025: # in course's home server.
1.637 raeburn 3026: #
1.477 raeburn 3027:
3028: sub process_coursefile {
1.1095 raeburn 3029: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3030: $mimetype)=@_;
1.477 raeburn 3031: my $fetchresult;
1.638 albertel 3032: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 3033: if ($action eq 'propagate') {
1.638 albertel 3034: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3035: $home);
1.481 raeburn 3036: } else {
1.477 raeburn 3037: my $fpath = '';
3038: my $fname = $file;
1.478 albertel 3039: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 3040: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 3041: my $filepath = &build_filepath($fpath);
1.481 raeburn 3042: if ($action eq 'copy') {
3043: if ($source eq '') {
3044: $fetchresult = 'no source file';
3045: return $fetchresult;
3046: } else {
3047: my $destination = $filepath.'/'.$fname;
3048: rename($source,$destination);
3049: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3050: $home);
1.481 raeburn 3051: }
3052: } elsif ($action eq 'uploaddoc') {
3053: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 3054: print $fh $env{'form.'.$source};
1.481 raeburn 3055: close($fh);
1.637 raeburn 3056: if ($parser eq 'parse') {
1.1024 raeburn 3057: my $mm = new File::MMagic;
1.1095 raeburn 3058: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3059: if ($type eq 'text/html') {
1.1024 raeburn 3060: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3061: unless ($parse_result eq 'ok') {
3062: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3063: }
1.637 raeburn 3064: }
1.1095 raeburn 3065: if (ref($mimetype)) {
3066: $$mimetype = $type;
3067: }
1.637 raeburn 3068: }
1.477 raeburn 3069: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3070: $home);
1.481 raeburn 3071: if ($fetchresult eq 'ok') {
3072: return '/uploaded/'.$fpath.'/'.$fname;
3073: } else {
3074: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3075: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 3076: return '/adm/notfound.html';
3077: }
1.477 raeburn 3078: }
3079: }
1.485 raeburn 3080: unless ( $fetchresult eq 'ok') {
1.477 raeburn 3081: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 3082: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 3083: }
3084: return $fetchresult;
3085: }
3086:
1.637 raeburn 3087: sub build_filepath {
3088: my ($fpath) = @_;
3089: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3090: unless ($fpath eq '') {
3091: my @parts=split('/',$fpath);
3092: foreach my $part (@parts) {
3093: $filepath.= '/'.$part;
3094: if ((-e $filepath)!=1) {
3095: mkdir($filepath,0777);
3096: }
3097: }
3098: }
3099: return $filepath;
3100: }
3101:
3102: sub store_edited_file {
1.638 albertel 3103: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 3104: my $file = $primary_url;
3105: $file =~ s#^/uploaded/$docudom/$docuname/##;
3106: my $fpath = '';
3107: my $fname = $file;
3108: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3109: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3110: my $filepath = &build_filepath($fpath);
3111: open(my $fh,'>'.$filepath.'/'.$fname);
3112: print $fh $content;
3113: close($fh);
1.638 albertel 3114: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 3115: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 3116: $home);
1.637 raeburn 3117: if ($$fetchresult eq 'ok') {
3118: return '/uploaded/'.$fpath.'/'.$fname;
3119: } else {
1.638 albertel 3120: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3121: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 3122: return '/adm/notfound.html';
3123: }
3124: }
3125:
1.531 albertel 3126: sub clean_filename {
1.831 albertel 3127: my ($fname,$args)=@_;
1.315 www 3128: # Replace Windows backslashes by forward slashes
1.257 www 3129: $fname=~s/\\/\//g;
1.831 albertel 3130: if (!$args->{'keep_path'}) {
3131: # Get rid of everything but the actual filename
3132: $fname=~s/^.*\/([^\/]+)$/$1/;
3133: }
1.315 www 3134: # Replace spaces by underscores
3135: $fname=~s/\s+/\_/g;
3136: # Replace all other weird characters by nothing
1.831 albertel 3137: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 3138: # Replace all .\d. sequences with _\d. so they no longer look like version
3139: # numbers
3140: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 3141: return $fname;
3142: }
1.1051 raeburn 3143: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3144: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3145: # image with the same aspect ratio as the original, but with dimensions which do
3146: # not exceed $resizewidth and $resizeheight.
3147:
1.984 neumanie 3148: sub resizeImage {
1.1051 raeburn 3149: my ($img_path,$resizewidth,$resizeheight) = @_;
3150: my $ima = Image::Magick->new;
3151: my $resized;
3152: if (-e $img_path) {
3153: $ima->Read($img_path);
3154: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3155: my $width = $ima->Get('width');
3156: my $height = $ima->Get('height');
3157: if ($width > $resizewidth) {
3158: my $factor = $width/$resizewidth;
3159: my $newheight = $height/$factor;
3160: $ima->Scale(width=>$resizewidth,height=>$newheight);
3161: $resized = 1;
3162: }
3163: }
3164: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3165: my $width = $ima->Get('width');
3166: my $height = $ima->Get('height');
3167: if ($height > $resizeheight) {
3168: my $factor = $height/$resizeheight;
3169: my $newwidth = $width/$factor;
3170: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3171: $resized = 1;
3172: }
3173: }
3174: if ($resized) {
3175: $ima->Write($img_path);
3176: }
3177: }
3178: return;
1.977 amueller 3179: }
3180:
1.608 albertel 3181: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 3182: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 3183: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 3184: # $context - possible values: coursedoc, existingfile, overwrite,
3185: # canceloverwrite, or ''.
3186: # if 'coursedoc': upload to the current course
3187: # if 'existingfile': write file to tmp/overwrites directory
3188: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3189: # $context is passed as argument to &finishuserfileupload
1.686 albertel 3190: # $subdir - directory in userfile to store the file into
1.858 raeburn 3191: # $parser - instruction to parse file for objects ($parser = parse)
3192: # $allfiles - reference to hash for embedded objects
3193: # $codebase - reference to hash for codebase of java objects
3194: # $desuname - username for permanent storage of uploaded file
3195: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 3196: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3197: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 3198: # $resizewidth - width (pixels) to which to resize uploaded image
3199: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 3200: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 3201: # from File::MMagic.
1.858 raeburn 3202: #
1.686 albertel 3203: # output: url of file in userspace, or error: <message>
3204: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 3205:
1.531 albertel 3206: sub userfileupload {
1.1090 raeburn 3207: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 3208: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 3209: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 3210: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 3211: $fname=&clean_filename($fname);
1.1090 raeburn 3212: # See if there is anything left
1.257 www 3213: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 3214: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3215: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3216: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3217: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 3218: my $now = time;
1.1090 raeburn 3219: my $filepath;
1.1095 raeburn 3220: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 3221: $filepath = 'tmp/helprequests/'.$now;
3222: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3223: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3224: '_'.$env{'user.domain'}.'/pending';
3225: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3226: my ($docuname,$docudom);
3227: if ($destudom) {
3228: $docudom = $destudom;
3229: } else {
3230: $docudom = $env{'user.domain'};
3231: }
3232: if ($destuname) {
3233: $docuname = $destuname;
3234: } else {
3235: $docuname = $env{'user.name'};
3236: }
3237: if (exists($env{'form.group'})) {
3238: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3239: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3240: }
3241: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3242: if ($context eq 'canceloverwrite') {
3243: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3244: if (-e $tempfile) {
3245: my @info = stat($tempfile);
3246: if ($info[9] eq $env{'form.timestamp'}) {
3247: unlink($tempfile);
3248: }
3249: }
3250: return;
1.523 raeburn 3251: }
3252: }
1.1090 raeburn 3253: # Create the directory if not present
1.741 raeburn 3254: my @parts=split(/\//,$filepath);
3255: my $fullpath = $perlvar{'lonDaemons'};
3256: for (my $i=0;$i<@parts;$i++) {
3257: $fullpath .= '/'.$parts[$i];
3258: if ((-e $fullpath)!=1) {
3259: mkdir($fullpath,0777);
3260: }
3261: }
3262: open(my $fh,'>'.$fullpath.'/'.$fname);
3263: print $fh $env{'form.'.$formname};
3264: close($fh);
1.1090 raeburn 3265: if ($context eq 'existingfile') {
3266: my @info = stat($fullpath.'/'.$fname);
3267: return ($fullpath.'/'.$fname,$info[9]);
3268: } else {
3269: return $fullpath.'/'.$fname;
3270: }
1.523 raeburn 3271: }
1.995 raeburn 3272: if ($subdir eq 'scantron') {
3273: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 3274: } else {
1.995 raeburn 3275: $fname="$subdir/$fname";
3276: }
1.1090 raeburn 3277: if ($context eq 'coursedoc') {
1.638 albertel 3278: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3279: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 3280: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 3281: return &finishuserfileupload($docuname,$docudom,
3282: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 3283: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 3284: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 3285: } else {
1.1218 raeburn 3286: if ($env{'form.folder'}) {
3287: $fname=$env{'form.folder'}.'/'.$fname;
3288: }
1.638 albertel 3289: return &process_coursefile('uploaddoc',$docuname,$docudom,
3290: $fname,$formname,$parser,
1.1095 raeburn 3291: $allfiles,$codebase,$mimetype);
1.481 raeburn 3292: }
1.719 banghart 3293: } elsif (defined($destuname)) {
3294: my $docuname=$destuname;
3295: my $docudom=$destudom;
1.860 raeburn 3296: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3297: $parser,$allfiles,$codebase,
1.1051 raeburn 3298: $thumbwidth,$thumbheight,
1.1095 raeburn 3299: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3300: } else {
1.638 albertel 3301: my $docuname=$env{'user.name'};
3302: my $docudom=$env{'user.domain'};
1.1220 raeburn 3303: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714 raeburn 3304: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3305: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3306: }
1.860 raeburn 3307: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3308: $parser,$allfiles,$codebase,
1.1051 raeburn 3309: $thumbwidth,$thumbheight,
1.1095 raeburn 3310: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 3311: }
1.271 www 3312: }
3313:
3314: sub finishuserfileupload {
1.860 raeburn 3315: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 3316: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 3317: my $path=$docudom.'/'.$docuname.'/';
1.258 www 3318: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 3319:
1.860 raeburn 3320: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 3321: $file=$fname;
3322: if ($fname=~m|/|) {
3323: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3324: $path.=$fnamepath.'/';
3325: }
1.259 www 3326: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 3327: my $count;
3328: for ($count=4;$count<=$#parts;$count++) {
3329: $filepath.="/$parts[$count]";
3330: if ((-e $filepath)!=1) {
3331: mkdir($filepath,0777);
3332: }
3333: }
1.984 neumanie 3334:
1.258 www 3335: # Save the file
3336: {
1.701 albertel 3337: if (!open(FH,'>'.$filepath.'/'.$file)) {
3338: &logthis('Failed to create '.$filepath.'/'.$file);
3339: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3340: return '/adm/notfound.html';
3341: }
1.1090 raeburn 3342: if ($context eq 'overwrite') {
1.1117 foxr 3343: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 3344: my $target = $filepath.'/'.$file;
3345: if (-e $source) {
3346: my @info = stat($source);
3347: if ($info[9] eq $env{'form.timestamp'}) {
3348: unless (&File::Copy::move($source,$target)) {
3349: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3350: return "Moving from $source failed";
3351: }
3352: } else {
3353: return "Temporary file: $source had unexpected date/time for last modification";
3354: }
3355: } else {
3356: return "Temporary file: $source missing";
3357: }
3358: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 3359: &logthis('Failed to write to '.$filepath.'/'.$file);
3360: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3361: return '/adm/notfound.html';
3362: }
1.570 albertel 3363: close(FH);
1.1051 raeburn 3364: if ($resizewidth && $resizeheight) {
3365: my $mm = new File::MMagic;
3366: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3367: if ($mime_type =~ m{^image/}) {
3368: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3369: }
1.977 amueller 3370: }
1.258 www 3371: }
1.1152 raeburn 3372: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3373: if (ref($mimetype)) {
3374: if ($$mimetype eq '') {
3375: my $mm = new File::MMagic;
3376: my $type = $mm->checktype_filename($filepath.'/'.$file);
3377: $$mimetype = $type;
3378: }
3379: }
3380: }
1.637 raeburn 3381: if ($parser eq 'parse') {
1.1152 raeburn 3382: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3383: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3384: $allfiles,$codebase);
3385: unless ($parse_result eq 'ok') {
3386: &logthis('Failed to parse '.$filepath.$file.
3387: ' for embedded media: '.$parse_result);
3388: }
1.637 raeburn 3389: }
3390: }
1.860 raeburn 3391: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3392: my $input = $filepath.'/'.$file;
3393: my $output = $filepath.'/'.'tn-'.$file;
3394: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3395: system("convert -sample $thumbsize $input $output");
3396: if (-e $filepath.'/'.'tn-'.$file) {
3397: $fetchthumb = 1;
3398: }
3399: }
1.858 raeburn 3400:
1.259 www 3401: # Notify homeserver to grep it
3402: #
1.984 neumanie 3403: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3404: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3405: if ($fetchresult eq 'ok') {
1.860 raeburn 3406: if ($fetchthumb) {
3407: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3408: if ($thumbresult ne 'ok') {
3409: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3410: $docuhome.': '.$thumbresult);
3411: }
3412: }
1.259 www 3413: #
1.258 www 3414: # Return the URL to it
1.494 albertel 3415: return '/uploaded/'.$path.$file;
1.263 www 3416: } else {
1.494 albertel 3417: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3418: ': '.$fetchresult);
1.263 www 3419: return '/adm/notfound.html';
1.858 raeburn 3420: }
1.493 albertel 3421: }
3422:
1.637 raeburn 3423: sub extract_embedded_items {
1.961 raeburn 3424: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3425: my @state = ();
1.1164 raeburn 3426: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3427: my %javafiles = (
3428: codebase => '',
3429: code => '',
3430: archive => ''
3431: );
3432: my %mediafiles = (
3433: src => '',
3434: movie => '',
3435: );
1.648 raeburn 3436: my $p;
3437: if ($content) {
3438: $p = HTML::LCParser->new($content);
3439: } else {
1.961 raeburn 3440: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3441: }
1.641 albertel 3442: while (my $t=$p->get_token()) {
1.640 albertel 3443: if ($t->[0] eq 'S') {
3444: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3445: push(@state, $tagname);
1.648 raeburn 3446: if (lc($tagname) eq 'allow') {
3447: &add_filetype($allfiles,$attr->{'src'},'src');
3448: }
1.640 albertel 3449: if (lc($tagname) eq 'img') {
3450: &add_filetype($allfiles,$attr->{'src'},'src');
3451: }
1.886 albertel 3452: if (lc($tagname) eq 'a') {
1.1222 raeburn 3453: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221 raeburn 3454: &add_filetype($allfiles,$attr->{'href'},'href');
3455: }
1.886 albertel 3456: }
1.645 raeburn 3457: if (lc($tagname) eq 'script') {
1.1164 raeburn 3458: my $src;
1.645 raeburn 3459: if ($attr->{'archive'} =~ /\.jar$/i) {
3460: &add_filetype($allfiles,$attr->{'archive'},'archive');
3461: } else {
1.1164 raeburn 3462: if ($attr->{'src'} ne '') {
3463: $src = $attr->{'src'};
3464: &add_filetype($allfiles,$src,'src');
3465: }
3466: }
3467: my $text = $p->get_trimmed_text();
3468: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3469: my @swfargs = split(/,/,$1);
3470: foreach my $item (@swfargs) {
3471: $item =~ s/["']//g;
3472: $item =~ s/^\s+//;
3473: $item =~ s/\s+$//;
3474: }
3475: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3476: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3477: push(@{$related{$swfargs[0]}},$swfargs[2]);
3478: } else {
3479: $related{$swfargs[0]} = [$swfargs[2]];
3480: }
3481: }
1.645 raeburn 3482: }
3483: }
3484: if (lc($tagname) eq 'link') {
3485: if (lc($attr->{'rel'}) eq 'stylesheet') {
3486: &add_filetype($allfiles,$attr->{'href'},'href');
3487: }
3488: }
1.640 albertel 3489: if (lc($tagname) eq 'object' ||
3490: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3491: foreach my $item (keys(%javafiles)) {
3492: $javafiles{$item} = '';
3493: }
1.1164 raeburn 3494: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3495: $lastids{lc($tagname)} = $attr->{'id'};
3496: }
1.640 albertel 3497: }
3498: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3499: my $name = lc($attr->{'name'});
3500: foreach my $item (keys(%javafiles)) {
3501: if ($name eq $item) {
3502: $javafiles{$item} = $attr->{'value'};
3503: last;
3504: }
3505: }
1.1164 raeburn 3506: my $pathfrom;
1.640 albertel 3507: foreach my $item (keys(%mediafiles)) {
3508: if ($name eq $item) {
1.1164 raeburn 3509: $pathfrom = $attr->{'value'};
3510: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3511: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3512: last;
3513: }
3514: }
1.1164 raeburn 3515: if ($name eq 'flashvars') {
3516: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3517: }
3518: if ($pathfrom ne '') {
3519: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3520: $pathfrom);
3521: }
1.640 albertel 3522: }
3523: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3524: foreach my $item (keys(%javafiles)) {
3525: if ($attr->{$item}) {
3526: $javafiles{$item} = $attr->{$item};
3527: last;
3528: }
3529: }
3530: foreach my $item (keys(%mediafiles)) {
3531: if ($attr->{$item}) {
3532: &add_filetype($allfiles,$attr->{$item},$item);
3533: last;
3534: }
3535: }
1.1164 raeburn 3536: if (lc($tagname) eq 'embed') {
3537: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3538: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3539: $attr->{'src'});
3540: }
3541: }
1.640 albertel 3542: }
1.1243 raeburn 3543: if (lc($tagname) eq 'iframe') {
3544: my $src = $attr->{'src'} ;
3545: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3546: &add_filetype($allfiles,$src,'src');
3547: } elsif ($src =~ m{^/}) {
3548: if ($env{'request.course.id'}) {
3549: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3550: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3551: my $url = &hreflocation('',$fullpath);
3552: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3553: my $relpath = $1;
3554: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3555: &add_filetype($allfiles,$1,'src');
3556: }
3557: }
3558: }
3559: }
3560: }
1.1164 raeburn 3561: if ($t->[4] =~ m{/>$}) {
1.1243 raeburn 3562: pop(@state);
1.1164 raeburn 3563: }
1.640 albertel 3564: } elsif ($t->[0] eq 'E') {
3565: my ($tagname) = ($t->[1]);
3566: if ($javafiles{'codebase'} ne '') {
3567: $javafiles{'codebase'} .= '/';
3568: }
3569: if (lc($tagname) eq 'applet' ||
3570: lc($tagname) eq 'object' ||
3571: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3572: ) {
3573: foreach my $item (keys(%javafiles)) {
3574: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3575: my $file=$javafiles{'codebase'}.$javafiles{$item};
3576: &add_filetype($allfiles,$file,$item);
3577: }
3578: }
3579: }
3580: pop @state;
3581: }
3582: }
1.1164 raeburn 3583: foreach my $id (sort(keys(%flashvars))) {
3584: if ($shockwave{$id} ne '') {
3585: my @pairs = split(/\&/,$flashvars{$id});
3586: foreach my $pair (@pairs) {
3587: my ($key,$value) = split(/\=/,$pair);
3588: if ($key eq 'thumb') {
3589: &add_filetype($allfiles,$value,$key);
3590: } elsif ($key eq 'content') {
3591: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3592: my ($ext) = ($value =~ /\.([^.]+)$/);
3593: if ($ext ne '') {
3594: &add_filetype($allfiles,$path.$value,$ext);
3595: }
3596: }
3597: }
3598: }
3599: }
1.637 raeburn 3600: return 'ok';
3601: }
3602:
1.639 albertel 3603: sub add_filetype {
3604: my ($allfiles,$file,$type)=@_;
3605: if (exists($allfiles->{$file})) {
3606: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3607: push(@{$allfiles->{$file}}, &escape($type));
3608: }
3609: } else {
3610: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3611: }
3612: }
3613:
1.1164 raeburn 3614: sub embedded_dependency {
3615: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3616: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3617: if (($identifier ne '') &&
3618: (ref($related->{$identifier}) eq 'ARRAY') &&
3619: ($pathfrom ne '')) {
3620: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3621: foreach my $dep (@{$related->{$identifier}}) {
3622: &add_filetype($allfiles,$path.$dep,'object');
3623: }
3624: }
3625: }
3626: return;
3627: }
3628:
1.493 albertel 3629: sub removeuploadedurl {
1.984 neumanie 3630: my ($url)=@_;
3631: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3632: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3633: }
3634:
3635: sub removeuserfile {
3636: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3637: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3638: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3639: if ($result eq 'ok') {
1.798 raeburn 3640: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3641: my $metafile = $fname.'.meta';
3642: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3643: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3644: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3645: my $sqlresult =
1.823 albertel 3646: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3647: 'portfolio_metadata',$group,
3648: 'delete');
1.798 raeburn 3649: }
3650: }
3651: return $result;
1.257 www 3652: }
1.15 www 3653:
1.530 albertel 3654: sub mkdiruserfile {
3655: my ($docuname,$docudom,$dir)=@_;
3656: my $home=&homeserver($docuname,$docudom);
3657: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3658: }
3659:
1.531 albertel 3660: sub renameuserfile {
3661: my ($docuname,$docudom,$old,$new)=@_;
3662: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3663: my $result = &reply("renameuserfile:$docudom:$docuname:".
3664: &escape("$old").':'.&escape("$new"),$home);
3665: if ($result eq 'ok') {
3666: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3667: my $oldmeta = $old.'.meta';
3668: my $newmeta = $new.'.meta';
3669: my $metaresult =
3670: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3671: my $url = "/uploaded/$docudom/$docuname/$old";
3672: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3673: my $sqlresult =
1.823 albertel 3674: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3675: 'portfolio_metadata',$group,
3676: 'delete');
1.798 raeburn 3677: }
3678: }
3679: return $result;
1.531 albertel 3680: }
3681:
1.14 www 3682: # ------------------------------------------------------------------------- Log
3683:
3684: sub log {
3685: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3686: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3687: }
3688:
3689: # ------------------------------------------------------------------ Course Log
1.352 www 3690: #
3691: # This routine flushes several buffers of non-mission-critical nature
3692: #
1.157 www 3693:
3694: sub flushcourselogs {
1.352 www 3695: &logthis('Flushing log buffers');
3696: #
3697: # course logs
3698: # This is a log of all transactions in a course, which can be used
3699: # for data mining purposes
3700: #
3701: # It also collects the courseid database, which lists last transaction
3702: # times and course titles for all courseids
3703: #
3704: my %courseidbuffer=();
1.921 raeburn 3705: foreach my $crsid (keys(%courselogs)) {
1.352 www 3706: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3707: &escape($courselogs{$crsid}),
3708: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3709: delete $courselogs{$crsid};
3710: } else {
3711: &logthis('Failed to flush log buffer for '.$crsid);
3712: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3713: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3714: " exceeded maximum size, deleting.</font>");
3715: delete $courselogs{$crsid};
3716: }
1.352 www 3717: }
1.920 raeburn 3718: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3719: 'description' => $coursedescrbuf{$crsid},
3720: 'inst_code' => $courseinstcodebuf{$crsid},
3721: 'type' => $coursetypebuf{$crsid},
3722: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3723: };
1.191 harris41 3724: }
1.352 www 3725: #
3726: # Write course id database (reverse lookup) to homeserver of courses
3727: # Is used in pickcourse
3728: #
1.840 albertel 3729: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3730: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3731: $courseidbuffer{$crs_home},
3732: $crs_home,'timeonly');
1.352 www 3733: }
3734: #
3735: # File accesses
3736: # Writes to the dynamic metadata of resources to get hit counts, etc.
3737: #
1.449 matthew 3738: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3739: if ($entry =~ /___count$/) {
3740: my ($dom,$name);
1.807 albertel 3741: ($dom,$name,undef)=
1.811 albertel 3742: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3743: if (! defined($dom) || $dom eq '' ||
3744: ! defined($name) || $name eq '') {
1.620 albertel 3745: my $cid = $env{'request.course.id'};
3746: $dom = $env{'request.'.$cid.'.domain'};
3747: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3748: }
1.450 matthew 3749: my $value = $accesshash{$entry};
3750: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3751: my %temphash=($url => $value);
1.449 matthew 3752: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3753: if ($result eq 'ok') {
3754: delete $accesshash{$entry};
3755: }
3756: } else {
1.811 albertel 3757: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3758: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3759: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3760: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3761: delete $accesshash{$entry};
3762: }
1.185 www 3763: }
1.191 harris41 3764: }
1.352 www 3765: #
3766: # Roles
3767: # Reverse lookup of user roles for course faculty/staff and co-authorship
3768: #
1.800 albertel 3769: foreach my $entry (keys(%userrolehash)) {
1.351 www 3770: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3771: split(/\:/,$entry);
3772: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3773: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3774: $rudom,$runame) eq 'ok') {
3775: delete $userrolehash{$entry};
3776: }
3777: }
1.662 raeburn 3778: #
3779: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3780: #
3781: my %domrolebuffer = ();
1.1000 raeburn 3782: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3783: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3784: if ($domrolebuffer{$rudom}) {
3785: $domrolebuffer{$rudom}.='&'.&escape($entry).
3786: '='.&escape($domainrolehash{$entry});
3787: } else {
3788: $domrolebuffer{$rudom}.=&escape($entry).
3789: '='.&escape($domainrolehash{$entry});
3790: }
3791: delete $domainrolehash{$entry};
3792: }
3793: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3794: my %servers = &get_servers($dom,'library');
3795: foreach my $tryserver (keys(%servers)) {
3796: unless (&reply('domroleput:'.$dom.':'.
3797: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3798: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3799: }
1.662 raeburn 3800: }
3801: }
1.186 www 3802: $dumpcount++;
1.157 www 3803: }
3804:
3805: sub courselog {
3806: my $what=shift;
1.158 www 3807: $what=time.':'.$what;
1.620 albertel 3808: unless ($env{'request.course.id'}) { return ''; }
3809: $coursedombuf{$env{'request.course.id'}}=
3810: $env{'course.'.$env{'request.course.id'}.'.domain'};
3811: $coursenumbuf{$env{'request.course.id'}}=
3812: $env{'course.'.$env{'request.course.id'}.'.num'};
3813: $coursehombuf{$env{'request.course.id'}}=
3814: $env{'course.'.$env{'request.course.id'}.'.home'};
3815: $coursedescrbuf{$env{'request.course.id'}}=
3816: $env{'course.'.$env{'request.course.id'}.'.description'};
3817: $courseinstcodebuf{$env{'request.course.id'}}=
3818: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3819: $courseownerbuf{$env{'request.course.id'}}=
3820: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3821: $coursetypebuf{$env{'request.course.id'}}=
3822: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3823: if (defined $courselogs{$env{'request.course.id'}}) {
3824: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3825: } else {
1.620 albertel 3826: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3827: }
1.620 albertel 3828: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3829: &flushcourselogs();
3830: }
1.158 www 3831: }
3832:
3833: sub courseacclog {
3834: my $fnsymb=shift;
1.620 albertel 3835: unless ($env{'request.course.id'}) { return ''; }
3836: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3837: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3838: $what.=':POST';
1.583 matthew 3839: # FIXME: Probably ought to escape things....
1.800 albertel 3840: foreach my $key (keys(%env)) {
3841: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3842: my $formitem = $1;
3843: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3844: $what.=':'.$formitem.'='.$env{$key};
3845: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3846: $what.=':'.$formitem.'='.$env{$key};
3847: }
1.158 www 3848: }
1.191 harris41 3849: }
1.583 matthew 3850: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3851: # FIXME: We should not be depending on a form parameter that someone
3852: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3853: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3854: $what.= ':POST';
3855: # FIXME: Probably ought to escape things....
3856: foreach my $element ('courseexp','crsfulltext','crsrelated',
3857: 'crsdiscuss') {
1.620 albertel 3858: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3859: }
3860: }
1.158 www 3861: }
3862: &courselog($what);
1.149 www 3863: }
3864:
1.185 www 3865: sub countacc {
3866: my $url=&declutter(shift);
1.458 matthew 3867: return if (! defined($url) || $url eq '');
1.620 albertel 3868: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3869: #
3870: # Mark that this url was used in this course
3871: #
1.620 albertel 3872: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3873: #
3874: # Increase the access count for this resource in this child process
3875: #
1.281 www 3876: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3877: $accesshash{$key}++;
1.185 www 3878: }
1.349 www 3879:
1.361 www 3880: sub linklog {
3881: my ($from,$to)=@_;
3882: $from=&declutter($from);
3883: $to=&declutter($to);
3884: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3885: $accesshash{$to.'___'.$from.'___goto'}=1;
3886: }
1.1160 www 3887:
3888: sub statslog {
3889: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3890: if ($users<2) { return; }
3891: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3892: 'course' => $env{'request.course.id'},
3893: 'sections' => '"all"',
3894: 'num_students' => $users,
3895: 'part' => $part,
3896: 'symb' => $symb,
3897: 'mean_tries' => $av_attempts,
3898: 'deg_of_diff' => $degdiff});
3899: foreach my $key (keys(%dynstore)) {
3900: $accesshash{$key}=$dynstore{$key};
3901: }
3902: }
1.361 www 3903:
1.349 www 3904: sub userrolelog {
3905: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3906: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3907: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3908: $userrolehash
3909: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3910: =$tend.':'.$tstart;
1.662 raeburn 3911: }
1.1169 droeschl 3912: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3913: $userrolehash
3914: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3915: =$tend.':'.$tstart;
3916: }
1.1169 droeschl 3917: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3918: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3919: $domainrolehash
3920: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3921: = $tend.':'.$tstart;
3922: }
1.351 www 3923: }
3924:
1.957 raeburn 3925: sub courserolelog {
3926: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 3927: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3928: my $cdom = $1;
3929: my $cnum = $2;
3930: my $sec = $3;
3931: my $namespace = 'rolelog';
3932: my %storehash = (
3933: role => $trole,
3934: start => $tstart,
3935: end => $tend,
3936: selfenroll => $selfenroll,
3937: context => $context,
3938: );
3939: if ($trole eq 'gr') {
3940: $namespace = 'groupslog';
3941: $storehash{'group'} = $sec;
3942: } else {
3943: $storehash{'section'} = $sec;
3944: }
1.1188 raeburn 3945: &write_log('course',$namespace,\%storehash,$delflag,$username,
3946: $domain,$cnum,$cdom);
1.1184 raeburn 3947: if (($trole ne 'st') || ($sec ne '')) {
3948: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3949: }
3950: }
3951: return;
3952: }
3953:
1.1184 raeburn 3954: sub domainrolelog {
3955: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3956: if ($area =~ m{^/($match_domain)/$}) {
3957: my $cdom = $1;
3958: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3959: my $namespace = 'rolelog';
3960: my %storehash = (
3961: role => $trole,
3962: start => $tstart,
3963: end => $tend,
3964: context => $context,
3965: );
1.1188 raeburn 3966: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3967: $domain,$domconfiguser,$cdom);
1.1184 raeburn 3968: }
3969: return;
3970:
3971: }
3972:
3973: sub coauthorrolelog {
3974: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3975: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3976: my $audom = $1;
3977: my $auname = $2;
3978: my $namespace = 'rolelog';
3979: my %storehash = (
3980: role => $trole,
3981: start => $tstart,
3982: end => $tend,
3983: context => $context,
3984: );
1.1188 raeburn 3985: &write_log('author',$namespace,\%storehash,$delflag,$username,
3986: $domain,$auname,$audom);
1.1184 raeburn 3987: }
3988: return;
3989: }
3990:
1.351 www 3991: sub get_course_adv_roles {
1.948 raeburn 3992: my ($cid,$codes) = @_;
1.620 albertel 3993: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3994: my %coursehash=&coursedescription($cid);
1.988 raeburn 3995: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3996: my %nothide=();
1.800 albertel 3997: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3998: if ($user !~ /:/) {
3999: $nothide{join(':',split(/[\@]/,$user))}=1;
4000: } else {
4001: $nothide{$user}=1;
4002: }
1.470 www 4003: }
1.1219 raeburn 4004: my @possdoms = ($coursehash{'domain'});
4005: if ($coursehash{'checkforpriv'}) {
4006: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4007: }
1.351 www 4008: my %returnhash=();
4009: my %dumphash=
4010: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4011: my $now=time;
1.997 raeburn 4012: my %privileged;
1.1000 raeburn 4013: foreach my $entry (keys(%dumphash)) {
1.800 albertel 4014: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 4015: if (($tstart) && ($tstart<0)) { next; }
4016: if (($tend) && ($tend<$now)) { next; }
4017: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 4018: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 4019: if ($username eq '' || $domain eq '') { next; }
1.1219 raeburn 4020: if ((&privileged($username,$domain,\@possdoms)) &&
1.997 raeburn 4021: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 4022: if ($role eq 'cr') { next; }
1.948 raeburn 4023: if ($codes) {
4024: if ($section) { $role .= ':'.$section; }
4025: if ($returnhash{$role}) {
4026: $returnhash{$role}.=','.$username.':'.$domain;
4027: } else {
4028: $returnhash{$role}=$username.':'.$domain;
4029: }
1.351 www 4030: } else {
1.988 raeburn 4031: my $key=&plaintext($role,$crstype);
1.973 bisitz 4032: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 4033: if ($returnhash{$key}) {
4034: $returnhash{$key}.=','.$username.':'.$domain;
4035: } else {
4036: $returnhash{$key}=$username.':'.$domain;
4037: }
1.351 www 4038: }
1.948 raeburn 4039: }
1.400 www 4040: return %returnhash;
4041: }
4042:
4043: sub get_my_roles {
1.937 raeburn 4044: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 4045: unless (defined($uname)) { $uname=$env{'user.name'}; }
4046: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 4047: my (%dumphash,%nothide);
1.1086 raeburn 4048: if ($context eq 'userroles') {
1.1166 raeburn 4049: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 4050: } else {
1.1219 raeburn 4051: %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 4052: if ($hidepriv) {
4053: my %coursehash=&coursedescription($udom.'_'.$uname);
4054: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4055: if ($user !~ /:/) {
4056: $nothide{join(':',split(/[\@]/,$user))} = 1;
4057: } else {
4058: $nothide{$user} = 1;
4059: }
4060: }
4061: }
1.858 raeburn 4062: }
1.400 www 4063: my %returnhash=();
4064: my $now=time;
1.999 raeburn 4065: my %privileged;
1.800 albertel 4066: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 4067: my ($role,$tend,$tstart);
4068: if ($context eq 'userroles') {
1.1149 raeburn 4069: next if ($entry =~ /^rolesdef/);
1.867 raeburn 4070: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4071: } else {
4072: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4073: }
1.400 www 4074: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 4075: my $status = 'active';
1.939 raeburn 4076: if (($tend) && ($tend<=$now)) {
1.832 raeburn 4077: $status = 'previous';
4078: }
4079: if (($tstart) && ($now<$tstart)) {
4080: $status = 'future';
4081: }
4082: if (ref($types) eq 'ARRAY') {
4083: if (!grep(/^\Q$status\E$/,@{$types})) {
4084: next;
4085: }
4086: } else {
4087: if ($status ne 'active') {
4088: next;
4089: }
4090: }
1.867 raeburn 4091: my ($rolecode,$username,$domain,$section,$area);
4092: if ($context eq 'userroles') {
1.1186 raeburn 4093: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 4094: (undef,$domain,$username,$section) = split(/\//,$area);
4095: } else {
4096: ($role,$username,$domain,$section) = split(/\:/,$entry);
4097: }
1.832 raeburn 4098: if (ref($roledoms) eq 'ARRAY') {
4099: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4100: next;
4101: }
4102: }
4103: if (ref($roles) eq 'ARRAY') {
4104: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 4105: if ($role =~ /^cr\//) {
4106: if (!grep(/^cr$/,@{$roles})) {
4107: next;
4108: }
1.1104 raeburn 4109: } elsif ($role =~ /^gr\//) {
4110: if (!grep(/^gr$/,@{$roles})) {
4111: next;
4112: }
1.922 raeburn 4113: } else {
4114: next;
4115: }
1.832 raeburn 4116: }
1.867 raeburn 4117: }
1.937 raeburn 4118: if ($hidepriv) {
1.1219 raeburn 4119: my @privroles = ('dc','su');
1.999 raeburn 4120: if ($context eq 'userroles') {
1.1219 raeburn 4121: next if (grep(/^\Q$role\E$/,@privroles));
1.999 raeburn 4122: } else {
1.1219 raeburn 4123: my $possdoms = [$domain];
4124: if (ref($roledoms) eq 'ARRAY') {
4125: push(@{$possdoms},@{$roledoms});
1.999 raeburn 4126: }
1.1219 raeburn 4127: if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999 raeburn 4128: if (!$nothide{$username.':'.$domain}) {
4129: next;
4130: }
4131: }
1.937 raeburn 4132: }
4133: }
1.933 raeburn 4134: if ($withsec) {
4135: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4136: $tstart.':'.$tend;
4137: } else {
4138: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4139: }
1.832 raeburn 4140: }
1.373 www 4141: return %returnhash;
1.399 www 4142: }
4143:
4144: # ----------------------------------------------------- Frontpage Announcements
4145: #
4146: #
4147:
4148: sub postannounce {
4149: my ($server,$text)=@_;
1.844 albertel 4150: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 4151: unless ($text=~/\w/) { $text=''; }
4152: return &reply('setannounce:'.&escape($text),$server);
4153: }
4154:
4155: sub getannounce {
1.448 albertel 4156:
4157: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 4158: my $announcement='';
1.800 albertel 4159: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 4160: close($fh);
1.399 www 4161: if ($announcement=~/\w/) {
4162: return
4163: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 4164: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 4165: } else {
4166: return '';
4167: }
4168: } else {
4169: return '';
4170: }
1.351 www 4171: }
1.353 www 4172:
4173: # ---------------------------------------------------------- Course ID routines
4174: # Deal with domain's nohist_courseid.db files
4175: #
4176:
4177: sub courseidput {
1.921 raeburn 4178: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 4179: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 4180: my $outcome;
4181: if ($caller eq 'timeonly') {
4182: my $cids = '';
4183: foreach my $item (keys(%$storehash)) {
4184: $cids.=&escape($item).'&';
4185: }
4186: $cids=~s/\&$//;
4187: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4188: $coursehome);
4189: } else {
4190: my $items = '';
4191: foreach my $item (keys(%$storehash)) {
4192: $items.= &escape($item).'='.
4193: &freeze_escape($$storehash{$item}).'&';
4194: }
4195: $items=~s/\&$//;
4196: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4197: $coursehome);
1.918 raeburn 4198: }
4199: if ($outcome eq 'unknown_cmd') {
4200: my $what;
4201: foreach my $cid (keys(%$storehash)) {
4202: $what .= &escape($cid).'=';
1.921 raeburn 4203: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 4204: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 4205: }
4206: $what =~ s/\:$/&/;
4207: }
4208: $what =~ s/\&$//;
4209: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4210: } else {
4211: return $outcome;
4212: }
1.353 www 4213: }
4214:
4215: sub courseiddump {
1.921 raeburn 4216: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 4217: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 4218: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247 raeburn 4219: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4220: $hasuniquecode)=@_;
1.918 raeburn 4221: my $as_hash = 1;
4222: my %returnhash;
4223: if (!$domfilter) { $domfilter=''; }
1.845 albertel 4224: my %libserv = &all_library();
4225: foreach my $tryserver (keys(%libserv)) {
4226: if ( ( $hostidflag == 1
4227: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4228: || (!defined($hostidflag)) ) {
4229:
1.918 raeburn 4230: if (($domfilter eq '') ||
4231: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 4232: my $rep;
4233: if (grep { $_ eq $tryserver } current_machine_ids()) {
4234: $rep = LONCAPA::Lond::dump_course_id_handler(
4235: join(":", (&host_domain($tryserver), $sincefilter,
4236: &escape($descfilter), &escape($instcodefilter),
4237: &escape($ownerfilter), &escape($coursefilter),
4238: &escape($typefilter), &escape($regexp_ok),
4239: $as_hash, &escape($selfenrollonly),
4240: &escape($catfilter), $showhidden, $caller,
4241: &escape($cloner), &escape($cc_clone), $cloneonly,
4242: &escape($createdbefore), &escape($createdafter),
1.1247 raeburn 4243: &escape($creationcontext), $domcloner, $hasuniquecode)));
1.1180 droeschl 4244: } else {
4245: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4246: $sincefilter.':'.&escape($descfilter).':'.
4247: &escape($instcodefilter).':'.&escape($ownerfilter).
4248: ':'.&escape($coursefilter).':'.&escape($typefilter).
4249: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4250: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4251: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4252: &escape($cc_clone).':'.$cloneonly.':'.
4253: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1247 raeburn 4254: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
1.1180 droeschl 4255: $tryserver);
4256: }
4257:
1.918 raeburn 4258: my @pairs=split(/\&/,$rep);
4259: foreach my $item (@pairs) {
4260: my ($key,$value)=split(/\=/,$item,2);
4261: $key = &unescape($key);
4262: next if ($key =~ /^error: 2 /);
4263: my $result = &thaw_unescape($value);
4264: if (ref($result) eq 'HASH') {
4265: $returnhash{$key}=$result;
4266: } else {
1.921 raeburn 4267: my @responses = split(/:/,$value);
4268: my @items = ('description','inst_code','owner','type');
1.918 raeburn 4269: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 4270: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 4271: }
1.1008 raeburn 4272: }
1.353 www 4273: }
4274: }
4275: }
4276: }
4277: return %returnhash;
4278: }
4279:
1.1055 raeburn 4280: sub courselastaccess {
4281: my ($cdom,$cnum,$hostidref) = @_;
4282: my %returnhash;
4283: if ($cdom && $cnum) {
4284: my $chome = &homeserver($cnum,$cdom);
4285: if ($chome ne 'no_host') {
4286: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4287: &extract_lastaccess(\%returnhash,$rep);
4288: }
4289: } else {
4290: if (!$cdom) { $cdom=''; }
4291: my %libserv = &all_library();
4292: foreach my $tryserver (keys(%libserv)) {
4293: if (ref($hostidref) eq 'ARRAY') {
4294: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4295: }
4296: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4297: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4298: &extract_lastaccess(\%returnhash,$rep);
4299: }
4300: }
4301: }
4302: return %returnhash;
4303: }
4304:
4305: sub extract_lastaccess {
4306: my ($returnhash,$rep) = @_;
4307: if (ref($returnhash) eq 'HASH') {
4308: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4309: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4310: $rep eq '') {
4311: my @pairs=split(/\&/,$rep);
4312: foreach my $item (@pairs) {
4313: my ($key,$value)=split(/\=/,$item,2);
4314: $key = &unescape($key);
4315: next if ($key =~ /^error: 2 /);
4316: $returnhash->{$key} = &thaw_unescape($value);
4317: }
4318: }
4319: }
4320: return;
4321: }
4322:
1.658 raeburn 4323: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 4324:
4325: sub dcmailput {
1.685 raeburn 4326: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 4327: my $status = &Apache::lonnet::critical(
1.740 www 4328: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4329: &escape($message),$server);
1.662 raeburn 4330: return $status;
4331: }
4332:
1.658 raeburn 4333: sub dcmaildump {
4334: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 4335: my %returnhash=();
1.846 albertel 4336:
4337: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 4338: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4339: &escape($enddate).':';
4340: my @esc_senders=map { &escape($_)} @$senders;
4341: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 4342: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 4343: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 4344: if (($key) && ($value)) {
4345: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 4346: }
4347: }
4348: }
4349: return %returnhash;
4350: }
1.662 raeburn 4351: # ---------------------------------------------------------- Domain roles
4352:
4353: sub get_domain_roles {
4354: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 4355: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 4356: $startdate = '.';
4357: }
1.1018 raeburn 4358: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 4359: $enddate = '.';
4360: }
1.922 raeburn 4361: my $rolelist;
4362: if (ref($roles) eq 'ARRAY') {
1.1219 raeburn 4363: $rolelist = join('&',@{$roles});
1.922 raeburn 4364: }
1.662 raeburn 4365: my %personnel = ();
1.841 albertel 4366:
4367: my %servers = &get_servers($dom,'library');
4368: foreach my $tryserver (keys(%servers)) {
4369: %{$personnel{$tryserver}}=();
4370: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4371: &escape($startdate).':'.
4372: &escape($enddate).':'.
4373: &escape($rolelist), $tryserver))) {
4374: my ($key,$value) = split(/\=/,$line,2);
4375: if (($key) && ($value)) {
4376: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4377: }
4378: }
1.662 raeburn 4379: }
4380: return %personnel;
4381: }
1.658 raeburn 4382:
1.1057 www 4383: # ----------------------------------------------------------- Interval timing
1.149 www 4384:
1.1153 www 4385: {
4386: # Caches needed for speedup of navmaps
4387: # We don't want to cache this for very long at all (5 seconds at most)
4388: #
4389: # The user for whom we cache
4390: my $cachedkey='';
4391: # The cached times for this user
4392: my %cachedtimes=();
4393: # When this was last done
4394: my $cachedtime=();
4395:
4396: sub load_all_first_access {
1.1154 raeburn 4397: my ($uname,$udom)=@_;
1.1156 www 4398: if (($cachedkey eq $uname.':'.$udom) &&
1.1174 raeburn 4399: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4400: return;
4401: }
4402: $cachedtime=time;
4403: $cachedkey=$uname.':'.$udom;
4404: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4405: }
4406:
1.504 albertel 4407: sub get_first_access {
1.1162 raeburn 4408: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4409: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4410: if ($argsymb) { $symb=$argsymb; }
4411: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4412: if ($argmap) { $map = $argmap; }
1.926 albertel 4413: if ($type eq 'course') {
4414: $res='course';
4415: } elsif ($type eq 'map') {
1.588 albertel 4416: $res=&symbread($map);
4417: } else {
4418: $res=$symb;
4419: }
1.1153 www 4420: &load_all_first_access($uname,$udom);
4421: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4422: }
4423:
4424: sub set_first_access {
1.1162 raeburn 4425: my ($type,$interval)=@_;
1.790 albertel 4426: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4427: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4428: if ($type eq 'course') {
4429: $res='course';
4430: } elsif ($type eq 'map') {
1.588 albertel 4431: $res=&symbread($map);
4432: } else {
4433: $res=$symb;
4434: }
1.1153 www 4435: $cachedkey='';
1.1162 raeburn 4436: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4437: if (!$firstaccess) {
1.1162 raeburn 4438: my $start = time;
4439: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4440: $udom,$uname);
4441: if ($putres eq 'ok') {
4442: &put('timerinterval',{"$courseid\0$res"=>$interval},
4443: $udom,$uname);
4444: &appenv(
4445: {
4446: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4447: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4448: }
4449: );
4450: }
4451: return $putres;
1.505 albertel 4452: }
4453: return 'already_set';
1.504 albertel 4454: }
1.1153 www 4455: }
1.110 www 4456: # --------------------------------------------- Set Expire Date for Spreadsheet
4457:
4458: sub expirespread {
4459: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4460: my $cid=$env{'request.course.id'};
1.110 www 4461: if ($cid) {
4462: my $now=time;
4463: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4464: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4465: $env{'course.'.$cid.'.num'}.
1.110 www 4466: ':nohist_expirationdates:'.
4467: &escape($key).'='.$now,
1.620 albertel 4468: $env{'course.'.$cid.'.home'})
1.110 www 4469: }
4470: return 'ok';
1.14 www 4471: }
4472:
1.109 www 4473: # ----------------------------------------------------- Devalidate Spreadsheets
4474:
4475: sub devalidate {
1.325 www 4476: my ($symb,$uname,$udom)=@_;
1.620 albertel 4477: my $cid=$env{'request.course.id'};
1.109 www 4478: if ($cid) {
1.391 matthew 4479: # delete the stored spreadsheets for
4480: # - the student level sheet of this user in course's homespace
4481: # - the assessment level sheet for this resource
4482: # for this user in user's homespace
1.553 albertel 4483: # - current conditional state info
1.325 www 4484: my $key=$uname.':'.$udom.':';
1.109 www 4485: my $status=
1.299 matthew 4486: &del('nohist_calculatedsheets',
1.391 matthew 4487: [$key.'studentcalc:'],
1.620 albertel 4488: $env{'course.'.$cid.'.domain'},
4489: $env{'course.'.$cid.'.num'})
1.133 albertel 4490: .' '.
4491: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4492: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4493: unless ($status eq 'ok ok') {
4494: &logthis('Could not devalidate spreadsheet '.
1.325 www 4495: $uname.' at '.$udom.' for '.
1.109 www 4496: $symb.': '.$status);
1.133 albertel 4497: }
1.553 albertel 4498: &delenv('user.state.'.$cid);
1.109 www 4499: }
4500: }
4501:
1.265 albertel 4502: sub get_scalar {
4503: my ($string,$end) = @_;
4504: my $value;
4505: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4506: $value = $1;
4507: } elsif ($$string =~ s/^([^&]*?)&//) {
4508: $value = $1;
4509: }
4510: return &unescape($value);
4511: }
4512:
4513: sub array2str {
4514: my (@array) = @_;
4515: my $result=&arrayref2str(\@array);
4516: $result=~s/^__ARRAY_REF__//;
4517: $result=~s/__END_ARRAY_REF__$//;
4518: return $result;
4519: }
4520:
1.204 albertel 4521: sub arrayref2str {
4522: my ($arrayref) = @_;
1.265 albertel 4523: my $result='__ARRAY_REF__';
1.204 albertel 4524: foreach my $elem (@$arrayref) {
1.265 albertel 4525: if(ref($elem) eq 'ARRAY') {
4526: $result.=&arrayref2str($elem).'&';
4527: } elsif(ref($elem) eq 'HASH') {
4528: $result.=&hashref2str($elem).'&';
4529: } elsif(ref($elem)) {
4530: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4531: } else {
4532: $result.=&escape($elem).'&';
4533: }
4534: }
4535: $result=~s/\&$//;
1.265 albertel 4536: $result .= '__END_ARRAY_REF__';
1.204 albertel 4537: return $result;
4538: }
4539:
1.168 albertel 4540: sub hash2str {
1.204 albertel 4541: my (%hash) = @_;
4542: my $result=&hashref2str(\%hash);
1.265 albertel 4543: $result=~s/^__HASH_REF__//;
4544: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4545: return $result;
4546: }
4547:
4548: sub hashref2str {
4549: my ($hashref)=@_;
1.265 albertel 4550: my $result='__HASH_REF__';
1.800 albertel 4551: foreach my $key (sort(keys(%$hashref))) {
4552: if (ref($key) eq 'ARRAY') {
4553: $result.=&arrayref2str($key).'=';
4554: } elsif (ref($key) eq 'HASH') {
4555: $result.=&hashref2str($key).'=';
4556: } elsif (ref($key)) {
1.265 albertel 4557: $result.='=';
1.800 albertel 4558: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4559: } else {
1.1132 raeburn 4560: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4561: }
4562:
1.800 albertel 4563: if(ref($hashref->{$key}) eq 'ARRAY') {
4564: $result.=&arrayref2str($hashref->{$key}).'&';
4565: } elsif(ref($hashref->{$key}) eq 'HASH') {
4566: $result.=&hashref2str($hashref->{$key}).'&';
4567: } elsif(ref($hashref->{$key})) {
1.265 albertel 4568: $result.='&';
1.800 albertel 4569: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4570: } else {
1.800 albertel 4571: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4572: }
4573: }
1.168 albertel 4574: $result=~s/\&$//;
1.265 albertel 4575: $result .= '__END_HASH_REF__';
1.168 albertel 4576: return $result;
4577: }
4578:
4579: sub str2hash {
1.265 albertel 4580: my ($string)=@_;
4581: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4582: return %$hash;
4583: }
4584:
4585: sub str2hashref {
1.168 albertel 4586: my ($string) = @_;
1.265 albertel 4587:
4588: my %hash;
4589:
4590: if($string !~ /^__HASH_REF__/) {
4591: if (! ($string eq '' || !defined($string))) {
4592: $hash{'error'}='Not hash reference';
4593: }
4594: return (\%hash, $string);
4595: }
4596:
4597: $string =~ s/^__HASH_REF__//;
4598:
4599: while($string !~ /^__END_HASH_REF__/) {
4600: #key
4601: my $key='';
4602: if($string =~ /^__HASH_REF__/) {
4603: ($key, $string)=&str2hashref($string);
4604: if(defined($key->{'error'})) {
4605: $hash{'error'}='Bad data';
4606: return (\%hash, $string);
4607: }
4608: } elsif($string =~ /^__ARRAY_REF__/) {
4609: ($key, $string)=&str2arrayref($string);
4610: if($key->[0] eq 'Array reference error') {
4611: $hash{'error'}='Bad data';
4612: return (\%hash, $string);
4613: }
4614: } else {
4615: $string =~ s/^(.*?)=//;
1.267 albertel 4616: $key=&unescape($1);
1.265 albertel 4617: }
4618: $string =~ s/^=//;
4619:
4620: #value
4621: my $value='';
4622: if($string =~ /^__HASH_REF__/) {
4623: ($value, $string)=&str2hashref($string);
4624: if(defined($value->{'error'})) {
4625: $hash{'error'}='Bad data';
4626: return (\%hash, $string);
4627: }
4628: } elsif($string =~ /^__ARRAY_REF__/) {
4629: ($value, $string)=&str2arrayref($string);
4630: if($value->[0] eq 'Array reference error') {
4631: $hash{'error'}='Bad data';
4632: return (\%hash, $string);
4633: }
4634: } else {
4635: $value=&get_scalar(\$string,'__END_HASH_REF__');
4636: }
4637: $string =~ s/^&//;
4638:
4639: $hash{$key}=$value;
1.204 albertel 4640: }
1.265 albertel 4641:
4642: $string =~ s/^__END_HASH_REF__//;
4643:
4644: return (\%hash, $string);
1.204 albertel 4645: }
4646:
4647: sub str2array {
1.265 albertel 4648: my ($string)=@_;
4649: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4650: return @$array;
4651: }
4652:
4653: sub str2arrayref {
1.204 albertel 4654: my ($string) = @_;
1.265 albertel 4655: my @array;
4656:
4657: if($string !~ /^__ARRAY_REF__/) {
4658: if (! ($string eq '' || !defined($string))) {
4659: $array[0]='Array reference error';
4660: }
4661: return (\@array, $string);
4662: }
4663:
4664: $string =~ s/^__ARRAY_REF__//;
4665:
4666: while($string !~ /^__END_ARRAY_REF__/) {
4667: my $value='';
4668: if($string =~ /^__HASH_REF__/) {
4669: ($value, $string)=&str2hashref($string);
4670: if(defined($value->{'error'})) {
4671: $array[0] ='Array reference error';
4672: return (\@array, $string);
4673: }
4674: } elsif($string =~ /^__ARRAY_REF__/) {
4675: ($value, $string)=&str2arrayref($string);
4676: if($value->[0] eq 'Array reference error') {
4677: $array[0] ='Array reference error';
4678: return (\@array, $string);
4679: }
4680: } else {
4681: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4682: }
4683: $string =~ s/^&//;
4684:
4685: push(@array, $value);
1.191 harris41 4686: }
1.265 albertel 4687:
4688: $string =~ s/^__END_ARRAY_REF__//;
4689:
4690: return (\@array, $string);
1.168 albertel 4691: }
4692:
1.167 albertel 4693: # -------------------------------------------------------------------Temp Store
4694:
1.168 albertel 4695: sub tmpreset {
4696: my ($symb,$namespace,$domain,$stuname) = @_;
4697: if (!$symb) {
4698: $symb=&symbread();
1.620 albertel 4699: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4700: }
4701: $symb=escape($symb);
4702:
1.620 albertel 4703: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4704: $namespace=~s/\//\_/g;
4705: $namespace=~s/\W//g;
4706:
1.620 albertel 4707: if (!$domain) { $domain=$env{'user.domain'}; }
4708: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4709: if ($domain eq 'public' && $stuname eq 'public') {
4710: $stuname=$ENV{'REMOTE_ADDR'};
4711: }
1.1117 foxr 4712: my $path=LONCAPA::tempdir();
1.168 albertel 4713: my %hash;
4714: if (tie(%hash,'GDBM_File',
4715: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4716: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4717: foreach my $key (keys(%hash)) {
1.180 albertel 4718: if ($key=~ /:$symb/) {
1.168 albertel 4719: delete($hash{$key});
4720: }
4721: }
4722: }
4723: }
4724:
1.167 albertel 4725: sub tmpstore {
1.168 albertel 4726: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4727:
4728: if (!$symb) {
4729: $symb=&symbread();
1.620 albertel 4730: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4731: }
4732: $symb=escape($symb);
4733:
4734: if (!$namespace) {
4735: # I don't think we would ever want to store this for a course.
4736: # it seems this will only be used if we don't have a course.
1.620 albertel 4737: #$namespace=$env{'request.course.id'};
1.168 albertel 4738: #if (!$namespace) {
1.620 albertel 4739: $namespace=$env{'request.state'};
1.168 albertel 4740: #}
4741: }
4742: $namespace=~s/\//\_/g;
4743: $namespace=~s/\W//g;
1.620 albertel 4744: if (!$domain) { $domain=$env{'user.domain'}; }
4745: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4746: if ($domain eq 'public' && $stuname eq 'public') {
4747: $stuname=$ENV{'REMOTE_ADDR'};
4748: }
1.168 albertel 4749: my $now=time;
4750: my %hash;
1.1117 foxr 4751: my $path=LONCAPA::tempdir();
1.168 albertel 4752: if (tie(%hash,'GDBM_File',
4753: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4754: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4755: $hash{"version:$symb"}++;
4756: my $version=$hash{"version:$symb"};
4757: my $allkeys='';
4758: foreach my $key (keys(%$storehash)) {
4759: $allkeys.=$key.':';
1.591 albertel 4760: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4761: }
4762: $hash{"$version:$symb:timestamp"}=$now;
4763: $allkeys.='timestamp';
4764: $hash{"$version:keys:$symb"}=$allkeys;
4765: if (untie(%hash)) {
4766: return 'ok';
4767: } else {
4768: return "error:$!";
4769: }
4770: } else {
4771: return "error:$!";
4772: }
4773: }
1.167 albertel 4774:
1.168 albertel 4775: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4776:
1.168 albertel 4777: sub tmprestore {
4778: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4779:
1.168 albertel 4780: if (!$symb) {
4781: $symb=&symbread();
1.620 albertel 4782: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4783: }
4784: $symb=escape($symb);
4785:
1.620 albertel 4786: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4787:
1.620 albertel 4788: if (!$domain) { $domain=$env{'user.domain'}; }
4789: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4790: if ($domain eq 'public' && $stuname eq 'public') {
4791: $stuname=$ENV{'REMOTE_ADDR'};
4792: }
1.168 albertel 4793: my %returnhash;
4794: $namespace=~s/\//\_/g;
4795: $namespace=~s/\W//g;
4796: my %hash;
1.1117 foxr 4797: my $path=LONCAPA::tempdir();
1.168 albertel 4798: if (tie(%hash,'GDBM_File',
4799: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4800: &GDBM_READER(),0640)) {
1.168 albertel 4801: my $version=$hash{"version:$symb"};
4802: $returnhash{'version'}=$version;
4803: my $scope;
4804: for ($scope=1;$scope<=$version;$scope++) {
4805: my $vkeys=$hash{"$scope:keys:$symb"};
4806: my @keys=split(/:/,$vkeys);
4807: my $key;
4808: $returnhash{"$scope:keys"}=$vkeys;
4809: foreach $key (@keys) {
1.591 albertel 4810: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4811: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4812: }
4813: }
1.168 albertel 4814: if (!(untie(%hash))) {
4815: return "error:$!";
4816: }
4817: } else {
4818: return "error:$!";
4819: }
4820: return %returnhash;
1.167 albertel 4821: }
4822:
1.9 www 4823: # ----------------------------------------------------------------------- Store
4824:
4825: sub store {
1.124 www 4826: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4827: my $home='';
4828:
1.168 albertel 4829: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4830:
1.213 www 4831: $symb=&symbclean($symb);
1.122 albertel 4832: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4833:
1.620 albertel 4834: if (!$domain) { $domain=$env{'user.domain'}; }
4835: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4836:
4837: &devalidate($symb,$stuname,$domain);
1.109 www 4838:
4839: $symb=escape($symb);
1.187 www 4840: if (!$namespace) {
1.620 albertel 4841: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4842: return '';
4843: }
4844: }
1.620 albertel 4845: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4846:
4847: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4848: $$storehash{'host'}=$perlvar{'lonHostID'};
4849:
1.12 www 4850: my $namevalue='';
1.800 albertel 4851: foreach my $key (keys(%$storehash)) {
4852: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4853: }
1.12 www 4854: $namevalue=~s/\&$//;
1.187 www 4855: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4856: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4857: }
4858:
1.47 www 4859: # -------------------------------------------------------------- Critical Store
4860:
4861: sub cstore {
1.124 www 4862: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4863: my $home='';
4864:
1.168 albertel 4865: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4866:
1.213 www 4867: $symb=&symbclean($symb);
1.122 albertel 4868: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4869:
1.620 albertel 4870: if (!$domain) { $domain=$env{'user.domain'}; }
4871: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4872:
4873: &devalidate($symb,$stuname,$domain);
1.109 www 4874:
4875: $symb=escape($symb);
1.187 www 4876: if (!$namespace) {
1.620 albertel 4877: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4878: return '';
4879: }
4880: }
1.620 albertel 4881: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4882:
4883: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4884: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4885:
1.47 www 4886: my $namevalue='';
1.800 albertel 4887: foreach my $key (keys(%$storehash)) {
4888: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4889: }
1.47 www 4890: $namevalue=~s/\&$//;
1.187 www 4891: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4892: return critical
4893: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4894: }
4895:
1.9 www 4896: # --------------------------------------------------------------------- Restore
4897:
4898: sub restore {
1.124 www 4899: my ($symb,$namespace,$domain,$stuname) = @_;
4900: my $home='';
4901:
1.168 albertel 4902: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4903:
1.122 albertel 4904: if (!$symb) {
1.1224 raeburn 4905: return if ($namespace eq 'courserequests');
4906: unless ($symb=escape(&symbread())) { return ''; }
1.122 albertel 4907: } else {
1.1224 raeburn 4908: unless ($namespace eq 'courserequests') {
4909: $symb=&escape(&symbclean($symb));
4910: }
1.122 albertel 4911: }
1.188 www 4912: if (!$namespace) {
1.620 albertel 4913: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4914: return '';
4915: }
4916: }
1.620 albertel 4917: if (!$domain) { $domain=$env{'user.domain'}; }
4918: if (!$stuname) { $stuname=$env{'user.name'}; }
4919: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4920: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4921:
1.12 www 4922: my %returnhash=();
1.800 albertel 4923: foreach my $line (split(/\&/,$answer)) {
4924: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4925: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4926: }
1.75 www 4927: my $version;
4928: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4929: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4930: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4931: }
1.75 www 4932: }
1.13 www 4933: return %returnhash;
1.34 www 4934: }
4935:
4936: # ---------------------------------------------------------- Course Description
1.1118 foxr 4937: #
4938: #
1.34 www 4939:
4940: sub coursedescription {
1.731 albertel 4941: my ($courseid,$args)=@_;
1.34 www 4942: $courseid=~s/^\///;
1.49 www 4943: $courseid=~s/\_/\//g;
1.34 www 4944: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4945: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4946: my $normalid=$cdomain.'_'.$cnum;
4947: # need to always cache even if we get errors otherwise we keep
4948: # trying and trying and trying to get the course description.
4949: my %envhash=();
4950: my %returnhash=();
1.731 albertel 4951:
4952: my $expiretime=600;
4953: if ($env{'request.course.id'} eq $normalid) {
4954: $expiretime=120;
4955: }
4956:
4957: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4958: if (!$args->{'freshen_cache'}
4959: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4960: foreach my $key (keys(%env)) {
4961: next if ($key !~ /^\Q$prefix\E(.*)/);
4962: my ($setting) = $1;
4963: $returnhash{$setting} = $env{$key};
4964: }
4965: return %returnhash;
4966: }
4967:
1.1118 foxr 4968: # get the data again
4969:
1.731 albertel 4970: if (!$args->{'one_time'}) {
4971: $envhash{'course.'.$normalid.'.last_cache'}=time;
4972: }
1.811 albertel 4973:
1.34 www 4974: if ($chome ne 'no_host') {
1.302 albertel 4975: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4976: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4977: my $username = $env{'user.name'}; # Defult username
4978: if(defined $args->{'user'}) {
4979: $username = $args->{'user'};
4980: }
1.129 albertel 4981: $returnhash{'home'}= $chome;
4982: $returnhash{'domain'} = $cdomain;
4983: $returnhash{'num'} = $cnum;
1.741 raeburn 4984: if (!defined($returnhash{'type'})) {
4985: $returnhash{'type'} = 'Course';
4986: }
1.130 albertel 4987: while (my ($name,$value) = each %returnhash) {
1.53 www 4988: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4989: }
1.270 www 4990: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4991: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4992: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4993: $envhash{'course.'.$normalid.'.home'}=$chome;
4994: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4995: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4996: }
4997: }
1.731 albertel 4998: if (!$args->{'one_time'}) {
1.949 raeburn 4999: &appenv(\%envhash);
1.731 albertel 5000: }
1.302 albertel 5001: return %returnhash;
1.461 www 5002: }
5003:
1.1080 raeburn 5004: sub update_released_required {
5005: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5006: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5007: $cid = $env{'request.course.id'};
5008: $cdom = $env{'course.'.$cid.'.domain'};
5009: $cnum = $env{'course.'.$cid.'.num'};
5010: $chome = $env{'course.'.$cid.'.home'};
5011: }
5012: if ($needsrelease) {
5013: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5014: my $needsupdate;
5015: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5016: $needsupdate = 1;
5017: } else {
5018: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5019: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5020: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5021: $needsupdate = 1;
5022: }
5023: }
5024: if ($needsupdate) {
5025: my %needshash = (
5026: 'internal.releaserequired' => $needsrelease,
5027: );
5028: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5029: if ($putresult eq 'ok') {
5030: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5031: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5032: if (ref($crsinfo{$cid}) eq 'HASH') {
5033: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5034: &courseidput($cdom,\%crsinfo,$chome,'notime');
5035: }
5036: }
5037: }
5038: }
5039: return;
5040: }
5041:
1.461 www 5042: # -------------------------------------------------See if a user is privileged
5043:
5044: sub privileged {
1.1219 raeburn 5045: my ($username,$domain,$possdomains,$possroles)=@_;
1.1170 droeschl 5046: my $now = time;
1.1219 raeburn 5047: my $roles;
5048: if (ref($possroles) eq 'ARRAY') {
5049: $roles = $possroles;
5050: } else {
5051: $roles = ['dc','su'];
5052: }
5053: if (ref($possdomains) eq 'ARRAY') {
5054: my %privileged = &privileged_by_domain($possdomains,$roles);
5055: foreach my $dom (@{$possdomains}) {
5056: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5057: (ref($privileged{$dom}) eq 'HASH')) {
5058: foreach my $role (@{$roles}) {
5059: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5060: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5061: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5062: return 1 unless (($end && $end < $now) ||
5063: ($start && $start > $now));
5064: }
5065: }
5066: }
5067: }
5068: }
5069: } else {
5070: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5071: my $now = time;
1.1170 droeschl 5072:
1.1219 raeburn 5073: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
1.1170 droeschl 5074: my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219 raeburn 5075: if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170 droeschl 5076: return 1 unless ($tend && $tend < $now)
1.1219 raeburn 5077: or ($tstart && $tstart > $now);
1.1170 droeschl 5078: }
1.1219 raeburn 5079: }
5080: }
5081: return 0;
5082: }
1.1170 droeschl 5083:
1.1219 raeburn 5084: sub privileged_by_domain {
5085: my ($domains,$roles) = @_;
5086: my %privileged = ();
5087: my $cachetime = 60*60*24;
5088: my $now = time;
5089: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5090: return %privileged;
5091: }
5092: foreach my $dom (@{$domains}) {
5093: next if (ref($privileged{$dom}) eq 'HASH');
5094: my $needroles;
5095: foreach my $role (@{$roles}) {
5096: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5097: if (defined($cached)) {
5098: if (ref($result) eq 'HASH') {
5099: $privileged{$dom}{$role} = $result;
5100: }
5101: } else {
5102: $needroles = 1;
5103: }
5104: }
5105: if ($needroles) {
5106: my %dompersonnel = &get_domain_roles($dom,$roles);
5107: $privileged{$dom} = {};
5108: foreach my $server (keys(%dompersonnel)) {
5109: if (ref($dompersonnel{$server}) eq 'HASH') {
5110: foreach my $item (keys(%{$dompersonnel{$server}})) {
5111: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5112: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5113: next if ($end && $end < $now);
5114: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5115: $dompersonnel{$server}{$item};
5116: }
5117: }
5118: }
5119: if (ref($privileged{$dom}) eq 'HASH') {
5120: foreach my $role (@{$roles}) {
5121: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5122: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5123: } else {
5124: my %hash = ();
5125: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5126: }
5127: }
5128: }
5129: }
5130: }
5131: return %privileged;
1.9 www 5132: }
1.1 albertel 5133:
1.103 harris41 5134: # -------------------------------------------------------- Get user privileges
1.11 www 5135:
5136: sub rolesinit {
1.1169 droeschl 5137: my ($domain, $username) = @_;
5138: my %userroles = ('user.login.time' => time);
5139: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5140:
5141: # firstaccess and timerinterval are related to timed maps/resources.
5142: # also, blocking can be triggered by an activating timer
5143: # it's saved in the user's %env.
5144: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5145: my %timerinterval = &dump('timerinterval', $domain, $username);
5146: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5147: %timerintchk, %timerintenv);
5148:
1.1162 raeburn 5149: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 5150: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 5151: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5152: }
1.1169 droeschl 5153:
1.1162 raeburn 5154: foreach my $key (keys(%timerinterval)) {
5155: my ($cid,$rest) = split(/\0/,$key);
5156: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5157: }
1.1169 droeschl 5158:
1.11 www 5159: my %allroles=();
1.1162 raeburn 5160: my %allgroups=();
1.11 www 5161:
1.1169 droeschl 5162: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5163: my $role = $rolesdump{$area};
5164: $area =~ s/\_\w\w$//;
5165:
5166: my ($trole, $tend, $tstart, $group_privs);
5167:
5168: if ($role =~ /^cr/) {
5169: # Custom role, defined by a user
5170: # e.g., user.role.cr/msu/smith/mynewrole
5171: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5172: $trole = $1;
5173: ($tend, $tstart) = split('_', $2);
5174: } else {
5175: $trole = $role;
5176: }
5177: } elsif ($role =~ m|^gr/|) {
5178: # Role of member in a group, defined within a course/community
5179: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5180: ($trole, $tend, $tstart) = split(/_/, $role);
5181: next if $tstart eq '-1';
5182: ($trole, $group_privs) = split(/\//, $trole);
5183: $group_privs = &unescape($group_privs);
5184: } else {
5185: # Just a normal role, defined in roles.tab
5186: ($trole, $tend, $tstart) = split(/_/,$role);
5187: }
5188:
5189: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5190: $username);
5191: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5192:
5193: # role expired or not available yet?
5194: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5195: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5196:
5197: next if $area eq '' or $trole eq '';
5198:
5199: my $spec = "$trole.$area";
5200: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5201:
5202: if ($trole =~ /^cr\//) {
5203: # Custom role, defined by a user
5204: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5205: } elsif ($trole eq 'gr') {
5206: # Role of a member in a group, defined within a course/community
5207: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5208: next;
5209: } else {
5210: # Normal role, defined in roles.tab
5211: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5212: }
5213:
5214: my $cid = $tdomain.'_'.$trest;
5215: unless ($firstaccchk{$cid}) {
5216: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5217: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5218: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5219: $coursetimerstarts{$cid}{$item};
5220: }
5221: }
5222: $firstaccchk{$cid} = 1;
5223: }
5224: unless ($timerintchk{$cid}) {
5225: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5226: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5227: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5228: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 5229: }
1.12 www 5230: }
1.1169 droeschl 5231: $timerintchk{$cid} = 1;
1.191 harris41 5232: }
1.11 www 5233: }
1.1169 droeschl 5234:
5235: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5236: \%allroles, \%allgroups);
5237: $env{'user.adv'} = $userroles{'user.adv'};
5238:
1.1162 raeburn 5239: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 5240: }
5241:
1.567 raeburn 5242: sub set_arearole {
1.1215 raeburn 5243: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5244: unless ($nolog) {
1.567 raeburn 5245: # log the associated role with the area
1.1215 raeburn 5246: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5247: }
1.743 albertel 5248: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 5249: }
5250:
5251: sub custom_roleprivs {
5252: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5253: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250 raeburn 5254: my $homsvr = &homeserver($rauthor,$rdomain);
1.838 albertel 5255: if (&hostname($homsvr) ne '') {
1.567 raeburn 5256: my ($rdummy,$roledef)=
5257: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5258: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5259: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5260: if (defined($syspriv)) {
1.1043 raeburn 5261: if ($trest =~ /^$match_community$/) {
5262: $syspriv =~ s/bre\&S//;
5263: }
1.567 raeburn 5264: $$allroles{'cm./'}.=':'.$syspriv;
5265: $$allroles{$spec.'./'}.=':'.$syspriv;
5266: }
5267: if ($tdomain ne '') {
5268: if (defined($dompriv)) {
5269: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5270: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5271: }
5272: if (($trest ne '') && (defined($coursepriv))) {
5273: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5274: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5275: }
5276: }
5277: }
5278: }
5279: }
5280:
1.678 raeburn 5281: sub group_roleprivs {
5282: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5283: my $access = 1;
5284: my $now = time;
5285: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5286: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5287: if ($access) {
1.811 albertel 5288: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 5289: $$allgroups{$course}{$group} .=':'.$group_privs;
5290: }
5291: }
1.567 raeburn 5292:
5293: sub standard_roleprivs {
5294: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5295: if (defined($pr{$trole.':s'})) {
5296: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5297: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5298: }
5299: if ($tdomain ne '') {
5300: if (defined($pr{$trole.':d'})) {
5301: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5302: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5303: }
5304: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5305: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5306: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5307: }
5308: }
5309: }
5310:
5311: sub set_userprivs {
1.1064 raeburn 5312: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 5313: my $author=0;
5314: my $adv=0;
1.678 raeburn 5315: my %grouproles = ();
5316: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 5317: my @groupkeys;
1.1000 raeburn 5318: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 5319: push(@groupkeys,$role);
5320: }
5321: if (ref($groups_roles) eq 'HASH') {
5322: foreach my $key (keys(%{$groups_roles})) {
5323: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5324: push(@groupkeys,$key);
5325: }
5326: }
5327: }
5328: if (@groupkeys > 0) {
5329: foreach my $role (@groupkeys) {
5330: my ($trole,$area,$sec,$extendedarea);
5331: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5332: $trole = $1;
5333: $area = $2;
5334: $sec = $3;
5335: $extendedarea = $area.$sec;
5336: if (exists($$allgroups{$area})) {
5337: foreach my $group (keys(%{$$allgroups{$area}})) {
5338: my $spec = $trole.'.'.$extendedarea;
5339: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 5340: $$allgroups{$area}{$group};
1.1064 raeburn 5341: }
1.678 raeburn 5342: }
5343: }
5344: }
5345: }
5346: }
1.800 albertel 5347: foreach my $group (keys(%grouproles)) {
5348: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 5349: }
1.800 albertel 5350: foreach my $role (keys(%{$allroles})) {
5351: my %thesepriv;
1.941 raeburn 5352: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 5353: foreach my $item (split(/:/,$$allroles{$role})) {
5354: if ($item ne '') {
5355: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 5356: if ($restrictions eq '') {
5357: $thesepriv{$privilege}='F';
5358: } elsif ($thesepriv{$privilege} ne 'F') {
5359: $thesepriv{$privilege}.=$restrictions;
5360: }
5361: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5362: }
5363: }
5364: my $thesestr='';
1.1104 raeburn 5365: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 5366: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5367: }
5368: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 5369: }
5370: return ($author,$adv);
5371: }
5372:
1.994 raeburn 5373: sub role_status {
1.1104 raeburn 5374: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 5375: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250 raeburn 5376: my ($one,$two) = split(m{\./},$rolekey,2);
5377: (undef,undef,$$role) = split(/\./,$one,3);
1.994 raeburn 5378: unless (!defined($$role) || $$role eq '') {
1.1251 raeburn 5379: $$where = '/'.$two;
1.994 raeburn 5380: $$trolecode=$$role.'.'.$$where;
5381: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5382: $$tstatus='is';
1.1104 raeburn 5383: if ($$tstart && $$tstart>$update) {
1.994 raeburn 5384: $$tstatus='future';
1.1034 raeburn 5385: if ($$tstart<$now) {
5386: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 5387: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 5388: my (%allroles,%allgroups,$group_privs,
5389: %groups_roles,@rolecodes);
1.1002 raeburn 5390: my %userroles = (
5391: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5392: );
1.1064 raeburn 5393: @rolecodes = ('cm');
1.1002 raeburn 5394: my $spec=$$role.'.'.$$where;
5395: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5396: if ($$role =~ /^cr\//) {
5397: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 5398: push(@rolecodes,'cr');
1.1002 raeburn 5399: } elsif ($$role eq 'gr') {
1.1064 raeburn 5400: push(@rolecodes,$$role);
1.1002 raeburn 5401: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5402: $env{'user.name'});
1.1064 raeburn 5403: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 5404: (undef,my $group_privs) = split(/\//,$trole);
5405: $group_privs = &unescape($group_privs);
5406: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 5407: 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 5408: &get_groups_roles($tdomain,$trest,
5409: \%course_roles,\@rolecodes,
5410: \%groups_roles);
1.1002 raeburn 5411: } else {
1.1064 raeburn 5412: push(@rolecodes,$$role);
1.1002 raeburn 5413: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5414: }
1.1064 raeburn 5415: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5416: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 5417: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5418: }
5419: }
1.1034 raeburn 5420: $$tstatus = 'is';
1.1002 raeburn 5421: }
1.994 raeburn 5422: }
5423: if ($$tend) {
1.1104 raeburn 5424: if ($$tend<$update) {
1.994 raeburn 5425: $$tstatus='expired';
5426: } elsif ($$tend<$now) {
5427: $$tstatus='will_not';
5428: }
5429: }
5430: }
5431: }
5432: }
5433:
1.1104 raeburn 5434: sub get_groups_roles {
5435: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5436: return unless((ref($cdom_courseroles) eq 'HASH') &&
5437: (ref($rolecodes) eq 'ARRAY') &&
5438: (ref($groups_roles) eq 'HASH'));
5439: if (keys(%{$cdom_courseroles}) > 0) {
5440: my ($cnum) = ($rest =~ /^($match_courseid)/);
5441: if ($cdom ne '' && $cnum ne '') {
5442: foreach my $key (keys(%{$cdom_courseroles})) {
5443: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5444: my $crsrole = $1;
5445: my $crssec = $2;
5446: if ($crsrole =~ /^cr/) {
5447: unless (grep(/^cr$/,@{$rolecodes})) {
5448: push(@{$rolecodes},'cr');
5449: }
5450: } else {
5451: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5452: push(@{$rolecodes},$crsrole);
5453: }
5454: }
5455: my $rolekey = "$crsrole./$cdom/$cnum";
5456: if ($crssec ne '') {
5457: $rolekey .= "/$crssec";
5458: }
5459: $rolekey .= './';
5460: $groups_roles->{$rolekey} = $rolecodes;
5461: }
5462: }
5463: }
5464: }
5465: return;
5466: }
5467:
5468: sub delete_env_groupprivs {
5469: my ($where,$courseroles,$possroles) = @_;
5470: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5471: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5472: unless (ref($courseroles->{$udom}) eq 'HASH') {
5473: %{$courseroles->{$udom}} =
5474: &get_my_roles('','','userroles',['active'],
5475: $possroles,[$udom],1);
5476: }
5477: if (ref($courseroles->{$udom}) eq 'HASH') {
5478: foreach my $item (keys(%{$courseroles->{$udom}})) {
5479: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5480: my $area = '/'.$cdom.'/'.$cnum;
5481: my $privkey = "user.priv.$crsrole.$area";
5482: if ($crssec ne '') {
5483: $privkey .= '/'.$crssec;
5484: }
5485: $privkey .= ".$area/$group";
5486: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5487: }
5488: }
5489: return;
5490: }
5491:
1.994 raeburn 5492: sub check_adhoc_privs {
1.1104 raeburn 5493: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5494: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5495: my $setprivs;
1.994 raeburn 5496: if ($env{$cckey}) {
5497: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5498: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5499: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5500: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5501: $setprivs = 1;
1.994 raeburn 5502: }
5503: } else {
1.1088 raeburn 5504: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5505: $setprivs = 1;
1.994 raeburn 5506: }
1.1185 raeburn 5507: return $setprivs;
1.994 raeburn 5508: }
5509:
5510: sub set_adhoc_privileges {
5511: # role can be cc or ca
1.1088 raeburn 5512: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5513: my $area = '/'.$dcdom.'/'.$pickedcourse;
5514: my $spec = $role.'.'.$area;
5515: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215 raeburn 5516: $env{'user.name'},1);
1.994 raeburn 5517: my %ccrole = ();
5518: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5519: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5520: &appenv(\%userroles,[$role,'cm']);
5521: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5522: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5523: &appenv( {'request.role' => $spec,
5524: 'request.role.domain' => $dcdom,
5525: 'request.course.sec' => ''
5526: }
5527: );
5528: my $tadv=0;
5529: if (&allowed('adv') eq 'F') { $tadv=1; }
5530: &appenv({'request.role.adv' => $tadv});
5531: }
1.994 raeburn 5532: }
5533:
1.12 www 5534: # --------------------------------------------------------------- get interface
5535:
5536: sub get {
1.131 albertel 5537: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5538: my $items='';
1.800 albertel 5539: foreach my $item (@$storearr) {
5540: $items.=&escape($item).'&';
1.191 harris41 5541: }
1.12 www 5542: $items=~s/\&$//;
1.620 albertel 5543: if (!$udomain) { $udomain=$env{'user.domain'}; }
5544: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5545: my $uhome=&homeserver($uname,$udomain);
5546:
1.133 albertel 5547: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5548: my @pairs=split(/\&/,$rep);
1.273 albertel 5549: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5550: return @pairs;
5551: }
1.15 www 5552: my %returnhash=();
1.42 www 5553: my $i=0;
1.800 albertel 5554: foreach my $item (@$storearr) {
5555: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5556: $i++;
1.191 harris41 5557: }
1.15 www 5558: return %returnhash;
1.27 www 5559: }
5560:
5561: # --------------------------------------------------------------- del interface
5562:
5563: sub del {
1.133 albertel 5564: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5565: my $items='';
1.800 albertel 5566: foreach my $item (@$storearr) {
5567: $items.=&escape($item).'&';
1.191 harris41 5568: }
1.984 neumanie 5569:
1.27 www 5570: $items=~s/\&$//;
1.620 albertel 5571: if (!$udomain) { $udomain=$env{'user.domain'}; }
5572: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5573: my $uhome=&homeserver($uname,$udomain);
5574: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5575: }
5576:
5577: # -------------------------------------------------------------- dump interface
5578:
1.1180 droeschl 5579: sub unserialize {
5580: my ($rep, $escapedkeys) = @_;
5581:
5582: return {} if $rep =~ /^error/;
5583:
5584: my %returnhash=();
1.1252 raeburn 5585: foreach my $item (split(/\&/,$rep)) {
1.1180 droeschl 5586: my ($key, $value) = split(/=/, $item, 2);
5587: $key = unescape($key) unless $escapedkeys;
5588: next if $key =~ /^error: 2 /;
1.1252 raeburn 5589: $returnhash{$key} = &thaw_unescape($value);
1.1180 droeschl 5590: }
5591: #return %returnhash;
5592: return \%returnhash;
5593: }
5594:
5595: # see Lond::dump_with_regexp
5596: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5597: sub dump {
1.1180 droeschl 5598: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5599: if (!$udomain) { $udomain=$env{'user.domain'}; }
5600: if (!$uname) { $uname=$env{'user.name'}; }
5601: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5602:
1.1180 droeschl 5603: my $reply;
5604: if (grep { $_ eq $uhome } current_machine_ids()) {
5605: # user is hosted on this machine
5606: $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226 raeburn 5607: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180 droeschl 5608: return %{unserialize($reply, $escapedkeys)};
5609: }
1.755 albertel 5610: if ($regexp) {
5611: $regexp=&escape($regexp);
5612: } else {
5613: $regexp='.';
5614: }
1.1166 raeburn 5615: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5616: my @pairs=split(/\&/,$rep);
5617: my %returnhash=();
1.1098 foxr 5618: if (!($rep =~ /^error/ )) {
5619: foreach my $item (@pairs) {
5620: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5621: $key = unescape($key) unless $escapedkeys;
5622: #$key = &unescape($key);
1.1098 foxr 5623: next if ($key =~ /^error: 2 /);
5624: $returnhash{$key}=&thaw_unescape($value);
5625: }
1.755 albertel 5626: }
5627: return %returnhash;
1.407 www 5628: }
5629:
1.1098 foxr 5630:
1.717 albertel 5631: # --------------------------------------------------------- dumpstore interface
5632:
5633: sub dumpstore {
5634: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5635: # same as dump but keys must be escaped. They may contain colon separated
5636: # lists of values that may themself contain colons (e.g. symbs).
5637: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5638: }
5639:
1.407 www 5640: # -------------------------------------------------------------- keys interface
5641:
5642: sub getkeys {
5643: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5644: if (!$udomain) { $udomain=$env{'user.domain'}; }
5645: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5646: my $uhome=&homeserver($uname,$udomain);
5647: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5648: my @keyarray=();
1.800 albertel 5649: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5650: next if ($key =~ /^error: 2 /);
1.800 albertel 5651: push(@keyarray,&unescape($key));
1.407 www 5652: }
5653: return @keyarray;
1.318 matthew 5654: }
5655:
1.319 matthew 5656: # --------------------------------------------------------------- currentdump
5657: sub currentdump {
1.328 matthew 5658: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5659: $courseid = $env{'request.course.id'} if (! defined($courseid));
5660: $sdom = $env{'user.domain'} if (! defined($sdom));
5661: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5662: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5663: my $rep;
5664:
5665: if (grep { $_ eq $uhome } current_machine_ids()) {
5666: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5667: $courseid)));
5668: } else {
5669: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5670: }
5671:
1.318 matthew 5672: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5673: #
1.318 matthew 5674: my %returnhash=();
1.319 matthew 5675: #
5676: if ($rep eq "unknown_cmd") {
5677: # an old lond will not know currentdump
5678: # Do a dump and make it look like a currentdump
1.822 albertel 5679: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5680: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5681: my %hash = @tmp;
5682: @tmp=();
1.424 matthew 5683: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5684: } else {
5685: my @pairs=split(/\&/,$rep);
1.800 albertel 5686: foreach my $pair (@pairs) {
5687: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5688: my ($symb,$param) = split(/:/,$key);
5689: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5690: &thaw_unescape($value);
1.319 matthew 5691: }
1.191 harris41 5692: }
1.12 www 5693: return %returnhash;
1.424 matthew 5694: }
5695:
5696: sub convert_dump_to_currentdump{
5697: my %hash = %{shift()};
5698: my %returnhash;
5699: # Code ripped from lond, essentially. The only difference
5700: # here is the unescaping done by lonnet::dump(). Conceivably
5701: # we might run in to problems with parameter names =~ /^v\./
5702: while (my ($key,$value) = each(%hash)) {
5703: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5704: $symb = &unescape($symb);
5705: $param = &unescape($param);
1.424 matthew 5706: next if ($v eq 'version' || $symb eq 'keys');
5707: next if (exists($returnhash{$symb}) &&
5708: exists($returnhash{$symb}->{$param}) &&
5709: $returnhash{$symb}->{'v.'.$param} > $v);
5710: $returnhash{$symb}->{$param}=$value;
5711: $returnhash{$symb}->{'v.'.$param}=$v;
5712: }
5713: #
5714: # Remove all of the keys in the hashes which keep track of
5715: # the version of the parameter.
5716: while (my ($symb,$param_hash) = each(%returnhash)) {
5717: # use a foreach because we are going to delete from the hash.
5718: foreach my $key (keys(%$param_hash)) {
5719: delete($param_hash->{$key}) if ($key =~ /^v\./);
5720: }
5721: }
5722: return \%returnhash;
1.12 www 5723: }
5724:
1.627 albertel 5725: # ------------------------------------------------------ critical inc interface
5726:
5727: sub cinc {
5728: return &inc(@_,'critical');
5729: }
5730:
1.449 matthew 5731: # --------------------------------------------------------------- inc interface
5732:
5733: sub inc {
1.627 albertel 5734: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5735: if (!$udomain) { $udomain=$env{'user.domain'}; }
5736: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5737: my $uhome=&homeserver($uname,$udomain);
5738: my $items='';
5739: if (! ref($store)) {
5740: # got a single value, so use that instead
5741: $items = &escape($store).'=&';
5742: } elsif (ref($store) eq 'SCALAR') {
5743: $items = &escape($$store).'=&';
5744: } elsif (ref($store) eq 'ARRAY') {
5745: $items = join('=&',map {&escape($_);} @{$store});
5746: } elsif (ref($store) eq 'HASH') {
5747: while (my($key,$value) = each(%{$store})) {
5748: $items.= &escape($key).'='.&escape($value).'&';
5749: }
5750: }
5751: $items=~s/\&$//;
1.627 albertel 5752: if ($critical) {
5753: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5754: } else {
5755: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5756: }
1.449 matthew 5757: }
5758:
1.12 www 5759: # --------------------------------------------------------------- put interface
5760:
5761: sub put {
1.134 albertel 5762: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5763: if (!$udomain) { $udomain=$env{'user.domain'}; }
5764: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5765: my $uhome=&homeserver($uname,$udomain);
1.12 www 5766: my $items='';
1.800 albertel 5767: foreach my $item (keys(%$storehash)) {
5768: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5769: }
1.12 www 5770: $items=~s/\&$//;
1.134 albertel 5771: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5772: }
5773:
1.631 albertel 5774: # ------------------------------------------------------------ newput interface
5775:
5776: sub newput {
5777: my ($namespace,$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 $items='';
5782: foreach my $key (keys(%$storehash)) {
5783: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5784: }
5785: $items=~s/\&$//;
5786: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5787: }
5788:
5789: # --------------------------------------------------------- putstore interface
5790:
1.524 raeburn 5791: sub putstore {
1.715 albertel 5792: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5793: if (!$udomain) { $udomain=$env{'user.domain'}; }
5794: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5795: my $uhome=&homeserver($uname,$udomain);
5796: my $items='';
1.715 albertel 5797: foreach my $key (keys(%$storehash)) {
5798: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5799: }
1.715 albertel 5800: $items=~s/\&$//;
1.716 albertel 5801: my $esc_symb=&escape($symb);
5802: my $esc_v=&escape($version);
1.715 albertel 5803: my $reply =
1.716 albertel 5804: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5805: $uhome);
5806: if ($reply eq 'unknown_cmd') {
1.716 albertel 5807: # gfall back to way things use to be done
1.715 albertel 5808: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5809: $uname);
1.524 raeburn 5810: }
1.715 albertel 5811: return $reply;
5812: }
5813:
5814: sub old_putstore {
1.716 albertel 5815: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5816: if (!$udomain) { $udomain=$env{'user.domain'}; }
5817: if (!$uname) { $uname=$env{'user.name'}; }
5818: my $uhome=&homeserver($uname,$udomain);
5819: my %newstorehash;
1.800 albertel 5820: foreach my $item (keys(%$storehash)) {
5821: my $key = $version.':'.&escape($symb).':'.$item;
5822: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5823: }
5824: my $items='';
5825: my %allitems = ();
1.800 albertel 5826: foreach my $item (keys(%newstorehash)) {
5827: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5828: my $key = $1.':keys:'.$2;
5829: $allitems{$key} .= $3.':';
5830: }
1.800 albertel 5831: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5832: }
1.800 albertel 5833: foreach my $item (keys(%allitems)) {
5834: $allitems{$item} =~ s/\:$//;
5835: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5836: }
5837: $items=~s/\&$//;
5838: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5839: }
5840:
1.47 www 5841: # ------------------------------------------------------ critical put interface
5842:
5843: sub cput {
1.134 albertel 5844: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5845: if (!$udomain) { $udomain=$env{'user.domain'}; }
5846: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5847: my $uhome=&homeserver($uname,$udomain);
1.47 www 5848: my $items='';
1.800 albertel 5849: foreach my $item (keys(%$storehash)) {
5850: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5851: }
1.47 www 5852: $items=~s/\&$//;
1.134 albertel 5853: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5854: }
5855:
5856: # -------------------------------------------------------------- eget interface
5857:
5858: sub eget {
1.133 albertel 5859: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5860: my $items='';
1.800 albertel 5861: foreach my $item (@$storearr) {
5862: $items.=&escape($item).'&';
1.191 harris41 5863: }
1.12 www 5864: $items=~s/\&$//;
1.620 albertel 5865: if (!$udomain) { $udomain=$env{'user.domain'}; }
5866: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5867: my $uhome=&homeserver($uname,$udomain);
5868: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5869: my @pairs=split(/\&/,$rep);
5870: my %returnhash=();
1.42 www 5871: my $i=0;
1.800 albertel 5872: foreach my $item (@$storearr) {
5873: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5874: $i++;
1.191 harris41 5875: }
1.12 www 5876: return %returnhash;
5877: }
5878:
1.667 albertel 5879: # ------------------------------------------------------------ tmpput interface
5880: sub tmpput {
1.802 raeburn 5881: my ($storehash,$server,$context)=@_;
1.667 albertel 5882: my $items='';
1.800 albertel 5883: foreach my $item (keys(%$storehash)) {
5884: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5885: }
5886: $items=~s/\&$//;
1.802 raeburn 5887: if (defined($context)) {
5888: $items .= ':'.&escape($context);
5889: }
1.667 albertel 5890: return &reply("tmpput:$items",$server);
5891: }
5892:
5893: # ------------------------------------------------------------ tmpget interface
5894: sub tmpget {
1.688 albertel 5895: my ($token,$server)=@_;
5896: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5897: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5898: my %returnhash;
5899: foreach my $item (split(/\&/,$rep)) {
5900: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5901: next if ($key =~ /^error: 2 /);
1.667 albertel 5902: $returnhash{&unescape($key)}=&thaw_unescape($value);
5903: }
5904: return %returnhash;
5905: }
5906:
1.1113 raeburn 5907: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5908: sub tmpdel {
5909: my ($token,$server)=@_;
5910: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5911: return &reply("tmpdel:$token",$server);
5912: }
5913:
1.1198 raeburn 5914: # ------------------------------------------------------------ get_timebased_id
5915:
5916: sub get_timebased_id {
5917: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5918: $maxtries) = @_;
5919: my ($newid,$error,$dellock);
5920: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5921: return ('','ok','invalid call to get suffix');
5922: }
5923:
5924: # set defaults for any optional args for which values were not supplied
5925: if ($who eq '') {
5926: $who = $env{'user.name'}.':'.$env{'user.domain'};
5927: }
5928: if (!$locktries) {
5929: $locktries = 3;
5930: }
5931: if (!$maxtries) {
5932: $maxtries = 10;
5933: }
5934:
5935: if (($cdom eq '') || ($cnum eq '')) {
5936: if ($env{'request.course.id'}) {
5937: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5938: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5939: }
5940: if (($cdom eq '') || ($cnum eq '')) {
5941: return ('','ok','call to get suffix not in course context');
5942: }
5943: }
5944:
5945: # construct locking item
5946: my $lockhash = {
5947: $prefix."\0".'locked_'.$keyid => $who,
5948: };
5949: my $tries = 0;
5950:
5951: # attempt to get lock on nohist_$namespace file
5952: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5953: while (($gotlock ne 'ok') && $tries <$locktries) {
5954: $tries ++;
5955: sleep 1;
5956: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5957: }
5958:
5959: # attempt to get unique identifier, based on current timestamp
5960: if ($gotlock eq 'ok') {
5961: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
5962: my $id = time;
5963: $newid = $id;
5964: my $idtries = 0;
5965: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
5966: if ($idtype eq 'concat') {
5967: $newid = $id.$idtries;
5968: } else {
5969: $newid ++;
5970: }
5971: $idtries ++;
5972: }
5973: if (!exists($inuse{$prefix."\0".$newid})) {
5974: my %new_item = (
5975: $prefix."\0".$newid => $who,
5976: );
5977: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
5978: $cdom,$cnum);
5979: if ($putresult ne 'ok') {
5980: undef($newid);
5981: $error = 'error saving new item: '.$putresult;
5982: }
5983: } else {
5984: $error = ('error: no unique suffix available for the new item ');
5985: }
5986: # remove lock
5987: my @del_lock = ($prefix."\0".'locked_'.$keyid);
5988: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
5989: } else {
5990: $error = "error: could not obtain lockfile\n";
5991: $dellock = 'ok';
5992: }
5993: return ($newid,$dellock,$error);
5994: }
5995:
1.765 albertel 5996: # -------------------------------------------------- portfolio access checking
5997:
5998: sub portfolio_access {
1.766 albertel 5999: my ($requrl) = @_;
1.765 albertel 6000: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6001: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 6002: if ($result) {
6003: my %setters;
6004: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6005: my ($startblock,$endblock) =
6006: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6007: if ($startblock && $endblock) {
6008: return 'B';
6009: }
6010: } else {
6011: my ($startblock,$endblock) =
6012: &Apache::loncommon::blockcheck(\%setters,'port');
6013: if ($startblock && $endblock) {
6014: return 'B';
6015: }
6016: }
6017: }
1.765 albertel 6018: if ($result eq 'ok') {
1.766 albertel 6019: return 'F';
1.765 albertel 6020: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 6021: return 'A';
1.765 albertel 6022: }
1.766 albertel 6023: return '';
1.765 albertel 6024: }
6025:
6026: sub get_portfolio_access {
1.767 albertel 6027: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
6028:
6029: if (!ref($access_hash)) {
6030: my $current_perms = &get_portfile_permissions($udom,$unum);
6031: my %access_controls = &get_access_controls($current_perms,$group,
6032: $file_name);
6033: $access_hash = $access_controls{$file_name};
6034: }
6035:
1.765 albertel 6036: my ($public,$guest,@domains,@users,@courses,@groups);
6037: my $now = time;
6038: if (ref($access_hash) eq 'HASH') {
6039: foreach my $key (keys(%{$access_hash})) {
6040: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6041: if ($start > $now) {
6042: next;
6043: }
6044: if ($end && $end<$now) {
6045: next;
6046: }
6047: if ($scope eq 'public') {
6048: $public = $key;
6049: last;
6050: } elsif ($scope eq 'guest') {
6051: $guest = $key;
6052: } elsif ($scope eq 'domains') {
6053: push(@domains,$key);
6054: } elsif ($scope eq 'users') {
6055: push(@users,$key);
6056: } elsif ($scope eq 'course') {
6057: push(@courses,$key);
6058: } elsif ($scope eq 'group') {
6059: push(@groups,$key);
6060: }
6061: }
6062: if ($public) {
6063: return 'ok';
6064: }
6065: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6066: if ($guest) {
6067: return $guest;
6068: }
6069: } else {
6070: if (@domains > 0) {
6071: foreach my $domkey (@domains) {
6072: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6073: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6074: return 'ok';
6075: }
6076: }
6077: }
6078: }
6079: if (@users > 0) {
6080: foreach my $userkey (@users) {
1.865 raeburn 6081: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6082: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6083: if (ref($item) eq 'HASH') {
6084: if (($item->{'uname'} eq $env{'user.name'}) &&
6085: ($item->{'udom'} eq $env{'user.domain'})) {
6086: return 'ok';
6087: }
6088: }
6089: }
6090: }
1.765 albertel 6091: }
6092: }
6093: my %roleshash;
6094: my @courses_and_groups = @courses;
6095: push(@courses_and_groups,@groups);
6096: if (@courses_and_groups > 0) {
6097: my (%allgroups,%allroles);
6098: my ($start,$end,$role,$sec,$group);
6099: foreach my $envkey (%env) {
1.1060 raeburn 6100: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6101: my $cid = $2.'_'.$3;
6102: if ($1 eq 'gr') {
6103: $group = $4;
6104: $allgroups{$cid}{$group} = $env{$envkey};
6105: } else {
6106: if ($4 eq '') {
6107: $sec = 'none';
6108: } else {
6109: $sec = $4;
6110: }
6111: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6112: }
1.811 albertel 6113: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 6114: my $cid = $2.'_'.$3;
6115: if ($4 eq '') {
6116: $sec = 'none';
6117: } else {
6118: $sec = $4;
6119: }
6120: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6121: }
6122: }
6123: if (keys(%allroles) == 0) {
6124: return;
6125: }
6126: foreach my $key (@courses_and_groups) {
6127: my %content = %{$$access_hash{$key}};
6128: my $cnum = $content{'number'};
6129: my $cdom = $content{'domain'};
6130: my $cid = $cdom.'_'.$cnum;
6131: if (!exists($allroles{$cid})) {
6132: next;
6133: }
6134: foreach my $role_id (keys(%{$content{'roles'}})) {
6135: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6136: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6137: my @status = @{$content{'roles'}{$role_id}{'access'}};
6138: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6139: foreach my $role (keys(%{$allroles{$cid}})) {
6140: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6141: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6142: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6143: if (grep/^all$/,@sections) {
6144: return 'ok';
6145: } else {
6146: if (grep/^$sec$/,@sections) {
6147: return 'ok';
6148: }
6149: }
6150: }
6151: }
6152: if (keys(%{$allgroups{$cid}}) == 0) {
6153: if (grep/^none$/,@groups) {
6154: return 'ok';
6155: }
6156: } else {
6157: if (grep/^all$/,@groups) {
6158: return 'ok';
6159: }
6160: foreach my $group (keys(%{$allgroups{$cid}})) {
6161: if (grep/^$group$/,@groups) {
6162: return 'ok';
6163: }
6164: }
6165: }
6166: }
6167: }
6168: }
6169: }
6170: }
6171: if ($guest) {
6172: return $guest;
6173: }
6174: }
6175: }
6176: return;
6177: }
6178:
6179: sub course_group_datechecker {
6180: my ($dates,$now,$status) = @_;
6181: my ($start,$end) = split(/\./,$dates);
6182: if (!$start && !$end) {
6183: return 'ok';
6184: }
6185: if (grep/^active$/,@{$status}) {
6186: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6187: return 'ok';
6188: }
6189: }
6190: if (grep/^previous$/,@{$status}) {
6191: if ($end > $now ) {
6192: return 'ok';
6193: }
6194: }
6195: if (grep/^future$/,@{$status}) {
6196: if ($start > $now) {
6197: return 'ok';
6198: }
6199: }
6200: return;
6201: }
6202:
6203: sub parse_portfolio_url {
6204: my ($url) = @_;
6205:
6206: my ($type,$udom,$unum,$group,$file_name);
6207:
1.823 albertel 6208: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 6209: $type = 1;
6210: $udom = $1;
6211: $unum = $2;
6212: $file_name = $3;
1.823 albertel 6213: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 6214: $type = 2;
6215: $udom = $1;
6216: $unum = $2;
6217: $group = $3;
6218: $file_name = $3.'/'.$4;
6219: }
6220: if (wantarray) {
6221: return ($type,$udom,$unum,$file_name,$group);
6222: }
6223: return $type;
6224: }
6225:
6226: sub is_portfolio_url {
6227: my ($url) = @_;
6228: return scalar(&parse_portfolio_url($url));
6229: }
6230:
1.798 raeburn 6231: sub is_portfolio_file {
6232: my ($file) = @_;
1.820 raeburn 6233: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 6234: return 1;
6235: }
6236: return;
6237: }
6238:
1.976 raeburn 6239: sub usertools_access {
1.1084 raeburn 6240: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 6241: my ($access,%tools);
6242: if ($context eq '') {
6243: $context = 'tools';
6244: }
6245: if ($context eq 'requestcourses') {
6246: %tools = (
6247: official => 1,
6248: unofficial => 1,
1.1006 raeburn 6249: community => 1,
1.1246 raeburn 6250: textbook => 1,
1.985 raeburn 6251: );
1.1183 raeburn 6252: } elsif ($context eq 'requestauthor') {
6253: %tools = (
6254: requestauthor => 1,
6255: );
1.985 raeburn 6256: } else {
6257: %tools = (
6258: aboutme => 1,
6259: blog => 1,
1.1177 raeburn 6260: webdav => 1,
1.985 raeburn 6261: portfolio => 1,
6262: );
6263: }
1.976 raeburn 6264: return if (!defined($tools{$tool}));
6265:
1.1242 raeburn 6266: if (($udom eq '') || ($uname eq '')) {
1.976 raeburn 6267: $udom = $env{'user.domain'};
6268: $uname = $env{'user.name'};
6269: }
6270:
1.978 raeburn 6271: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6272: if ($action ne 'reload') {
1.985 raeburn 6273: if ($context eq 'requestcourses') {
6274: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 6275: } elsif ($context eq 'requestauthor') {
6276: return $env{'environment.canrequest.author'};
1.985 raeburn 6277: } else {
6278: return $env{'environment.availabletools.'.$tool};
6279: }
6280: }
1.976 raeburn 6281: }
6282:
1.1183 raeburn 6283: my ($toolstatus,$inststatus,$envkey);
6284: if ($context eq 'requestauthor') {
6285: $envkey = $context;
6286: } else {
6287: $envkey = $context.'.'.$tool;
6288: }
1.976 raeburn 6289:
1.985 raeburn 6290: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6291: ($action ne 'reload')) {
1.1183 raeburn 6292: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 6293: $inststatus = $env{'environment.inststatus'};
6294: } else {
1.1084 raeburn 6295: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 6296: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 6297: $inststatus = $userenvref->{'inststatus'};
6298: } else {
1.1183 raeburn 6299: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6300: $toolstatus = $userenv{$envkey};
1.1084 raeburn 6301: $inststatus = $userenv{'inststatus'};
6302: }
1.976 raeburn 6303: }
6304:
6305: if ($toolstatus ne '') {
6306: if ($toolstatus) {
6307: $access = 1;
6308: } else {
6309: $access = 0;
6310: }
6311: return $access;
6312: }
6313:
1.1084 raeburn 6314: my ($is_adv,%domdef);
6315: if (ref($is_advref) eq 'HASH') {
6316: $is_adv = $is_advref->{'is_adv'};
6317: } else {
6318: $is_adv = &is_advanced_user($udom,$uname);
6319: }
6320: if (ref($domdefref) eq 'HASH') {
6321: %domdef = %{$domdefref};
6322: } else {
6323: %domdef = &get_domain_defaults($udom);
6324: }
1.976 raeburn 6325: if (ref($domdef{$tool}) eq 'HASH') {
6326: if ($is_adv) {
6327: if ($domdef{$tool}{'_LC_adv'} ne '') {
6328: if ($domdef{$tool}{'_LC_adv'}) {
6329: $access = 1;
6330: } else {
6331: $access = 0;
6332: }
6333: return $access;
6334: }
6335: }
6336: if ($inststatus ne '') {
6337: my ($hasaccess,$hasnoaccess);
6338: foreach my $affiliation (split(/:/,$inststatus)) {
6339: if ($domdef{$tool}{$affiliation} ne '') {
6340: if ($domdef{$tool}{$affiliation}) {
6341: $hasaccess = 1;
6342: } else {
6343: $hasnoaccess = 1;
6344: }
6345: }
6346: }
6347: if ($hasaccess || $hasnoaccess) {
6348: if ($hasaccess) {
6349: $access = 1;
6350: } elsif ($hasnoaccess) {
6351: $access = 0;
6352: }
6353: return $access;
6354: }
6355: } else {
6356: if ($domdef{$tool}{'default'} ne '') {
6357: if ($domdef{$tool}{'default'}) {
6358: $access = 1;
6359: } elsif ($domdef{$tool}{'default'} == 0) {
6360: $access = 0;
6361: }
6362: return $access;
6363: }
6364: }
6365: } else {
1.1177 raeburn 6366: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 6367: $access = 1;
6368: } else {
6369: $access = 0;
6370: }
1.976 raeburn 6371: return $access;
6372: }
6373: }
6374:
1.1050 raeburn 6375: sub is_course_owner {
6376: my ($cdom,$cnum,$udom,$uname) = @_;
6377: if (($udom eq '') || ($uname eq '')) {
6378: $udom = $env{'user.domain'};
6379: $uname = $env{'user.name'};
6380: }
6381: unless (($udom eq '') || ($uname eq '')) {
6382: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6383: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6384: return 1;
6385: } else {
6386: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6387: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6388: return 1;
6389: }
6390: }
6391: }
6392: }
6393: return;
6394: }
6395:
1.976 raeburn 6396: sub is_advanced_user {
6397: my ($udom,$uname) = @_;
1.1085 raeburn 6398: if ($udom ne '' && $uname ne '') {
6399: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 6400: if (wantarray) {
6401: return ($env{'user.adv'},$env{'user.author'});
6402: } else {
6403: return $env{'user.adv'};
6404: }
1.1085 raeburn 6405: }
6406: }
1.976 raeburn 6407: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6408: my %allroles;
1.1128 raeburn 6409: my ($is_adv,$is_author);
1.976 raeburn 6410: foreach my $role (keys(%roleshash)) {
6411: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6412: my $area = '/'.$tdomain.'/'.$trest;
6413: if ($sec ne '') {
6414: $area .= '/'.$sec;
6415: }
6416: if (($area ne '') && ($trole ne '')) {
6417: my $spec=$trole.'.'.$area;
6418: if ($trole =~ /^cr\//) {
6419: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6420: } elsif ($trole ne 'gr') {
6421: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6422: }
1.1128 raeburn 6423: if ($trole eq 'au') {
6424: $is_author = 1;
6425: }
1.976 raeburn 6426: }
6427: }
6428: foreach my $role (keys(%allroles)) {
6429: last if ($is_adv);
6430: foreach my $item (split(/:/,$allroles{$role})) {
6431: if ($item ne '') {
6432: my ($privilege,$restrictions)=split(/&/,$item);
6433: if ($privilege eq 'adv') {
6434: $is_adv = 1;
6435: last;
6436: }
6437: }
6438: }
6439: }
1.1128 raeburn 6440: if (wantarray) {
6441: return ($is_adv,$is_author);
6442: }
1.976 raeburn 6443: return $is_adv;
6444: }
1.798 raeburn 6445:
1.1035 raeburn 6446: sub check_can_request {
1.1036 raeburn 6447: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 6448: my $canreq = 0;
6449: my ($types,$typename) = &Apache::loncommon::course_types();
6450: my @options = ('approval','validate','autolimit');
6451: my $optregex = join('|',@options);
6452: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6453: foreach my $type (@{$types}) {
6454: if (&usertools_access($env{'user.name'},
6455: $env{'user.domain'},
6456: $type,undef,'requestcourses')) {
6457: $canreq ++;
1.1036 raeburn 6458: if (ref($request_domains) eq 'HASH') {
6459: push(@{$request_domains->{$type}},$env{'user.domain'});
6460: }
1.1035 raeburn 6461: if ($dom eq $env{'user.domain'}) {
6462: $can_request->{$type} = 1;
6463: }
6464: }
6465: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6466: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6467: if (@curr > 0) {
1.1036 raeburn 6468: foreach my $item (@curr) {
6469: if (ref($request_domains) eq 'HASH') {
6470: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6471: if ($otherdom ne '') {
6472: if (ref($request_domains->{$type}) eq 'ARRAY') {
6473: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6474: push(@{$request_domains->{$type}},$otherdom);
6475: }
6476: } else {
6477: push(@{$request_domains->{$type}},$otherdom);
6478: }
6479: }
6480: }
6481: }
6482: unless($dom eq $env{'user.domain'}) {
6483: $canreq ++;
1.1035 raeburn 6484: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6485: $can_request->{$type} = 1;
6486: }
6487: }
6488: }
6489: }
6490: }
6491: }
6492: return $canreq;
6493: }
6494:
1.341 www 6495: # ---------------------------------------------- Custom access rule evaluation
6496:
6497: sub customaccess {
6498: my ($priv,$uri)=@_;
1.807 albertel 6499: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 6500: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 6501: $udom = &LONCAPA::clean_domain($udom);
6502: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 6503: my $access=0;
1.800 albertel 6504: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 6505: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6506: if ($type eq 'user') {
6507: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 6508: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 6509: if ($tdom) {
6510: if ($tdom ne $env{'user.domain'}) { next; }
6511: }
1.896 albertel 6512: if ($tuname) {
6513: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 6514: }
6515: $access=($effect eq 'allow');
6516: last;
6517: }
6518: } else {
6519: if ($role) {
6520: if ($role ne $urole) { next; }
6521: }
6522: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6523: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6524: if ($tdom) {
6525: if ($tdom ne $udom) { next; }
6526: }
6527: if ($tcrs) {
6528: if ($tcrs ne $ucrs) { next; }
6529: }
6530: if ($tsec) {
6531: if ($tsec ne $usec) { next; }
6532: }
6533: $access=($effect eq 'allow');
6534: last;
6535: }
6536: if ($realm eq '' && $role eq '') {
6537: $access=($effect eq 'allow');
6538: }
1.402 bowersj2 6539: }
1.341 www 6540: }
6541: return $access;
6542: }
6543:
1.103 harris41 6544: # ------------------------------------------------- Check for a user privilege
1.12 www 6545:
6546: sub allowed {
1.810 raeburn 6547: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6548: my $ver_orguri=$uri;
1.439 www 6549: $uri=&deversion($uri);
1.152 www 6550: my $orguri=$uri;
1.52 www 6551: $uri=&declutter($uri);
1.809 raeburn 6552:
1.810 raeburn 6553: if ($priv eq 'evb') {
6554: # Evade communication block restrictions for specified role in a course
6555: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6556: return $1;
6557: } else {
6558: return;
6559: }
6560: }
6561:
1.620 albertel 6562: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6563: # Free bre access to adm and meta resources
1.775 albertel 6564: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6565: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6566: && ($priv eq 'bre')) {
1.14 www 6567: return 'F';
1.159 www 6568: }
6569:
1.545 banghart 6570: # Free bre access to user's own portfolio contents
1.714 raeburn 6571: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6572: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6573: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6574: my %setters;
6575: my ($startblock,$endblock) =
6576: &Apache::loncommon::blockcheck(\%setters,'port');
6577: if ($startblock && $endblock) {
6578: return 'B';
6579: } else {
6580: return 'F';
6581: }
1.545 banghart 6582: }
6583:
1.762 raeburn 6584: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6585: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6586: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6587: if (exists($env{'request.course.id'})) {
6588: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6589: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6590: if (($domain eq $cdom) && ($name eq $cnum)) {
6591: my $courseprivid=$env{'request.course.id'};
6592: $courseprivid=~s/\_/\//;
6593: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6594: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6595: return $1;
1.762 raeburn 6596: } else {
6597: if ($env{'request.course.sec'}) {
6598: $courseprivid.='/'.$env{'request.course.sec'};
6599: }
6600: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6601: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6602: return $2;
6603: }
1.714 raeburn 6604: }
6605: }
6606: }
6607: }
6608:
1.159 www 6609: # Free bre to public access
6610:
6611: if ($priv eq 'bre') {
1.238 www 6612: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6613: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6614: return 'F';
6615: }
1.238 www 6616: if ($copyright eq 'priv') {
6617: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6618: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6619: return '';
6620: }
6621: }
6622: if ($copyright eq 'domain') {
6623: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6624: unless (($env{'user.domain'} eq $1) ||
6625: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6626: return '';
6627: }
1.262 matthew 6628: }
1.620 albertel 6629: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6630: # Library role, so allow browsing of resources in this domain.
6631: return 'F';
1.238 www 6632: }
1.341 www 6633: if ($copyright eq 'custom') {
6634: unless (&customaccess($priv,$uri)) { return ''; }
6635: }
1.14 www 6636: }
1.264 matthew 6637: # Domain coordinator is trying to create a course
1.620 albertel 6638: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6639: # uri is the requested domain in this case.
6640: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6641: # a role of dc for the domain in question.
1.620 albertel 6642: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6643: }
1.29 www 6644:
1.52 www 6645: my $thisallowed='';
6646: my $statecond=0;
6647: my $courseprivid='';
6648:
1.1039 raeburn 6649: my $ownaccess;
1.1043 raeburn 6650: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6651: if (($priv eq 'bro') && ($env{'user.author'})) {
6652: if ($uri eq '') {
6653: $ownaccess = 1;
6654: } else {
6655: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6656: my $udom = $env{'user.domain'};
6657: my $uname = $env{'user.name'};
6658: if ($uri =~ m{^\Q$udom\E/?$}) {
6659: $ownaccess = 1;
1.1040 raeburn 6660: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6661: unless ($uri =~ m{\.\./}) {
6662: $ownaccess = 1;
6663: }
6664: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6665: my $now = time;
6666: if ($uri =~ m{^([^/]+)/?$}) {
6667: my $adom = $1;
6668: foreach my $key (keys(%env)) {
1.1042 raeburn 6669: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6670: my ($start,$end) = split('.',$env{$key});
6671: if (($now >= $start) && (!$end || $end < $now)) {
6672: $ownaccess = 1;
6673: last;
6674: }
6675: }
6676: }
6677: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6678: my $adom = $1;
6679: my $aname = $2;
1.1042 raeburn 6680: foreach my $role ('ca','aa') {
6681: if ($env{"user.role.$role./$adom/$aname"}) {
6682: my ($start,$end) =
6683: split('.',$env{"user.role.$role./$adom/$aname"});
6684: if (($now >= $start) && (!$end || $end < $now)) {
6685: $ownaccess = 1;
6686: last;
6687: }
1.1039 raeburn 6688: }
6689: }
6690: }
6691: }
6692: }
6693: }
6694: }
6695:
1.52 www 6696: # Course
6697:
1.620 albertel 6698: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6699: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6700: $thisallowed.=$1;
6701: }
1.52 www 6702: }
1.29 www 6703:
1.52 www 6704: # Domain
6705:
1.620 albertel 6706: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6707: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6708: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6709: $thisallowed.=$1;
6710: }
1.12 www 6711: }
1.52 www 6712:
1.1141 raeburn 6713: # User who is not author or co-author might still be able to edit
6714: # resource of an author in the domain (e.g., if Domain Coordinator).
6715: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6716: (&allowed('mdc',$env{'request.course.id'}))) {
6717: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6718: $thisallowed.=$1;
6719: }
6720: }
6721:
1.52 www 6722: # Course: uri itself is a course
1.66 www 6723: my $courseuri=$uri;
6724: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6725: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6726:
1.620 albertel 6727: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6728: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6729: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6730: $thisallowed.=$1;
6731: }
1.12 www 6732: }
1.29 www 6733:
1.665 albertel 6734: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6735: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6736: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6737: $thisallowed='';
1.671 raeburn 6738: my ($match)=&is_on_map($uri);
6739: if ($match) {
6740: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6741: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6742: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6743: if (@blockers > 0) {
6744: $thisallowed = 'B';
6745: } else {
6746: $thisallowed.=$1;
6747: }
1.671 raeburn 6748: }
6749: } else {
1.705 albertel 6750: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6751: if ($refuri) {
6752: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6753: $thisallowed='F';
1.671 raeburn 6754: } else {
6755: $refuri=&declutter($refuri);
6756: my ($match) = &is_on_map($refuri);
6757: if ($match) {
1.1162 raeburn 6758: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6759: if (@blockers > 0) {
6760: $thisallowed = 'B';
6761: } else {
6762: $thisallowed='F';
6763: }
1.671 raeburn 6764: }
1.669 raeburn 6765: }
1.671 raeburn 6766: }
6767: }
1.314 www 6768: }
1.492 albertel 6769:
1.766 albertel 6770: if ($priv eq 'bre'
6771: && $thisallowed ne 'F'
6772: && $thisallowed ne '2'
6773: && &is_portfolio_url($uri)) {
6774: $thisallowed = &portfolio_access($uri);
6775: }
1.1250 raeburn 6776:
1.52 www 6777: # Full access at system, domain or course-wide level? Exit.
1.29 www 6778: if ($thisallowed=~/F/) {
6779: return 'F';
6780: }
6781:
1.52 www 6782: # If this is generating or modifying users, exit with special codes
1.29 www 6783:
1.643 www 6784: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6785: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6786: my ($audom,$auname)=split('/',$uri);
1.643 www 6787: # no author name given, so this just checks on the general right to make a co-author in this domain
6788: unless ($auname) { return $thisallowed; }
6789: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6790: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6791: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6792: ($audom ne $env{'request.role.domain'}))) { return ''; }
6793: }
1.52 www 6794: return $thisallowed;
6795: }
6796: #
1.103 harris41 6797: # Gathered so far: system, domain and course wide privileges
1.52 www 6798: #
6799: # Course: See if uri or referer is an individual resource that is part of
6800: # the course
6801:
1.620 albertel 6802: if ($env{'request.course.id'}) {
1.232 www 6803:
1.620 albertel 6804: $courseprivid=$env{'request.course.id'};
6805: if ($env{'request.course.sec'}) {
6806: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6807: }
6808: $courseprivid=~s/\_/\//;
6809: my $checkreferer=1;
1.232 www 6810: my ($match,$cond)=&is_on_map($uri);
6811: if ($match) {
6812: $statecond=$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,$uri);
6818: if (@blockers > 0) {
6819: $thisallowed = 'B';
6820: } else {
6821: $thisallowed.=$value;
6822: }
6823: } else {
6824: $thisallowed.=$value;
6825: }
1.52 www 6826: $checkreferer=0;
6827: }
1.29 www 6828: }
1.83 www 6829:
1.148 www 6830: if ($checkreferer) {
1.620 albertel 6831: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6832: unless ($refuri) {
1.800 albertel 6833: foreach my $key (keys(%env)) {
6834: if ($key=~/^httpref\..*\*/) {
6835: my $pattern=$key;
1.156 www 6836: $pattern=~s/^httpref\.\/res\///;
1.148 www 6837: $pattern=~s/\*/\[\^\/\]\+/g;
6838: $pattern=~s/\//\\\//g;
1.152 www 6839: if ($orguri=~/$pattern/) {
1.800 albertel 6840: $refuri=$env{$key};
1.148 www 6841: }
6842: }
1.191 harris41 6843: }
1.148 www 6844: }
1.232 www 6845:
1.148 www 6846: if ($refuri) {
1.152 www 6847: $refuri=&declutter($refuri);
1.232 www 6848: my ($match,$cond)=&is_on_map($refuri);
6849: if ($match) {
6850: my $refstatecond=$cond;
1.620 albertel 6851: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6852: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6853: my $value = $1;
6854: if ($priv eq 'bre') {
6855: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6856: if (@blockers > 0) {
6857: $thisallowed = 'B';
6858: } else {
6859: $thisallowed.=$value;
6860: }
6861: } else {
6862: $thisallowed.=$value;
6863: }
1.53 www 6864: $uri=$refuri;
6865: $statecond=$refstatecond;
1.52 www 6866: }
6867: }
1.148 www 6868: }
1.29 www 6869: }
1.52 www 6870: }
1.29 www 6871:
1.52 www 6872: #
1.103 harris41 6873: # Gathered now: all privileges that could apply, and condition number
1.52 www 6874: #
6875: #
6876: # Full or no access?
6877: #
1.29 www 6878:
1.52 www 6879: if ($thisallowed=~/F/) {
6880: return 'F';
6881: }
1.29 www 6882:
1.52 www 6883: unless ($thisallowed) {
6884: return '';
6885: }
1.29 www 6886:
1.52 www 6887: # Restrictions exist, deal with them
6888: #
6889: # C:according to course preferences
6890: # R:according to resource settings
6891: # L:unless locked
6892: # X:according to user session state
6893: #
6894:
6895: # Possibly locked functionality, check all courses
1.54 www 6896: # Locks might take effect only after 10 minutes cache expiration for other
6897: # courses, and 2 minutes for current course
1.52 www 6898:
6899: my $envkey;
6900: if ($thisallowed=~/L/) {
1.1000 raeburn 6901: foreach $envkey (keys(%env)) {
1.54 www 6902: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6903: my $courseid=$2;
6904: my $roleid=$1.'.'.$2;
1.92 www 6905: $courseid=~s/^\///;
1.54 www 6906: my $expiretime=600;
1.620 albertel 6907: if ($env{'request.role'} eq $roleid) {
1.54 www 6908: $expiretime=120;
6909: }
6910: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6911: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6912: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6913: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6914: }
1.620 albertel 6915: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6916: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6917: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6918: &log($env{'user.domain'},$env{'user.name'},
6919: $env{'user.home'},
1.57 www 6920: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6921: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6922: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6923: return '';
6924: }
6925: }
1.620 albertel 6926: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6927: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6928: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6929: &log($env{'user.domain'},$env{'user.name'},
6930: $env{'user.home'},
1.57 www 6931: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6932: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6933: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6934: return '';
6935: }
6936: }
6937: }
1.29 www 6938: }
1.52 www 6939: }
6940:
6941: #
6942: # Rest of the restrictions depend on selected course
6943: #
6944:
1.620 albertel 6945: unless ($env{'request.course.id'}) {
1.766 albertel 6946: if ($thisallowed eq 'A') {
6947: return 'A';
1.814 raeburn 6948: } elsif ($thisallowed eq 'B') {
6949: return 'B';
1.766 albertel 6950: } else {
6951: return '1';
6952: }
1.52 www 6953: }
1.29 www 6954:
1.52 www 6955: #
6956: # Now user is definitely in a course
6957: #
1.53 www 6958:
6959:
6960: # Course preferences
6961:
6962: if ($thisallowed=~/C/) {
1.620 albertel 6963: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6964: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6965: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6966: =~/\Q$rolecode\E/) {
1.1103 raeburn 6967: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6968: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6969: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6970: $env{'request.course.id'});
6971: }
1.237 www 6972: return '';
6973: }
6974:
1.620 albertel 6975: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6976: =~/\Q$unamedom\E/) {
1.1103 raeburn 6977: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6978: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6979: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6980: $env{'request.course.id'});
6981: }
1.54 www 6982: return '';
6983: }
1.53 www 6984: }
6985:
6986: # Resource preferences
6987:
6988: if ($thisallowed=~/R/) {
1.620 albertel 6989: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6990: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6991: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6992: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6993: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6994: }
6995: return '';
1.54 www 6996: }
1.53 www 6997: }
1.30 www 6998:
1.246 www 6999: # Restricted by state or randomout?
1.30 www 7000:
1.52 www 7001: if ($thisallowed=~/X/) {
1.620 albertel 7002: if ($env{'acc.randomout'}) {
1.579 albertel 7003: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 7004: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 7005: return '';
7006: }
1.247 www 7007: }
7008: if (&condval($statecond)) {
1.52 www 7009: return '2';
7010: } else {
7011: return '';
7012: }
7013: }
1.30 www 7014:
1.766 albertel 7015: if ($thisallowed eq 'A') {
7016: return 'A';
1.814 raeburn 7017: } elsif ($thisallowed eq 'B') {
7018: return 'B';
1.766 albertel 7019: }
1.52 www 7020: return 'F';
1.232 www 7021: }
1.1162 raeburn 7022:
1.1192 raeburn 7023: # ------------------------------------------- Check construction space access
7024:
7025: sub constructaccess {
7026: my ($url,$setpriv)=@_;
7027:
7028: # We do not allow editing of previous versions of files
7029: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7030:
7031: # Get username and domain from URL
7032: my ($ownername,$ownerdomain,$ownerhome);
7033:
7034: ($ownerdomain,$ownername) =
7035: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7036:
7037: # The URL does not really point to any authorspace, forget it
7038: unless (($ownername) && ($ownerdomain)) { return ''; }
7039:
7040: # Now we need to see if the user has access to the authorspace of
7041: # $ownername at $ownerdomain
7042:
7043: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7044: # Real author for this?
7045: $ownerhome = $env{'user.home'};
7046: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7047: return ($ownername,$ownerdomain,$ownerhome);
7048: }
7049: } else {
7050: # Co-author for this?
7051: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7052: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7053: $ownerhome = &homeserver($ownername,$ownerdomain);
7054: return ($ownername,$ownerdomain,$ownerhome);
7055: }
7056: }
7057:
7058: # We don't have any access right now. If we are not possibly going to do anything about this,
7059: # we might as well leave
7060: unless ($setpriv) { return ''; }
7061:
7062: # Backdoor access?
7063: my $allowed=&allowed('eco',$ownerdomain);
7064: # Nope
7065: unless ($allowed) { return ''; }
7066: # Looks like we may have access, but could be locked by the owner of the construction space
7067: if ($allowed eq 'U') {
7068: my %blocked=&get('environment',['domcoord.author'],
7069: $ownerdomain,$ownername);
7070: # Is blocked by owner
7071: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7072: }
7073: if (($allowed eq 'F') || ($allowed eq 'U')) {
7074: # Grant temporary access
7075: my $then=$env{'user.login.time'};
1.1209 raeburn 7076: my $update=$env{'user.update.time'};
1.1192 raeburn 7077: if (!$update) { $update = $then; }
7078: my $refresh=$env{'user.refresh.time'};
7079: if (!$refresh) { $refresh = $update; }
7080: my $now = time;
7081: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7082: $now,'ca','constructaccess');
7083: $ownerhome = &homeserver($ownername,$ownerdomain);
7084: return($ownername,$ownerdomain,$ownerhome);
7085: }
7086: # No business here
7087: return '';
7088: }
7089:
1.1162 raeburn 7090: sub get_comm_blocks {
7091: my ($cdom,$cnum) = @_;
7092: if ($cdom eq '' || $cnum eq '') {
7093: return unless ($env{'request.course.id'});
7094: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7095: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7096: }
7097: my %commblocks;
7098: my $hashid=$cdom.'_'.$cnum;
7099: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7100: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7101: %commblocks = %{$blocksref};
7102: } else {
7103: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7104: my $cachetime = 600;
7105: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7106: }
7107: return %commblocks;
7108: }
7109:
7110: sub has_comm_blocking {
7111: my ($priv,$symb,$uri,$blocks) = @_;
7112: return unless ($env{'request.course.id'});
7113: return unless ($priv eq 'bre');
7114: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7115: my %commblocks;
7116: if (ref($blocks) eq 'HASH') {
7117: %commblocks = %{$blocks};
7118: } else {
7119: %commblocks = &get_comm_blocks();
7120: }
7121: return unless (keys(%commblocks) > 0);
7122: if (!$symb) { $symb=&symbread($uri,1); }
7123: my ($map,$resid,undef)=&decode_symb($symb);
7124: my %tocheck = (
7125: maps => $map,
7126: resources => $symb,
7127: );
7128: my @blockers;
7129: my $now = time;
1.1163 raeburn 7130: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 7131: foreach my $block (keys(%commblocks)) {
7132: if ($block =~ /^(\d+)____(\d+)$/) {
7133: my ($start,$end) = ($1,$2);
7134: if ($start <= $now && $end >= $now) {
7135: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7136: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7137: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7138: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7139: unless (grep(/^\Q$block\E$/,@blockers)) {
7140: push(@blockers,$block);
7141: }
7142: }
7143: }
7144: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7145: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7146: unless (grep(/^\Q$block\E$/,@blockers)) {
7147: push(@blockers,$block);
7148: }
7149: }
7150: }
7151: }
7152: }
7153: }
7154: } elsif ($block =~ /^firstaccess____(.+)$/) {
7155: my $item = $1;
1.1163 raeburn 7156: my @to_test;
1.1162 raeburn 7157: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7158: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7159: my $check_interval;
7160: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7161: my @interval;
7162: my $type = 'map';
7163: if ($item eq 'course') {
7164: $type = 'course';
7165: @interval=&EXT("resource.0.interval");
7166: } else {
7167: if ($item =~ /___\d+___/) {
7168: $type = 'resource';
7169: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 7170: if (ref($navmap)) {
7171: my $res = $navmap->getBySymb($item);
7172: push(@to_test,$res);
7173: }
1.1162 raeburn 7174: } else {
7175: my $mapsymb = &symbread($item,1);
7176: if ($mapsymb) {
7177: if (ref($navmap)) {
7178: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 7179: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7180: foreach my $res (@to_test) {
1.1162 raeburn 7181: my $symb = $res->symb();
7182: next if ($symb eq $mapsymb);
7183: if ($symb ne '') {
7184: @interval=&EXT("resource.0.interval",$symb);
7185: last;
7186: }
7187: }
7188: }
7189: }
7190: }
7191: }
7192: if ($interval[0] =~ /\d+/) {
7193: my $first_access;
7194: if ($type eq 'resource') {
7195: $first_access=&get_first_access($interval[1],$item);
7196: } elsif ($type eq 'map') {
7197: $first_access=&get_first_access($interval[1],undef,$item);
7198: } else {
7199: $first_access=&get_first_access($interval[1]);
7200: }
7201: if ($first_access) {
7202: my $timesup = $first_access+$interval[0];
7203: if ($timesup > $now) {
1.1163 raeburn 7204: foreach my $res (@to_test) {
7205: if ($res->is_problem()) {
7206: if ($res->completable()) {
7207: unless (grep(/^\Q$block\E$/,@blockers)) {
7208: push(@blockers,$block);
7209: }
7210: last;
7211: }
7212: }
1.1162 raeburn 7213: }
7214: }
7215: }
7216: }
7217: }
7218: }
7219: }
7220: }
7221: }
7222: return @blockers;
7223: }
7224:
7225: sub check_docs_block {
7226: my ($docsblock,$tocheck) =@_;
7227: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7228: return;
7229: }
7230: if (ref($docsblock->{'maps'}) eq 'HASH') {
7231: if ($tocheck->{'maps'}) {
7232: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7233: return 1;
7234: }
7235: }
7236: }
7237: if (ref($docsblock->{'resources'}) eq 'HASH') {
7238: if ($tocheck->{'resources'}) {
7239: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7240: return 1;
7241: }
7242: }
7243: }
7244: return;
7245: }
7246:
1.1133 foxr 7247: #
7248: # Removes the versino from a URI and
7249: # splits it in to its filename and path to the filename.
7250: # Seems like File::Basename could have done this more clearly.
7251: # Parameters:
7252: # $uri - input URI
7253: # Returns:
7254: # Two element list consisting of
7255: # $pathname - the URI up to and excluding the trailing /
7256: # $filename - The part of the URI following the last /
7257: # NOTE:
7258: # Another realization of this is simply:
7259: # use File::Basename;
7260: # ...
7261: # $uri = shift;
7262: # $filename = basename($uri);
7263: # $path = dirname($uri);
7264: # return ($filename, $path);
7265: #
7266: # The implementation below is probably faster however.
7267: #
1.710 albertel 7268: sub split_uri_for_cond {
7269: my $uri=&deversion(&declutter(shift));
7270: my @uriparts=split(/\//,$uri);
7271: my $filename=pop(@uriparts);
7272: my $pathname=join('/',@uriparts);
7273: return ($pathname,$filename);
7274: }
1.232 www 7275: # --------------------------------------------------- Is a resource on the map?
7276:
7277: sub is_on_map {
1.710 albertel 7278: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 7279: #Trying to find the conditional for the file
1.620 albertel 7280: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 7281: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 7282: if ($match) {
1.289 bowersj2 7283: return (1,$1);
7284: } else {
1.434 www 7285: return (0,0);
1.289 bowersj2 7286: }
1.12 www 7287: }
7288:
1.427 www 7289: # --------------------------------------------------------- Get symb from alias
7290:
7291: sub get_symb_from_alias {
7292: my $symb=shift;
7293: my ($map,$resid,$url)=&decode_symb($symb);
7294: # Already is a symb
7295: if ($url) { return $symb; }
7296: # Must be an alias
7297: my $aliassymb='';
7298: my %bighash;
1.620 albertel 7299: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 7300: &GDBM_READER(),0640)) {
7301: my $rid=$bighash{'mapalias_'.$symb};
7302: if ($rid) {
7303: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 7304: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7305: $resid,$bighash{'src_'.$rid});
1.427 www 7306: }
7307: untie %bighash;
7308: }
7309: return $aliassymb;
7310: }
7311:
1.12 www 7312: # ----------------------------------------------------------------- Define Role
7313:
7314: sub definerole {
7315: if (allowed('mcr','/')) {
7316: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 7317: foreach my $role (split(':',$sysrole)) {
7318: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7319: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7320: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7321: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7322: return "refused:s:$crole&$cqual";
7323: }
7324: }
1.191 harris41 7325: }
1.800 albertel 7326: foreach my $role (split(':',$domrole)) {
7327: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7328: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7329: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7330: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 7331: return "refused:d:$crole&$cqual";
7332: }
7333: }
1.191 harris41 7334: }
1.800 albertel 7335: foreach my $role (split(':',$courole)) {
7336: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 7337: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7338: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7339: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 7340: return "refused:c:$crole&$cqual";
7341: }
7342: }
1.191 harris41 7343: }
1.620 albertel 7344: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7345: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7346: "rolesdef_$rolename=".
7347: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 7348: return reply($command,$env{'user.home'});
1.12 www 7349: } else {
7350: return 'refused';
7351: }
1.105 harris41 7352: }
7353:
7354: # ---------------- Make a metadata query against the network of library servers
7355:
7356: sub metadata_query {
1.1237 raeburn 7357: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120 harris41 7358: my %rhash;
1.845 albertel 7359: my %libserv = &all_library();
1.244 matthew 7360: my @server_list = (defined($server_array) ? @$server_array
7361: : keys(%libserv) );
7362: for my $server (@server_list) {
1.1237 raeburn 7363: my $domains = '';
7364: if (ref($domains_hash) eq 'HASH') {
7365: $domains = $domains_hash->{$server};
7366: }
1.118 harris41 7367: unless ($custom or $customshow) {
1.1237 raeburn 7368: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118 harris41 7369: $rhash{$server}=$reply;
7370: }
7371: else {
7372: my $reply=&reply("querysend:".&escape($query).':'.
1.1237 raeburn 7373: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118 harris41 7374: $server);
7375: $rhash{$server}=$reply;
7376: }
1.112 harris41 7377: }
1.118 harris41 7378: return \%rhash;
1.240 www 7379: }
7380:
7381: # ----------------------------------------- Send log queries and wait for reply
7382:
7383: sub log_query {
7384: my ($uname,$udom,$query,%filters)=@_;
7385: my $uhome=&homeserver($uname,$udom);
7386: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 7387: my $uhost=&hostname($uhome);
1.800 albertel 7388: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 7389: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7390: $uhome);
1.479 albertel 7391: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 7392: return get_query_reply($queryid);
7393: }
7394:
1.818 raeburn 7395: # -------------------------- Update MySQL table for portfolio file
7396:
7397: sub update_portfolio_table {
1.821 raeburn 7398: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 7399: if ($group ne '') {
7400: $file_name =~s /^\Q$group\E//;
7401: }
1.818 raeburn 7402: my $homeserver = &homeserver($uname,$udom);
7403: my $queryid=
1.821 raeburn 7404: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7405: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 7406: my $reply = &get_query_reply($queryid);
7407: return $reply;
7408: }
7409:
1.899 raeburn 7410: # -------------------------- Update MySQL allusers table
7411:
7412: sub update_allusers_table {
7413: my ($uname,$udom,$names) = @_;
7414: my $homeserver = &homeserver($uname,$udom);
7415: my $queryid=
7416: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7417: 'lastname='.&escape($names->{'lastname'}).'%%'.
7418: 'firstname='.&escape($names->{'firstname'}).'%%'.
7419: 'middlename='.&escape($names->{'middlename'}).'%%'.
7420: 'generation='.&escape($names->{'generation'}).'%%'.
7421: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7422: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 7423: return;
1.899 raeburn 7424: }
7425:
1.508 raeburn 7426: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 7427:
7428: sub fetch_enrollment_query {
1.511 raeburn 7429: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 7430: my $homeserver;
1.547 raeburn 7431: my $maxtries = 1;
1.508 raeburn 7432: if ($context eq 'automated') {
7433: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 7434: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 7435: } else {
7436: $homeserver = &homeserver($cnum,$dom);
7437: }
1.838 albertel 7438: my $host=&hostname($homeserver);
1.506 raeburn 7439: my $cmd = '';
1.1000 raeburn 7440: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 7441: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 7442: }
7443: $cmd =~ s/%%$//;
7444: $cmd = &escape($cmd);
7445: my $query = 'fetchenrollment';
1.620 albertel 7446: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 7447: unless ($queryid=~/^\Q$host\E\_/) {
7448: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7449: return 'error: '.$queryid;
7450: }
1.506 raeburn 7451: my $reply = &get_query_reply($queryid);
1.547 raeburn 7452: my $tries = 1;
7453: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7454: $reply = &get_query_reply($queryid);
7455: $tries ++;
7456: }
1.526 raeburn 7457: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 7458: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 7459: } else {
1.901 albertel 7460: my @responses = split(/:/,$reply);
1.515 raeburn 7461: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 7462: foreach my $line (@responses) {
7463: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 7464: $$replyref{$key} = $value;
7465: }
7466: } else {
1.1117 foxr 7467: my $pathname = LONCAPA::tempdir();
1.800 albertel 7468: foreach my $line (@responses) {
7469: my ($key,$value) = split(/=/,$line);
1.506 raeburn 7470: $$replyref{$key} = $value;
7471: if ($value > 0) {
1.800 albertel 7472: foreach my $item (@{$$affiliatesref{$key}}) {
7473: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 7474: my $destname = $pathname.'/'.$filename;
7475: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 7476: if ($xml_classlist =~ /^error/) {
7477: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7478: } else {
1.506 raeburn 7479: if ( open(FILE,">$destname") ) {
7480: print FILE &unescape($xml_classlist);
7481: close(FILE);
1.526 raeburn 7482: } else {
7483: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 7484: }
7485: }
7486: }
7487: }
7488: }
7489: }
7490: return 'ok';
7491: }
7492: return 'error';
7493: }
7494:
1.242 www 7495: sub get_query_reply {
7496: my $queryid=shift;
1.1117 foxr 7497: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 7498: my $reply='';
7499: for (1..100) {
7500: sleep 2;
7501: if (-e $replyfile.'.end') {
1.448 albertel 7502: if (open(my $fh,$replyfile)) {
1.904 albertel 7503: $reply = join('',<$fh>);
7504: close($fh);
1.240 www 7505: } else { return 'error: reply_file_error'; }
1.242 www 7506: return &unescape($reply);
7507: }
1.240 www 7508: }
1.242 www 7509: return 'timeout:'.$queryid;
1.240 www 7510: }
7511:
7512: sub courselog_query {
1.241 www 7513: #
7514: # possible filters:
7515: # url: url or symb
7516: # username
7517: # domain
7518: # action: view, submit, grade
7519: # start: timestamp
7520: # end: timestamp
7521: #
1.240 www 7522: my (%filters)=@_;
1.620 albertel 7523: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 7524: if ($filters{'url'}) {
7525: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7526: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7527: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7528: }
1.620 albertel 7529: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7530: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 7531: return &log_query($cname,$cdom,'courselog',%filters);
7532: }
7533:
7534: sub userlog_query {
1.858 raeburn 7535: #
7536: # possible filters:
7537: # action: log check role
7538: # start: timestamp
7539: # end: timestamp
7540: #
1.240 www 7541: my ($uname,$udom,%filters)=@_;
7542: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 7543: }
7544:
1.506 raeburn 7545: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7546:
7547: sub auto_run {
1.508 raeburn 7548: my ($cnum,$cdom) = @_;
1.876 raeburn 7549: my $response = 0;
7550: my $settings;
7551: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7552: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7553: $settings = $domconfig{'autoenroll'};
7554: if ($settings->{'run'} eq '1') {
7555: $response = 1;
7556: }
7557: } else {
1.934 raeburn 7558: my $homeserver;
7559: if (&is_course($cdom,$cnum)) {
7560: $homeserver = &homeserver($cnum,$cdom);
7561: } else {
7562: $homeserver = &domain($cdom,'primary');
7563: }
7564: if ($homeserver ne 'no_host') {
7565: $response = &reply('autorun:'.$cdom,$homeserver);
7566: }
1.876 raeburn 7567: }
1.506 raeburn 7568: return $response;
7569: }
1.776 albertel 7570:
1.506 raeburn 7571: sub auto_get_sections {
1.508 raeburn 7572: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 7573: my $homeserver;
7574: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7575: $homeserver = &homeserver($cnum,$cdom);
7576: }
7577: if (!defined($homeserver)) {
7578: if ($cdom =~ /^$match_domain$/) {
7579: $homeserver = &domain($cdom,'primary');
7580: }
7581: }
7582: my @secs;
7583: if (defined($homeserver)) {
7584: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7585: unless ($response eq 'refused') {
7586: @secs = split(/:/,$response);
7587: }
1.506 raeburn 7588: }
7589: return @secs;
7590: }
1.776 albertel 7591:
1.506 raeburn 7592: sub auto_new_course {
1.1099 raeburn 7593: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 7594: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 7595: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 7596: return $response;
7597: }
1.776 albertel 7598:
1.506 raeburn 7599: sub auto_validate_courseID {
1.508 raeburn 7600: my ($cnum,$cdom,$inst_course_id) = @_;
7601: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7602: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7603: return $response;
7604: }
1.776 albertel 7605:
1.1007 raeburn 7606: sub auto_validate_instcode {
1.1020 raeburn 7607: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7608: my ($homeserver,$response);
7609: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7610: $homeserver = &homeserver($cnum,$cdom);
7611: }
7612: if (!defined($homeserver)) {
7613: if ($cdom =~ /^$match_domain$/) {
7614: $homeserver = &domain($cdom,'primary');
7615: }
7616: }
1.1065 raeburn 7617: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7618: &escape($instcode).':'.&escape($owner),$homeserver));
1.1216 raeburn 7619: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7620: return ($outcome,$description,$defaultcredits);
1.1007 raeburn 7621: }
7622:
1.506 raeburn 7623: sub auto_create_password {
1.873 raeburn 7624: my ($cnum,$cdom,$authparam,$udom) = @_;
7625: my ($homeserver,$response);
1.506 raeburn 7626: my $create_passwd = 0;
7627: my $authchk = '';
1.873 raeburn 7628: if ($udom =~ /^$match_domain$/) {
7629: $homeserver = &domain($udom,'primary');
7630: }
7631: if ($homeserver eq '') {
7632: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7633: $homeserver = &homeserver($cnum,$cdom);
7634: }
7635: }
7636: if ($homeserver eq '') {
7637: $authchk = 'nodomain';
1.506 raeburn 7638: } else {
1.873 raeburn 7639: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7640: if ($response eq 'refused') {
7641: $authchk = 'refused';
7642: } else {
1.901 albertel 7643: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7644: }
1.506 raeburn 7645: }
7646: return ($authparam,$create_passwd,$authchk);
7647: }
7648:
1.706 raeburn 7649: sub auto_photo_permission {
7650: my ($cnum,$cdom,$students) = @_;
7651: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7652: my ($outcome,$perm_reqd,$conditions) =
7653: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7654: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7655: return (undef,undef);
7656: }
1.706 raeburn 7657: return ($outcome,$perm_reqd,$conditions);
7658: }
7659:
7660: sub auto_checkphotos {
7661: my ($uname,$udom,$pid) = @_;
7662: my $homeserver = &homeserver($uname,$udom);
7663: my ($result,$resulttype);
7664: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7665: &escape($uname).':'.&escape($pid),
7666: $homeserver));
1.709 albertel 7667: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7668: return (undef,undef);
7669: }
1.706 raeburn 7670: if ($outcome) {
7671: ($result,$resulttype) = split(/:/,$outcome);
7672: }
7673: return ($result,$resulttype);
7674: }
7675:
7676: sub auto_photochoice {
7677: my ($cnum,$cdom) = @_;
7678: my $homeserver = &homeserver($cnum,$cdom);
7679: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7680: &escape($cdom),
7681: $homeserver)));
1.709 albertel 7682: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7683: return (undef,undef);
7684: }
1.706 raeburn 7685: return ($update,$comment);
7686: }
7687:
7688: sub auto_photoupdate {
7689: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7690: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7691: my $host=&hostname($homeserver);
1.706 raeburn 7692: my $cmd = '';
7693: my $maxtries = 1;
1.800 albertel 7694: foreach my $affiliate (keys(%{$affiliatesref})) {
7695: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7696: }
7697: $cmd =~ s/%%$//;
7698: $cmd = &escape($cmd);
7699: my $query = 'institutionalphotos';
7700: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7701: unless ($queryid=~/^\Q$host\E\_/) {
7702: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7703: return 'error: '.$queryid;
7704: }
7705: my $reply = &get_query_reply($queryid);
7706: my $tries = 1;
7707: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7708: $reply = &get_query_reply($queryid);
7709: $tries ++;
7710: }
7711: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7712: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7713: } else {
7714: my @responses = split(/:/,$reply);
7715: my $outcome = shift(@responses);
7716: foreach my $item (@responses) {
7717: my ($key,$value) = split(/=/,$item);
7718: $$photo{$key} = $value;
7719: }
7720: return $outcome;
7721: }
7722: return 'error';
7723: }
7724:
1.521 raeburn 7725: sub auto_instcode_format {
1.793 albertel 7726: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7727: $cat_order) = @_;
1.521 raeburn 7728: my $courses = '';
1.772 raeburn 7729: my @homeservers;
1.521 raeburn 7730: if ($caller eq 'global') {
1.841 albertel 7731: my %servers = &get_servers($codedom,'library');
7732: foreach my $tryserver (keys(%servers)) {
7733: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7734: push(@homeservers,$tryserver);
7735: }
1.584 raeburn 7736: }
1.1022 raeburn 7737: } elsif ($caller eq 'requests') {
7738: if ($codedom =~ /^$match_domain$/) {
7739: my $chome = &domain($codedom,'primary');
7740: unless ($chome eq 'no_host') {
7741: push(@homeservers,$chome);
7742: }
7743: }
1.521 raeburn 7744: } else {
1.772 raeburn 7745: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7746: }
1.793 albertel 7747: foreach my $code (keys(%{$instcodes})) {
7748: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7749: }
7750: chop($courses);
1.772 raeburn 7751: my $ok_response = 0;
7752: my $response;
7753: while (@homeservers > 0 && $ok_response == 0) {
7754: my $server = shift(@homeservers);
7755: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7756: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7757: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7758: split(/:/,$response);
1.772 raeburn 7759: %{$codes} = (%{$codes},&str2hash($codes_str));
7760: push(@{$codetitles},&str2array($codetitles_str));
7761: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7762: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7763: $ok_response = 1;
7764: }
7765: }
7766: if ($ok_response) {
1.521 raeburn 7767: return 'ok';
1.772 raeburn 7768: } else {
7769: return $response;
1.521 raeburn 7770: }
7771: }
7772:
1.792 raeburn 7773: sub auto_instcode_defaults {
7774: my ($domain,$returnhash,$code_order) = @_;
7775: my @homeservers;
1.841 albertel 7776:
7777: my %servers = &get_servers($domain,'library');
7778: foreach my $tryserver (keys(%servers)) {
7779: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7780: push(@homeservers,$tryserver);
7781: }
1.792 raeburn 7782: }
1.841 albertel 7783:
1.792 raeburn 7784: my $response;
1.841 albertel 7785: foreach my $server (@homeservers) {
1.792 raeburn 7786: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7787: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7788:
7789: foreach my $pair (split(/\&/,$response)) {
7790: my ($name,$value)=split(/\=/,$pair);
7791: if ($name eq 'code_order') {
7792: @{$code_order} = split(/\&/,&unescape($value));
7793: } else {
7794: $returnhash->{&unescape($name)}=&unescape($value);
7795: }
7796: }
7797: return 'ok';
1.792 raeburn 7798: }
1.841 albertel 7799:
7800: return $response;
1.1003 raeburn 7801: }
7802:
7803: sub auto_possible_instcodes {
1.1007 raeburn 7804: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7805: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7806: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7807: return;
7808: }
1.1003 raeburn 7809: my (@homeservers,$uhome);
7810: if (defined(&domain($domain,'primary'))) {
7811: $uhome=&domain($domain,'primary');
7812: push(@homeservers,&domain($domain,'primary'));
7813: } else {
7814: my %servers = &get_servers($domain,'library');
7815: foreach my $tryserver (keys(%servers)) {
7816: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7817: push(@homeservers,$tryserver);
7818: }
7819: }
7820: }
7821: my $response;
7822: foreach my $server (@homeservers) {
7823: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7824: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7825: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7826: split(':',$response);
7827: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7828: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7829: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7830: my ($name,$value)=split('=',$item);
7831: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7832: }
7833: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7834: my ($name,$value)=split('=',$item);
7835: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7836: }
7837: return 'ok';
7838: }
7839: return $response;
7840: }
1.792 raeburn 7841:
1.1010 raeburn 7842: sub auto_courserequest_checks {
7843: my ($dom) = @_;
1.1020 raeburn 7844: my ($homeserver,%validations);
7845: if ($dom =~ /^$match_domain$/) {
7846: $homeserver = &domain($dom,'primary');
7847: }
7848: unless ($homeserver eq 'no_host') {
7849: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7850: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7851: my @items = split(/&/,$response);
7852: foreach my $item (@items) {
7853: my ($key,$value) = split('=',$item);
7854: $validations{&unescape($key)} = &thaw_unescape($value);
7855: }
7856: }
7857: }
1.1010 raeburn 7858: return %validations;
7859: }
7860:
1.1020 raeburn 7861: sub auto_courserequest_validation {
1.1255 raeburn 7862: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020 raeburn 7863: my ($homeserver,$response);
7864: if ($dom =~ /^$match_domain$/) {
7865: $homeserver = &domain($dom,'primary');
7866: }
1.1255 raeburn 7867: unless ($homeserver eq 'no_host') {
7868: my $customdata;
7869: if (ref($custominfo) eq 'HASH') {
7870: $customdata = &freeze_escape($custominfo);
7871: }
1.1020 raeburn 7872: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7873: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255 raeburn 7874: ':'.&escape($instcode).':'.&escape($instseclist).':'.
7875: $customdata,$homeserver));
1.1020 raeburn 7876: }
7877: return $response;
7878: }
7879:
1.777 albertel 7880: sub auto_validate_class_sec {
1.918 raeburn 7881: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7882: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7883: my $ownerlist;
7884: if (ref($owners) eq 'ARRAY') {
7885: $ownerlist = join(',',@{$owners});
7886: } else {
7887: $ownerlist = $owners;
7888: }
1.773 raeburn 7889: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7890: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7891: return $response;
7892: }
7893:
1.1248 raeburn 7894: sub auto_crsreq_update {
7895: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257 ! raeburn 7896: $code,$accessstart,$accessend,$inbound) = @_;
1.1248 raeburn 7897: my ($homeserver,%crsreqresponse);
7898: if ($cdom =~ /^$match_domain$/) {
7899: $homeserver = &domain($cdom,'primary');
7900: }
7901: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
7902: my $info;
7903: if (ref($inbound) eq 'HASH') {
7904: $info = &freeze_escape($inbound);
7905: }
7906: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
7907: ':'.&escape($action).':'.&escape($ownername).':'.
7908: &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257 ! raeburn 7909: &escape($title).':'.&escape($code).':'.
! 7910: &escape($accessstart).':'.&escape($accessend).':'.$info,
! 7911: $homeserver);
1.1248 raeburn 7912: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7913: my @items = split(/&/,$response);
7914: foreach my $item (@items) {
7915: my ($key,$value) = split('=',$item);
7916: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
7917: }
7918: }
7919: }
7920: return \%crsreqresponse;
7921: }
7922:
1.679 raeburn 7923: # ------------------------------------------------------- Course Group routines
7924:
7925: sub get_coursegroups {
1.809 raeburn 7926: my ($cdom,$cnum,$group,$namespace) = @_;
7927: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7928: }
7929:
1.679 raeburn 7930: sub modify_coursegroup {
7931: my ($cdom,$cnum,$groupsettings) = @_;
7932: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7933: }
7934:
1.809 raeburn 7935: sub toggle_coursegroup_status {
7936: my ($cdom,$cnum,$group,$action) = @_;
7937: my ($from_namespace,$to_namespace);
7938: if ($action eq 'delete') {
7939: $from_namespace = 'coursegroups';
7940: $to_namespace = 'deleted_groups';
7941: } else {
7942: $from_namespace = 'deleted_groups';
7943: $to_namespace = 'coursegroups';
7944: }
7945: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7946: if (my $tmp = &error(%curr_group)) {
7947: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7948: return ('read error',$tmp);
7949: } else {
7950: my %savedsettings = %curr_group;
1.809 raeburn 7951: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7952: my $deloutcome;
7953: if ($result eq 'ok') {
1.809 raeburn 7954: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7955: } else {
7956: return ('write error',$result);
7957: }
7958: if ($deloutcome eq 'ok') {
7959: return 'ok';
7960: } else {
7961: return ('delete error',$deloutcome);
7962: }
7963: }
7964: }
7965:
1.679 raeburn 7966: sub modify_group_roles {
1.957 raeburn 7967: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7968: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7969: my $role = 'gr/'.&escape($userprivs);
7970: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7971: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7972: if ($result eq 'ok') {
7973: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7974: }
1.679 raeburn 7975: return $result;
7976: }
7977:
7978: sub modify_coursegroup_membership {
7979: my ($cdom,$cnum,$membership) = @_;
7980: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7981: return $result;
7982: }
7983:
1.682 raeburn 7984: sub get_active_groups {
7985: my ($udom,$uname,$cdom,$cnum) = @_;
7986: my $now = time;
7987: my %groups = ();
7988: foreach my $key (keys(%env)) {
1.811 albertel 7989: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7990: my ($start,$end) = split(/\./,$env{$key});
7991: if (($end!=0) && ($end<$now)) { next; }
7992: if (($start!=0) && ($start>$now)) { next; }
7993: if ($1 eq $cdom && $2 eq $cnum) {
7994: $groups{$3} = $env{$key} ;
7995: }
7996: }
7997: }
7998: return %groups;
7999: }
8000:
1.683 raeburn 8001: sub get_group_membership {
8002: my ($cdom,$cnum,$group) = @_;
8003: return(&dump('groupmembership',$cdom,$cnum,$group));
8004: }
8005:
8006: sub get_users_groups {
8007: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 8008: my @usersgroups;
1.683 raeburn 8009: my $cachetime=1800;
8010:
8011: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 8012: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8013: if (defined($cached)) {
1.734 albertel 8014: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 8015: } else {
8016: $grouplist = '';
1.816 raeburn 8017: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 8018: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 8019: my $access_end = $env{'course.'.$courseid.
8020: '.default_enrollment_end_date'};
8021: my $now = time;
8022: foreach my $key (keys(%roleshash)) {
8023: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8024: my $group = $1;
8025: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8026: my $start = $2;
8027: my $end = $1;
8028: if ($start == -1) { next; } # deleted from group
8029: if (($start!=0) && ($start>$now)) { next; }
8030: if (($end!=0) && ($end<$now)) {
8031: if ($access_end && $access_end < $now) {
8032: if ($access_end - $end < 86400) {
8033: push(@usersgroups,$group);
1.733 raeburn 8034: }
8035: }
1.817 raeburn 8036: next;
1.733 raeburn 8037: }
1.817 raeburn 8038: push(@usersgroups,$group);
1.683 raeburn 8039: }
8040: }
8041: }
1.817 raeburn 8042: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8043: $grouplist = join(':',@usersgroups);
8044: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 8045: }
1.733 raeburn 8046: return @usersgroups;
1.683 raeburn 8047: }
8048:
8049: sub devalidate_getgroups_cache {
8050: my ($udom,$uname,$cdom,$cnum)=@_;
8051: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 8052:
1.683 raeburn 8053: my $hashid="$udom:$uname:$courseid";
8054: &devalidate_cache_new('getgroups',$hashid);
8055: }
8056:
1.12 www 8057: # ------------------------------------------------------------------ Plain Text
8058:
8059: sub plaintext {
1.988 raeburn 8060: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 8061: if ($short =~ m{^cr/}) {
1.758 albertel 8062: return (split('/',$short))[-1];
8063: }
1.742 raeburn 8064: if (!defined($cid)) {
8065: $cid = $env{'request.course.id'};
8066: }
8067: my %rolenames = (
1.1008 raeburn 8068: Course => 'std',
8069: Community => 'alt1',
1.742 raeburn 8070: );
1.1037 raeburn 8071: if ($cid ne '') {
8072: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8073: unless ($forcedefault) {
8074: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8075: &Apache::lonlocal::mt_escape(\$roletext);
8076: return &Apache::lonlocal::mt($roletext);
8077: }
8078: }
8079: }
8080: if ((defined($type)) && (defined($rolenames{$type})) &&
8081: (defined($rolenames{$type})) &&
8082: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 8083: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 8084: } elsif ($cid ne '') {
8085: my $crstype = $env{'course.'.$cid.'.type'};
8086: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8087: (defined($prp{$short}{$rolenames{$crstype}}))) {
8088: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8089: }
1.742 raeburn 8090: }
1.1037 raeburn 8091: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 8092: }
8093:
8094: # ----------------------------------------------------------------- Assign Role
8095:
8096: sub assignrole {
1.957 raeburn 8097: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8098: $context)=@_;
1.21 www 8099: my $mrole;
8100: if ($role =~ /^cr\//) {
1.393 www 8101: my $cwosec=$url;
1.811 albertel 8102: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 8103: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 8104: my $refused = 1;
8105: if ($context eq 'requestcourses') {
8106: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8107: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8108: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8109: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8110: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8111: if ($crsenv{'internal.courseowner'} eq
8112: $env{'user.name'}.':'.$env{'user.domain'}) {
8113: $refused = '';
8114: }
8115: }
8116: }
8117: }
8118: }
8119: if ($refused) {
8120: &logthis('Refused custom assignrole: '.
8121: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8122: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8123: return 'refused';
8124: }
1.104 www 8125: }
1.21 www 8126: $mrole='cr';
1.678 raeburn 8127: } elsif ($role =~ /^gr\//) {
8128: my $cwogrp=$url;
1.811 albertel 8129: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 8130: unless (&allowed('mdg',$cwogrp)) {
8131: &logthis('Refused group assignrole: '.
8132: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8133: $env{'user.name'}.' at '.$env{'user.domain'});
8134: return 'refused';
8135: }
8136: $mrole='gr';
1.21 www 8137: } else {
1.82 www 8138: my $cwosec=$url;
1.811 albertel 8139: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 8140: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8141: my $refused;
8142: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8143: if (!(&allowed('c'.$role,$url))) {
8144: $refused = 1;
8145: }
8146: } else {
8147: $refused = 1;
8148: }
1.947 raeburn 8149: if ($refused) {
1.1045 raeburn 8150: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8151: if (!$selfenroll && $context eq 'course') {
8152: my %crsenv;
8153: if ($role eq 'cc' || $role eq 'co') {
8154: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8155: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8156: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8157: if ($crsenv{'internal.courseowner'} eq
8158: $env{'user.name'}.':'.$env{'user.domain'}) {
8159: $refused = '';
8160: }
8161: }
8162: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8163: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8164: if ($crsenv{'internal.courseowner'} eq
8165: $env{'user.name'}.':'.$env{'user.domain'}) {
8166: $refused = '';
8167: }
8168: }
8169: }
8170: }
8171: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 8172: $refused = '';
1.1017 raeburn 8173: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 8174: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 8175: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 8176: my $wrongcc;
8177: if ($cnum =~ /^$match_community$/) {
8178: $wrongcc = 1 if ($role eq 'cc');
8179: } else {
8180: $wrongcc = 1 if ($role eq 'co');
8181: }
8182: unless ($wrongcc) {
8183: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8184: if ($crsenv{'internal.courseowner'} eq
8185: $env{'user.name'}.':'.$env{'user.domain'}) {
8186: $refused = '';
8187: }
1.1017 raeburn 8188: }
8189: }
1.1183 raeburn 8190: } elsif ($context eq 'requestauthor') {
8191: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8192: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8193: if ($env{'environment.requestauthor'} eq 'automatic') {
8194: $refused = '';
8195: } else {
8196: my %domdefaults = &get_domain_defaults($udom);
8197: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8198: my $checkbystatus;
8199: if ($env{'user.adv'}) {
8200: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8201: if ($disposition eq 'automatic') {
8202: $refused = '';
8203: } elsif ($disposition eq '') {
8204: $checkbystatus = 1;
8205: }
8206: } else {
8207: $checkbystatus = 1;
8208: }
8209: if ($checkbystatus) {
8210: if ($env{'environment.inststatus'}) {
8211: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8212: foreach my $type (@inststatuses) {
8213: if (($type ne '') &&
8214: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8215: $refused = '';
8216: }
8217: }
8218: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8219: $refused = '';
8220: }
8221: }
8222: }
8223: }
8224: }
1.1017 raeburn 8225: }
8226: if ($refused) {
1.947 raeburn 8227: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8228: ' '.$role.' '.$end.' '.$start.' by '.
8229: $env{'user.name'}.' at '.$env{'user.domain'});
8230: return 'refused';
8231: }
1.932 raeburn 8232: }
1.1131 raeburn 8233: } elsif ($role eq 'au') {
8234: if ($url ne '/'.$udom.'/') {
8235: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8236: ' to assign author role for '.$uname.':'.$udom.
8237: ' in domain: '.$url.' refused (wrong domain).');
8238: return 'refused';
8239: }
1.104 www 8240: }
1.21 www 8241: $mrole=$role;
8242: }
1.620 albertel 8243: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 8244: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 8245: if ($end) { $command.='_'.$end; }
1.21 www 8246: if ($start) {
8247: if ($end) {
1.81 www 8248: $command.='_'.$start;
1.21 www 8249: } else {
1.81 www 8250: $command.='_0_'.$start;
1.21 www 8251: }
8252: }
1.739 raeburn 8253: my $origstart = $start;
8254: my $origend = $end;
1.957 raeburn 8255: my $delflag;
1.357 www 8256: # actually delete
8257: if ($deleteflag) {
1.373 www 8258: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 8259: # modify command to delete the role
1.620 albertel 8260: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 8261: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 8262: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 8263: # set start and finish to negative values for userrolelog
8264: $start=-1;
8265: $end=-1;
1.957 raeburn 8266: $delflag = 1;
1.357 www 8267: }
8268: }
8269: # send command
1.349 www 8270: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 8271: # log new user role if status is ok
1.349 www 8272: if ($answer eq 'ok') {
1.663 raeburn 8273: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184 raeburn 8274: if (($role eq 'cc') || ($role eq 'in') ||
8275: ($role eq 'ep') || ($role eq 'ad') ||
8276: ($role eq 'ta') || ($role eq 'st') ||
8277: ($role=~/^cr/) || ($role eq 'gr') ||
8278: ($role eq 'co')) {
1.1200 raeburn 8279: # for course roles, perform group memberships changes triggered by role change.
8280: unless ($role =~ /^gr/) {
8281: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8282: $origstart,$selfenroll,$context);
8283: }
1.1184 raeburn 8284: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8285: $selfenroll,$context);
8286: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8287: ($role eq 'au') || ($role eq 'dc')) {
8288: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8289: $context);
8290: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8291: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8292: $context);
8293: }
1.1053 raeburn 8294: if ($role eq 'cc') {
8295: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8296: }
1.349 www 8297: }
8298: return $answer;
1.169 harris41 8299: }
8300:
1.1053 raeburn 8301: sub autoupdate_coowners {
8302: my ($url,$end,$start,$uname,$udom) = @_;
8303: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8304: if (($cdom ne '') && ($cnum ne '')) {
8305: my $now = time;
8306: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8307: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8308: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8309: my $instcode = $coursehash{'internal.coursecode'};
8310: if ($instcode ne '') {
1.1056 raeburn 8311: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8312: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 8313: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 8314: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8315: if ($result eq 'valid') {
8316: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 8317: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8318: push(@newcoowners,$coowner);
8319: }
8320: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8321: push(@newcoowners,$uname.':'.$udom);
8322: }
8323: @newcoowners = sort(@newcoowners);
8324: } else {
8325: push(@newcoowners,$uname.':'.$udom);
8326: }
8327: } else {
8328: if ($coursehash{'internal.co-owners'}) {
8329: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8330: unless ($coowner eq $uname.':'.$udom) {
8331: push(@newcoowners,$coowner);
8332: }
8333: }
8334: unless (@newcoowners > 0) {
8335: $delcoowners = 1;
8336: $coowners = '';
8337: }
8338: }
8339: }
8340: if (@newcoowners || $delcoowners) {
8341: &store_coowners($cdom,$cnum,$coursehash{'home'},
8342: $delcoowners,@newcoowners);
8343: }
8344: }
8345: }
8346: }
8347: }
8348: }
8349: }
8350:
8351: sub store_coowners {
8352: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8353: my $cid = $cdom.'_'.$cnum;
8354: my ($coowners,$delresult,$putresult);
8355: if (@newcoowners) {
8356: $coowners = join(',',@newcoowners);
8357: my %coownershash = (
8358: 'internal.co-owners' => $coowners,
8359: );
8360: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8361: if ($putresult eq 'ok') {
8362: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8363: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8364: }
8365: }
8366: }
8367: if ($delcoowners) {
8368: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8369: if ($delresult eq 'ok') {
8370: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8371: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8372: }
8373: }
8374: }
8375: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8376: my %crsinfo =
8377: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8378: if (ref($crsinfo{$cid}) eq 'HASH') {
8379: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8380: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8381: }
8382: }
8383: }
8384:
1.169 harris41 8385: # -------------------------------------------------- Modify user authentication
1.197 www 8386: # Overrides without validation
8387:
1.169 harris41 8388: sub modifyuserauth {
8389: my ($udom,$uname,$umode,$upass)=@_;
8390: my $uhome=&homeserver($uname,$udom);
1.197 www 8391: unless (&allowed('mau',$udom)) { return 'refused'; }
8392: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 8393: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8394: ' in domain '.$env{'request.role.domain'});
1.169 harris41 8395: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8396: &escape($upass),$uhome);
1.620 albertel 8397: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 8398: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8399: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8400: &log($udom,,$uname,$uhome,
1.620 albertel 8401: 'Authentication changed by '.$env{'user.domain'}.', '.
8402: $env{'user.name'}.', '.$umode.
1.197 www 8403: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 8404: unless ($reply eq 'ok') {
1.197 www 8405: &logthis('Authentication mode error: '.$reply);
1.169 harris41 8406: return 'error: '.$reply;
8407: }
1.170 harris41 8408: return 'ok';
1.80 www 8409: }
8410:
1.81 www 8411: # --------------------------------------------------------------- Modify a user
1.80 www 8412:
1.81 www 8413: sub modifyuser {
1.206 matthew 8414: my ($udom, $uname, $uid,
8415: $umode, $upass, $first,
8416: $middle, $last, $gene,
1.1058 raeburn 8417: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 8418: $udom= &LONCAPA::clean_domain($udom);
8419: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 8420: my $showcandelete = 'none';
8421: if (ref($candelete) eq 'ARRAY') {
8422: if (@{$candelete} > 0) {
8423: $showcandelete = join(', ',@{$candelete});
8424: }
8425: }
1.81 www 8426: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 8427: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 8428: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 8429: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8430: ' desiredhome not specified').
1.620 albertel 8431: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8432: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 8433: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 8434: my $newuser;
8435: if ($uhome eq 'no_host') {
8436: $newuser = 1;
8437: }
1.80 www 8438: # ----------------------------------------------------------------- Create User
1.406 albertel 8439: if (($uhome eq 'no_host') &&
8440: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 8441: my $unhome='';
1.844 albertel 8442: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 8443: $unhome = $desiredhome;
1.620 albertel 8444: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8445: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 8446: } else { # load balancing routine for determining $unhome
1.81 www 8447: my $loadm=10000000;
1.841 albertel 8448: my %servers = &get_servers($udom,'library');
8449: foreach my $tryserver (keys(%servers)) {
8450: my $answer=reply('load',$tryserver);
8451: if (($answer=~/\d+/) && ($answer<$loadm)) {
8452: $loadm=$answer;
8453: $unhome=$tryserver;
8454: }
1.80 www 8455: }
8456: }
8457: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 8458: return 'error: unable to find a home server for '.$uname.
8459: ' in domain '.$udom;
1.80 www 8460: }
8461: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8462: &escape($upass),$unhome);
8463: unless ($reply eq 'ok') {
8464: return 'error: '.$reply;
8465: }
1.230 stredwic 8466: $uhome=&homeserver($uname,$udom,'true');
1.80 www 8467: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 8468: return 'error: unable verify users home machine.';
1.80 www 8469: }
1.209 matthew 8470: } # End of creation of new user
1.80 www 8471: # ---------------------------------------------------------------------- Add ID
8472: if ($uid) {
8473: $uid=~tr/A-Z/a-z/;
8474: my %uidhash=&idrget($udom,$uname);
1.196 www 8475: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8476: && (!$forceid)) {
1.80 www 8477: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 8478: return 'error: user id "'.$uid.'" does not match '.
8479: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 8480: }
8481: } else {
8482: &idput($udom,($uname => $uid));
8483: }
8484: }
8485: # -------------------------------------------------------------- Add names, etc
1.313 matthew 8486: my @tmp=&get('environment',
1.899 raeburn 8487: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 8488: 'permanentemail','inststatus'],
1.134 albertel 8489: $udom,$uname);
1.1075 raeburn 8490: my (%names,%oldnames);
1.313 matthew 8491: if ($tmp[0] =~ m/^error:.*/) {
8492: %names=();
8493: } else {
8494: %names = @tmp;
1.1075 raeburn 8495: %oldnames = %names;
1.313 matthew 8496: }
1.388 www 8497: #
1.1058 raeburn 8498: # If name, email and/or uid are blank (e.g., because an uploaded file
8499: # of users did not contain them), do not overwrite existing values
8500: # unless field is in $candelete array ref.
8501: #
8502:
8503: my @fields = ('firstname','middlename','lastname','generation',
8504: 'permanentemail','id');
8505: my %newvalues;
8506: if (ref($candelete) eq 'ARRAY') {
8507: foreach my $field (@fields) {
8508: if (grep(/^\Q$field\E$/,@{$candelete})) {
8509: if ($field eq 'firstname') {
8510: $names{$field} = $first;
8511: } elsif ($field eq 'middlename') {
8512: $names{$field} = $middle;
8513: } elsif ($field eq 'lastname') {
8514: $names{$field} = $last;
8515: } elsif ($field eq 'generation') {
8516: $names{$field} = $gene;
8517: } elsif ($field eq 'permanentemail') {
8518: $names{$field} = $email;
8519: } elsif ($field eq 'id') {
8520: $names{$field} = $uid;
8521: }
8522: }
8523: }
8524: }
1.388 www 8525: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 8526: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 8527: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 8528: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 8529: if ($email) {
8530: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 8531: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 8532: }
1.899 raeburn 8533: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 8534: if (defined($inststatus)) {
8535: $names{'inststatus'} = '';
8536: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8537: if (ref($usertypes) eq 'HASH') {
8538: my @okstatuses;
8539: foreach my $item (split(/:/,$inststatus)) {
8540: if (defined($usertypes->{$item})) {
8541: push(@okstatuses,$item);
8542: }
8543: }
8544: if (@okstatuses) {
8545: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8546: }
8547: }
8548: }
1.1075 raeburn 8549: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 8550: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 8551: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 8552: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8553: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8554: } else {
8555: $logmsg .= ' during self creation';
8556: }
1.1075 raeburn 8557: my $changed;
8558: if ($newuser) {
8559: $changed = 1;
8560: } else {
8561: foreach my $field (@fields) {
8562: if ($names{$field} ne $oldnames{$field}) {
8563: $changed = 1;
8564: last;
8565: }
8566: }
8567: }
8568: unless ($changed) {
8569: $logmsg = 'No changes in user information needed for: '.$logmsg;
8570: &logthis($logmsg);
8571: return 'ok';
8572: }
8573: my $reply = &put('environment', \%names, $udom,$uname);
8574: if ($reply ne 'ok') {
8575: return 'error: '.$reply;
8576: }
1.1087 raeburn 8577: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8578: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8579: }
1.1075 raeburn 8580: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8581: &devalidate_cache_new('namescache',$uname.':'.$udom);
8582: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 8583: &logthis($logmsg);
1.134 albertel 8584: return 'ok';
1.80 www 8585: }
8586:
1.81 www 8587: # -------------------------------------------------------------- Modify student
1.80 www 8588:
1.81 www 8589: sub modifystudent {
8590: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 8591: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216 raeburn 8592: $selfenroll,$context,$inststatus,$credits)=@_;
1.455 albertel 8593: if (!$cid) {
1.620 albertel 8594: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8595: return 'not_in_class';
8596: }
1.80 www 8597: }
8598: # --------------------------------------------------------------- Make the user
1.81 www 8599: my $reply=&modifyuser
1.209 matthew 8600: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 8601: $desiredhome,$email,$inststatus);
1.80 www 8602: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 8603: # This will cause &modify_student_enrollment to get the uid from the
1.1235 raeburn 8604: # student's environment
1.297 matthew 8605: $uid = undef if (!$forceid);
1.455 albertel 8606: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216 raeburn 8607: $gene,$usec,$end,$start,$type,$locktype,
8608: $cid,$selfenroll,$context,$credits);
1.297 matthew 8609: return $reply;
8610: }
8611:
8612: sub modify_student_enrollment {
1.1216 raeburn 8613: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8614: $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455 albertel 8615: my ($cdom,$cnum,$chome);
8616: if (!$cid) {
1.620 albertel 8617: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 8618: return 'not_in_class';
8619: }
1.620 albertel 8620: $cdom=$env{'course.'.$cid.'.domain'};
8621: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 8622: } else {
8623: ($cdom,$cnum)=split(/_/,$cid);
8624: }
1.620 albertel 8625: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 8626: if (!$chome) {
1.457 raeburn 8627: $chome=&homeserver($cnum,$cdom);
1.297 matthew 8628: }
1.455 albertel 8629: if (!$chome) { return 'unknown_course'; }
1.297 matthew 8630: # Make sure the user exists
1.81 www 8631: my $uhome=&homeserver($uname,$udom);
8632: if (($uhome eq '') || ($uhome eq 'no_host')) {
8633: return 'error: no such user';
8634: }
1.297 matthew 8635: # Get student data if we were not given enough information
8636: if (!defined($first) || $first eq '' ||
8637: !defined($last) || $last eq '' ||
8638: !defined($uid) || $uid eq '' ||
8639: !defined($middle) || $middle eq '' ||
8640: !defined($gene) || $gene eq '') {
1.294 matthew 8641: # They did not supply us with enough data to enroll the student, so
8642: # we need to pick up more information.
1.297 matthew 8643: my %tmp = &get('environment',
1.294 matthew 8644: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8645: ,$udom,$uname);
8646:
1.800 albertel 8647: #foreach my $key (keys(%tmp)) {
8648: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8649: #}
1.294 matthew 8650: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8651: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8652: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8653: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8654: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8655: }
1.556 albertel 8656: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8657: my $user = "$uname:$udom";
8658: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8659: my $reply=cput('classlist',
1.1148 raeburn 8660: {$user =>
1.1216 raeburn 8661: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487 albertel 8662: $cdom,$cnum);
1.1148 raeburn 8663: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8664: &devalidate_getsection_cache($udom,$uname,$cid);
8665: } else {
1.81 www 8666: return 'error: '.$reply;
8667: }
1.297 matthew 8668: # Add student role to user
1.83 www 8669: my $uurl='/'.$cid;
1.81 www 8670: $uurl=~s/\_/\//g;
8671: if ($usec) {
8672: $uurl.='/'.$usec;
8673: }
1.1148 raeburn 8674: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8675: $selfenroll,$context);
8676: if ($result ne 'ok') {
8677: if ($old_entry{$user} ne '') {
8678: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8679: } else {
8680: $reply = &del('classlist',[$user],$cdom,$cnum);
8681: }
8682: }
8683: return $result;
1.21 www 8684: }
8685:
1.556 albertel 8686: sub format_name {
8687: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8688: my $name;
8689: if ($first ne 'lastname') {
8690: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8691: } else {
8692: if ($lastname=~/\S/) {
8693: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8694: $name=~s/\s+,/,/;
8695: } else {
8696: $name.= $firstname.' '.$middlename.' '.$generation;
8697: }
8698: }
8699: $name=~s/^\s+//;
8700: $name=~s/\s+$//;
8701: $name=~s/\s+/ /g;
8702: return $name;
8703: }
8704:
1.84 www 8705: # ------------------------------------------------- Write to course preferences
8706:
8707: sub writecoursepref {
8708: my ($courseid,%prefs)=@_;
8709: $courseid=~s/^\///;
8710: $courseid=~s/\_/\//g;
8711: my ($cdomain,$cnum)=split(/\//,$courseid);
8712: my $chome=homeserver($cnum,$cdomain);
8713: if (($chome eq '') || ($chome eq 'no_host')) {
8714: return 'error: no such course';
8715: }
8716: my $cstring='';
1.800 albertel 8717: foreach my $pref (keys(%prefs)) {
8718: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8719: }
1.84 www 8720: $cstring=~s/\&$//;
8721: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8722: }
8723:
8724: # ---------------------------------------------------------- Make/modify course
8725:
8726: sub createcourse {
1.741 raeburn 8727: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8728: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8729: $url=&declutter($url);
8730: my $cid='';
1.1028 raeburn 8731: if ($context eq 'requestcourses') {
8732: my $can_create = 0;
8733: my ($ownername,$ownerdom) = split(':',$course_owner);
8734: if ($udom eq $ownerdom) {
8735: if (&usertools_access($ownername,$ownerdom,$category,undef,
8736: $context)) {
8737: $can_create = 1;
8738: }
8739: } else {
8740: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8741: $category);
8742: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8743: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8744: if (@curr > 0) {
8745: my @options = qw(approval validate autolimit);
8746: my $optregex = join('|',@options);
8747: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8748: $can_create = 1;
8749: }
8750: }
8751: }
8752: }
8753: if ($can_create) {
8754: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8755: unless (&allowed('ccc',$udom)) {
8756: return 'refused';
8757: }
1.1017 raeburn 8758: }
8759: } else {
8760: return 'refused';
8761: }
1.1028 raeburn 8762: } elsif (!&allowed('ccc',$udom)) {
8763: return 'refused';
1.84 www 8764: }
1.1011 raeburn 8765: # --------------------------------------------------------------- Get Unique ID
8766: my $uname;
8767: if ($cnum =~ /^$match_courseid$/) {
8768: my $chome=&homeserver($cnum,$udom,'true');
8769: if (($chome eq '') || ($chome eq 'no_host')) {
8770: $uname = $cnum;
8771: } else {
1.1038 raeburn 8772: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8773: }
8774: } else {
1.1038 raeburn 8775: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8776: }
8777: return $uname if ($uname =~ /^error/);
8778: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8779: if (!defined($course_server)) {
8780: if (defined(&domain($udom,'primary'))) {
8781: $course_server = &domain($udom,'primary');
8782: } else {
8783: $course_server = $env{'user.home'};
8784: }
8785: }
8786: my %host_servers =
8787: &Apache::lonnet::get_servers($udom,'library');
8788: unless ($host_servers{$course_server}) {
8789: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8790: }
1.84 www 8791: # ------------------------------------------------------------- Make the course
8792: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8793: $course_server);
1.84 www 8794: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8795: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8796: if (($uhome eq '') || ($uhome eq 'no_host')) {
8797: return 'error: no such course';
8798: }
1.271 www 8799: # ----------------------------------------------------------------- Course made
1.516 raeburn 8800: # log existence
1.1029 raeburn 8801: my $now = time;
1.918 raeburn 8802: my $newcourse = {
8803: $udom.'_'.$uname => {
1.921 raeburn 8804: description => $description,
8805: inst_code => $inst_code,
8806: owner => $course_owner,
8807: type => $crstype,
1.1029 raeburn 8808: creator => $env{'user.name'}.':'.
8809: $env{'user.domain'},
8810: created => $now,
8811: context => $context,
1.918 raeburn 8812: },
8813: };
1.921 raeburn 8814: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8815: # set toplevel url
1.271 www 8816: my $topurl=$url;
8817: unless ($nonstandard) {
8818: # ------------------------------------------ For standard courses, make top url
8819: my $mapurl=&clutter($url);
1.278 www 8820: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8821: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8822: <map>
8823: <resource id="1" type="start"></resource>
8824: <resource id="2" src="$mapurl"></resource>
8825: <resource id="3" type="finish"></resource>
8826: <link index="1" from="1" to="2"></link>
8827: <link index="2" from="2" to="3"></link>
8828: </map>
8829: ENDINITMAP
8830: $topurl=&declutter(
1.638 albertel 8831: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8832: );
8833: }
8834: # ----------------------------------------------------------- Write preferences
1.84 www 8835: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8836: ('description' => $description,
8837: 'url' => $topurl,
8838: 'internal.creator' => $env{'user.name'}.':'.
8839: $env{'user.domain'},
8840: 'internal.created' => $now,
8841: 'internal.creationcontext' => $context)
8842: );
1.84 www 8843: return '/'.$udom.'/'.$uname;
8844: }
8845:
1.1011 raeburn 8846: # ------------------------------------------------------------------- Create ID
8847: sub generate_coursenum {
1.1038 raeburn 8848: my ($udom,$crstype) = @_;
1.1011 raeburn 8849: my $domdesc = &domain($udom);
8850: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8851: my $first;
8852: if ($crstype eq 'Community') {
8853: $first = '0';
8854: } else {
8855: $first = int(1+rand(9));
8856: }
8857: my $uname=$first.
1.1011 raeburn 8858: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8859: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8860: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8861: # ----------------------------------------------- Make sure that does not exist
8862: my $uhome=&homeserver($uname,$udom,'true');
8863: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8864: if ($crstype eq 'Community') {
8865: $first = '0';
8866: } else {
8867: $first = int(1+rand(9));
8868: }
8869: $uname=$first.
1.1011 raeburn 8870: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8871: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8872: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8873: $uhome=&homeserver($uname,$udom,'true');
8874: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8875: return 'error: unable to generate unique course-ID';
8876: }
8877: }
8878: return $uname;
8879: }
8880:
1.813 albertel 8881: sub is_course {
1.1167 droeschl 8882: my ($cdom, $cnum) = scalar(@_) == 1 ?
8883: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8884:
8885: return unless $cdom and $cnum;
8886:
8887: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8888: '.');
8889:
1.1219 raeburn 8890: return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167 droeschl 8891: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8892: }
8893:
1.1015 raeburn 8894: sub store_userdata {
8895: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8896: my $result;
1.1016 raeburn 8897: if ($datakey ne '') {
1.1013 raeburn 8898: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8899: if ($udom eq '' || $uname eq '') {
8900: $udom = $env{'user.domain'};
8901: $uname = $env{'user.name'};
8902: }
8903: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8904: if (($uhome eq '') || ($uhome eq 'no_host')) {
8905: $result = 'error: no_host';
8906: } else {
8907: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8908: $storehash->{'host'} = $perlvar{'lonHostID'};
8909:
8910: my $namevalue='';
8911: foreach my $key (keys(%{$storehash})) {
8912: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8913: }
8914: $namevalue=~s/\&$//;
1.1224 raeburn 8915: unless ($namespace eq 'courserequests') {
8916: $datakey = &escape($datakey);
8917: }
1.1105 raeburn 8918: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8919: $namevalue,$uhome);
1.1013 raeburn 8920: }
8921: } else {
8922: $result = 'error: data to store was not a hash reference';
8923: }
8924: } else {
8925: $result= 'error: invalid requestkey';
8926: }
8927: return $result;
8928: }
8929:
1.21 www 8930: # ---------------------------------------------------------- Assign Custom Role
8931:
8932: sub assigncustomrole {
1.957 raeburn 8933: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8934: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8935: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8936: }
8937:
8938: # ----------------------------------------------------------------- Revoke Role
8939:
8940: sub revokerole {
1.957 raeburn 8941: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8942: my $now=time;
1.965 raeburn 8943: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8944: }
8945:
8946: # ---------------------------------------------------------- Revoke Custom Role
8947:
8948: sub revokecustomrole {
1.957 raeburn 8949: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8950: my $now=time;
1.357 www 8951: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8952: $deleteflag,$selfenroll,$context);
1.17 www 8953: }
8954:
1.533 banghart 8955: # ------------------------------------------------------------ Disk usage
1.535 albertel 8956: sub diskusage {
1.955 raeburn 8957: my ($udom,$uname,$directorypath,$getpropath)=@_;
8958: $directorypath =~ s/\/$//;
8959: my $listing=&reply('du2:'.&escape($directorypath).':'
8960: .&escape($getpropath).':'.&escape($uname).':'
8961: .&escape($udom),homeserver($uname,$udom));
8962: if ($listing eq 'unknown_cmd') {
8963: if ($getpropath) {
8964: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8965: }
8966: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8967: }
1.514 albertel 8968: return $listing;
1.512 banghart 8969: }
8970:
1.566 banghart 8971: sub is_locked {
1.1096 raeburn 8972: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8973: my @check;
8974: my $is_locked;
1.1093 raeburn 8975: push (@check,$file_name);
1.613 albertel 8976: my %locked = &get('file_permissions',\@check,
1.620 albertel 8977: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8978: my ($tmp)=keys(%locked);
8979: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8980:
1.566 banghart 8981: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8982: $is_locked = 'false';
8983: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8984: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8985: $is_locked = 'true';
1.1096 raeburn 8986: if (ref($which) eq 'ARRAY') {
8987: push(@{$which},$entry);
8988: } else {
8989: last;
8990: }
1.745 raeburn 8991: }
8992: }
1.566 banghart 8993: } else {
8994: $is_locked = 'false';
8995: }
1.1093 raeburn 8996: return $is_locked;
1.566 banghart 8997: }
8998:
1.759 albertel 8999: sub declutter_portfile {
9000: my ($file) = @_;
1.833 albertel 9001: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 9002: return $file;
9003: }
9004:
1.559 banghart 9005: # ------------------------------------------------------------- Mark as Read Only
9006:
9007: sub mark_as_readonly {
9008: my ($domain,$user,$files,$what) = @_;
1.613 albertel 9009: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9010: my ($tmp)=keys(%current_permissions);
9011: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 9012: foreach my $file (@{$files}) {
1.759 albertel 9013: $file = &declutter_portfile($file);
1.561 banghart 9014: push(@{$current_permissions{$file}},$what);
1.559 banghart 9015: }
1.613 albertel 9016: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9017: return;
9018: }
9019:
1.572 banghart 9020: # ------------------------------------------------------------Save Selected Files
9021:
9022: sub save_selected_files {
9023: my ($user, $path, @files) = @_;
9024: my $filename = $user."savedfiles";
1.573 banghart 9025: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 9026: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 9027: foreach my $file (@files) {
1.620 albertel 9028: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 9029: }
9030: foreach my $file (@other_files) {
1.574 banghart 9031: print (OUT $file."\n");
1.572 banghart 9032: }
1.574 banghart 9033: close (OUT);
1.572 banghart 9034: return 'ok';
9035: }
9036:
1.574 banghart 9037: sub clear_selected_files {
9038: my ($user) = @_;
9039: my $filename = $user."savedfiles";
1.1117 foxr 9040: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 9041: print (OUT undef);
9042: close (OUT);
9043: return ("ok");
9044: }
9045:
1.572 banghart 9046: sub files_in_path {
9047: my ($user, $path) = @_;
9048: my $filename = $user."savedfiles";
9049: my %return_files;
1.1117 foxr 9050: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 9051: while (my $line_in = <IN>) {
1.574 banghart 9052: chomp ($line_in);
9053: my @paths_and_file = split (m!/!, $line_in);
9054: my $file_part = pop (@paths_and_file);
9055: my $path_part = join ('/', @paths_and_file);
1.573 banghart 9056: $path_part.='/';
9057: my $path_and_file = $path_part.$file_part;
9058: if ($path_part eq $path) {
9059: $return_files{$file_part}= 'selected';
9060: }
9061: }
1.574 banghart 9062: close (IN);
9063: return (\%return_files);
1.572 banghart 9064: }
9065:
9066: # called in portfolio select mode, to show files selected NOT in current directory
9067: sub files_not_in_path {
9068: my ($user, $path) = @_;
9069: my $filename = $user."savedfiles";
9070: my @return_files;
9071: my $path_part;
1.1117 foxr 9072: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 9073: while (my $line = <IN>) {
1.572 banghart 9074: #ok, I know it's clunky, but I want it to work
1.800 albertel 9075: my @paths_and_file = split(m|/|, $line);
9076: my $file_part = pop(@paths_and_file);
9077: chomp($file_part);
9078: my $path_part = join('/', @paths_and_file);
1.572 banghart 9079: $path_part .= '/';
9080: my $path_and_file = $path_part.$file_part;
9081: if ($path_part ne $path) {
1.800 albertel 9082: push(@return_files, ($path_and_file));
1.572 banghart 9083: }
9084: }
1.800 albertel 9085: close(OUT);
1.574 banghart 9086: return (@return_files);
1.572 banghart 9087: }
9088:
1.745 raeburn 9089: #----------------------------------------------Get portfolio file permissions
1.629 banghart 9090:
1.745 raeburn 9091: sub get_portfile_permissions {
9092: my ($domain,$user) = @_;
1.613 albertel 9093: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 9094: my ($tmp)=keys(%current_permissions);
9095: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9096: return \%current_permissions;
9097: }
9098:
9099: #---------------------------------------------Get portfolio file access controls
9100:
1.749 raeburn 9101: sub get_access_controls {
1.745 raeburn 9102: my ($current_permissions,$group,$file) = @_;
1.769 albertel 9103: my %access;
9104: my $real_file = $file;
9105: $file =~ s/\.meta$//;
1.745 raeburn 9106: if (defined($file)) {
1.749 raeburn 9107: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9108: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 9109: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 9110: }
9111: }
1.745 raeburn 9112: } else {
1.749 raeburn 9113: foreach my $key (keys(%{$current_permissions})) {
9114: if ($key =~ /\0accesscontrol$/) {
9115: if (defined($group)) {
9116: if ($key !~ m-^\Q$group\E/-) {
9117: next;
9118: }
9119: }
9120: my ($fullpath) = split(/\0/,$key);
9121: if (ref($$current_permissions{$key}) eq 'HASH') {
9122: foreach my $control (keys(%{$$current_permissions{$key}})) {
9123: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9124: }
9125: }
9126: }
9127: }
9128: }
9129: return %access;
9130: }
9131:
9132: sub modify_access_controls {
9133: my ($file_name,$changes,$domain,$user)=@_;
9134: my ($outcome,$deloutcome);
9135: my %store_permissions;
9136: my %new_values;
9137: my %new_control;
9138: my %translation;
9139: my @deletions = ();
9140: my $now = time;
9141: if (exists($$changes{'activate'})) {
9142: if (ref($$changes{'activate'}) eq 'HASH') {
9143: my @newitems = sort(keys(%{$$changes{'activate'}}));
9144: my $numnew = scalar(@newitems);
9145: for (my $i=0; $i<$numnew; $i++) {
9146: my $newkey = $newitems[$i];
9147: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 9148: if ($newkey =~ /^\d+:/) {
9149: $newkey =~ s/^(\d+)/$newid/;
9150: $translation{$1} = $newid;
9151: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9152: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9153: $translation{$1} = $newid;
9154: }
1.749 raeburn 9155: $new_values{$file_name."\0".$newkey} =
9156: $$changes{'activate'}{$newitems[$i]};
9157: $new_control{$newkey} = $now;
9158: }
9159: }
9160: }
9161: my %todelete;
9162: my %changed_items;
9163: foreach my $action ('delete','update') {
9164: if (exists($$changes{$action})) {
9165: if (ref($$changes{$action}) eq 'HASH') {
9166: foreach my $key (keys(%{$$changes{$action}})) {
9167: my ($itemnum) = ($key =~ /^([^:]+):/);
9168: if ($action eq 'delete') {
9169: $todelete{$itemnum} = 1;
9170: } else {
9171: $changed_items{$itemnum} = $key;
9172: }
9173: }
1.745 raeburn 9174: }
9175: }
1.749 raeburn 9176: }
9177: # get lock on access controls for file.
9178: my $lockhash = {
9179: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9180: ':'.$env{'user.domain'},
9181: };
9182: my $tries = 0;
9183: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9184:
9185: while (($gotlock ne 'ok') && $tries <3) {
9186: $tries ++;
9187: sleep 1;
9188: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9189: }
9190: if ($gotlock eq 'ok') {
9191: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9192: my ($tmp)=keys(%curr_permissions);
9193: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9194: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9195: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9196: if (ref($curr_controls) eq 'HASH') {
9197: foreach my $control_item (keys(%{$curr_controls})) {
9198: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9199: if (defined($todelete{$itemnum})) {
9200: push(@deletions,$file_name."\0".$control_item);
9201: } else {
9202: if (defined($changed_items{$itemnum})) {
9203: $new_control{$changed_items{$itemnum}} = $now;
9204: push(@deletions,$file_name."\0".$control_item);
9205: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9206: } else {
9207: $new_control{$control_item} = $$curr_controls{$control_item};
9208: }
9209: }
1.745 raeburn 9210: }
9211: }
9212: }
1.970 raeburn 9213: my ($group);
9214: if (&is_course($domain,$user)) {
9215: ($group,my $file) = split(/\//,$file_name,2);
9216: }
1.749 raeburn 9217: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9218: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9219: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9220: # remove lock
9221: my @del_lock = ($file_name."\0".'locked_access_records');
9222: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 9223: my $sqlresult =
1.970 raeburn 9224: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 9225: $group);
1.749 raeburn 9226: } else {
9227: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 9228: }
1.749 raeburn 9229: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 9230: }
9231:
1.827 raeburn 9232: sub make_public_indefinitely {
9233: my ($requrl) = @_;
9234: my $now = time;
9235: my $action = 'activate';
9236: my $aclnum = 0;
9237: if (&is_portfolio_url($requrl)) {
9238: my (undef,$udom,$unum,$file_name,$group) =
9239: &parse_portfolio_url($requrl);
9240: my $current_perms = &get_portfile_permissions($udom,$unum);
9241: my %access_controls = &get_access_controls($current_perms,
9242: $group,$file_name);
9243: foreach my $key (keys(%{$access_controls{$file_name}})) {
9244: my ($num,$scope,$end,$start) =
9245: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9246: if ($scope eq 'public') {
9247: if ($start <= $now && $end == 0) {
9248: $action = 'none';
9249: } else {
9250: $action = 'update';
9251: $aclnum = $num;
9252: }
9253: last;
9254: }
9255: }
9256: if ($action eq 'none') {
9257: return 'ok';
9258: } else {
9259: my %changes;
9260: my $newend = 0;
9261: my $newstart = $now;
9262: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9263: $changes{$action}{$newkey} = {
9264: type => 'public',
9265: time => {
9266: start => $newstart,
9267: end => $newend,
9268: },
9269: };
9270: my ($outcome,$deloutcome,$new_values,$translation) =
9271: &modify_access_controls($file_name,\%changes,$udom,$unum);
9272: return $outcome;
9273: }
9274: } else {
9275: return 'invalid';
9276: }
9277: }
9278:
1.745 raeburn 9279: #------------------------------------------------------Get Marked as Read Only
9280:
9281: sub get_marked_as_readonly {
9282: my ($domain,$user,$what,$group) = @_;
9283: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 9284: my @readonly_files;
1.629 banghart 9285: my $cmp1=$what;
9286: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 9287: while (my ($file_name,$value) = each(%{$current_permissions})) {
9288: if (defined($group)) {
9289: if ($file_name !~ m-^\Q$group\E/-) {
9290: next;
9291: }
9292: }
1.561 banghart 9293: if (ref($value) eq "ARRAY"){
9294: foreach my $stored_what (@{$value}) {
1.629 banghart 9295: my $cmp2=$stored_what;
1.759 albertel 9296: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 9297: $cmp2=join('',@{$stored_what});
1.745 raeburn 9298: }
1.629 banghart 9299: if ($cmp1 eq $cmp2) {
1.561 banghart 9300: push(@readonly_files, $file_name);
1.745 raeburn 9301: last;
1.563 banghart 9302: } elsif (!defined($what)) {
9303: push(@readonly_files, $file_name);
1.745 raeburn 9304: last;
1.561 banghart 9305: }
9306: }
1.745 raeburn 9307: }
1.561 banghart 9308: }
9309: return @readonly_files;
9310: }
1.577 banghart 9311: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 9312:
1.577 banghart 9313: sub get_marked_as_readonly_hash {
1.745 raeburn 9314: my ($current_permissions,$group,$what) = @_;
1.577 banghart 9315: my %readonly_files;
1.745 raeburn 9316: while (my ($file_name,$value) = each(%{$current_permissions})) {
9317: if (defined($group)) {
9318: if ($file_name !~ m-^\Q$group\E/-) {
9319: next;
9320: }
9321: }
1.577 banghart 9322: if (ref($value) eq "ARRAY"){
9323: foreach my $stored_what (@{$value}) {
1.745 raeburn 9324: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 9325: foreach my $lock_descriptor(@{$stored_what}) {
9326: if ($lock_descriptor eq 'graded') {
9327: $readonly_files{$file_name} = 'graded';
9328: } elsif ($lock_descriptor eq 'handback') {
9329: $readonly_files{$file_name} = 'handback';
9330: } else {
9331: if (!exists($readonly_files{$file_name})) {
9332: $readonly_files{$file_name} = 'locked';
9333: }
9334: }
1.745 raeburn 9335: }
1.750 banghart 9336: }
1.577 banghart 9337: }
9338: }
9339: }
9340: return %readonly_files;
9341: }
1.559 banghart 9342: # ------------------------------------------------------------ Unmark as Read Only
9343:
9344: sub unmark_as_readonly {
1.629 banghart 9345: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9346: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 9347: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 9348: $file_name = &declutter_portfile($file_name);
1.634 albertel 9349: my $symb_crs = $what;
9350: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 9351: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 9352: my ($tmp)=keys(%current_permissions);
9353: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 9354: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 9355: foreach my $file (@readonly_files) {
1.759 albertel 9356: my $clean_file = &declutter_portfile($file);
9357: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 9358: my $current_locks = $current_permissions{$file};
1.563 banghart 9359: my @new_locks;
9360: my @del_keys;
9361: if (ref($current_locks) eq "ARRAY"){
9362: foreach my $locker (@{$current_locks}) {
1.632 albertel 9363: my $compare=$locker;
1.749 raeburn 9364: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 9365: $compare=join('',@{$locker});
1.746 raeburn 9366: if ($compare ne $symb_crs) {
9367: push(@new_locks, $locker);
9368: }
1.563 banghart 9369: }
9370: }
1.650 albertel 9371: if (scalar(@new_locks) > 0) {
1.563 banghart 9372: $current_permissions{$file} = \@new_locks;
9373: } else {
9374: push(@del_keys, $file);
1.613 albertel 9375: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 9376: delete($current_permissions{$file});
1.563 banghart 9377: }
9378: }
1.561 banghart 9379: }
1.613 albertel 9380: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 9381: return;
9382: }
1.512 banghart 9383:
1.17 www 9384: # ------------------------------------------------------------ Directory lister
9385:
9386: sub dirlist {
1.955 raeburn 9387: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 9388: $uri=~s/^\///;
9389: $uri=~s/\/$//;
1.253 stredwic 9390: my ($udom, $uname);
1.955 raeburn 9391: if ($getuserdir) {
1.253 stredwic 9392: $udom = $userdomain;
9393: $uname = $username;
1.955 raeburn 9394: } else {
9395: (undef,$udom,$uname)=split(/\//,$uri);
9396: if(defined($userdomain)) {
9397: $udom = $userdomain;
9398: }
9399: if(defined($username)) {
9400: $uname = $username;
9401: }
1.253 stredwic 9402: }
1.955 raeburn 9403: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 9404:
1.955 raeburn 9405: $dirRoot = $perlvar{'lonDocRoot'};
9406: if (defined($getpropath)) {
9407: $dirRoot = &propath($udom,$uname);
1.253 stredwic 9408: $dirRoot =~ s/\/$//;
1.955 raeburn 9409: } elsif (defined($getuserdir)) {
9410: my $subdir=$uname.'__';
9411: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9412: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9413: ."/$udom/$subdir/$uname";
9414: } elsif (defined($alternateRoot)) {
9415: $dirRoot = $alternateRoot;
1.751 banghart 9416: }
1.253 stredwic 9417:
9418: if($udom) {
9419: if($uname) {
1.1135 raeburn 9420: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 9421: if ($uhome eq 'no_host') {
9422: return ([],'no_host');
9423: }
1.955 raeburn 9424: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 9425: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 9426: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 9427: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9428: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 9429: } else {
9430: @listing_results = map { &unescape($_); } split(/:/,$listing);
9431: }
1.605 matthew 9432: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 9433: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 9434: @listing_results = split(/:/,$listing);
9435: } else {
9436: @listing_results = map { &unescape($_); } split(/:/,$listing);
9437: }
1.1135 raeburn 9438: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 9439: ($listing eq 'rejected') || ($listing eq 'refused') ||
9440: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9441: return ([],$listing);
9442: } else {
9443: return (\@listing_results);
1.1135 raeburn 9444: }
1.955 raeburn 9445: } elsif(!$alternateRoot) {
1.1136 raeburn 9446: my (%allusers,%listerror);
1.841 albertel 9447: my %servers = &get_servers($udom,'library');
1.955 raeburn 9448: foreach my $tryserver (keys(%servers)) {
9449: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9450: &escape($udom),$tryserver);
9451: if ($listing eq 'unknown_cmd') {
9452: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9453: $udom, $tryserver);
9454: } else {
9455: @listing_results = map { &unescape($_); } split(/:/,$listing);
9456: }
1.841 albertel 9457: if ($listing eq 'unknown_cmd') {
9458: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9459: $udom, $tryserver);
9460: @listing_results = split(/:/,$listing);
9461: } else {
9462: @listing_results =
9463: map { &unescape($_); } split(/:/,$listing);
9464: }
1.1136 raeburn 9465: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9466: ($listing eq 'rejected') || ($listing eq 'refused') ||
9467: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9468: $listerror{$tryserver} = $listing;
9469: } else {
1.841 albertel 9470: foreach my $line (@listing_results) {
9471: my ($entry) = split(/&/,$line,2);
9472: $allusers{$entry} = 1;
9473: }
9474: }
1.253 stredwic 9475: }
1.1136 raeburn 9476: my @alluserslist=();
1.800 albertel 9477: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 9478: push(@alluserslist,$user.'&user');
1.253 stredwic 9479: }
1.1136 raeburn 9480: return (\@alluserslist);
1.253 stredwic 9481: } else {
1.1136 raeburn 9482: return ([],'missing username');
1.253 stredwic 9483: }
1.955 raeburn 9484: } elsif(!defined($getpropath)) {
1.1136 raeburn 9485: my $path = $perlvar{'lonDocRoot'}.'/res/';
9486: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9487: return (\@all_domains);
1.955 raeburn 9488: } else {
1.1136 raeburn 9489: return ([],'missing domain');
1.275 stredwic 9490: }
9491: }
9492:
9493: # --------------------------------------------- GetFileTimestamp
9494: # This function utilizes dirlist and returns the date stamp for
9495: # when it was last modified. It will also return an error of -1
9496: # if an error occurs
9497:
9498: sub GetFileTimestamp {
1.955 raeburn 9499: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 9500: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9501: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 9502: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9503: undef,$getuserdir);
9504: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9505: return -1;
9506: }
9507: if (ref($fileref) eq 'ARRAY') {
9508: my @stats = split('&',$fileref->[0]);
1.375 matthew 9509: # @stats contains first the filename, then the stat output
9510: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 9511: } else {
9512: return -1;
1.253 stredwic 9513: }
1.26 www 9514: }
9515:
1.712 albertel 9516: sub stat_file {
9517: my ($uri) = @_;
1.787 albertel 9518: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 9519:
1.955 raeburn 9520: my ($udom,$uname,$file);
1.712 albertel 9521: if ($uri =~ m-^/(uploaded|editupload)/-) {
9522: ($udom,$uname,$file) =
1.811 albertel 9523: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 9524: $file = 'userfiles/'.$file;
9525: }
9526: if ($uri =~ m-^/res/-) {
9527: ($udom,$uname) =
1.807 albertel 9528: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 9529: $file = $uri;
9530: }
9531:
9532: if (!$udom || !$uname || !$file) {
9533: # unable to handle the uri
9534: return ();
9535: }
1.956 raeburn 9536: my $getpropath;
9537: if ($file =~ /^userfiles\//) {
9538: $getpropath = 1;
9539: }
1.1136 raeburn 9540: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9541: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9542: return ();
9543: } else {
9544: if (ref($listref) eq 'ARRAY') {
9545: my @stats = split('&',$listref->[0]);
9546: shift(@stats); #filename is first
9547: return @stats;
9548: }
1.712 albertel 9549: }
9550: return ();
9551: }
9552:
1.26 www 9553: # -------------------------------------------------------- Value of a Condition
9554:
1.713 albertel 9555: # gets the value of a specific preevaluated condition
9556: # stored in the string $env{user.state.<cid>}
9557: # or looks up a condition reference in the bighash and if if hasn't
9558: # already been evaluated recurses into docondval to get the value of
9559: # the condition, then memoizing it to
9560: # $env{user.state.<cid>.<condition>}
1.40 www 9561: sub directcondval {
9562: my $number=shift;
1.620 albertel 9563: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 9564: &Apache::lonuserstate::evalstate();
9565: }
1.713 albertel 9566: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9567: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9568: } elsif ($number =~ /^_/) {
9569: my $sub_condition;
9570: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9571: &GDBM_READER(),0640)) {
9572: $sub_condition=$bighash{'conditions'.$number};
9573: untie(%bighash);
9574: }
9575: my $value = &docondval($sub_condition);
1.949 raeburn 9576: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 9577: return $value;
9578: }
1.620 albertel 9579: if ($env{'user.state.'.$env{'request.course.id'}}) {
9580: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 9581: } else {
9582: return 2;
9583: }
9584: }
9585:
1.713 albertel 9586: # get the collection of conditions for this resource
1.26 www 9587: sub condval {
9588: my $condidx=shift;
1.54 www 9589: my $allpathcond='';
1.713 albertel 9590: foreach my $cond (split(/\|/,$condidx)) {
9591: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9592: $allpathcond.=
9593: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9594: }
1.191 harris41 9595: }
1.54 www 9596: $allpathcond=~s/\|$//;
1.713 albertel 9597: return &docondval($allpathcond);
9598: }
9599:
9600: #evaluates an expression of conditions
9601: sub docondval {
9602: my ($allpathcond) = @_;
9603: my $result=0;
9604: if ($env{'request.course.id'}
9605: && defined($allpathcond)) {
9606: my $operand='|';
9607: my @stack;
9608: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9609: if ($chunk eq '(') {
9610: push @stack,($operand,$result);
9611: } elsif ($chunk eq ')') {
9612: my $before=pop @stack;
9613: if (pop @stack eq '&') {
9614: $result=$result>$before?$before:$result;
9615: } else {
9616: $result=$result>$before?$result:$before;
9617: }
9618: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9619: $operand=$chunk;
9620: } else {
9621: my $new=directcondval($chunk);
9622: if ($operand eq '&') {
9623: $result=$result>$new?$new:$result;
9624: } else {
9625: $result=$result>$new?$result:$new;
9626: }
9627: }
9628: }
1.26 www 9629: }
9630: return $result;
1.421 albertel 9631: }
9632:
9633: # ---------------------------------------------------- Devalidate courseresdata
9634:
9635: sub devalidatecourseresdata {
9636: my ($coursenum,$coursedomain)=@_;
9637: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9638: &devalidate_cache_new('courseres',$hashid);
1.28 www 9639: }
9640:
1.763 www 9641:
1.200 www 9642: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9643: #
9644: # Parameters:
9645: # $coursenum - Number of the course.
9646: # $coursedomain - Domain at which the course was created.
9647: # Returns:
9648: # A hash of the course parameters along (I think) with timestamps
9649: # and version info.
1.877 foxr 9650:
1.624 albertel 9651: sub get_courseresdata {
9652: my ($coursenum,$coursedomain)=@_;
1.200 www 9653: my $coursehom=&homeserver($coursenum,$coursedomain);
9654: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9655: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9656: my %dumpreply;
1.417 albertel 9657: unless (defined($cached)) {
1.624 albertel 9658: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9659: $result=\%dumpreply;
1.251 albertel 9660: my ($tmp) = keys(%dumpreply);
9661: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9662: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9663: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9664: return $tmp;
1.416 albertel 9665: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9666: $result=undef;
1.599 albertel 9667: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9668: }
9669: }
1.624 albertel 9670: return $result;
9671: }
9672:
1.633 albertel 9673: sub devalidateuserresdata {
9674: my ($uname,$udom)=@_;
9675: my $hashid="$udom:$uname";
9676: &devalidate_cache_new('userres',$hashid);
9677: }
9678:
1.624 albertel 9679: sub get_userresdata {
9680: my ($uname,$udom)=@_;
9681: #most student don\'t have any data set, check if there is some data
9682: if (&EXT_cache_status($udom,$uname)) { return undef; }
9683:
9684: my $hashid="$udom:$uname";
9685: my ($result,$cached)=&is_cached_new('userres',$hashid);
9686: if (!defined($cached)) {
9687: my %resourcedata=&dump('resourcedata',$udom,$uname);
9688: $result=\%resourcedata;
9689: &do_cache_new('userres',$hashid,$result,600);
9690: }
9691: my ($tmp)=keys(%$result);
9692: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9693: return $result;
9694: }
9695: #error 2 occurs when the .db doesn't exist
9696: if ($tmp!~/error: 2 /) {
1.672 albertel 9697: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9698: " Trying to get resource data for ".
9699: $uname." at ".$udom.": ".
9700: $tmp."</font>");
9701: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9702: #&EXT_cache_set($udom,$uname);
9703: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9704: undef($tmp); # not really an error so don't send it back
1.624 albertel 9705: }
9706: return $tmp;
9707: }
1.879 foxr 9708: #----------------------------------------------- resdata - return resource data
9709: # Purpose:
9710: # Return resource data for either users or for a course.
9711: # Parameters:
9712: # $name - Course/user name.
9713: # $domain - Name of the domain the user/course is registered on.
9714: # $type - Type of thing $name is (must be 'course' or 'user'
9715: # @which - Array of names of resources desired.
9716: # Returns:
9717: # The value of the first reasource in @which that is found in the
9718: # resource hash.
9719: # Exceptional Conditions:
9720: # If the $type passed in is not valid (not the string 'course' or
9721: # 'user', an undefined reference is returned.
9722: # If none of the resources are found, an undef is returned
1.624 albertel 9723: sub resdata {
9724: my ($name,$domain,$type,@which)=@_;
9725: my $result;
9726: if ($type eq 'course') {
9727: $result=&get_courseresdata($name,$domain);
9728: } elsif ($type eq 'user') {
9729: $result=&get_userresdata($name,$domain);
9730: }
9731: if (!ref($result)) { return $result; }
1.251 albertel 9732: foreach my $item (@which) {
1.927 albertel 9733: if (defined($result->{$item->[0]})) {
9734: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9735: }
1.250 albertel 9736: }
1.291 albertel 9737: return undef;
1.200 www 9738: }
9739:
1.1236 raeburn 9740: sub get_numsuppfiles {
9741: my ($cnum,$cdom,$ignorecache)=@_;
9742: my $hashid=$cnum.':'.$cdom;
9743: my ($suppcount,$cached);
9744: unless ($ignorecache) {
9745: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9746: }
9747: unless (defined($cached)) {
9748: my $chome=&homeserver($cnum,$cdom);
9749: unless ($chome eq 'no_host') {
9750: ($suppcount,my $errors) = (0,0);
9751: my $suppmap = 'supplemental.sequence';
9752: ($suppcount,$errors) =
9753: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9754: }
9755: &do_cache_new('suppcount',$hashid,$suppcount,600);
9756: }
9757: return $suppcount;
9758: }
9759:
1.379 matthew 9760: #
9761: # EXT resource caching routines
9762: #
9763:
9764: sub clear_EXT_cache_status {
1.383 albertel 9765: &delenv('cache.EXT.');
1.379 matthew 9766: }
9767:
9768: sub EXT_cache_status {
9769: my ($target_domain,$target_user) = @_;
1.383 albertel 9770: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9771: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9772: # We know already the user has no data
9773: return 1;
9774: } else {
9775: return 0;
9776: }
9777: }
9778:
9779: sub EXT_cache_set {
9780: my ($target_domain,$target_user) = @_;
1.383 albertel 9781: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9782: #&appenv({$cachename => time});
1.379 matthew 9783: }
9784:
1.28 www 9785: # --------------------------------------------------------- Value of a Variable
1.58 www 9786: sub EXT {
1.715 albertel 9787:
1.1228 raeburn 9788: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68 www 9789: unless ($varname) { return ''; }
1.218 albertel 9790: #get real user name/domain, courseid and symb
9791: my $courseid;
1.359 albertel 9792: my $publicuser;
1.427 www 9793: if ($symbparm) {
9794: $symbparm=&get_symb_from_alias($symbparm);
9795: }
1.218 albertel 9796: if (!($uname && $udom)) {
1.790 albertel 9797: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9798: if (!$symbparm) { $symbparm=$cursymb; }
9799: } else {
1.620 albertel 9800: $courseid=$env{'request.course.id'};
1.218 albertel 9801: }
1.48 www 9802: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9803: my $rest;
1.320 albertel 9804: if (defined($therest[0])) {
1.48 www 9805: $rest=join('.',@therest);
9806: } else {
9807: $rest='';
9808: }
1.320 albertel 9809:
1.57 www 9810: my $qualifierrest=$qualifier;
9811: if ($rest) { $qualifierrest.='.'.$rest; }
9812: my $spacequalifierrest=$space;
9813: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9814: if ($realm eq 'user') {
1.48 www 9815: # --------------------------------------------------------------- user.resource
9816: if ($space eq 'resource') {
1.651 albertel 9817: if ( (defined($Apache::lonhomework::parsing_a_problem)
9818: || defined($Apache::lonhomework::parsing_a_task))
9819: &&
1.744 albertel 9820: ($symbparm eq &symbread()) ) {
9821: # if we are in the middle of processing the resource the
9822: # get the value we are planning on committing
9823: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9824: return $Apache::lonhomework::results{$qualifierrest};
9825: } else {
9826: return $Apache::lonhomework::history{$qualifierrest};
9827: }
1.335 albertel 9828: } else {
1.359 albertel 9829: my %restored;
1.620 albertel 9830: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9831: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9832: } else {
9833: %restored=&restore($symbparm,$courseid,$udom,$uname);
9834: }
1.335 albertel 9835: return $restored{$qualifierrest};
9836: }
1.48 www 9837: # ----------------------------------------------------------------- user.access
9838: } elsif ($space eq 'access') {
1.218 albertel 9839: # FIXME - not supporting calls for a specific user
1.48 www 9840: return &allowed($qualifier,$rest);
9841: # ------------------------------------------ user.preferences, user.environment
9842: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9843: if (($uname eq $env{'user.name'}) &&
9844: ($udom eq $env{'user.domain'})) {
9845: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9846: } else {
1.359 albertel 9847: my %returnhash;
9848: if (!$publicuser) {
9849: %returnhash=&userenvironment($udom,$uname,
9850: $qualifierrest);
9851: }
1.218 albertel 9852: return $returnhash{$qualifierrest};
9853: }
1.48 www 9854: # ----------------------------------------------------------------- user.course
9855: } elsif ($space eq 'course') {
1.218 albertel 9856: # FIXME - not supporting calls for a specific user
1.620 albertel 9857: return $env{join('.',('request.course',$qualifier))};
1.48 www 9858: # ------------------------------------------------------------------- user.role
9859: } elsif ($space eq 'role') {
1.218 albertel 9860: # FIXME - not supporting calls for a specific user
1.620 albertel 9861: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9862: if ($qualifier eq 'value') {
9863: return $role;
9864: } elsif ($qualifier eq 'extent') {
9865: return $where;
9866: }
9867: # ----------------------------------------------------------------- user.domain
9868: } elsif ($space eq 'domain') {
1.218 albertel 9869: return $udom;
1.48 www 9870: # ------------------------------------------------------------------- user.name
9871: } elsif ($space eq 'name') {
1.218 albertel 9872: return $uname;
1.48 www 9873: # ---------------------------------------------------- Any other user namespace
1.29 www 9874: } else {
1.359 albertel 9875: my %reply;
9876: if (!$publicuser) {
9877: %reply=&get($space,[$qualifierrest],$udom,$uname);
9878: }
9879: return $reply{$qualifierrest};
1.48 www 9880: }
1.236 www 9881: } elsif ($realm eq 'query') {
9882: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9883: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9884: [$spacequalifierrest]);
1.620 albertel 9885: return $env{'form.'.$spacequalifierrest};
1.236 www 9886: } elsif ($realm eq 'request') {
1.48 www 9887: # ------------------------------------------------------------- request.browser
9888: if ($space eq 'browser') {
1.1145 bisitz 9889: return $env{'browser.'.$qualifier};
1.57 www 9890: # ------------------------------------------------------------ request.filename
9891: } else {
1.620 albertel 9892: return $env{'request.'.$spacequalifierrest};
1.29 www 9893: }
1.28 www 9894: } elsif ($realm eq 'course') {
1.48 www 9895: # ---------------------------------------------------------- course.description
1.620 albertel 9896: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9897: } elsif ($realm eq 'resource') {
1.165 www 9898:
1.620 albertel 9899: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9900: if (!$symbparm) { $symbparm=&symbread(); }
9901: }
1.693 albertel 9902:
1.1232 raeburn 9903: if ($qualifier eq '') {
9904: if ($space eq 'title') {
9905: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9906: return &gettitle($symbparm);
9907: }
1.693 albertel 9908:
1.1232 raeburn 9909: if ($space eq 'map') {
9910: my ($map) = &decode_symb($symbparm);
9911: return &symbread($map);
9912: }
9913: if ($space eq 'maptitle') {
9914: my ($map) = &decode_symb($symbparm);
9915: return &gettitle($map);
9916: }
9917: if ($space eq 'filename') {
9918: if ($symbparm) {
9919: return &clutter((&decode_symb($symbparm))[2]);
9920: }
9921: return &hreflocation('',$env{'request.filename'});
1.905 albertel 9922: }
1.1232 raeburn 9923:
1.1233 raeburn 9924: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
9925: if ($space eq 'visibleparts') {
9926: my $navmap = Apache::lonnavmaps::navmap->new();
9927: my $item;
9928: if (ref($navmap)) {
9929: my $res = $navmap->getBySymb($symbparm);
9930: my $parts = $res->parts();
9931: if (ref($parts) eq 'ARRAY') {
9932: $item = join(',',@{$parts});
9933: }
9934: undef($navmap);
1.1232 raeburn 9935: }
1.1233 raeburn 9936: return $item;
1.1232 raeburn 9937: }
9938: }
9939: }
1.693 albertel 9940:
9941: my ($section, $group, @groups);
1.593 albertel 9942: my ($courselevelm,$courselevel);
1.1228 raeburn 9943: if (($courseid eq '') && ($cid)) {
9944: $courseid = $cid;
9945: }
9946: if (($symbparm && $courseid) &&
9947: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165 www 9948:
1.218 albertel 9949: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9950:
1.60 www 9951: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9952: my $symbp=$symbparm;
1.735 albertel 9953: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9954:
9955: my $symbparm=$symbp.'.'.$spacequalifierrest;
9956: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9957:
1.620 albertel 9958: if (($env{'user.name'} eq $uname) &&
9959: ($env{'user.domain'} eq $udom)) {
9960: $section=$env{'request.course.sec'};
1.733 raeburn 9961: @groups = split(/:/,$env{'request.course.groups'});
9962: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9963: } else {
1.539 albertel 9964: if (! defined($usection)) {
1.551 albertel 9965: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9966: } else {
9967: $section = $usection;
9968: }
1.733 raeburn 9969: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9970: }
9971:
9972: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9973: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9974: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9975:
1.593 albertel 9976: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9977: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9978: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9979:
1.60 www 9980: # ----------------------------------------------------------- first, check user
1.624 albertel 9981:
9982: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9983: ([$courselevelr,'resource'],
9984: [$courselevelm,'map' ],
9985: [$courselevel, 'course' ]));
1.931 albertel 9986: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9987:
1.594 albertel 9988: # ------------------------------------------------ second, check some of course
1.684 raeburn 9989: my $coursereply;
1.691 raeburn 9990: if (@groups > 0) {
9991: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9992: $mapparm,$spacequalifierrest);
1.927 albertel 9993: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9994: }
1.96 www 9995:
1.684 raeburn 9996: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9997: $env{'course.'.$courseid.'.domain'},
9998: 'course',
9999: ([$seclevelr, 'resource'],
10000: [$seclevelm, 'map' ],
10001: [$seclevel, 'course' ],
10002: [$courselevelr,'resource']));
10003: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 10004:
1.60 www 10005: # ------------------------------------------------------ third, check map parms
1.218 albertel 10006: my %parmhash=();
10007: my $thisparm='';
10008: if (tie(%parmhash,'GDBM_File',
1.620 albertel 10009: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 10010: &GDBM_READER(),0640)) {
1.218 albertel 10011: $thisparm=$parmhash{$symbparm};
10012: untie(%parmhash);
10013: }
1.927 albertel 10014: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 10015: }
1.594 albertel 10016: # ------------------------------------------ fourth, look in resource metadata
1.71 www 10017:
1.218 albertel 10018: $spacequalifierrest=~s/\./\_/;
1.282 albertel 10019: my $filename;
10020: if (!$symbparm) { $symbparm=&symbread(); }
10021: if ($symbparm) {
1.409 www 10022: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 10023: } else {
1.620 albertel 10024: $filename=$env{'request.filename'};
1.282 albertel 10025: }
10026: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 10027: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 10028: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 10029: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 10030:
1.927 albertel 10031: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 10032: if ($symbparm && defined($courseid) &&
1.620 albertel 10033: $courseid eq $env{'request.course.id'}) {
1.624 albertel 10034: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10035: $env{'course.'.$courseid.'.domain'},
10036: 'course',
1.927 albertel 10037: ([$courselevelm,'map' ],
10038: [$courselevel, 'course']));
10039: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 10040: }
1.145 www 10041: # ------------------------------------------------------------------ Cascade up
1.218 albertel 10042: unless ($space eq '0') {
1.336 albertel 10043: my @parts=split(/_/,$space);
10044: my $id=pop(@parts);
10045: my $part=join('_',@parts);
10046: if ($part eq '') { $part='0'; }
1.927 albertel 10047: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 10048: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 10049: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 10050: }
1.395 albertel 10051: if ($recurse) { return undef; }
10052: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 10053: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 10054: # ---------------------------------------------------- Any other user namespace
10055: } elsif ($realm eq 'environment') {
10056: # ----------------------------------------------------------------- environment
1.620 albertel 10057: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10058: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 10059: } else {
1.770 albertel 10060: if ($uname eq 'anonymous' && $udom eq '') {
10061: return '';
10062: }
1.219 albertel 10063: my %returnhash=&userenvironment($udom,$uname,
10064: $spacequalifierrest);
10065: return $returnhash{$spacequalifierrest};
10066: }
1.28 www 10067: } elsif ($realm eq 'system') {
1.48 www 10068: # ----------------------------------------------------------------- system.time
10069: if ($space eq 'time') {
10070: return time;
10071: }
1.696 albertel 10072: } elsif ($realm eq 'server') {
10073: # ----------------------------------------------------------------- system.time
10074: if ($space eq 'name') {
10075: return $ENV{'SERVER_NAME'};
10076: }
1.28 www 10077: }
1.48 www 10078: return '';
1.61 www 10079: }
10080:
1.927 albertel 10081: sub get_reply {
10082: my ($reply_value) = @_;
1.940 raeburn 10083: if (ref($reply_value) eq 'ARRAY') {
10084: if (wantarray) {
10085: return @$reply_value;
10086: }
10087: return $reply_value->[0];
10088: } else {
10089: return $reply_value;
1.927 albertel 10090: }
10091: }
10092:
1.691 raeburn 10093: sub check_group_parms {
10094: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10095: my @groupitems = ();
10096: my $resultitem;
1.927 albertel 10097: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 10098: foreach my $group (@{$groups}) {
10099: foreach my $level (@levels) {
1.927 albertel 10100: my $item = $courseid.'.['.$group.'].'.$level->[0];
10101: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 10102: }
10103: }
10104: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10105: $env{'course.'.$courseid.'.domain'},
10106: 'course',@groupitems);
10107: return $coursereply;
10108: }
10109:
10110: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 10111: my ($courseid,@groups) = @_;
10112: @groups = sort(@groups);
1.691 raeburn 10113: return @groups;
10114: }
10115:
1.395 albertel 10116: sub packages_tab_default {
10117: my ($uri,$varname)=@_;
10118: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 10119:
10120: my (@extension,@specifics,$do_default);
10121: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 10122: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 10123: if ($pack_type eq 'default') {
10124: $do_default=1;
10125: } elsif ($pack_type eq 'extension') {
10126: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 10127: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 10128: # only look at packages defaults for packages that this id is
1.738 albertel 10129: push(@specifics,[$package,$pack_type,$pack_part]);
10130: }
10131: }
10132: # first look for a package that matches the requested part id
10133: foreach my $package (@specifics) {
10134: my (undef,$pack_type,$pack_part)=@{$package};
10135: next if ($pack_part ne $part);
10136: if (defined($packagetab{"$pack_type&$name&default"})) {
10137: return $packagetab{"$pack_type&$name&default"};
10138: }
10139: }
10140: # look for any possible matching non extension_ package
10141: foreach my $package (@specifics) {
10142: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 10143: if (defined($packagetab{"$pack_type&$name&default"})) {
10144: return $packagetab{"$pack_type&$name&default"};
10145: }
1.585 albertel 10146: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 10147: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10148: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 10149: }
10150: }
1.738 albertel 10151: # look for any posible extension_ match
10152: foreach my $package (@extension) {
10153: my ($package,$pack_type)=@{$package};
10154: if (defined($packagetab{"$pack_type&$name&default"})) {
10155: return $packagetab{"$pack_type&$name&default"};
10156: }
10157: if (defined($packagetab{$package."&$name&default"})) {
10158: return $packagetab{$package."&$name&default"};
10159: }
10160: }
10161: # look for a global default setting
10162: if ($do_default && defined($packagetab{"default&$name&default"})) {
10163: return $packagetab{"default&$name&default"};
10164: }
1.395 albertel 10165: return undef;
10166: }
10167:
1.334 albertel 10168: sub add_prefix_and_part {
10169: my ($prefix,$part)=@_;
10170: my $keyroot;
10171: if (defined($prefix) && $prefix !~ /^__/) {
10172: # prefix that has a part already
10173: $keyroot=$prefix;
10174: } elsif (defined($prefix)) {
10175: # prefix that is missing a part
10176: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10177: } else {
10178: # no prefix at all
10179: if (defined($part)) { $keyroot='_'.$part; }
10180: }
10181: return $keyroot;
10182: }
10183:
1.71 www 10184: # ---------------------------------------------------------------- Get metadata
10185:
1.599 albertel 10186: my %metaentry;
1.1070 www 10187: my %importedpartids;
1.71 www 10188: sub metadata {
1.176 www 10189: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 10190: $uri=&declutter($uri);
1.288 albertel 10191: # if it is a non metadata possible uri return quickly
1.529 albertel 10192: if (($uri eq '') ||
10193: (($uri =~ m|^/*adm/|) &&
1.1217 raeburn 10194: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108 raeburn 10195: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 10196: return undef;
10197: }
1.1140 www 10198: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 10199: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 10200: return undef;
1.288 albertel 10201: }
1.73 www 10202: my $filename=$uri;
10203: $uri=~s/\.meta$//;
1.172 www 10204: #
10205: # Is the metadata already cached?
1.177 www 10206: # Look at timestamp of caching
1.172 www 10207: # Everything is cached by the main uri, libraries are never directly cached
10208: #
1.428 albertel 10209: if (!defined($liburi)) {
1.599 albertel 10210: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 10211: if (defined($cached)) { return $result->{':'.$what}; }
10212: }
10213: {
1.1069 www 10214: # Imported parts would go here
1.1070 www 10215: my %importedids=();
10216: my @origfileimportpartids=();
1.1069 www 10217: my $importedparts=0;
1.172 www 10218: #
10219: # Is this a recursive call for a library?
10220: #
1.599 albertel 10221: # if (! exists($metacache{$uri})) {
10222: # $metacache{$uri}={};
10223: # }
1.924 albertel 10224: my $cachetime = 60*60;
1.171 www 10225: if ($liburi) {
10226: $liburi=&declutter($liburi);
10227: $filename=$liburi;
1.401 bowersj2 10228: } else {
1.599 albertel 10229: &devalidate_cache_new('meta',$uri);
10230: undef(%metaentry);
1.401 bowersj2 10231: }
1.140 www 10232: my %metathesekeys=();
1.73 www 10233: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 10234: my $metastring;
1.1140 www 10235: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 10236: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 10237: $metastring =
1.929 albertel 10238: &Apache::lonnet::ssi_body($which,
1.924 albertel 10239: ('grade_target' => 'meta'));
10240: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 10241: } elsif (($uri !~ m -^(editupload)/-) &&
10242: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 10243: my $file=&filelocation('',&clutter($filename));
1.599 albertel 10244: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 10245: $metastring=&getfile($file);
1.489 albertel 10246: }
1.208 albertel 10247: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 10248: my $token;
1.140 www 10249: undef %metathesekeys;
1.71 www 10250: while ($token=$parser->get_token) {
1.339 albertel 10251: if ($token->[0] eq 'S') {
10252: if (defined($token->[2]->{'package'})) {
1.172 www 10253: #
10254: # This is a package - get package info
10255: #
1.339 albertel 10256: my $package=$token->[2]->{'package'};
10257: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10258: if (defined($token->[2]->{'id'})) {
10259: $keyroot.='_'.$token->[2]->{'id'};
10260: }
1.599 albertel 10261: if ($metaentry{':packages'}) {
10262: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 10263: } else {
1.599 albertel 10264: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 10265: }
1.736 albertel 10266: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 10267: my $part=$keyroot;
10268: $part=~s/^\_//;
1.736 albertel 10269: if ($pack_entry=~/^\Q$package\E\&/ ||
10270: $pack_entry=~/^\Q$package\E_0\&/) {
10271: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 10272: # ignore package.tab specified default values
10273: # here &package_tab_default() will fetch those
10274: if ($subp eq 'default') { next; }
1.736 albertel 10275: my $value=$packagetab{$pack_entry};
1.432 albertel 10276: my $unikey;
10277: if ($pack =~ /_0$/) {
10278: $unikey='parameter_0_'.$name;
10279: $part=0;
10280: } else {
10281: $unikey='parameter'.$keyroot.'_'.$name;
10282: }
1.339 albertel 10283: if ($subp eq 'display') {
10284: $value.=' [Part: '.$part.']';
10285: }
1.599 albertel 10286: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 10287: $metathesekeys{$unikey}=1;
1.599 albertel 10288: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10289: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 10290: }
1.599 albertel 10291: if (defined($metaentry{':'.$unikey.'.default'})) {
10292: $metaentry{':'.$unikey}=
10293: $metaentry{':'.$unikey.'.default'};
1.356 albertel 10294: }
1.339 albertel 10295: }
10296: }
10297: } else {
1.172 www 10298: #
10299: # This is not a package - some other kind of start tag
1.339 albertel 10300: #
10301: my $entry=$token->[1];
1.1068 www 10302: my $unikey='';
1.175 www 10303:
1.339 albertel 10304: if ($entry eq 'import') {
1.175 www 10305: #
10306: # Importing a library here
1.339 albertel 10307: #
1.1067 www 10308: my $location=$parser->get_text('/import');
10309: my $dir=$filename;
10310: $dir=~s|[^/]*$||;
10311: $location=&filelocation($dir,$location);
1.1069 www 10312:
1.1068 www 10313: my $importmode=$token->[2]->{'importmode'};
10314: if ($importmode eq 'problem') {
1.1069 www 10315: # Import as problem/response
1.1068 www 10316: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10317: } elsif ($importmode eq 'part') {
10318: # Import as part(s)
1.1069 www 10319: $importedparts=1;
10320: # We need to get the original file and the imported file to get the part order correct
10321: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10322: # Load and inspect original file
1.1070 www 10323: if ($#origfileimportpartids<0) {
10324: undef(%importedpartids);
10325: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10326: my $origfile=&getfile($origfilelocation);
10327: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10328: }
10329:
1.1069 www 10330: # Load and inspect imported file
10331: my $impfile=&getfile($location);
10332: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10333: if ($#impfilepartids>=0) {
10334: # This problem had parts
1.1070 www 10335: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 10336: } else {
10337: # Importing by turning a single problem into a problem part
10338: # It gets the import-tags ID as part-ID
10339: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 10340: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 10341: }
1.1068 www 10342: } else {
10343: # Normal import
10344: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10345: if (defined($token->[2]->{'id'})) {
10346: $unikey.='_'.$token->[2]->{'id'};
10347: }
1.1067 www 10348: }
10349:
1.339 albertel 10350: if ($depthcount<20) {
1.736 albertel 10351: my $metadata =
10352: &metadata($uri,'keys', $location,$unikey,
10353: $depthcount+1);
10354: foreach my $meta (split(',',$metadata)) {
10355: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10356: $metathesekeys{$meta}=1;
1.339 albertel 10357: }
1.1068 www 10358:
10359: }
1.1067 www 10360: } else {
10361: #
10362: # Not importing, some other kind of non-package, non-library start tag
10363: #
10364: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10365: if (defined($token->[2]->{'id'})) {
10366: $unikey.='_'.$token->[2]->{'id'};
10367: }
1.339 albertel 10368: if (defined($token->[2]->{'name'})) {
10369: $unikey.='_'.$token->[2]->{'name'};
10370: }
10371: $metathesekeys{$unikey}=1;
1.736 albertel 10372: foreach my $param (@{$token->[3]}) {
10373: $metaentry{':'.$unikey.'.'.$param} =
10374: $token->[2]->{$param};
1.339 albertel 10375: }
10376: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 10377: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 10378: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10379: # only ws inside the tag, and not in default, so use default
10380: # as value
1.599 albertel 10381: $metaentry{':'.$unikey}=$default;
1.908 albertel 10382: } elsif ( $internaltext =~ /\S/ ) {
10383: # something interesting inside the tag
10384: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 10385: } else {
1.908 albertel 10386: # no interesting values, don't set a default
1.339 albertel 10387: }
1.172 www 10388: # end of not-a-package not-a-library import
1.339 albertel 10389: }
1.172 www 10390: # end of not-a-package start tag
1.339 albertel 10391: }
1.172 www 10392: # the next is the end of "start tag"
1.339 albertel 10393: }
10394: }
1.483 albertel 10395: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 10396: $extension = lc($extension);
10397: if ($extension eq 'htm') { $extension='html'; }
10398:
1.737 albertel 10399: foreach my $key (keys(%packagetab)) {
1.483 albertel 10400: #no specific packages #how's our extension
10401: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 10402: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 10403: \%metathesekeys);
10404: }
1.883 albertel 10405:
10406: if (!exists($metaentry{':packages'})
10407: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 10408: foreach my $key (keys(%packagetab)) {
1.483 albertel 10409: #no specific packages well let's get default then
10410: if ($key!~/^default&/) { next; }
1.488 albertel 10411: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 10412: \%metathesekeys);
10413: }
10414: }
1.338 www 10415: # are there custom rights to evaluate
1.599 albertel 10416: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 10417:
1.338 www 10418: #
10419: # Importing a rights file here
1.339 albertel 10420: #
10421: unless ($depthcount) {
1.599 albertel 10422: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 10423: my $dir=$filename;
10424: $dir=~s|[^/]*$||;
10425: $location=&filelocation($dir,$location);
1.736 albertel 10426: my $rights_metadata =
10427: &metadata($uri,'keys',$location,'_rights',
10428: $depthcount+1);
10429: foreach my $rights (split(',',$rights_metadata)) {
10430: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10431: $metathesekeys{$rights}=1;
1.339 albertel 10432: }
10433: }
10434: }
1.737 albertel 10435: # uniqifiy package listing
10436: my %seen;
10437: my @uniq_packages =
10438: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10439: $metaentry{':packages'} = join(',',@uniq_packages);
10440:
1.1070 www 10441: if ($importedparts) {
10442: # We had imported parts and need to rebuild partorder
10443: $metaentry{':partorder'}='';
10444: $metathesekeys{'partorder'}=1;
10445: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10446: if ($origfileimportpartids[$index] eq 'part') {
10447: # original part, part of the problem
10448: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10449: } else {
10450: # we have imported parts at this position
10451: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10452: }
10453: }
10454: $metaentry{':partorder'}=~s/^\,//;
10455: }
10456:
1.737 albertel 10457: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 10458: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10459: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 10460: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 10461: # this is the end of "was not already recently cached
1.71 www 10462: }
1.599 albertel 10463: return $metaentry{':'.$what};
1.261 albertel 10464: }
10465:
1.488 albertel 10466: sub metadata_create_package_def {
1.483 albertel 10467: my ($uri,$key,$package,$metathesekeys)=@_;
10468: my ($pack,$name,$subp)=split(/\&/,$key);
10469: if ($subp eq 'default') { next; }
10470:
1.599 albertel 10471: if (defined($metaentry{':packages'})) {
10472: $metaentry{':packages'}.=','.$package;
1.483 albertel 10473: } else {
1.599 albertel 10474: $metaentry{':packages'}=$package;
1.483 albertel 10475: }
10476: my $value=$packagetab{$key};
10477: my $unikey;
10478: $unikey='parameter_0_'.$name;
1.599 albertel 10479: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 10480: $$metathesekeys{$unikey}=1;
1.599 albertel 10481: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10482: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 10483: }
1.599 albertel 10484: if (defined($metaentry{':'.$unikey.'.default'})) {
10485: $metaentry{':'.$unikey}=
10486: $metaentry{':'.$unikey.'.default'};
1.483 albertel 10487: }
10488: }
10489:
1.261 albertel 10490: sub metadata_generate_part0 {
10491: my ($metadata,$metacache,$uri) = @_;
10492: my %allnames;
1.737 albertel 10493: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 10494: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 10495: my $part=$$metacache{':'.$metakey.'.part'};
10496: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 10497: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 10498: $allnames{$name}=$part;
10499: }
10500: }
10501: }
10502: foreach my $name (keys(%allnames)) {
10503: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 10504: my $key=":parameter_0_$name";
1.261 albertel 10505: $$metacache{"$key.part"}='0';
10506: $$metacache{"$key.name"}=$name;
1.428 albertel 10507: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 10508: $allnames{$name}.'_'.$name.
10509: '.type'};
1.428 albertel 10510: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 10511: '.display'};
1.644 www 10512: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 10513: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 10514: $$metacache{"$key.display"}=$olddis;
10515: }
1.71 www 10516: }
10517:
1.764 albertel 10518: # ------------------------------------------------------ Devalidate title cache
10519:
10520: sub devalidate_title_cache {
10521: my ($url)=@_;
10522: if (!$env{'request.course.id'}) { return; }
10523: my $symb=&symbread($url);
10524: if (!$symb) { return; }
10525: my $key=$env{'request.course.id'}."\0".$symb;
10526: &devalidate_cache_new('title',$key);
10527: }
10528:
1.1014 droeschl 10529: # ------------------------------------------------- Get the title of a course
10530:
10531: sub current_course_title {
10532: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10533: }
1.301 www 10534: # ------------------------------------------------- Get the title of a resource
10535:
10536: sub gettitle {
10537: my $urlsymb=shift;
10538: my $symb=&symbread($urlsymb);
1.534 albertel 10539: if ($symb) {
1.620 albertel 10540: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 10541: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 10542: if (defined($cached)) {
10543: return $result;
10544: }
1.534 albertel 10545: my ($map,$resid,$url)=&decode_symb($symb);
10546: my $title='';
1.907 albertel 10547: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10548: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10549: } else {
10550: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10551: &GDBM_READER(),0640)) {
10552: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10553: $title=$bighash{'title_'.$mapid.'.'.$resid};
10554: untie(%bighash);
10555: }
1.534 albertel 10556: }
10557: $title=~s/\&colon\;/\:/gs;
10558: if ($title) {
1.1159 www 10559: # Remember both $symb and $title for dynamic metadata
10560: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 10561: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 10562: # Cache this title and then return it
1.599 albertel 10563: return &do_cache_new('title',$key,$title,600);
1.534 albertel 10564: }
10565: $urlsymb=$url;
10566: }
10567: my $title=&metadata($urlsymb,'title');
10568: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10569: return $title;
1.301 www 10570: }
1.613 albertel 10571:
1.614 albertel 10572: sub get_slot {
10573: my ($which,$cnum,$cdom)=@_;
10574: if (!$cnum || !$cdom) {
1.790 albertel 10575: (undef,my $courseid)=&whichuser();
1.620 albertel 10576: $cdom=$env{'course.'.$courseid.'.domain'};
10577: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 10578: }
1.703 albertel 10579: my $key=join("\0",'slots',$cdom,$cnum,$which);
10580: my %slotinfo;
10581: if (exists($remembered{$key})) {
10582: $slotinfo{$which} = $remembered{$key};
10583: } else {
10584: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10585: &Apache::lonhomework::showhash(%slotinfo);
10586: my ($tmp)=keys(%slotinfo);
10587: if ($tmp=~/^error:/) { return (); }
10588: $remembered{$key} = $slotinfo{$which};
10589: }
1.616 albertel 10590: if (ref($slotinfo{$which}) eq 'HASH') {
10591: return %{$slotinfo{$which}};
10592: }
10593: return $slotinfo{$which};
1.614 albertel 10594: }
1.1150 raeburn 10595:
10596: sub get_reservable_slots {
10597: my ($cnum,$cdom,$uname,$udom) = @_;
10598: my $now = time;
10599: my $reservable_info;
10600: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10601: if (exists($remembered{$key})) {
10602: $reservable_info = $remembered{$key};
10603: } else {
10604: my %resv;
10605: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10606: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10607: $reservable_info = \%resv;
10608: $remembered{$key} = $reservable_info;
10609: }
10610: return $reservable_info;
10611: }
10612:
10613: sub get_course_slots {
10614: my ($cnum,$cdom) = @_;
10615: my $hashid=$cnum.':'.$cdom;
10616: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10617: if (defined($cached)) {
10618: if (ref($result) eq 'HASH') {
10619: return %{$result};
10620: }
10621: } else {
10622: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10623: my ($tmp) = keys(%slots);
10624: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219 raeburn 10625: &do_cache_new('allslots',$hashid,\%slots,600);
1.1150 raeburn 10626: return %slots;
10627: }
10628: }
10629: return;
10630: }
10631:
10632: sub devalidate_slots_cache {
10633: my ($cnum,$cdom)=@_;
10634: my $hashid=$cnum.':'.$cdom;
10635: &devalidate_cache_new('allslots',$hashid);
10636: }
10637:
1.1181 raeburn 10638: sub get_coursechange {
10639: my ($cdom,$cnum) = @_;
10640: if ($cdom eq '' || $cnum eq '') {
10641: return unless ($env{'request.course.id'});
10642: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10643: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10644: }
10645: my $hashid=$cdom.'_'.$cnum;
10646: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10647: if ((defined($cached)) && ($change ne '')) {
10648: return $change;
10649: } else {
10650: my %crshash;
10651: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10652: if ($crshash{'internal.contentchange'} eq '') {
10653: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10654: if ($change eq '') {
10655: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10656: $change = $crshash{'internal.created'};
10657: }
10658: } else {
10659: $change = $crshash{'internal.contentchange'};
10660: }
10661: my $cachetime = 600;
10662: &do_cache_new('crschange',$hashid,$change,$cachetime);
10663: }
10664: return $change;
10665: }
10666:
10667: sub devalidate_coursechange_cache {
10668: my ($cnum,$cdom)=@_;
10669: my $hashid=$cnum.':'.$cdom;
10670: &devalidate_cache_new('crschange',$hashid);
10671: }
10672:
1.31 www 10673: # ------------------------------------------------- Update symbolic store links
10674:
10675: sub symblist {
10676: my ($mapname,%newhash)=@_;
1.438 www 10677: $mapname=&deversion(&declutter($mapname));
1.31 www 10678: my %hash;
1.620 albertel 10679: if (($env{'request.course.fn'}) && (%newhash)) {
10680: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10681: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10682: foreach my $url (keys(%newhash)) {
1.711 albertel 10683: next if ($url eq 'last_known'
10684: && $env{'form.no_update_last_known'});
10685: $hash{declutter($url)}=&encode_symb($mapname,
10686: $newhash{$url}->[1],
10687: $newhash{$url}->[0]);
1.191 harris41 10688: }
1.31 www 10689: if (untie(%hash)) {
10690: return 'ok';
10691: }
10692: }
10693: }
10694: return 'error';
1.212 www 10695: }
10696:
10697: # --------------------------------------------------------------- Verify a symb
10698:
10699: sub symbverify {
1.1190 raeburn 10700: my ($symb,$thisurl,$encstate)=@_;
1.510 www 10701: my $thisfn=$thisurl;
1.439 www 10702: $thisfn=&declutter($thisfn);
1.215 www 10703: # direct jump to resource in page or to a sequence - will construct own symbs
10704: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10705: # check URL part
1.409 www 10706: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10707:
1.431 www 10708: unless ($url eq $thisfn) { return 0; }
1.213 www 10709:
1.216 www 10710: $symb=&symbclean($symb);
1.510 www 10711: $thisurl=&deversion($thisurl);
1.439 www 10712: $thisfn=&deversion($thisfn);
1.213 www 10713:
10714: my %bighash;
10715: my $okay=0;
1.431 www 10716:
1.620 albertel 10717: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10718: &GDBM_READER(),0640)) {
1.1204 raeburn 10719: my $noclutter;
1.1032 raeburn 10720: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10721: $thisurl =~ s/\?.+$//;
1.1204 raeburn 10722: if ($map =~ m{^uploaded/.+\.page$}) {
10723: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10724: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10725: $noclutter = 1;
10726: }
10727: }
10728: my $ids;
10729: if ($noclutter) {
10730: $ids=$bighash{'ids_'.$thisurl};
10731: } else {
10732: $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032 raeburn 10733: }
1.1102 raeburn 10734: unless ($ids) {
10735: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10736: $ids=$bighash{$idkey};
1.216 www 10737: }
10738: if ($ids) {
10739: # ------------------------------------------------------------------- Has ID(s)
1.1202 raeburn 10740: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203 raeburn 10741: $symb =~ s/\?.+$//;
1.1202 raeburn 10742: }
1.800 albertel 10743: foreach my $id (split(/\,/,$ids)) {
10744: my ($mapid,$resid)=split(/\./,$id);
1.216 www 10745: if (
10746: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190 raeburn 10747: eq $symb) {
10748: if (ref($encstate)) {
10749: $$encstate = $bighash{'encrypted_'.$id};
10750: }
1.620 albertel 10751: if (($env{'request.role.adv'}) ||
1.1101 raeburn 10752: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10753: ($thisurl eq '/adm/navmaps')) {
1.1190 raeburn 10754: $okay=1;
1.1202 raeburn 10755: last;
1.582 albertel 10756: }
10757: }
1.216 www 10758: }
10759: }
1.213 www 10760: untie(%bighash);
10761: }
10762: return $okay;
1.31 www 10763: }
10764:
1.210 www 10765: # --------------------------------------------------------------- Clean-up symb
10766:
10767: sub symbclean {
10768: my $symb=shift;
1.568 albertel 10769: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10770: # remove version from map
10771: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10772:
1.210 www 10773: # remove version from URL
10774: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10775:
1.507 www 10776: # remove wrapper
10777:
1.510 www 10778: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10779: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10780: return $symb;
1.409 www 10781: }
10782:
10783: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10784:
10785: sub encode_symb {
10786: my ($map,$resid,$url)=@_;
10787: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10788: }
1.409 www 10789:
10790: sub decode_symb {
1.568 albertel 10791: my $symb=shift;
10792: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10793: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10794: return (&fixversion($map),$resid,&fixversion($url));
10795: }
10796:
10797: sub fixversion {
10798: my $fn=shift;
1.609 banghart 10799: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10800: my %bighash;
10801: my $uri=&clutter($fn);
1.620 albertel 10802: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10803: # is this cached?
1.599 albertel 10804: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10805: if (defined($cached)) { return $result; }
10806: # unfortunately not cached, or expired
1.620 albertel 10807: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10808: &GDBM_READER(),0640)) {
10809: if ($bighash{'version_'.$uri}) {
10810: my $version=$bighash{'version_'.$uri};
1.444 www 10811: unless (($version eq 'mostrecent') ||
10812: ($version==&getversion($uri))) {
1.440 www 10813: $uri=~s/\.(\w+)$/\.$version\.$1/;
10814: }
10815: }
10816: untie %bighash;
1.413 www 10817: }
1.599 albertel 10818: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10819: }
10820:
10821: sub deversion {
10822: my $url=shift;
10823: $url=~s/\.\d+\.(\w+)$/\.$1/;
10824: return $url;
1.210 www 10825: }
10826:
1.31 www 10827: # ------------------------------------------------------ Return symb list entry
10828:
10829: sub symbread {
1.249 www 10830: my ($thisfn,$donotrecurse)=@_;
1.1206 raeburn 10831: my $cache_str;
10832: if ($thisfn ne '') {
10833: $cache_str='request.symbread.cached.'.$thisfn;
10834: if ($env{$cache_str} ne '') {
1.1179 raeburn 10835: return $env{$cache_str};
10836: }
1.1206 raeburn 10837: } else {
1.242 www 10838: # no filename provided? try from environment
1.620 albertel 10839: if ($env{'request.symb'}) {
10840: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 10841: }
1.620 albertel 10842: $thisfn=$env{'request.filename'};
1.44 www 10843: }
1.569 albertel 10844: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10845: # is that filename actually a symb? Verify, clean, and return
10846: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10847: if (&symbverify($thisfn,$1)) {
1.620 albertel 10848: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10849: }
1.242 www 10850: }
1.44 www 10851: $thisfn=declutter($thisfn);
1.31 www 10852: my %hash;
1.37 www 10853: my %bighash;
10854: my $syval='';
1.620 albertel 10855: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10856: my $targetfn = $thisfn;
1.609 banghart 10857: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10858: $targetfn = 'adm/wrapper/'.$thisfn;
10859: }
1.687 albertel 10860: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10861: $targetfn=$1;
10862: }
1.620 albertel 10863: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10864: &GDBM_READER(),0640)) {
1.481 raeburn 10865: $syval=$hash{$targetfn};
1.37 www 10866: untie(%hash);
10867: }
10868: # ---------------------------------------------------------- There was an entry
10869: if ($syval) {
1.601 albertel 10870: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10871: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10872: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10873: #return $env{$cache_str}='';
1.601 albertel 10874: #}
10875: #$syval.=$1;
10876: #}
1.37 www 10877: } else {
10878: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10879: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10880: &GDBM_READER(),0640)) {
1.37 www 10881: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10882: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10883: unless ($ids) {
10884: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10885: }
10886: unless ($ids) {
10887: # alias?
10888: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10889: }
1.37 www 10890: if ($ids) {
10891: # ------------------------------------------------------------------- Has ID(s)
10892: my @possibilities=split(/\,/,$ids);
1.39 www 10893: if ($#possibilities==0) {
10894: # ----------------------------------------------- There is only one possibility
1.37 www 10895: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10896: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10897: $resid,$thisfn);
1.249 www 10898: } elsif (!$donotrecurse) {
1.39 www 10899: # ------------------------------------------ There is more than one possibility
10900: my $realpossible=0;
1.800 albertel 10901: foreach my $id (@possibilities) {
10902: my $file=$bighash{'src_'.$id};
1.39 www 10903: if (&allowed('bre',$file)) {
1.800 albertel 10904: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10905: if ($bighash{'map_type_'.$mapid} ne 'page') {
10906: $realpossible++;
1.626 albertel 10907: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10908: $resid,$thisfn);
1.39 www 10909: }
10910: }
1.191 harris41 10911: }
1.39 www 10912: if ($realpossible!=1) { $syval=''; }
1.249 www 10913: } else {
10914: $syval='';
1.37 www 10915: }
10916: }
10917: untie(%bighash)
1.481 raeburn 10918: }
1.31 www 10919: }
1.62 www 10920: if ($syval) {
1.620 albertel 10921: return $env{$cache_str}=$syval;
1.62 www 10922: }
1.31 www 10923: }
1.949 raeburn 10924: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10925: return $env{$cache_str}='';
1.31 www 10926: }
10927:
10928: # ---------------------------------------------------------- Return random seed
10929:
1.32 www 10930: sub numval {
10931: my $txt=shift;
10932: $txt=~tr/A-J/0-9/;
10933: $txt=~tr/a-j/0-9/;
10934: $txt=~tr/K-T/0-9/;
10935: $txt=~tr/k-t/0-9/;
10936: $txt=~tr/U-Z/0-5/;
10937: $txt=~tr/u-z/0-5/;
10938: $txt=~s/\D//g;
1.564 albertel 10939: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10940: return int($txt);
1.368 albertel 10941: }
10942:
1.484 albertel 10943: sub numval2 {
10944: my $txt=shift;
10945: $txt=~tr/A-J/0-9/;
10946: $txt=~tr/a-j/0-9/;
10947: $txt=~tr/K-T/0-9/;
10948: $txt=~tr/k-t/0-9/;
10949: $txt=~tr/U-Z/0-5/;
10950: $txt=~tr/u-z/0-5/;
10951: $txt=~s/\D//g;
10952: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10953: my $total;
10954: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10955: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10956: return int($total);
10957: }
10958:
1.575 albertel 10959: sub numval3 {
10960: use integer;
10961: my $txt=shift;
10962: $txt=~tr/A-J/0-9/;
10963: $txt=~tr/a-j/0-9/;
10964: $txt=~tr/K-T/0-9/;
10965: $txt=~tr/k-t/0-9/;
10966: $txt=~tr/U-Z/0-5/;
10967: $txt=~tr/u-z/0-5/;
10968: $txt=~s/\D//g;
10969: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10970: my $total;
10971: foreach my $val (@txts) { $total+=$val; }
10972: if ($_64bit) { $total=(($total<<32)>>32); }
10973: return $total;
10974: }
10975:
1.675 albertel 10976: sub digest {
10977: my ($data)=@_;
10978: my $digest=&Digest::MD5::md5($data);
10979: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10980: my ($e,$f);
10981: {
10982: use integer;
10983: $e=($a+$b);
10984: $f=($c+$d);
10985: if ($_64bit) {
10986: $e=(($e<<32)>>32);
10987: $f=(($f<<32)>>32);
10988: }
10989: }
10990: if (wantarray) {
10991: return ($e,$f);
10992: } else {
10993: my $g;
10994: {
10995: use integer;
10996: $g=($e+$f);
10997: if ($_64bit) {
10998: $g=(($g<<32)>>32);
10999: }
11000: }
11001: return $g;
11002: }
11003: }
11004:
1.368 albertel 11005: sub latest_rnd_algorithm_id {
1.675 albertel 11006: return '64bit5';
1.366 albertel 11007: }
1.32 www 11008:
1.503 albertel 11009: sub get_rand_alg {
11010: my ($courseid)=@_;
1.790 albertel 11011: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 11012: if ($courseid) {
1.620 albertel 11013: return $env{"course.$courseid.rndseed"};
1.503 albertel 11014: }
11015: return &latest_rnd_algorithm_id();
11016: }
11017:
1.562 albertel 11018: sub validCODE {
11019: my ($CODE)=@_;
11020: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11021: return 0;
11022: }
11023:
1.491 albertel 11024: sub getCODE {
1.620 albertel 11025: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 11026: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11027: defined($Apache::lonhomework::parsing_a_task) ) &&
11028: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 11029: return $Apache::lonhomework::history{'resource.CODE'};
11030: }
11031: return undef;
11032: }
1.1133 foxr 11033: #
11034: # Determines the random seed for a specific context:
11035: #
11036: # parameters:
11037: # symb - in course context the symb for the seed.
11038: # course_id - The course id of the form domain_coursenum.
11039: # domain - Domain for the user.
11040: # course - Course for the user.
11041: # cenv - environment of the course.
11042: #
11043: # NOTE:
11044: # All parameters are picked out of the environment if missing
11045: # or not defined.
11046: # If a symb cannot be determined the current time is used instead.
11047: #
11048: # For a given well defined symb, courside, domain, username,
11049: # and course environment, the seed is reproducible.
11050: #
1.31 www 11051: sub rndseed {
1.1133 foxr 11052: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 11053: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 11054: if (!defined($symb)) {
1.366 albertel 11055: unless ($symb=$wsymb) { return time; }
11056: }
1.1146 foxr 11057: if (!defined $courseid) {
11058: $courseid=$wcourseid;
11059: }
11060: if (!defined $domain) { $domain=$wdomain; }
11061: if (!defined $username) { $username=$wusername }
1.1133 foxr 11062:
11063: my $which;
11064: if (defined($cenv->{'rndseed'})) {
11065: $which = $cenv->{'rndseed'};
11066: } else {
11067: $which =&get_rand_alg($courseid);
11068: }
1.491 albertel 11069: if (defined(&getCODE())) {
1.1133 foxr 11070:
1.675 albertel 11071: if ($which eq '64bit5') {
11072: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11073: } elsif ($which eq '64bit4') {
1.575 albertel 11074: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11075: } else {
11076: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11077: }
1.675 albertel 11078: } elsif ($which eq '64bit5') {
11079: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 11080: } elsif ($which eq '64bit4') {
11081: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 11082: } elsif ($which eq '64bit3') {
11083: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 11084: } elsif ($which eq '64bit2') {
11085: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 11086: } elsif ($which eq '64bit') {
11087: return &rndseed_64bit($symb,$courseid,$domain,$username);
11088: }
11089: return &rndseed_32bit($symb,$courseid,$domain,$username);
11090: }
11091:
11092: sub rndseed_32bit {
11093: my ($symb,$courseid,$domain,$username)=@_;
11094: {
11095: use integer;
11096: my $symbchck=unpack("%32C*",$symb) << 27;
11097: my $symbseed=numval($symb) << 22;
11098: my $namechck=unpack("%32C*",$username) << 17;
11099: my $nameseed=numval($username) << 12;
11100: my $domainseed=unpack("%32C*",$domain) << 7;
11101: my $courseseed=unpack("%32C*",$courseid);
11102: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 11103: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11104: #&logthis("rndseed :$num:$symb");
1.564 albertel 11105: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 11106: return $num;
11107: }
11108: }
11109:
11110: sub rndseed_64bit {
11111: my ($symb,$courseid,$domain,$username)=@_;
11112: {
11113: use integer;
11114: my $symbchck=unpack("%32S*",$symb) << 21;
11115: my $symbseed=numval($symb) << 10;
11116: my $namechck=unpack("%32S*",$username);
11117:
11118: my $nameseed=numval($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 :$num:$symb");
1.564 albertel 11126: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 11127: return "$num1,$num2";
1.155 albertel 11128: }
1.366 albertel 11129: }
11130:
1.443 albertel 11131: sub rndseed_64bit2 {
11132: my ($symb,$courseid,$domain,$username)=@_;
11133: {
11134: use integer;
11135: # strings need to be an even # of cahracters long, it it is odd the
11136: # last characters gets thrown away
11137: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11138: my $symbseed=numval($symb) << 10;
11139: my $namechck=unpack("%32S*",$username.' ');
11140:
11141: my $nameseed=numval($username) << 21;
1.501 albertel 11142: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11143: my $courseseed=unpack("%32S*",$courseid.' ');
11144:
11145: my $num1=$symbchck+$symbseed+$namechck;
11146: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11147: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11148: #&logthis("rndseed :$num:$symb");
1.803 albertel 11149: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 11150: return "$num1,$num2";
11151: }
11152: }
11153:
11154: sub rndseed_64bit3 {
11155: my ($symb,$courseid,$domain,$username)=@_;
11156: {
11157: use integer;
11158: # strings need to be an even # of cahracters long, it it is odd the
11159: # last characters gets thrown away
11160: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11161: my $symbseed=numval2($symb) << 10;
11162: my $namechck=unpack("%32S*",$username.' ');
11163:
11164: my $nameseed=numval2($username) << 21;
1.443 albertel 11165: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11166: my $courseseed=unpack("%32S*",$courseid.' ');
11167:
11168: my $num1=$symbchck+$symbseed+$namechck;
11169: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11170: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11171: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 11172: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11173:
1.503 albertel 11174: return "$num1:$num2";
1.443 albertel 11175: }
11176: }
11177:
1.575 albertel 11178: sub rndseed_64bit4 {
11179: my ($symb,$courseid,$domain,$username)=@_;
11180: {
11181: use integer;
11182: # strings need to be an even # of cahracters long, it it is odd the
11183: # last characters gets thrown away
11184: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11185: my $symbseed=numval3($symb) << 10;
11186: my $namechck=unpack("%32S*",$username.' ');
11187:
11188: my $nameseed=numval3($username) << 21;
11189: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11190: my $courseseed=unpack("%32S*",$courseid.' ');
11191:
11192: my $num1=$symbchck+$symbseed+$namechck;
11193: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 11194: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11195: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 11196: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 11197:
1.575 albertel 11198: return "$num1:$num2";
11199: }
11200: }
11201:
1.675 albertel 11202: sub rndseed_64bit5 {
11203: my ($symb,$courseid,$domain,$username)=@_;
11204: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11205: return "$num1:$num2";
11206: }
11207:
1.366 albertel 11208: sub rndseed_CODE_64bit {
11209: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 11210: {
1.366 albertel 11211: use integer;
1.443 albertel 11212: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 11213: my $symbseed=numval2($symb);
1.491 albertel 11214: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11215: my $CODEseed=numval(&getCODE());
1.443 albertel 11216: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 11217: my $num1=$symbseed+$CODEchck;
11218: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11219: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11220: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 11221: if ($_64bit) { $num1=(($num1<<32)>>32); }
11222: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 11223: return "$num1:$num2";
1.366 albertel 11224: }
11225: }
11226:
1.575 albertel 11227: sub rndseed_CODE_64bit4 {
11228: my ($symb,$courseid,$domain,$username)=@_;
11229: {
11230: use integer;
11231: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11232: my $symbseed=numval3($symb);
11233: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11234: my $CODEseed=numval3(&getCODE());
11235: my $courseseed=unpack("%32S*",$courseid.' ');
11236: my $num1=$symbseed+$CODEchck;
11237: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 11238: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11239: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 11240: if ($_64bit) { $num1=(($num1<<32)>>32); }
11241: if ($_64bit) { $num2=(($num2<<32)>>32); }
11242: return "$num1:$num2";
11243: }
11244: }
11245:
1.675 albertel 11246: sub rndseed_CODE_64bit5 {
11247: my ($symb,$courseid,$domain,$username)=@_;
11248: my $code = &getCODE();
11249: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11250: return "$num1:$num2";
11251: }
11252:
1.366 albertel 11253: sub setup_random_from_rndseed {
11254: my ($rndseed)=@_;
1.503 albertel 11255: if ($rndseed =~/([,:])/) {
11256: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 11257: &Math::Random::random_set_seed(abs($num1),abs($num2));
11258: } else {
11259: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 11260: }
1.36 albertel 11261: }
11262:
1.474 albertel 11263: sub latest_receipt_algorithm_id {
1.835 albertel 11264: return 'receipt3';
1.474 albertel 11265: }
11266:
1.480 www 11267: sub recunique {
11268: my $fucourseid=shift;
11269: my $unique;
1.835 albertel 11270: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11271: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11272: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 11273: } else {
11274: $unique=$perlvar{'lonReceipt'};
11275: }
11276: return unpack("%32C*",$unique);
11277: }
11278:
11279: sub recprefix {
11280: my $fucourseid=shift;
11281: my $prefix;
1.835 albertel 11282: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11283: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 11284: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 11285: } else {
11286: $prefix=$perlvar{'lonHostID'};
11287: }
11288: return unpack("%32C*",$prefix);
11289: }
11290:
1.76 www 11291: sub ireceipt {
1.474 albertel 11292: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 11293:
11294: my $return =&recprefix($fucourseid).'-';
11295:
11296: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11297: $env{'request.state'} eq 'construct') {
11298: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11299: return $return;
11300: }
11301:
1.76 www 11302: my $cuname=unpack("%32C*",$funame);
11303: my $cudom=unpack("%32C*",$fudom);
11304: my $cucourseid=unpack("%32C*",$fucourseid);
11305: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 11306: my $cunique=&recunique($fucourseid);
1.474 albertel 11307: my $cpart=unpack("%32S*",$part);
1.835 albertel 11308: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11309:
1.790 albertel 11310: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 11311:
11312: $return.= ($cunique%$cuname+
11313: $cunique%$cudom+
11314: $cusymb%$cuname+
11315: $cusymb%$cudom+
11316: $cucourseid%$cuname+
11317: $cucourseid%$cudom+
11318: $cpart%$cuname+
11319: $cpart%$cudom);
11320: } else {
11321: $return.= ($cunique%$cuname+
11322: $cunique%$cudom+
11323: $cusymb%$cuname+
11324: $cusymb%$cudom+
11325: $cucourseid%$cuname+
11326: $cucourseid%$cudom);
11327: }
11328: return $return;
1.76 www 11329: }
11330:
11331: sub receipt {
1.474 albertel 11332: my ($part)=@_;
1.790 albertel 11333: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 11334: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 11335: }
1.260 ng 11336:
1.790 albertel 11337: sub whichuser {
11338: my ($passedsymb)=@_;
11339: my ($symb,$courseid,$domain,$name,$publicuser);
11340: if (defined($env{'form.grade_symb'})) {
11341: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11342: my $allowed=&allowed('vgr',$tmp_courseid);
11343: if (!$allowed &&
11344: exists($env{'request.course.sec'}) &&
11345: $env{'request.course.sec'} !~ /^\s*$/) {
11346: $allowed=&allowed('vgr',$tmp_courseid.
11347: '/'.$env{'request.course.sec'});
11348: }
11349: if ($allowed) {
11350: ($symb)=&get_env_multiple('form.grade_symb');
11351: $courseid=$tmp_courseid;
11352: ($domain)=&get_env_multiple('form.grade_domain');
11353: ($name)=&get_env_multiple('form.grade_username');
11354: return ($symb,$courseid,$domain,$name,$publicuser);
11355: }
11356: }
11357: if (!$passedsymb) {
11358: $symb=&symbread();
11359: } else {
11360: $symb=$passedsymb;
11361: }
11362: $courseid=$env{'request.course.id'};
11363: $domain=$env{'user.domain'};
11364: $name=$env{'user.name'};
11365: if ($name eq 'public' && $domain eq 'public') {
11366: if (!defined($env{'form.username'})) {
11367: $env{'form.username'}.=time.rand(10000000);
11368: }
11369: $name.=$env{'form.username'};
11370: }
11371: return ($symb,$courseid,$domain,$name,$publicuser);
11372:
11373: }
11374:
1.36 albertel 11375: # ------------------------------------------------------------ Serves up a file
1.472 albertel 11376: # returns either the contents of the file or
11377: # -1 if the file doesn't exist
1.481 raeburn 11378: #
11379: # if the target is a file that was uploaded via DOCS,
11380: # a check will be made to see if a current copy exists on the local server,
11381: # if it does this will be served, otherwise a copy will be retrieved from
11382: # the home server for the course and stored in /home/httpd/html/userfiles on
11383: # the local server.
1.472 albertel 11384:
1.36 albertel 11385: sub getfile {
1.538 albertel 11386: my ($file) = @_;
1.609 banghart 11387: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 11388: &repcopy($file);
11389: return &readfile($file);
11390: }
11391:
11392: sub repcopy_userfile {
11393: my ($file)=@_;
1.1142 raeburn 11394: my $londocroot = $perlvar{'lonDocRoot'};
11395: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 11396: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 11397: my ($cdom,$cnum,$filename) =
1.811 albertel 11398: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 11399: my $uri="/uploaded/$cdom/$cnum/$filename";
11400: if (-e "$file") {
1.828 www 11401: # we already have a local copy, check it out
1.538 albertel 11402: my @fileinfo = stat($file);
1.828 www 11403: my $rtncode;
11404: my $info;
1.538 albertel 11405: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 11406: if ($lwpresp ne 'ok') {
1.828 www 11407: # there is no such file anymore, even though we had a local copy
1.482 albertel 11408: if ($rtncode eq '404') {
1.538 albertel 11409: unlink($file);
1.482 albertel 11410: }
11411: return -1;
11412: }
11413: if ($info < $fileinfo[9]) {
1.828 www 11414: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 11415: return 'ok';
1.828 www 11416: } else {
11417: # the file is outdated, get rid of it
11418: unlink($file);
1.482 albertel 11419: }
1.828 www 11420: }
11421: # one way or the other, at this point, we don't have the file
11422: # construct the correct path for the file
11423: my @parts = ($cdom,$cnum);
11424: if ($filename =~ m|^(.+)/[^/]+$|) {
11425: push @parts, split(/\//,$1);
11426: }
11427: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11428: foreach my $part (@parts) {
11429: $path .= '/'.$part;
11430: if (!-e $path) {
11431: mkdir($path,0770);
1.482 albertel 11432: }
11433: }
1.828 www 11434: # now the path exists for sure
11435: # get a user agent
11436: my $ua=new LWP::UserAgent;
11437: my $transferfile=$file.'.in.transfer';
11438: # FIXME: this should flock
11439: if (-e $transferfile) { return 'ok'; }
11440: my $request;
11441: $uri=~s/^\///;
1.980 raeburn 11442: my $homeserver = &homeserver($cnum,$cdom);
11443: my $protocol = $protocol{$homeserver};
11444: $protocol = 'http' if ($protocol ne 'https');
11445: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 11446: my $response=$ua->request($request,$transferfile);
11447: # did it work?
11448: if ($response->is_error()) {
11449: unlink($transferfile);
11450: &logthis("Userfile repcopy failed for $uri");
11451: return -1;
11452: }
11453: # worked, rename the transfer file
11454: rename($transferfile,$file);
1.607 raeburn 11455: return 'ok';
1.481 raeburn 11456: }
11457:
1.517 albertel 11458: sub tokenwrapper {
11459: my $uri=shift;
1.980 raeburn 11460: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 11461: $uri=~s|^/||;
1.620 albertel 11462: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 11463: my $token=$1;
1.552 albertel 11464: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11465: if ($udom && $uname && $file) {
11466: $file=~s|(\?\.*)*$||;
1.949 raeburn 11467: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 11468: my $homeserver = &homeserver($uname,$udom);
11469: my $protocol = $protocol{$homeserver};
11470: $protocol = 'http' if ($protocol ne 'https');
11471: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 11472: (($uri=~/\?/)?'&':'?').'token='.$token.
11473: '&tokenissued='.$perlvar{'lonHostID'};
11474: } else {
11475: return '/adm/notfound.html';
11476: }
11477: }
11478:
1.828 www 11479: # call with reqtype HEAD: get last modification time
11480: # call with reqtype GET: get the file contents
11481: # Do not call this with reqtype GET for large files! It loads everything into memory
11482: #
1.481 raeburn 11483: sub getuploaded {
11484: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11485: $uri=~s/^\///;
1.980 raeburn 11486: my $homeserver = &homeserver($cnum,$cdom);
11487: my $protocol = $protocol{$homeserver};
11488: $protocol = 'http' if ($protocol ne 'https');
11489: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 11490: my $ua=new LWP::UserAgent;
11491: my $request=new HTTP::Request($reqtype,$uri);
11492: my $response=$ua->request($request);
11493: $$rtncode = $response->code;
1.482 albertel 11494: if (! $response->is_success()) {
11495: return 'failed';
11496: }
11497: if ($reqtype eq 'HEAD') {
1.486 www 11498: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 11499: } elsif ($reqtype eq 'GET') {
11500: $$info = $response->content;
1.472 albertel 11501: }
1.482 albertel 11502: return 'ok';
1.36 albertel 11503: }
11504:
1.481 raeburn 11505: sub readfile {
11506: my $file = shift;
11507: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11508: my $fh;
11509: open($fh,"<$file");
11510: my $a='';
1.800 albertel 11511: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 11512: return $a;
11513: }
11514:
1.36 albertel 11515: sub filelocation {
1.590 banghart 11516: my ($dir,$file) = @_;
11517: my $location;
11518: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 11519:
11520: if ($file =~ m-^/adm/-) {
11521: $file=~s-^/adm/wrapper/-/-;
11522: $file=~s-^/adm/coursedocs/showdoc/-/-;
11523: }
1.882 albertel 11524:
1.1139 www 11525: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 11526: $location = $file;
1.609 banghart 11527: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 11528: my ($udom,$uname,$filename)=
1.811 albertel 11529: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 11530: my $home=&homeserver($uname,$udom);
11531: my $is_me=0;
11532: my @ids=¤t_machine_ids();
11533: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11534: if ($is_me) {
1.1117 foxr 11535: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 11536: } else {
11537: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11538: $udom.'/'.$uname.'/'.$filename;
11539: }
1.882 albertel 11540: } elsif ($file =~ m-^/adm/-) {
11541: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 11542: } else {
11543: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 11544: $file=~s:^/(res|priv)/:/:;
11545: my $space=$1;
1.590 banghart 11546: if ( !( $file =~ m:^/:) ) {
11547: $location = $dir. '/'.$file;
11548: } else {
1.1142 raeburn 11549: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 11550: }
1.59 albertel 11551: }
1.590 banghart 11552: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 11553: while ($location=~m{/\.\./}) {
11554: if ($location =~ m{/[^/]+/\.\./}) {
11555: $location=~ s{/[^/]+/\.\./}{/}g;
11556: } else {
11557: $location=~ s{/\.\./}{/}g;
11558: }
11559: } #remove dir/..
1.590 banghart 11560: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11561: return $location;
1.46 www 11562: }
1.36 albertel 11563:
1.46 www 11564: sub hreflocation {
11565: my ($dir,$file)=@_;
1.980 raeburn 11566: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 11567: $file=filelocation($dir,$file);
1.700 albertel 11568: } elsif ($file=~m-^/adm/-) {
11569: $file=~s-^/adm/wrapper/-/-;
11570: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 11571: }
11572: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11573: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11574: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 11575: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11576: {/uploaded/$1/$2/}x;
1.46 www 11577: }
1.913 albertel 11578: if ($file=~ m{^/userfiles/}) {
11579: $file =~ s{^/userfiles/}{/uploaded/};
11580: }
1.462 albertel 11581: return $file;
1.465 albertel 11582: }
11583:
1.1139 www 11584:
11585:
11586:
11587:
1.465 albertel 11588: sub current_machine_domains {
1.853 albertel 11589: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11590: }
11591:
11592: sub machine_domains {
11593: my ($hostname) = @_;
1.465 albertel 11594: my @domains;
1.838 albertel 11595: my %hostname = &all_hostnames();
1.465 albertel 11596: while( my($id, $name) = each(%hostname)) {
1.467 matthew 11597: # &logthis("-$id-$name-$hostname-");
1.465 albertel 11598: if ($hostname eq $name) {
1.844 albertel 11599: push(@domains,&host_domain($id));
1.465 albertel 11600: }
11601: }
11602: return @domains;
11603: }
11604:
11605: sub current_machine_ids {
1.853 albertel 11606: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11607: }
11608:
11609: sub machine_ids {
11610: my ($hostname) = @_;
11611: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 11612: my @ids;
1.888 albertel 11613: my %name_to_host = &all_names();
1.889 albertel 11614: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11615: return @{ $name_to_host{$hostname} };
11616: }
11617: return;
1.31 www 11618: }
11619:
1.824 raeburn 11620: sub additional_machine_domains {
11621: my @domains;
11622: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11623: while( my $line = <$fh>) {
11624: $line =~ s/\s//g;
11625: push(@domains,$line);
11626: }
11627: return @domains;
11628: }
11629:
11630: sub default_login_domain {
11631: my $domain = $perlvar{'lonDefDomain'};
11632: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11633: foreach my $posdom (¤t_machine_domains(),
11634: &additional_machine_domains()) {
11635: if (lc($posdom) eq lc($testdomain)) {
11636: $domain=$posdom;
11637: last;
11638: }
11639: }
11640: return $domain;
11641: }
11642:
1.31 www 11643: # ------------------------------------------------------------- Declutters URLs
11644:
11645: sub declutter {
11646: my $thisfn=shift;
1.569 albertel 11647: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 11648: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 11649: $thisfn=~s/^\///;
1.697 albertel 11650: $thisfn=~s|^adm/wrapper/||;
11651: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 11652: $thisfn=~s/^res\///;
1.1172 bisitz 11653: $thisfn=~s/^priv\///;
1.1032 raeburn 11654: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11655: $thisfn=~s/\?.+$//;
11656: }
1.268 www 11657: return $thisfn;
11658: }
11659:
11660: # ------------------------------------------------------------- Clutter up URLs
11661:
11662: sub clutter {
11663: my $thisfn='/'.&declutter(shift);
1.887 albertel 11664: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 11665: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 11666: $thisfn='/res'.$thisfn;
11667: }
1.1031 raeburn 11668: if ($thisfn !~m|^/adm|) {
11669: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 11670: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 11671: } else {
11672: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11673: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 11674: if ($embstyle eq 'ssi'
11675: || ($embstyle eq 'hdn')
11676: || ($embstyle eq 'rat')
11677: || ($embstyle eq 'prv')
11678: || ($embstyle eq 'ign')) {
11679: #do nothing with these
11680: } elsif (($embstyle eq 'img')
1.695 albertel 11681: || ($embstyle eq 'emb')
11682: || ($embstyle eq 'wrp')) {
11683: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 11684: } elsif ($embstyle eq 'unk'
11685: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 11686: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 11687: } else {
1.718 www 11688: # &logthis("Got a blank emb style");
1.695 albertel 11689: }
1.694 albertel 11690: }
11691: }
1.31 www 11692: return $thisfn;
1.12 www 11693: }
11694:
1.787 albertel 11695: sub clutter_with_no_wrapper {
11696: my $uri = &clutter(shift);
11697: if ($uri =~ m-^/adm/-) {
11698: $uri =~ s-^/adm/wrapper/-/-;
11699: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11700: }
11701: return $uri;
11702: }
11703:
1.557 albertel 11704: sub freeze_escape {
11705: my ($value)=@_;
11706: if (ref($value)) {
11707: $value=&nfreeze($value);
11708: return '__FROZEN__'.&escape($value);
11709: }
11710: return &escape($value);
11711: }
11712:
1.11 www 11713:
1.557 albertel 11714: sub thaw_unescape {
11715: my ($value)=@_;
11716: if ($value =~ /^__FROZEN__/) {
11717: substr($value,0,10,undef);
11718: $value=&unescape($value);
11719: return &thaw($value);
11720: }
11721: return &unescape($value);
11722: }
11723:
1.436 albertel 11724: sub correct_line_ends {
11725: my ($result)=@_;
11726: $$result =~s/\r\n/\n/mg;
11727: $$result =~s/\r/\n/mg;
1.415 albertel 11728: }
1.1 albertel 11729: # ================================================================ Main Program
11730:
1.184 www 11731: sub goodbye {
1.204 albertel 11732: &logthis("Starting Shut down");
1.443 albertel 11733: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11734: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11735: #converted
1.599 albertel 11736: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11737: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11738: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11739: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11740: #1.1 only
1.870 albertel 11741: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11742: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11743: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11744: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11745: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11746: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11747: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11748: &flushcourselogs();
11749: &logthis("Shutting down");
11750: }
11751:
1.852 albertel 11752: sub get_dns {
1.1210 raeburn 11753: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869 albertel 11754: if (!$ignore_cache) {
11755: my ($content,$cached)=
11756: &Apache::lonnet::is_cached_new('dns',$url);
11757: if ($cached) {
1.1210 raeburn 11758: &$func($content,$hashref);
1.869 albertel 11759: return;
11760: }
11761: }
11762:
11763: my %alldns;
1.852 albertel 11764: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11765: foreach my $dns (<$config>) {
11766: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11767: my $line = $1;
11768: my ($host,$protocol) = split(/:/,$line);
11769: if ($protocol ne 'https') {
11770: $protocol = 'http';
11771: }
11772: $alldns{$host} = $protocol;
1.869 albertel 11773: }
11774: while (%alldns) {
11775: my ($dns) = keys(%alldns);
1.852 albertel 11776: my $ua=new LWP::UserAgent;
1.1134 raeburn 11777: $ua->timeout(30);
1.979 raeburn 11778: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11779: my $response=$ua->request($request);
1.979 raeburn 11780: delete($alldns{$dns});
1.852 albertel 11781: next if ($response->is_error());
11782: my @content = split("\n",$response->content);
1.1210 raeburn 11783: unless ($nocache) {
1.1219 raeburn 11784: &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210 raeburn 11785: }
11786: &$func(\@content,$hashref);
1.869 albertel 11787: return;
1.852 albertel 11788: }
11789: close($config);
1.871 albertel 11790: my $which = (split('/',$url))[3];
11791: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11792: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11793: my @content = <$config>;
1.1210 raeburn 11794: &$func(\@content,$hashref);
11795: return;
11796: }
11797:
11798: # ------------------------------------------------------Get DNS checksums file
1.1211 raeburn 11799: sub parse_dns_checksums_tab {
1.1210 raeburn 11800: my ($lines,$hashref) = @_;
11801: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11802: my $loncaparev = &get_server_loncaparev($machine_dom);
11803: my ($release,$timestamp) = split(/\-/,$loncaparev);
11804: my (%chksum,%revnum);
11805: if (ref($lines) eq 'ARRAY') {
11806: chomp(@{$lines});
1.1238 raeburn 11807: my $version = shift(@{$lines});
11808: if ($version eq $release) {
1.1210 raeburn 11809: foreach my $line (@{$lines}) {
1.1238 raeburn 11810: my ($file,$version,$shasum) = split(/,/,$line);
11811: $chksum{$file} = $shasum;
11812: $revnum{$file} = $version;
1.1210 raeburn 11813: }
11814: if (ref($hashref) eq 'HASH') {
11815: %{$hashref} = (
11816: sums => \%chksum,
11817: versions => \%revnum,
11818: );
11819: }
11820: }
11821: }
1.869 albertel 11822: return;
1.852 albertel 11823: }
1.1210 raeburn 11824:
11825: sub fetch_dns_checksums {
1.1238 raeburn 11826: my %checksums;
11827: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11828: my $loncaparev = &get_server_loncaparev($machine_dom);
11829: my ($release,$timestamp) = split(/\-/,$loncaparev);
11830: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211 raeburn 11831: \%checksums);
1.1210 raeburn 11832: return \%checksums;
11833: }
11834:
1.327 albertel 11835: # ------------------------------------------------------------ Read domain file
11836: {
1.852 albertel 11837: my $loaded;
1.846 albertel 11838: my %domain;
11839:
1.852 albertel 11840: sub parse_domain_tab {
11841: my ($lines) = @_;
11842: foreach my $line (@$lines) {
11843: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11844:
1.846 albertel 11845: chomp($line);
1.852 albertel 11846: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11847: my %this_domain;
11848: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11849: 'lang_def', 'city', 'longi', 'lati',
11850: 'primary') {
11851: $this_domain{$field} = shift(@elements);
11852: }
11853: $domain{$name} = \%this_domain;
1.852 albertel 11854: }
11855: }
1.864 albertel 11856:
11857: sub reset_domain_info {
11858: undef($loaded);
11859: undef(%domain);
11860: }
11861:
1.852 albertel 11862: sub load_domain_tab {
1.869 albertel 11863: my ($ignore_cache) = @_;
11864: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11865: my $fh;
11866: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11867: my @lines = <$fh>;
11868: &parse_domain_tab(\@lines);
1.448 albertel 11869: }
1.852 albertel 11870: close($fh);
11871: $loaded = 1;
1.327 albertel 11872: }
1.846 albertel 11873:
11874: sub domain {
1.852 albertel 11875: &load_domain_tab() if (!$loaded);
11876:
1.846 albertel 11877: my ($name,$what) = @_;
11878: return if ( !exists($domain{$name}) );
11879:
11880: if (!$what) {
11881: return $domain{$name}{'description'};
11882: }
11883: return $domain{$name}{$what};
11884: }
1.974 raeburn 11885:
11886: sub domain_info {
11887: &load_domain_tab() if (!$loaded);
11888: return %domain;
11889: }
11890:
1.327 albertel 11891: }
11892:
11893:
1.1 albertel 11894: # ------------------------------------------------------------- Read hosts file
11895: {
1.838 albertel 11896: my %hostname;
1.844 albertel 11897: my %hostdom;
1.845 albertel 11898: my %libserv;
1.852 albertel 11899: my $loaded;
1.888 albertel 11900: my %name_to_host;
1.1074 raeburn 11901: my %internetdom;
1.1107 raeburn 11902: my %LC_dns_serv;
1.852 albertel 11903:
11904: sub parse_hosts_tab {
11905: my ($file) = @_;
11906: foreach my $configline (@$file) {
11907: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11908: chomp($configline);
11909: if ($configline =~ /^\^/) {
11910: if ($configline =~ /^\^([\w.\-]+)/) {
11911: $LC_dns_serv{$1} = 1;
11912: }
11913: next;
11914: }
1.1074 raeburn 11915: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11916: $name=~s/\s//g;
11917: if ($id && $domain && $role && $name) {
11918: $hostname{$id}=$name;
1.888 albertel 11919: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11920: $hostdom{$id}=$domain;
11921: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11922: if (defined($protocol)) {
11923: if ($protocol eq 'https') {
11924: $protocol{$id} = $protocol;
11925: } else {
11926: $protocol{$id} = 'http';
11927: }
1.968 raeburn 11928: } else {
1.969 raeburn 11929: $protocol{$id} = 'http';
1.968 raeburn 11930: }
1.1074 raeburn 11931: if (defined($intdom)) {
11932: $internetdom{$id} = $intdom;
11933: }
1.852 albertel 11934: }
11935: }
11936: }
1.864 albertel 11937:
11938: sub reset_hosts_info {
1.897 albertel 11939: &purge_remembered();
1.864 albertel 11940: &reset_domain_info();
11941: &reset_hosts_ip_info();
1.892 albertel 11942: undef(%name_to_host);
1.864 albertel 11943: undef(%hostname);
11944: undef(%hostdom);
11945: undef(%libserv);
11946: undef($loaded);
11947: }
1.1 albertel 11948:
1.852 albertel 11949: sub load_hosts_tab {
1.869 albertel 11950: my ($ignore_cache) = @_;
11951: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11952: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11953: my @config = <$config>;
11954: &parse_hosts_tab(\@config);
11955: close($config);
11956: $loaded=1;
1.1 albertel 11957: }
1.852 albertel 11958:
1.838 albertel 11959: sub hostname {
1.852 albertel 11960: &load_hosts_tab() if (!$loaded);
11961:
1.838 albertel 11962: my ($lonid) = @_;
11963: return $hostname{$lonid};
11964: }
1.845 albertel 11965:
1.838 albertel 11966: sub all_hostnames {
1.852 albertel 11967: &load_hosts_tab() if (!$loaded);
11968:
1.838 albertel 11969: return %hostname;
11970: }
1.845 albertel 11971:
1.888 albertel 11972: sub all_names {
11973: &load_hosts_tab() if (!$loaded);
11974:
11975: return %name_to_host;
11976: }
11977:
1.974 raeburn 11978: sub all_host_domain {
11979: &load_hosts_tab() if (!$loaded);
11980: return %hostdom;
11981: }
11982:
1.845 albertel 11983: sub is_library {
1.852 albertel 11984: &load_hosts_tab() if (!$loaded);
11985:
1.845 albertel 11986: return exists($libserv{$_[0]});
11987: }
11988:
11989: sub all_library {
1.852 albertel 11990: &load_hosts_tab() if (!$loaded);
11991:
1.845 albertel 11992: return %libserv;
11993: }
11994:
1.1062 droeschl 11995: sub unique_library {
11996: #2x reverse removes all hostnames that appear more than once
11997: my %unique = reverse &all_library();
11998: return reverse %unique;
11999: }
12000:
1.841 albertel 12001: sub get_servers {
1.852 albertel 12002: &load_hosts_tab() if (!$loaded);
12003:
1.841 albertel 12004: my ($domain,$type) = @_;
12005: my %possible_hosts = ($type eq 'library') ? %libserv
12006: : %hostname;
12007: my %result;
1.842 albertel 12008: if (ref($domain) eq 'ARRAY') {
12009: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 12010: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 12011: $result{$host} = $hostname;
12012: }
12013: }
12014: } else {
12015: while ( my ($host,$hostname) = each(%possible_hosts)) {
12016: if ($hostdom{$host} eq $domain) {
12017: $result{$host} = $hostname;
12018: }
1.841 albertel 12019: }
12020: }
12021: return %result;
12022: }
1.845 albertel 12023:
1.1062 droeschl 12024: sub get_unique_servers {
12025: my %unique = reverse &get_servers(@_);
12026: return reverse %unique;
12027: }
12028:
1.844 albertel 12029: sub host_domain {
1.852 albertel 12030: &load_hosts_tab() if (!$loaded);
12031:
1.844 albertel 12032: my ($lonid) = @_;
12033: return $hostdom{$lonid};
12034: }
12035:
1.841 albertel 12036: sub all_domains {
1.852 albertel 12037: &load_hosts_tab() if (!$loaded);
12038:
1.841 albertel 12039: my %seen;
12040: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12041: return @uniq;
12042: }
1.1074 raeburn 12043:
12044: sub internet_dom {
12045: &load_hosts_tab() if (!$loaded);
12046:
12047: my ($lonid) = @_;
12048: return $internetdom{$lonid};
12049: }
1.1107 raeburn 12050:
12051: sub is_LC_dns {
12052: &load_hosts_tab() if (!$loaded);
12053:
12054: my ($hostname) = @_;
12055: return exists($LC_dns_serv{$hostname});
12056: }
12057:
1.1 albertel 12058: }
12059:
1.847 albertel 12060: {
12061: my %iphost;
1.856 albertel 12062: my %name_to_ip;
12063: my %lonid_to_ip;
1.869 albertel 12064:
1.847 albertel 12065: sub get_hosts_from_ip {
12066: my ($ip) = @_;
12067: my %iphosts = &get_iphost();
12068: if (ref($iphosts{$ip})) {
12069: return @{$iphosts{$ip}};
12070: }
12071: return;
1.839 albertel 12072: }
1.864 albertel 12073:
12074: sub reset_hosts_ip_info {
12075: undef(%iphost);
12076: undef(%name_to_ip);
12077: undef(%lonid_to_ip);
12078: }
1.856 albertel 12079:
12080: sub get_host_ip {
12081: my ($lonid) = @_;
12082: if (exists($lonid_to_ip{$lonid})) {
12083: return $lonid_to_ip{$lonid};
12084: }
12085: my $name=&hostname($lonid);
12086: my $ip = gethostbyname($name);
12087: return if (!$ip || length($ip) ne 4);
12088: $ip=inet_ntoa($ip);
12089: $name_to_ip{$name} = $ip;
12090: $lonid_to_ip{$lonid} = $ip;
12091: return $ip;
12092: }
1.847 albertel 12093:
12094: sub get_iphost {
1.869 albertel 12095: my ($ignore_cache) = @_;
1.894 albertel 12096:
1.869 albertel 12097: if (!$ignore_cache) {
12098: if (%iphost) {
12099: return %iphost;
12100: }
12101: my ($ip_info,$cached)=
12102: &Apache::lonnet::is_cached_new('iphost','iphost');
12103: if ($cached) {
12104: %iphost = %{$ip_info->[0]};
12105: %name_to_ip = %{$ip_info->[1]};
12106: %lonid_to_ip = %{$ip_info->[2]};
12107: return %iphost;
12108: }
12109: }
1.894 albertel 12110:
12111: # get yesterday's info for fallback
12112: my %old_name_to_ip;
12113: my ($ip_info,$cached)=
12114: &Apache::lonnet::is_cached_new('iphost','iphost');
12115: if ($cached) {
12116: %old_name_to_ip = %{$ip_info->[1]};
12117: }
12118:
1.888 albertel 12119: my %name_to_host = &all_names();
12120: foreach my $name (keys(%name_to_host)) {
1.847 albertel 12121: my $ip;
12122: if (!exists($name_to_ip{$name})) {
12123: $ip = gethostbyname($name);
12124: if (!$ip || length($ip) ne 4) {
1.894 albertel 12125: if (defined($old_name_to_ip{$name})) {
12126: $ip = $old_name_to_ip{$name};
12127: &logthis("Can't find $name defaulting to old $ip");
12128: } else {
12129: &logthis("Name $name no IP found");
12130: next;
12131: }
12132: } else {
12133: $ip=inet_ntoa($ip);
1.847 albertel 12134: }
12135: $name_to_ip{$name} = $ip;
12136: } else {
12137: $ip = $name_to_ip{$name};
1.653 albertel 12138: }
1.888 albertel 12139: foreach my $id (@{ $name_to_host{$name} }) {
12140: $lonid_to_ip{$id} = $ip;
12141: }
12142: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 12143: }
1.1219 raeburn 12144: &do_cache_new('iphost','iphost',
12145: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12146: 48*60*60);
1.869 albertel 12147:
1.847 albertel 12148: return %iphost;
1.598 albertel 12149: }
12150:
1.992 raeburn 12151: #
12152: # Given a DNS returns the loncapa host name for that DNS
12153: #
12154: sub host_from_dns {
12155: my ($dns) = @_;
12156: my @hosts;
12157: my $ip;
12158:
1.993 raeburn 12159: if (exists($name_to_ip{$dns})) {
1.992 raeburn 12160: $ip = $name_to_ip{$dns};
12161: }
12162: if (!$ip) {
12163: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12164: if (length($ip) == 4) {
12165: $ip = &IO::Socket::inet_ntoa($ip);
12166: }
12167: }
12168: if ($ip) {
12169: @hosts = get_hosts_from_ip($ip);
12170: return $hosts[0];
12171: }
12172: return undef;
1.986 foxr 12173: }
1.992 raeburn 12174:
1.1074 raeburn 12175: sub get_internet_names {
12176: my ($lonid) = @_;
12177: return if ($lonid eq '');
12178: my ($idnref,$cached)=
12179: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12180: if ($cached) {
12181: return $idnref;
12182: }
12183: my $ip = &get_host_ip($lonid);
12184: my @hosts = &get_hosts_from_ip($ip);
12185: my %iphost = &get_iphost();
12186: my (@idns,%seen);
12187: foreach my $id (@hosts) {
12188: my $dom = &host_domain($id);
12189: my $prim_id = &domain($dom,'primary');
12190: my $prim_ip = &get_host_ip($prim_id);
12191: next if ($seen{$prim_ip});
12192: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12193: foreach my $id (@{$iphost{$prim_ip}}) {
12194: my $intdom = &internet_dom($id);
12195: unless (grep(/^\Q$intdom\E$/,@idns)) {
12196: push(@idns,$intdom);
12197: }
12198: }
12199: }
12200: $seen{$prim_ip} = 1;
12201: }
1.1219 raeburn 12202: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074 raeburn 12203: }
12204:
1.986 foxr 12205: }
12206:
1.1079 raeburn 12207: sub all_loncaparevs {
1.1249 raeburn 12208: return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11);
1.1079 raeburn 12209: }
12210:
1.1227 raeburn 12211: # ---------------------------------------------------------- Read loncaparev table
12212: {
12213: sub load_loncaparevs {
12214: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12215: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12216: while (my $configline=<$config>) {
12217: chomp($configline);
12218: my ($hostid,$loncaparev)=split(/:/,$configline);
12219: $loncaparevs{$hostid}=$loncaparev;
12220: }
12221: close($config);
12222: }
12223: }
12224: }
12225: }
12226:
12227: # ---------------------------------------------------------- Read serverhostID table
12228: {
12229: sub load_serverhomeIDs {
12230: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12231: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12232: while (my $configline=<$config>) {
12233: chomp($configline);
12234: my ($name,$id)=split(/:/,$configline);
12235: $serverhomeIDs{$name}=$id;
12236: }
12237: close($config);
12238: }
12239: }
12240: }
12241: }
12242:
12243:
1.862 albertel 12244: BEGIN {
12245:
12246: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12247: unless ($readit) {
12248: {
12249: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12250: %perlvar = (%perlvar,%{$configvars});
12251: }
12252:
12253:
1.1 albertel 12254: # ------------------------------------------------------ Read spare server file
12255: {
1.448 albertel 12256: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 12257:
12258: while (my $configline=<$config>) {
12259: chomp($configline);
1.284 matthew 12260: if ($configline) {
1.784 albertel 12261: my ($host,$type) = split(':',$configline,2);
1.785 albertel 12262: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 12263: push(@{ $spareid{$type} }, $host);
1.1 albertel 12264: }
12265: }
1.448 albertel 12266: close($config);
1.1 albertel 12267: }
1.11 www 12268: # ------------------------------------------------------------ Read permissions
12269: {
1.448 albertel 12270: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 12271:
12272: while (my $configline=<$config>) {
1.448 albertel 12273: chomp($configline);
12274: if ($configline) {
12275: my ($role,$perm)=split(/ /,$configline);
12276: if ($perm ne '') { $pr{$role}=$perm; }
12277: }
1.11 www 12278: }
1.448 albertel 12279: close($config);
1.11 www 12280: }
12281:
12282: # -------------------------------------------- Read plain texts for permissions
12283: {
1.448 albertel 12284: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 12285:
12286: while (my $configline=<$config>) {
1.448 albertel 12287: chomp($configline);
12288: if ($configline) {
1.742 raeburn 12289: my ($short,@plain)=split(/:/,$configline);
12290: %{$prp{$short}} = ();
12291: if (@plain > 0) {
12292: $prp{$short}{'std'} = $plain[0];
12293: for (my $i=1; $i<@plain; $i++) {
12294: $prp{$short}{'alt'.$i} = $plain[$i];
12295: }
12296: }
1.448 albertel 12297: }
1.135 www 12298: }
1.448 albertel 12299: close($config);
1.135 www 12300: }
12301:
12302: # ---------------------------------------------------------- Read package table
12303: {
1.448 albertel 12304: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 12305:
12306: while (my $configline=<$config>) {
1.483 albertel 12307: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 12308: chomp($configline);
12309: my ($short,$plain)=split(/:/,$configline);
12310: my ($pack,$name)=split(/\&/,$short);
12311: if ($plain ne '') {
12312: $packagetab{$pack.'&'.$name.'&name'}=$name;
12313: $packagetab{$short}=$plain;
12314: }
1.11 www 12315: }
1.448 albertel 12316: close($config);
1.329 matthew 12317: }
12318:
1.1073 raeburn 12319: # ---------------------------------------------------------- Read loncaparev table
1.1227 raeburn 12320:
12321: &load_loncaparevs();
1.1073 raeburn 12322:
1.1074 raeburn 12323: # ---------------------------------------------------------- Read serverhostID table
12324:
1.1227 raeburn 12325: &load_serverhomeIDs();
12326:
12327: # ---------------------------------------------------------- Read releaseslist XML
1.1079 raeburn 12328: {
12329: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12330: if (-e $file) {
12331: my $parser = HTML::LCParser->new($file);
12332: while (my $token = $parser->get_token()) {
12333: if ($token->[0] eq 'S') {
12334: my $item = $token->[1];
12335: my $name = $token->[2]{'name'};
12336: my $value = $token->[2]{'value'};
12337: if ($item ne '' && $name ne '' && $value ne '') {
12338: my $release = $parser->get_text();
12339: $release =~ s/(^\s*|\s*$ )//gx;
12340: $needsrelease{$item.':'.$name.':'.$value} = $release;
12341: }
12342: }
12343: }
12344: }
1.1073 raeburn 12345: }
12346:
1.1138 raeburn 12347: # ---------------------------------------------------------- Read managers table
12348: {
12349: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12350: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12351: while (my $configline=<$config>) {
12352: chomp($configline);
12353: next if ($configline =~ /^\#/);
12354: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12355: $managerstab{$configline} = 1;
12356: }
12357: }
12358: close($config);
12359: }
12360: }
12361: }
12362:
1.329 matthew 12363: # ------------- set up temporary directory
12364: {
1.1117 foxr 12365: $tmpdir = LONCAPA::tempdir();
1.329 matthew 12366:
1.11 www 12367: }
12368:
1.794 albertel 12369: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12370: 'compress_threshold'=> 20_000,
12371: });
1.185 www 12372:
1.281 www 12373: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 12374: $dumpcount=0;
1.958 www 12375: $locknum=0;
1.22 www 12376:
1.163 harris41 12377: &logtouch();
1.672 albertel 12378: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 12379: $readit=1;
1.564 albertel 12380: {
12381: use integer;
12382: my $test=(2**32)+1;
1.568 albertel 12383: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 12384: &logthis(" Detected 64bit platform ($_64bit)");
12385: }
1.195 www 12386: }
1.1 albertel 12387: }
1.179 www 12388:
1.1 albertel 12389: 1;
1.191 harris41 12390: __END__
12391:
1.243 albertel 12392: =pod
12393:
1.191 harris41 12394: =head1 NAME
12395:
1.243 albertel 12396: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 12397:
12398: =head1 SYNOPSIS
12399:
1.243 albertel 12400: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 12401:
12402: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12403:
1.243 albertel 12404: Common parameters:
12405:
12406: =over 4
12407:
12408: =item *
12409:
12410: $uname : an internal username (if $cname expecting a course Id specifically)
12411:
12412: =item *
12413:
12414: $udom : a domain (if $cdom expecting a course's domain specifically)
12415:
12416: =item *
12417:
12418: $symb : a resource instance identifier
12419:
12420: =item *
12421:
12422: $namespace : the name of a .db file that contains the data needed or
12423: being set.
12424:
12425: =back
12426:
1.394 bowersj2 12427: =head1 OVERVIEW
1.191 harris41 12428:
1.394 bowersj2 12429: lonnet provides subroutines which interact with the
12430: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12431: about classes, users, and resources.
1.243 albertel 12432:
12433: For many of these objects you can also use this to store data about
12434: them or modify them in various ways.
1.191 harris41 12435:
1.394 bowersj2 12436: =head2 Symbs
1.191 harris41 12437:
1.394 bowersj2 12438: To identify a specific instance of a resource, LON-CAPA uses symbols
12439: or "symbs"X<symb>. These identifiers are built from the URL of the
12440: map, the resource number of the resource in the map, and the URL of
12441: the resource itself. The latter is somewhat redundant, but might help
12442: if maps change.
12443:
12444: An example is
12445:
12446: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12447:
12448: The respective map entry is
12449:
12450: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12451: title="Problem 2">
12452: </resource>
12453:
12454: Symbs are used by the random number generator, as well as to store and
12455: restore data specific to a certain instance of for example a problem.
12456:
12457: =head2 Storing And Retrieving Data
12458:
12459: X<store()>X<cstore()>X<restore()>Three of the most important functions
12460: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12461: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12462: is is the non-critical message twin of cstore. These functions are for
12463: handlers to store a perl hash to a user's permanent data space in an
12464: easy manner, and to retrieve it again on another call. It is expected
12465: that a handler would use this once at the beginning to retrieve data,
12466: and then again once at the end to send only the new data back.
12467:
12468: The data is stored in the user's data directory on the user's
12469: homeserver under the ID of the course.
12470:
12471: The hash that is returned by restore will have all of the previous
12472: value for all of the elements of the hash.
12473:
12474: Example:
12475:
12476: #creating a hash
12477: my %hash;
12478: $hash{'foo'}='bar';
12479:
12480: #storing it
12481: &Apache::lonnet::cstore(\%hash);
12482:
12483: #changing a value
12484: $hash{'foo'}='notbar';
12485:
12486: #adding a new value
12487: $hash{'bar'}='foo';
12488: &Apache::lonnet::cstore(\%hash);
12489:
12490: #retrieving the hash
12491: my %history=&Apache::lonnet::restore();
12492:
12493: #print the hash
12494: foreach my $key (sort(keys(%history))) {
12495: print("\%history{$key} = $history{$key}");
12496: }
12497:
12498: Will print out:
1.191 harris41 12499:
1.394 bowersj2 12500: %history{1:foo} = bar
12501: %history{1:keys} = foo:timestamp
12502: %history{1:timestamp} = 990455579
12503: %history{2:bar} = foo
12504: %history{2:foo} = notbar
12505: %history{2:keys} = foo:bar:timestamp
12506: %history{2:timestamp} = 990455580
12507: %history{bar} = foo
12508: %history{foo} = notbar
12509: %history{timestamp} = 990455580
12510: %history{version} = 2
12511:
12512: Note that the special hash entries C<keys>, C<version> and
12513: C<timestamp> were added to the hash. C<version> will be equal to the
12514: total number of versions of the data that have been stored. The
12515: C<timestamp> attribute will be the UNIX time the hash was
12516: stored. C<keys> is available in every historical section to list which
12517: keys were added or changed at a specific historical revision of a
12518: hash.
12519:
12520: B<Warning>: do not store the hash that restore returns directly. This
12521: will cause a mess since it will restore the historical keys as if the
12522: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 12523:
1.394 bowersj2 12524: Calling convention:
1.191 harris41 12525:
1.1225 raeburn 12526: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12527: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
1.191 harris41 12528:
1.394 bowersj2 12529: For more detailed information, see lonnet specific documentation.
1.191 harris41 12530:
1.394 bowersj2 12531: =head1 RETURN MESSAGES
1.191 harris41 12532:
1.394 bowersj2 12533: =over 4
1.191 harris41 12534:
1.394 bowersj2 12535: =item * B<con_lost>: unable to contact remote host
1.191 harris41 12536:
1.394 bowersj2 12537: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12538: when the connection is brought back up
1.191 harris41 12539:
1.394 bowersj2 12540: =item * B<con_failed>: unable to contact remote host and unable to save message
12541: for later delivery
1.191 harris41 12542:
1.967 bisitz 12543: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 12544:
1.394 bowersj2 12545: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 12546: that was requested
1.191 harris41 12547:
1.243 albertel 12548: =back
1.191 harris41 12549:
1.243 albertel 12550: =head1 PUBLIC SUBROUTINES
1.191 harris41 12551:
1.243 albertel 12552: =head2 Session Environment Functions
1.191 harris41 12553:
1.243 albertel 12554: =over 4
1.191 harris41 12555:
1.394 bowersj2 12556: =item *
12557: X<appenv()>
1.949 raeburn 12558: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 12559: the user envirnoment file, and will be restored for each access this
1.620 albertel 12560: user makes during this session, also modifies the %env for the current
1.949 raeburn 12561: process. Optional rolesarrayref - if defined contains a reference to an array
12562: of roles which are exempt from the restriction on modifying user.role entries
12563: in the user's environment.db and in %env.
1.191 harris41 12564:
12565: =item *
1.394 bowersj2 12566: X<delenv()>
1.987 raeburn 12567: B<delenv($delthis,$regexp)>: removes all items from the session
12568: environment file that begin with $delthis. If the
12569: optional second arg - $regexp - is true, $delthis is treated as a
12570: regular expression, otherwise \Q$delthis\E is used.
12571: The values are also deleted from the current processes %env.
1.191 harris41 12572:
1.795 albertel 12573: =item * get_env_multiple($name)
12574:
12575: gets $name from the %env hash, it seemlessly handles the cases where multiple
12576: values may be defined and end up as an array ref.
12577:
12578: returns an array of values
12579:
1.243 albertel 12580: =back
12581:
12582: =head2 User Information
1.191 harris41 12583:
1.243 albertel 12584: =over 4
1.191 harris41 12585:
12586: =item *
1.394 bowersj2 12587: X<queryauthenticate()>
12588: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 12589: authentication scheme
12590:
12591: =item *
1.394 bowersj2 12592: X<authenticate()>
1.1073 raeburn 12593: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 12594: authenticate user from domain's lib servers (first use the current
12595: one). C<$upass> should be the users password.
1.1073 raeburn 12596: $checkdefauth is optional (value is 1 if a check should be made to
12597: authenticate user using default authentication method, and allow
12598: account creation if username does not have account in the domain).
12599: $clientcancheckhost is optional (value is 1 if checking whether the
12600: server can host will occur on the client side in lonauth.pm).
1.191 harris41 12601:
12602: =item *
1.394 bowersj2 12603: X<homeserver()>
12604: B<homeserver($uname,$udom)>: find the server which has
12605: the user's directory and files (there must be only one), this caches
12606: the answer, and also caches if there is a borken connection.
1.191 harris41 12607:
12608: =item *
1.394 bowersj2 12609: X<idget()>
12610: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12611: (IDs are a unique resource in a domain, there must be only 1 ID per
12612: username, and only 1 username per ID in a specific domain) (returns
12613: hash: id=>name,id=>name)
1.191 harris41 12614:
12615: =item *
1.394 bowersj2 12616: X<idrget()>
12617: B<idrget($udom,@unames)>: find the IDs behind a list of
12618: usernames (returns hash: name=>id,name=>id)
1.191 harris41 12619:
12620: =item *
1.394 bowersj2 12621: X<idput()>
12622: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 12623:
12624: =item *
1.394 bowersj2 12625: X<rolesinit()>
1.1169 droeschl 12626: B<rolesinit($udom,$username)>: get user privileges.
12627: returns user role, first access and timer interval hashes
1.243 albertel 12628:
12629: =item *
1.1171 droeschl 12630: X<privileged()>
12631: B<privileged($username,$domain)>: returns a true if user has a
12632: privileged and active role (i.e. su or dc), false otherwise.
12633:
12634: =item *
1.551 albertel 12635: X<getsection()>
12636: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 12637: course $cname, return section name/number or '' for "not in course"
12638: and '-1' for "no section"
12639:
12640: =item *
1.394 bowersj2 12641: X<userenvironment()>
12642: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 12643: passed in @what from the requested user's environment, returns a hash
12644:
1.858 raeburn 12645: =item *
12646: X<userlog_query()>
1.859 albertel 12647: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12648: activity.log file. %filters defines filters applied when parsing the
12649: log file. These can be start or end timestamps, or the type of action
12650: - log to look for Login or Logout events, check for Checkin or
12651: Checkout, role for role selection. The response is in the form
12652: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12653: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 12654:
1.243 albertel 12655: =back
12656:
12657: =head2 User Roles
12658:
12659: =over 4
12660:
12661: =item *
12662:
1.810 raeburn 12663: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 12664: F: full access
12665: U,I,K: authentication modes (cxx only)
12666: '': forbidden
12667: 1: user needs to choose course
12668: 2: browse allowed
1.766 albertel 12669: A: passphrase authentication needed
1.243 albertel 12670:
12671: =item *
12672:
1.1192 raeburn 12673: constructaccess($url,$setpriv) : check for access to construction space URL
12674:
12675: See if the owner domain and name in the URL match those in the
12676: expected environment. If so, return three element list
12677: ($ownername,$ownerdomain,$ownerhome).
12678:
12679: Otherwise return the null string.
12680:
12681: If second argument 'setpriv' is true, it assigns the privileges,
12682: and returns the same three element list, unless the owner has
12683: blocked "ad hoc" Domain Coordinator access to the Author Space,
12684: in which case the null string is returned.
12685:
12686: =item *
12687:
1.243 albertel 12688: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12689: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12690: and course level
12691:
12692: =item *
12693:
1.988 raeburn 12694: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12695: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 12696: $type is Course (default) or Community.
1.988 raeburn 12697: If $forcedefault evaluates to true, text returned will be default
12698: text for $type. Otherwise, if this is a course, the text returned
12699: will be a custom name for the role (if defined in the course's
12700: environment). If no custom name is defined the default is returned.
12701:
1.832 raeburn 12702: =item *
12703:
1.1219 raeburn 12704: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858 raeburn 12705: All arguments are optional. Returns a hash of a roles, either for
12706: co-author/assistant author roles for a user's Construction Space
1.906 albertel 12707: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 12708: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12709: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12710: For each key, value is set to colon-separated start and end times for
12711: the role. If no username and domain are specified, will default to
1.934 raeburn 12712: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 12713: of role statuses (active, future or previous), roles
12714: (e.g., cc,in, st etc.) and domains of the roles which can be used
12715: to restrict the list of roles reported. If no array ref is
12716: provided for types, will default to return only active roles.
1.834 albertel 12717:
1.1195 raeburn 12718: =item *
12719:
12720: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196 raeburn 12721: user: $uname:$udom has a role in the course: $cdom_$cnum.
12722:
12723: Additional optional arguments are: $type (if role checking is to be restricted
12724: to certain user status types -- previous (expired roles), active (currently
1.1195 raeburn 12725: available roles) or future (roles available in the future), and
12726: $hideprivileged -- if true will not report course roles for users who
1.1219 raeburn 12727: have active Domain Coordinator role in course's domain or in additional
12728: domains (specified in 'Domains to check for privileged users' in course
12729: environment -- set via: Course Settings -> Classlists and staff listing).
12730:
12731: =item *
12732:
12733: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12734: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12735: $possdomains and $possroles are optional array refs -- to domains to check and
12736: roles to check. If $possdomains is not specified, a dump will be done of the
12737: users' roles.db to check for a dc or su role in any domain. This can be
12738: time consuming if &privileged is called repeatedly (e.g., when displaying a
12739: classlist), so in such cases, supplying a $possdomains array is preferred, as
12740: this then allows &privileged_by_domain() to be used, which caches the identity
12741: of privileged users, eliminating the need for repeated calls to &dump().
12742:
12743: =item *
12744:
12745: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12746: where the outer hash keys are domains specified in the $possdomains array ref,
12747: next inner hash keys are privileged roles specified in the $roles array ref,
12748: and the innermost hash contains key = value pairs for username:domain = end:start
12749: for active or future "privileged" users with that role in that domain. To avoid
12750: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12751: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195 raeburn 12752:
1.243 albertel 12753: =back
12754:
12755: =head2 User Modification
12756:
12757: =over 4
12758:
12759: =item *
12760:
1.957 raeburn 12761: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 12762: user for the level given by URL. Optional start and end dates (leave empty
12763: string or zero for "no date")
1.191 harris41 12764:
12765: =item *
12766:
1.243 albertel 12767: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12768: change a users, password, possible return values are: ok,
12769: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12770: refused
1.191 harris41 12771:
12772: =item *
12773:
1.243 albertel 12774: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 12775:
12776: =item *
12777:
1.1058 raeburn 12778: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12779: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12780:
12781: will update user information (firstname,middlename,lastname,generation,
12782: permanentemail), and if forceid is true, student/employee ID also.
12783: A user's institutional affiliation(s) can also be updated.
12784: User information fields will not be overwritten with empty entries
12785: unless the field is included in the $candelete array reference.
12786: This array is included when a single user is modified via "Manage Users",
12787: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 12788:
12789: =item *
12790:
1.286 matthew 12791: modifystudent
12792:
1.957 raeburn 12793: modify a student's enrollment and identification information.
1.1235 raeburn 12794: The course id is resolved based on the current user's environment.
12795: This means the invoking user must be a course coordinator or otherwise
1.286 matthew 12796: associated with a course.
12797:
1.297 matthew 12798: This call is essentially a wrapper for lonnet::modifyuser and
12799: lonnet::modify_student_enrollment
1.286 matthew 12800:
12801: Inputs:
12802:
12803: =over 4
12804:
1.957 raeburn 12805: =item B<$udom> Student's loncapa domain
1.286 matthew 12806:
1.957 raeburn 12807: =item B<$uname> Student's loncapa login name
1.286 matthew 12808:
1.964 bisitz 12809: =item B<$uid> Student/Employee ID
1.286 matthew 12810:
1.957 raeburn 12811: =item B<$umode> Student's authentication mode
1.286 matthew 12812:
1.957 raeburn 12813: =item B<$upass> Student's password
1.286 matthew 12814:
1.957 raeburn 12815: =item B<$first> Student's first name
1.286 matthew 12816:
1.957 raeburn 12817: =item B<$middle> Student's middle name
1.286 matthew 12818:
1.957 raeburn 12819: =item B<$last> Student's last name
1.286 matthew 12820:
1.957 raeburn 12821: =item B<$gene> Student's generation
1.286 matthew 12822:
1.957 raeburn 12823: =item B<$usec> Student's section in course
1.286 matthew 12824:
12825: =item B<$end> Unix time of the roles expiration
12826:
12827: =item B<$start> Unix time of the roles start date
12828:
12829: =item B<$forceid> If defined, allow $uid to be changed
12830:
12831: =item B<$desiredhome> server to use as home server for student
12832:
1.957 raeburn 12833: =item B<$email> Student's permanent e-mail address
12834:
12835: =item B<$type> Type of enrollment (auto or manual)
12836:
1.963 raeburn 12837: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12838:
12839: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12840:
1.963 raeburn 12841: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12842:
1.963 raeburn 12843: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12844:
1.1216 raeburn 12845: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12846:
12847: =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 12848:
1.286 matthew 12849: =back
1.297 matthew 12850:
12851: =item *
12852:
12853: modify_student_enrollment
12854:
1.1235 raeburn 12855: Change a student's enrollment status in a class. The environment variable
1.297 matthew 12856: 'role.request.course' must be defined for this function to proceed.
12857:
12858: Inputs:
12859:
12860: =over 4
12861:
1.1235 raeburn 12862: =item $udom, student's domain
1.297 matthew 12863:
1.1235 raeburn 12864: =item $uname, student's name
1.297 matthew 12865:
1.1235 raeburn 12866: =item $uid, student's user id
1.297 matthew 12867:
1.1235 raeburn 12868: =item $first, student's first name
1.297 matthew 12869:
12870: =item $middle
12871:
12872: =item $last
12873:
12874: =item $gene
12875:
12876: =item $usec
12877:
12878: =item $end
12879:
12880: =item $start
12881:
1.957 raeburn 12882: =item $type
12883:
12884: =item $locktype
12885:
12886: =item $cid
12887:
12888: =item $selfenroll
12889:
12890: =item $context
12891:
1.1216 raeburn 12892: =item $credits, number of credits student will earn from this class
12893:
1.297 matthew 12894: =back
12895:
1.191 harris41 12896:
12897: =item *
12898:
1.243 albertel 12899: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12900: custom role; give a custom role to a user for the level given by URL. Specify
12901: name and domain of role author, and role name
1.191 harris41 12902:
12903: =item *
12904:
1.243 albertel 12905: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12906:
12907: =item *
12908:
1.243 albertel 12909: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12910:
12911: =back
12912:
12913: =head2 Course Infomation
12914:
12915: =over 4
1.191 harris41 12916:
12917: =item *
12918:
1.1118 foxr 12919: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12920: specified course id, including all environment settings for the
12921: course, the description of the course will be in the hash under the
12922: key 'description'
1.191 harris41 12923:
1.1118 foxr 12924: $options is an optional parameter that if supplied is a hash reference that controls
12925: what how this function works. It has the following key/values:
12926:
12927: =over 4
12928:
12929: =item freshen_cache
12930:
12931: If defined, and the environment cache for the course is valid, it is
12932: returned in the returned hash.
12933:
12934: =item one_time
12935:
12936: If defined, the last cache time is set to _now_
12937:
12938: =item user
12939:
12940: If defined, the supplied username is used instead of the current user.
12941:
12942:
12943: =back
12944:
1.191 harris41 12945: =item *
12946:
1.624 albertel 12947: resdata($name,$domain,$type,@which) : request for current parameter
12948: setting for a specific $type, where $type is either 'course' or 'user',
12949: @what should be a list of parameters to ask about. This routine caches
1.1235 raeburn 12950: answers for 10 minutes.
1.243 albertel 12951:
1.877 foxr 12952: =item *
12953:
12954: get_courseresdata($courseid, $domain) : dump the entire course resource
12955: data base, returning a hash that is keyed by the resource name and has
12956: values that are the resource value. I believe that the timestamps and
12957: versions are also returned.
12958:
1.1236 raeburn 12959: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12960: supplemental content area. This routine caches the number of files for
12961: 10 minutes.
12962:
1.243 albertel 12963: =back
12964:
12965: =head2 Course Modification
12966:
12967: =over 4
1.191 harris41 12968:
12969: =item *
12970:
1.243 albertel 12971: writecoursepref($courseid,%prefs) : write preferences (environment
12972: database) for a course
1.191 harris41 12973:
12974: =item *
12975:
1.1011 raeburn 12976: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12977:
12978: =item *
12979:
1.1038 raeburn 12980: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 12981:
1.1167 droeschl 12982: =item *
12983:
12984: is_course($courseid), is_course($cdom, $cnum)
12985:
12986: Accepts either a combined $courseid (in the form of domain_courseid) or the
12987: two component version $cdom, $cnum. It checks if the specified course exists.
12988:
12989: Returns:
12990: undef if the course doesn't exist, otherwise
12991: in scalar context the combined courseid.
12992: in list context the two components of the course identifier, domain and
12993: courseid.
12994:
1.243 albertel 12995: =back
12996:
12997: =head2 Resource Subroutines
12998:
12999: =over 4
1.191 harris41 13000:
13001: =item *
13002:
1.243 albertel 13003: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 13004:
13005: =item *
13006:
1.243 albertel 13007: repcopy($filename) : subscribes to the requested file, and attempts to
13008: replicate from the owning library server, Might return
1.607 raeburn 13009: 'unavailable', 'not_found', 'forbidden', 'ok', or
13010: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 13011: resource. Expects the local filesystem pathname
13012: (/home/httpd/html/res/....)
13013:
13014: =back
13015:
13016: =head2 Resource Information
13017:
13018: =over 4
1.191 harris41 13019:
13020: =item *
13021:
1.1228 raeburn 13022: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13023: and returns the value of a variety of different possible values,
13024: $varname should be a request string, and the other parameters can be
13025: used to specify who and what one is asking about. Ordinarily, $cid
13026: does not need to be specified, as it is retrived from
13027: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13028: within lonuserstate::loadmap() when initializing a course, before
13029: $env{'request.course.id'} has been set, so it needs to be provided
13030: in that one case.
1.243 albertel 13031:
13032: Possible values for $varname are environment.lastname (or other item
13033: from the envirnment hash), user.name (or someother aspect about the
13034: user), resource.0.maxtries (or some other part and parameter of a
13035: resource)
1.204 albertel 13036:
13037: =item *
13038:
1.243 albertel 13039: directcondval($number) : get current value of a condition; reads from a state
13040: string
1.204 albertel 13041:
13042: =item *
13043:
1.243 albertel 13044: condval($condidx) : value of condition index based on state
1.204 albertel 13045:
13046: =item *
13047:
1.243 albertel 13048: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13049: resource's metadata, $what should be either a specific key, or either
13050: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13051: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13052:
13053: this function automatically caches all requests
1.191 harris41 13054:
13055: =item *
13056:
1.243 albertel 13057: metadata_query($query,$custom,$customshow) : make a metadata query against the
13058: network of library servers; returns file handle of where SQL and regex results
13059: will be stored for query
1.191 harris41 13060:
13061: =item *
13062:
1.243 albertel 13063: symbread($filename) : return symbolic list entry (filename argument optional);
13064: returns the data handle
1.191 harris41 13065:
13066: =item *
13067:
1.1190 raeburn 13068: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13069: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582 albertel 13070: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190 raeburn 13071: on failure, user must be in a course, as it assumes the existence of
13072: the course initial hash, and uses $env('request.course.id'}. The third
13073: arg is an optional reference to a scalar. If this arg is passed in the
13074: call to symbverify, it will be set to 1 if the symb has been set to be
13075: encrypted; otherwise it will be null.
1.191 harris41 13076:
13077: =item *
13078:
1.243 albertel 13079: symbclean($symb) : removes versions numbers from a symb, returns the
13080: cleaned symb
1.191 harris41 13081:
13082: =item *
13083:
1.243 albertel 13084: is_on_map($uri) : checks if the $uri is somewhere on the current
13085: course map, user must be in a course for it to work.
1.191 harris41 13086:
13087: =item *
13088:
1.243 albertel 13089: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 13090:
13091: =item *
13092:
1.243 albertel 13093: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13094: a random seed, all arguments are optional, if they aren't sent it uses the
13095: environment to derive them. Note: if symb isn't sent and it can't get one
13096: from &symbread it will use the current time as its return value
1.191 harris41 13097:
13098: =item *
13099:
1.243 albertel 13100: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13101: unfakeable, receipt
1.191 harris41 13102:
13103: =item *
13104:
1.620 albertel 13105: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 13106:
13107: =item *
13108:
1.243 albertel 13109: countacc($url) : count the number of accesses to a given URL
1.191 harris41 13110:
13111: =item *
13112:
1.243 albertel 13113: 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 13114:
13115: =item *
13116:
1.243 albertel 13117: 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 13118:
13119: =item *
13120:
1.243 albertel 13121: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 13122:
13123: =item *
13124:
1.243 albertel 13125: devalidate($symb) : devalidate temporary spreadsheet calculations,
13126: forcing spreadsheet to reevaluate the resource scores next time.
13127:
1.1195 raeburn 13128: =item *
13129:
1.1196 raeburn 13130: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13131: when viewing in course context.
1.1195 raeburn 13132:
1.1196 raeburn 13133: input: six args -- filename (decluttered), course number, course domain,
13134: url, symb (if registered) and group (if this is a
13135: group item -- e.g., bulletin board, group page etc.).
1.1195 raeburn 13136:
1.1196 raeburn 13137: output: array of five scalars --
1.1195 raeburn 13138: $cfile -- url for file editing if editable on current server
13139: $home -- homeserver of resource (i.e., for author if published,
13140: or course if uploaded.).
13141: $switchserver -- 1 if server switch will be needed.
1.1196 raeburn 13142: $forceedit -- 1 if icon/link should be to go to edit mode
13143: $forceview -- 1 if icon/link should be to go to view mode
1.1195 raeburn 13144:
13145: =item *
13146:
13147: is_course_upload($file,$cnum,$cdom)
13148:
13149: Used in course context to determine if current file was uploaded to
13150: the course (i.e., would be found in /userfiles/docs on the course's
13151: homeserver.
13152:
13153: input: 3 args -- filename (decluttered), course number and course domain.
13154: output: boolean -- 1 if file was uploaded.
13155:
1.243 albertel 13156: =back
13157:
13158: =head2 Storing/Retreiving Data
13159:
13160: =over 4
1.191 harris41 13161:
13162: =item *
13163:
1.243 albertel 13164: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13165: for this url; hashref needs to be given and should be a \%hashname; the
13166: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 13167: be derived from the env
1.191 harris41 13168:
13169: =item *
13170:
1.243 albertel 13171: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13172: uses critical subroutine
1.191 harris41 13173:
13174: =item *
13175:
1.243 albertel 13176: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13177: all args are optional
1.191 harris41 13178:
13179: =item *
13180:
1.717 albertel 13181: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13182: dumps the complete (or key matching regexp) namespace into a hash
13183: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13184: normally &store()ed into
13185:
13186: $range should be either an integer '100' (give me the first 100
13187: matching records)
13188: or be two integers sperated by a - with no spaces
13189: '30-50' (give me the 30th through the 50th matching
13190: records)
13191:
13192:
13193: =item *
13194:
13195: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13196: replaces a &store() version of data with a replacement set of data
13197: for a particular resource in a namespace passed in the $storehash hash
13198: reference
13199:
13200: =item *
13201:
1.243 albertel 13202: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13203: works very similar to store/cstore, but all data is stored in a
13204: temporary location and can be reset using tmpreset, $storehash should
13205: be a hash reference, returns nothing on success
1.191 harris41 13206:
13207: =item *
13208:
1.243 albertel 13209: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13210: similar to restore, but all data is stored in a temporary location and
13211: can be reset using tmpreset. Returns a hash of values on success,
13212: error string otherwise.
1.191 harris41 13213:
13214: =item *
13215:
1.243 albertel 13216: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13217: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 13218:
13219: =item *
13220:
1.243 albertel 13221: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13222: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 13223:
13224: =item *
13225:
1.243 albertel 13226: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13227: namesp ($udom and $uname are optional)
1.191 harris41 13228:
13229: =item *
13230:
1.702 albertel 13231: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 13232: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 13233: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 13234:
1.702 albertel 13235: $range should be either an integer '100' (give me the first 100
13236: matching records)
13237: or be two integers sperated by a - with no spaces
13238: '30-50' (give me the 30th through the 50th matching
13239: records)
1.449 matthew 13240: =item *
13241:
13242: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13243: $store can be a scalar, an array reference, or if the amount to be
13244: incremented is > 1, a hash reference.
13245:
13246: ($udom and $uname are optional)
1.191 harris41 13247:
13248: =item *
13249:
1.243 albertel 13250: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13251: ($udom and $uname are optional)
1.191 harris41 13252:
13253: =item *
13254:
1.243 albertel 13255: cput($namespace,$storehash,$udom,$uname) : critical put
13256: ($udom and $uname are optional)
1.191 harris41 13257:
13258: =item *
13259:
1.748 albertel 13260: newput($namespace,$storehash,$udom,$uname) :
13261:
13262: Attempts to store the items in the $storehash, but only if they don't
13263: currently exist, if this succeeds you can be certain that you have
13264: successfully created a new key value pair in the $namespace db.
13265:
13266:
13267: Args:
13268: $namespace: name of database to store values to
13269: $storehash: hashref to store to the db
13270: $udom: (optional) domain of user containing the db
13271: $uname: (optional) name of user caontaining the db
13272:
13273: Returns:
13274: 'ok' -> succeeded in storing all keys of $storehash
13275: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13276: least <key> already existed in the db (other
13277: requested keys may also already exist)
1.967 bisitz 13278: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 13279: 'con_lost' -> unable to contact request server
13280: 'refused' -> action was not allowed by remote machine
13281:
13282:
13283: =item *
13284:
1.243 albertel 13285: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13286: reference filled in from namesp (encrypts the return communication)
13287: ($udom and $uname are optional)
1.191 harris41 13288:
13289: =item *
13290:
1.243 albertel 13291: log($udom,$name,$home,$message) : write to permanent log for user; use
13292: critical subroutine
13293:
1.806 raeburn 13294: =item *
13295:
1.860 raeburn 13296: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13297: array reference filled in from namespace found in domain level on either
13298: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 13299:
13300: =item *
13301:
1.860 raeburn 13302: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13303: domain level either on specified domain server ($uhome) or primary domain
13304: server ($udom and $uhome are optional)
1.806 raeburn 13305:
1.943 raeburn 13306: =item *
13307:
1.1240 raeburn 13308: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13309: for: authentication, language, quotas, timezone, date locale, and portal URL in
13310: the target domain.
13311:
13312: May also include additional key => value pairs for the following groups:
13313:
13314: =over
13315:
13316: =item
13317: disk quotas (MB allocated by default to portfolios and authoring spaces).
13318:
13319: =over
13320:
13321: =item defaultquota, authorquota
13322:
13323: =back
13324:
13325: =item
13326: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13327: portfolio for users).
13328:
13329: =over
13330:
13331: =item
13332: aboutme, blog, webdav, portfolio
13333:
13334: =back
13335:
13336: =item
13337: requestcourses: ability to request courses, and how requests are processed.
13338:
13339: =over
13340:
13341: =item
1.1246 raeburn 13342: official, unofficial, community, textbook
1.1240 raeburn 13343:
13344: =back
13345:
13346: =item
13347: inststatus: types of institutional affiliation, and order in which they are displayed.
13348:
13349: =over
13350:
13351: =item
1.1256 raeburn 13352: inststatustypes, inststatusorder, inststatusguest
1.1240 raeburn 13353:
13354: =back
13355:
13356: =item
13357: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13358: for course's uploaded content.
13359:
13360: =over
13361:
13362: =item
1.1246 raeburn 13363: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13364: communityquota, textbookquota
1.1240 raeburn 13365:
13366: =back
13367:
13368: =item
13369: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13370: on your servers.
13371:
13372: =over
13373:
13374: =item
13375: remotesessions, hostedsessions
13376:
13377: =back
13378:
13379: =back
13380:
13381: In cases where a domain coordinator has never used the "Set Domain Configuration"
13382: utility to create a configuration.db file on a domain's primary library server
13383: only the following domain defaults: auth_def, auth_arg_def, lang_def
13384: -- corresponding values are authentication type (internal, krb4, krb5,
13385: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13386: will be available. Values are retrieved from cache (if current), unless the
13387: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13388: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13389:
13390: Typical usage:
1.943 raeburn 13391:
1.1240 raeburn 13392: %domdefaults = &get_domain_defaults($target_domain);
1.943 raeburn 13393:
1.243 albertel 13394: =back
13395:
13396: =head2 Network Status Functions
13397:
13398: =over 4
1.191 harris41 13399:
13400: =item *
13401:
1.1137 raeburn 13402: dirlist() : return directory list based on URI (first arg).
13403:
13404: Inputs: 1 required, 5 optional.
13405:
13406: =over
13407:
13408: =item
13409: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13410:
13411: =item
13412: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13413:
13414: =item
13415: $username - username of user/course to be listed. Extracted from $uri if absent.
13416:
13417: =item
13418: $getpropath - boolean: 1 if prepend path using &propath().
13419:
13420: =item
13421: $getuserdir - boolean: 1 if prepend path for "userfiles".
13422:
13423: =item
13424: $alternateRoot - path to prepend in place of path from $uri.
13425:
13426: =back
13427:
13428: Returns: Array of up to two items.
13429:
13430: =over
13431:
13432: a reference to an array of files/subdirectories
13433:
13434: =over
13435:
13436: Each element in the array of files/subdirectories is a & separated list of
13437: item name and the result of running stat on the item. If dirlist was requested
13438: for a file instead of a directory, the item name will be ''. For a directory
13439: listing, if the item is a metadata file, the element will end &N&M
13440: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13441: default copyright set (1).
13442:
13443: =back
13444:
13445: a scalar containing error condition (if encountered).
13446:
13447: =over
13448:
13449: =item
13450: no_host (no homeserver identified for $username:$domain).
13451:
13452: =item
13453: no_such_host (server contacted for listing not identified as valid host).
13454:
13455: =item
13456: con_lost (connection to remote server failed).
13457:
13458: =item
13459: refused (invalid $username:$domain received on lond side).
13460:
13461: =item
13462: no_such_dir (directory at specified path on lond side does not exist).
13463:
13464: =item
13465: empty (directory at specified path on lond side is empty).
13466:
13467: =over
13468:
13469: This is currently not encountered because the &ls3, &ls2,
13470: &ls (_handler) routines on the lond side do not filter out
13471: . and .. from a directory listing.
13472:
13473: =back
13474:
13475: =back
13476:
13477: =back
1.191 harris41 13478:
13479: =item *
13480:
1.243 albertel 13481: spareserver() : find server with least workload from spare.tab
13482:
1.986 foxr 13483:
13484: =item *
13485:
13486: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13487: if there is no corresponding loncapa host.
13488:
1.243 albertel 13489: =back
13490:
1.986 foxr 13491:
1.243 albertel 13492: =head2 Apache Request
13493:
13494: =over 4
1.191 harris41 13495:
13496: =item *
13497:
1.243 albertel 13498: ssi($url,%hash) : server side include, does a complete request cycle on url to
13499: localhost, posts hash
13500:
13501: =back
13502:
13503: =head2 Data to String to Data
13504:
13505: =over 4
1.191 harris41 13506:
13507: =item *
13508:
1.243 albertel 13509: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13510: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 13511:
13512: =item *
13513:
1.243 albertel 13514: hashref2str($hashref) : convert a hashref into a string complete with
13515: escaping and '=' and '&' separators, supports elements that are
13516: arrayrefs and hashrefs
1.191 harris41 13517:
13518: =item *
13519:
1.243 albertel 13520: arrayref2str($arrayref) : convert an arrayref into a string complete
13521: with escaping and '&' separators, supports elements that are arrayrefs
13522: and hashrefs
1.191 harris41 13523:
13524: =item *
13525:
1.243 albertel 13526: str2hash($string) : convert string to hash using unescaping and
13527: splitting on '=' and '&', supports elements that are arrayrefs and
13528: hashrefs
1.191 harris41 13529:
13530: =item *
13531:
1.243 albertel 13532: str2array($string) : convert string to hash using unescaping and
13533: splitting on '&', supports elements that are arrayrefs and hashrefs
13534:
13535: =back
13536:
13537: =head2 Logging Routines
13538:
13539:
13540: These routines allow one to make log messages in the lonnet.log and
13541: lonnet.perm logfiles.
1.191 harris41 13542:
1.1119 foxr 13543: =over 4
13544:
1.191 harris41 13545: =item *
13546:
1.243 albertel 13547: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 13548:
13549: =item *
13550:
1.243 albertel 13551: logthis() : append message to the normal lonnet.log file, it gets
13552: preiodically rolled over and deleted.
1.191 harris41 13553:
13554: =item *
13555:
1.243 albertel 13556: logperm() : append a permanent message to lonnet.perm.log, this log
13557: file never gets deleted by any automated portion of the system, only
13558: messages of critical importance should go in here.
13559:
1.1119 foxr 13560:
1.243 albertel 13561: =back
13562:
13563: =head2 General File Helper Routines
13564:
13565: =over 4
1.191 harris41 13566:
13567: =item *
13568:
1.481 raeburn 13569: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13570: (a) files in /uploaded
13571: (i) If a local copy of the file exists -
13572: compares modification date of local copy with last-modified date for
13573: definitive version stored on home server for course. If local copy is
13574: stale, requests a new version from the home server and stores it.
13575: If the original has been removed from the home server, then local copy
13576: is unlinked.
13577: (ii) If local copy does not exist -
13578: requests the file from the home server and stores it.
13579:
13580: If $caller is 'uploadrep':
13581: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13582: for request for files originally uploaded via DOCS.
13583: - returns 'ok' if fresh local copy now available, -1 otherwise.
13584:
13585: Otherwise:
13586: This indicates a call from the content generation phase of the request.
13587: - returns the entire contents of the file or -1.
13588:
13589: (b) files in /res
13590: - returns the entire contents of a file or -1;
13591: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 13592:
1.712 albertel 13593:
13594: =item *
13595:
13596: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13597: reference
13598:
13599: returns either a stat() list of data about the file or an empty list
13600: if the file doesn't exist or couldn't find out about it (connection
13601: problems or user unknown)
13602:
1.191 harris41 13603: =item *
13604:
1.243 albertel 13605: filelocation($dir,$file) : returns file system location of a file
13606: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13607: directory that relative $file lookups are to looked in ($dir of /a/dir
13608: and a file of ../bob will become /a/bob)
1.191 harris41 13609:
13610: =item *
13611:
13612: hreflocation($dir,$file) : returns file system location or a URL; same as
13613: filelocation except for hrefs
13614:
13615: =item *
13616:
13617: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13618:
1.243 albertel 13619: =back
13620:
1.608 albertel 13621: =head2 Usererfile file routines (/uploaded*)
13622:
13623: =over 4
13624:
13625: =item *
13626:
13627: userfileupload(): main rotine for putting a file in a user or course's
13628: filespace, arguments are,
13629:
1.620 albertel 13630: formname - required - this is the name of the element in $env where the
1.608 albertel 13631: filename, and the contents of the file to create/modifed exist
1.620 albertel 13632: the filename is in $env{'form.'.$formname.'.filename'} and the
13633: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 13634: context - if coursedoc, store the file in the course of the active role
13635: of the current user;
13636: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13637: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 13638: subdir - required - subdirectory to put the file in under ../userfiles/
13639: if undefined, it will be placed in "unknown"
13640:
13641: (This routine calls clean_filename() to remove any dangerous
13642: characters from the filename, and then calls finuserfileupload() to
13643: complete the transaction)
13644:
13645: returns either the url of the uploaded file (/uploaded/....) if successful
13646: and /adm/notfound.html if unsuccessful
13647:
13648: =item *
13649:
13650: clean_filename(): routine for cleaing a filename up for storage in
13651: userfile space, argument is:
13652:
13653: filename - proposed filename
13654:
13655: returns: the new clean filename
13656:
13657: =item *
13658:
1.1090 raeburn 13659: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 13660: userspace, probably shouldn't be called directly
13661:
13662: docuname: username or courseid of destination for the file
13663: docudom: domain of user/course of destination for the file
13664: formname: same as for userfileupload()
1.1090 raeburn 13665: fname: filename (including subdirectories) for the file
13666: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13667: allfiles: reference to hash used to store objects found by parser
13668: codebase: reference to hash used for codebases of java objects found by parser
13669: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13670: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13671: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13672: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13673: context: if 'overwrite', will move the uploaded file from its temporary location to
13674: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 13675: mimetype: reference to scalar to accommodate mime type determined
13676: from File::MMagic if $parser = parse.
1.608 albertel 13677:
13678: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 13679: and /adm/notfound.html if unsuccessful (or an error message if context
13680: was 'overwrite').
13681:
1.608 albertel 13682:
13683: =item *
13684:
13685: renameuserfile(): renames an existing userfile to a new name
13686:
13687: Args:
13688: docuname: username or courseid of destination for the file
13689: docudom: domain of user/course of destination for the file
13690: old: current file name (including any subdirs under userfiles)
13691: new: desired file name (including any subdirs under userfiles)
13692:
13693: =item *
13694:
13695: mkdiruserfile(): creates a directory is a userfiles dir
13696:
13697: Args:
13698: docuname: username or courseid of destination for the file
13699: docudom: domain of user/course of destination for the file
13700: dir: dir to create (including any subdirs under userfiles)
13701:
13702: =item *
13703:
13704: removeuserfile(): removes a file that exists in userfiles
13705:
13706: Args:
13707: docuname: username or courseid of destination for the file
13708: docudom: domain of user/course of destination for the file
13709: fname: filname to delete (including any subdirs under userfiles)
13710:
13711: =item *
13712:
13713: removeuploadedurl(): convience function for removeuserfile()
13714:
13715: Args:
13716: url: a full /uploaded/... url to delete
13717:
1.747 albertel 13718: =item *
13719:
13720: get_portfile_permissions():
13721: Args:
13722: domain: domain of user or course contain the portfolio files
13723: user: name of user or num of course contain the portfolio files
13724: Returns:
13725: hashref of a dump of the proper file_permissions.db
13726:
13727:
13728: =item *
13729:
13730: get_access_controls():
13731:
13732: Args:
13733: current_permissions: the hash ref returned from get_portfile_permissions()
13734: group: (optional) the group you want the files associated with
13735: file: (optional) the file you want access info on
13736:
13737: Returns:
1.749 raeburn 13738: a hash (keys are file names) of hashes containing
13739: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13740: values are XML containing access control settings (see below)
1.747 albertel 13741:
13742: Internal notes:
13743:
1.749 raeburn 13744: access controls are stored in file_permissions.db as key=value pairs.
13745: key -> path to file/file_name\0uniqueID:scope_end_start
13746: where scope -> public,guest,course,group,domains or users.
13747: end -> UNIX time for end of access (0 -> no end date)
13748: start -> UNIX time for start of access
13749:
13750: value -> XML description of access control
13751: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13752: <start></start>
13753: <end></end>
13754:
13755: <password></password> for scope type = guest
13756:
13757: <domain></domain> for scope type = course or group
13758: <number></number>
13759: <roles id="">
13760: <role></role>
13761: <access></access>
13762: <section></section>
13763: <group></group>
13764: </roles>
13765:
13766: <dom></dom> for scope type = domains
13767:
13768: <users> for scope type = users
13769: <user>
13770: <uname></uname>
13771: <udom></udom>
13772: </user>
13773: </users>
13774: </scope>
13775:
13776: Access data is also aggregated for each file in an additional key=value pair:
13777: key -> path to file/file_name\0accesscontrol
13778: value -> reference to hash
13779: hash contains key = value pairs
13780: where key = uniqueID:scope_end_start
13781: value = UNIX time record was last updated
13782:
13783: Used to improve speed of look-ups of access controls for each file.
13784:
13785: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13786:
1.1198 raeburn 13787: =item *
13788:
1.749 raeburn 13789: modify_access_controls():
13790:
13791: Modifies access controls for a portfolio file
13792: Args
13793: 1. file name
13794: 2. reference to hash of required changes,
13795: 3. domain
13796: 4. username
13797: where domain,username are the domain of the portfolio owner
13798: (either a user or a course)
13799:
13800: Returns:
13801: 1. result of additions or updates ('ok' or 'error', with error message).
13802: 2. result of deletions ('ok' or 'error', with error message).
13803: 3. reference to hash of any new or updated access controls.
13804: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13805: key = integer (inbound ID)
1.1198 raeburn 13806: value = uniqueID
13807:
13808: =item *
13809:
13810: get_timebased_id():
13811:
13812: Attempts to get a unique timestamp-based suffix for use with items added to a
13813: course via the Course Editor (e.g., folders, composite pages,
13814: group bulletin boards).
13815:
13816: Args: (first three required; six others optional)
13817:
13818: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13819: docssequence, or name of group
13820:
13821: 2. keyid (alphanumeric): name of temporary locking key in hash,
13822: e.g., num, boardids
13823:
13824: 3. namespace: name of gdbm file used to store suffixes already assigned;
13825: file will be named nohist_namespace.db
13826:
13827: 4. cdom: domain of course; default is current course domain from %env
13828:
13829: 5. cnum: course number; default is current course number from %env
13830:
13831: 6. idtype: set to concat if an additional digit is to be appended to the
13832: unix timestamp to form the suffix, if the plain timestamp is already
13833: in use. Default is to not do this, but simply increment the unix
13834: timestamp by 1 until a unique key is obtained.
13835:
13836: 7. who: holder of locking key; defaults to user:domain for user.
13837:
13838: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13839: retrying); default is 3.
13840:
13841: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13842:
13843: Returns:
13844:
13845: 1. suffix obtained (numeric)
13846:
13847: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13848:
13849: 3. error: contains (localized) error message if an error occurred.
13850:
1.747 albertel 13851:
1.608 albertel 13852: =back
13853:
1.243 albertel 13854: =head2 HTTP Helper Routines
13855:
13856: =over 4
13857:
1.191 harris41 13858: =item *
13859:
13860: escape() : unpack non-word characters into CGI-compatible hex codes
13861:
13862: =item *
13863:
13864: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13865:
1.243 albertel 13866: =back
13867:
13868: =head1 PRIVATE SUBROUTINES
13869:
13870: =head2 Underlying communication routines (Shouldn't call)
13871:
13872: =over 4
13873:
13874: =item *
13875:
13876: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13877:
13878: =item *
13879:
13880: reply() : uses subreply to send a message to remote machine, logs all failures
13881:
13882: =item *
13883:
13884: critical() : passes a critical message to another server; if cannot
13885: get through then place message in connection buffer directory and
13886: returns con_delayed, if incapable of saving message, returns
13887: con_failed
13888:
13889: =item *
13890:
13891: reconlonc() : tries to reconnect lonc client processes.
13892:
13893: =back
13894:
13895: =head2 Resource Access Logging
13896:
13897: =over 4
13898:
13899: =item *
13900:
13901: flushcourselogs() : flush (save) buffer logs and access logs
13902:
13903: =item *
13904:
13905: courselog($what) : save message for course in hash
13906:
13907: =item *
13908:
13909: courseacclog($what) : save message for course using &courselog(). Perform
13910: special processing for specific resource types (problems, exams, quizzes, etc).
13911:
1.191 harris41 13912: =item *
13913:
13914: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13915: as a PerlChildExitHandler
1.243 albertel 13916:
13917: =back
13918:
13919: =head2 Other
13920:
13921: =over 4
13922:
13923: =item *
13924:
13925: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 13926:
13927: =back
13928:
13929: =cut
1.877 foxr 13930:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>