Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1162
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1162 ! raeburn 4: # $Id: lonnet.pm,v 1.1161 2012/03/20 13:36:22 www 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.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
1.871 albertel 81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 85: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 86:
1.1 albertel 87: use IO::Socket;
1.31 www 88: use GDBM_File;
1.208 albertel 89: use HTML::LCParser;
1.88 www 90: use Fcntl qw(:flock);
1.870 albertel 91: use Storable qw(thaw nfreeze);
1.539 albertel 92: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 93: use Cache::Memcached;
1.676 albertel 94: use Digest::MD5;
1.790 albertel 95: use Math::Random;
1.1024 raeburn 96: use File::MMagic;
1.807 albertel 97: use LONCAPA qw(:DEFAULT :match);
1.740 www 98: use LONCAPA::Configuration;
1.1160 www 99: use LONCAPA::lonmetadata;
1.1117 foxr 100:
1.1090 raeburn 101: use File::Copy;
1.676 albertel 102:
1.195 www 103: my $readit;
1.550 foxr 104: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 105:
1.619 albertel 106: require Exporter;
107:
108: our @ISA = qw (Exporter);
109: our @EXPORT = qw(%env);
110:
1.449 matthew 111:
1.1 albertel 112: # --------------------------------------------------------------------- Logging
1.729 www 113: {
114: my $logid;
115: sub instructor_log {
1.957 raeburn 116: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
117: if (($cnum eq '') || ($cdom eq '')) {
118: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
119: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
120: }
1.729 www 121: $logid++;
1.957 raeburn 122: my $now = time();
123: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 124: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 125: { $id => {
126: 'exe_uname' => $env{'user.name'},
127: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 128: 'exe_time' => $now,
1.730 www 129: 'exe_ip' => $ENV{'REMOTE_ADDR'},
130: 'delflag' => $delflag,
131: 'logentry' => $storehash,
132: 'uname' => $uname,
133: 'udom' => $udom,
134: }
1.957 raeburn 135: },$cdom,$cnum);
1.729 www 136: }
137: }
1.1 albertel 138:
1.163 harris41 139: sub logtouch {
140: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 141: unless (-e "$execdir/logs/lonnet.log") {
142: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 143: close $fh;
144: }
145: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
146: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
147: }
148:
1.1 albertel 149: sub logthis {
150: my $message=shift;
151: my $execdir=$perlvar{'lonDaemons'};
152: my $now=time;
153: my $local=localtime($now);
1.448 albertel 154: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 155: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
156: print $fh $logstring;
1.448 albertel 157: close($fh);
158: }
1.1 albertel 159: return 1;
160: }
161:
162: sub logperm {
163: my $message=shift;
164: my $execdir=$perlvar{'lonDaemons'};
165: my $now=time;
166: my $local=localtime($now);
1.448 albertel 167: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
168: print $fh "$now:$message:$local\n";
169: close($fh);
170: }
1.1 albertel 171: return 1;
172: }
173:
1.850 albertel 174: sub create_connection {
1.853 albertel 175: my ($hostname,$lonid) = @_;
1.851 albertel 176: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 177: Type => SOCK_STREAM,
178: Timeout => 10);
179: return 0 if (!$client);
1.890 albertel 180: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 181: my $result = <$client>;
182: chomp($result);
183: return 1 if ($result eq 'done');
184: return 0;
185: }
186:
1.983 raeburn 187: sub get_server_timezone {
188: my ($cnum,$cdom) = @_;
189: my $home=&homeserver($cnum,$cdom);
190: if ($home ne 'no_host') {
191: my $cachetime = 24*3600;
192: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
193: if (defined($cached)) {
194: return $timezone;
195: } else {
196: my $timezone = &reply('servertimezone',$home);
197: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
198: }
199: }
200: }
1.850 albertel 201:
1.1106 raeburn 202: sub get_server_distarch {
203: my ($lonhost,$ignore_cache) = @_;
204: if (defined($lonhost)) {
205: if (!defined(&hostname($lonhost))) {
206: return;
207: }
208: my $cachetime = 12*3600;
209: if (!$ignore_cache) {
210: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
211: if (defined($cached)) {
212: return $distarch;
213: }
214: }
215: my $rep = &reply('serverdistarch',$lonhost);
216: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
217: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
218: $rep eq '') {
219: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
220: }
221: }
222: return;
223: }
224:
1.993 raeburn 225: sub get_server_loncaparev {
1.1073 raeburn 226: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 227: if (defined($lonhost)) {
228: if (!defined(&hostname($lonhost))) {
229: undef($lonhost);
230: }
231: }
232: if (!defined($lonhost)) {
233: if (defined(&domain($dom,'primary'))) {
234: $lonhost=&domain($dom,'primary');
235: if ($lonhost eq 'no_host') {
236: undef($lonhost);
237: }
238: }
239: }
240: if (defined($lonhost)) {
1.1073 raeburn 241: my $cachetime = 12*3600;
242: if (!$ignore_cache) {
243: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
244: if (defined($cached)) {
245: return $loncaparev;
246: }
247: }
248: my ($answer,$loncaparev);
249: my @ids=¤t_machine_ids();
250: if (grep(/^\Q$lonhost\E$/,@ids)) {
251: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 252: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 253: $loncaparev = $1;
254: }
255: } else {
256: $answer = &reply('serverloncaparev',$lonhost);
257: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
258: if ($caller eq 'loncron') {
259: my $ua=new LWP::UserAgent;
1.1082 raeburn 260: $ua->timeout(4);
1.1073 raeburn 261: my $protocol = $protocol{$lonhost};
262: $protocol = 'http' if ($protocol ne 'https');
263: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
264: my $request=new HTTP::Request('GET',$url);
265: my $response=$ua->request($request);
266: unless ($response->is_error()) {
267: my $content = $response->content;
1.1081 raeburn 268: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 269: $loncaparev = $1;
270: }
271: }
272: } else {
273: $loncaparev = $loncaparevs{$lonhost};
274: }
1.1081 raeburn 275: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 276: $loncaparev = $1;
277: }
1.993 raeburn 278: }
1.1073 raeburn 279: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 280: }
281: }
282:
1.1074 raeburn 283: sub get_server_homeID {
284: my ($hostname,$ignore_cache,$caller) = @_;
285: unless ($ignore_cache) {
286: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
287: if (defined($cached)) {
288: return $serverhomeID;
289: }
290: }
291: my $cachetime = 12*3600;
292: my $serverhomeID;
293: if ($caller eq 'loncron') {
294: my @machine_ids = &machine_ids($hostname);
295: foreach my $id (@machine_ids) {
296: my $response = &reply('serverhomeID',$id);
297: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
298: $serverhomeID = $response;
299: last;
300: }
301: }
302: if ($serverhomeID eq '') {
303: $serverhomeID = $machine_ids[-1];
304: }
305: } else {
306: $serverhomeID = $serverhomeIDs{$hostname};
307: }
308: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
309: }
310:
1.1121 raeburn 311: sub get_remote_globals {
312: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 313: my ($result,%returnhash,%whatneeded);
314: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 315: foreach my $what (sort(keys(%{$whathash}))) {
316: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 317: my ($response,$cached);
1.1121 raeburn 318: unless ($ignore_cache) {
1.1125 raeburn 319: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 320: }
321: if (defined($cached)) {
1.1125 raeburn 322: $returnhash{$what} = $response;
1.1121 raeburn 323: } else {
1.1125 raeburn 324: $whatneeded{$what} = 1;
1.1121 raeburn 325: }
326: }
1.1125 raeburn 327: if (keys(%whatneeded) == 0) {
328: $result = 'ok';
329: } else {
1.1121 raeburn 330: my $requested = &freeze_escape(\%whatneeded);
331: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 332: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
333: ($rep eq 'unknown_cmd')) {
334: $result = $rep;
335: } else {
336: $result = 'ok';
1.1121 raeburn 337: my @pairs=split(/\&/,$rep);
1.1125 raeburn 338: foreach my $item (@pairs) {
339: my ($key,$value)=split(/=/,$item,2);
340: my $what = &unescape($key);
341: my $hashid = $lonhost.'-'.$what;
342: $returnhash{$what}=&thaw_unescape($value);
343: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 344: }
345: }
346: }
347: }
1.1125 raeburn 348: return ($result,\%returnhash);
1.1121 raeburn 349: }
350:
1.1124 raeburn 351: sub remote_devalidate_cache {
352: my ($lonhost,$name,$id) = @_;
1.1130 raeburn 353: my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124 raeburn 354: return $response;
355: }
356:
1.1 albertel 357: # -------------------------------------------------- Non-critical communication
358: sub subreply {
359: my ($cmd,$server)=@_;
1.838 albertel 360: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 361: #
362: # With loncnew process trimming, there's a timing hole between lonc server
363: # process exit and the master server picking up the listen on the AF_UNIX
364: # socket. In that time interval, a lock file will exist:
365:
366: my $lockfile=$peerfile.".lock";
367: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
368: sleep(1);
369: }
370: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 371: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 372: #
1.550 foxr 373: # We'll give the connection a few tries before abandoning it. If
374: # connection is not possible, we'll con_lost back to the client.
375: #
376: my $client;
377: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
378: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
379: Type => SOCK_STREAM,
380: Timeout => 10);
1.869 albertel 381: if ($client) {
1.550 foxr 382: last; # Connected!
1.850 albertel 383: } else {
1.853 albertel 384: &create_connection(&hostname($server),$server);
1.550 foxr 385: }
1.850 albertel 386: sleep(1); # Try again later if failed connection.
1.550 foxr 387: }
388: my $answer;
389: if ($client) {
1.704 albertel 390: print $client "sethost:$server:$cmd\n";
1.550 foxr 391: $answer=<$client>;
392: if (!$answer) { $answer="con_lost"; }
393: chomp($answer);
394: } else {
395: $answer = 'con_lost'; # Failed connection.
396: }
1.1 albertel 397: return $answer;
398: }
399:
400: sub reply {
401: my ($cmd,$server)=@_;
1.838 albertel 402: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 403: my $answer=subreply($cmd,$server);
1.65 www 404: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 405: &logthis("<font color=\"blue\">WARNING:".
1.12 www 406: " $cmd to $server returned $answer</font>");
407: }
1.1 albertel 408: return $answer;
409: }
410:
411: # ----------------------------------------------------------- Send USR1 to lonc
412:
413: sub reconlonc {
1.891 albertel 414: my ($lonid) = @_;
415: my $hostname = &hostname($lonid);
416: if ($lonid) {
417: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
418: if ($hostname && -e $peerfile) {
419: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
420: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
421: Type => SOCK_STREAM,
422: Timeout => 10);
423: if ($client) {
424: print $client ("reset_retries\n");
425: my $answer=<$client>;
426: #reset just this one.
427: }
428: }
429: return;
430: }
431:
1.836 www 432: &logthis("Trying to reconnect lonc");
1.1 albertel 433: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 434: if (open(my $fh,"<$loncfile")) {
1.1 albertel 435: my $loncpid=<$fh>;
436: chomp($loncpid);
437: if (kill 0 => $loncpid) {
438: &logthis("lonc at pid $loncpid responding, sending USR1");
439: kill USR1 => $loncpid;
440: sleep 1;
1.836 www 441: } else {
1.12 www 442: &logthis(
1.672 albertel 443: "<font color=\"blue\">WARNING:".
1.12 www 444: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 445: }
446: } else {
1.836 www 447: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 448: }
449: }
450:
451: # ------------------------------------------------------ Critical communication
1.12 www 452:
1.1 albertel 453: sub critical {
454: my ($cmd,$server)=@_;
1.838 albertel 455: unless (&hostname($server)) {
1.672 albertel 456: &logthis("<font color=\"blue\">WARNING:".
1.89 www 457: " Critical message to unknown server ($server)</font>");
458: return 'no_such_host';
459: }
1.1 albertel 460: my $answer=reply($cmd,$server);
461: if ($answer eq 'con_lost') {
462: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 463: my $answer=reply($cmd,$server);
1.1 albertel 464: if ($answer eq 'con_lost') {
465: my $now=time;
466: my $middlename=$cmd;
1.5 www 467: $middlename=substr($middlename,0,16);
1.1 albertel 468: $middlename=~s/\W//g;
469: my $dfilename=
1.305 www 470: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
471: $dumpcount++;
1.1 albertel 472: {
1.448 albertel 473: my $dfh;
474: if (open($dfh,">$dfilename")) {
475: print $dfh "$cmd\n";
476: close($dfh);
477: }
1.1 albertel 478: }
479: sleep 2;
480: my $wcmd='';
481: {
1.448 albertel 482: my $dfh;
483: if (open($dfh,"<$dfilename")) {
484: $wcmd=<$dfh>;
485: close($dfh);
486: }
1.1 albertel 487: }
488: chomp($wcmd);
1.7 www 489: if ($wcmd eq $cmd) {
1.672 albertel 490: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 491: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 492: &logperm("D:$server:$cmd");
493: return 'con_delayed';
494: } else {
1.672 albertel 495: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 496: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 497: &logperm("F:$server:$cmd");
498: return 'con_failed';
499: }
500: }
501: }
502: return $answer;
1.405 albertel 503: }
504:
1.755 albertel 505: # ------------------------------------------- check if return value is an error
506:
507: sub error {
508: my ($result) = @_;
1.756 albertel 509: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 510: if ($2 == 2) { return undef; }
511: return $1;
512: }
513: return undef;
514: }
515:
1.783 albertel 516: sub convert_and_load_session_env {
517: my ($lonidsdir,$handle)=@_;
518: my @profile;
519: {
1.917 albertel 520: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
521: if (!$opened) {
1.915 albertel 522: return 0;
523: }
1.783 albertel 524: flock($idf,LOCK_SH);
525: @profile=<$idf>;
526: close($idf);
527: }
528: my %temp_env;
529: foreach my $line (@profile) {
1.786 albertel 530: if ($line !~ m/=/) {
531: return 0;
532: }
1.783 albertel 533: chomp($line);
534: my ($envname,$envvalue)=split(/=/,$line,2);
535: $temp_env{&unescape($envname)} = &unescape($envvalue);
536: }
537: unlink("$lonidsdir/$handle.id");
538: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
539: 0640)) {
540: %disk_env = %temp_env;
541: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
542: untie(%disk_env);
543: }
1.786 albertel 544: return 1;
1.783 albertel 545: }
546:
1.374 www 547: # ------------------------------------------- Transfer profile into environment
1.780 albertel 548: my $env_loaded;
549: sub transfer_profile_to_env {
1.788 albertel 550: my ($lonidsdir,$handle,$force_transfer) = @_;
551: if (!$force_transfer && $env_loaded) { return; }
1.374 www 552:
1.720 albertel 553: if (!defined($lonidsdir)) {
554: $lonidsdir = $perlvar{'lonIDsDir'};
555: }
556: if (!defined($handle)) {
557: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
558: }
559:
1.786 albertel 560: my $convert;
561: {
1.917 albertel 562: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
563: if (!$opened) {
1.915 albertel 564: return;
565: }
1.786 albertel 566: flock($idf,LOCK_SH);
567: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
568: &GDBM_READER(),0640)) {
569: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
570: untie(%disk_env);
571: } else {
572: $convert = 1;
573: }
574: }
575: if ($convert) {
576: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
577: &logthis("Failed to load session, or convert session.");
578: }
1.374 www 579: }
1.783 albertel 580:
1.786 albertel 581: my %remove;
1.783 albertel 582: while ( my $envname = each(%env) ) {
1.433 matthew 583: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
584: if ($time < time-300) {
1.783 albertel 585: $remove{$key}++;
1.433 matthew 586: }
587: }
588: }
1.783 albertel 589:
1.619 albertel 590: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 591: $env_loaded=1;
1.783 albertel 592: foreach my $expired_key (keys(%remove)) {
1.433 matthew 593: &delenv($expired_key);
1.374 www 594: }
1.1 albertel 595: }
596:
1.916 albertel 597: # ---------------------------------------------------- Check for valid session
598: sub check_for_valid_session {
1.1155 raeburn 599: my ($r,$name) = @_;
1.916 albertel 600: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 601: if ($name eq '') {
602: $name = 'lonID';
603: }
604: my $lonid=$cookies{$name};
1.916 albertel 605: return undef if (!$lonid);
606:
607: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 608: my $lonidsdir;
609: if ($name eq 'lonDAV') {
610: $lonidsdir=$r->dir_config('lonDAVsessDir');
611: } else {
612: $lonidsdir=$r->dir_config('lonIDsDir');
613: }
1.916 albertel 614: return undef if (!-e "$lonidsdir/$handle.id");
615:
1.917 albertel 616: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
617: return undef if (!$opened);
1.916 albertel 618:
619: flock($idf,LOCK_SH);
620: my %disk_env;
621: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
622: &GDBM_READER(),0640)) {
623: return undef;
624: }
625:
626: if (!defined($disk_env{'user.name'})
627: || !defined($disk_env{'user.domain'})) {
628: return undef;
629: }
630: return $handle;
631: }
632:
1.830 albertel 633: sub timed_flock {
634: my ($file,$lock_type) = @_;
635: my $failed=0;
636: eval {
637: local $SIG{__DIE__}='DEFAULT';
638: local $SIG{ALRM}=sub {
639: $failed=1;
640: die("failed lock");
641: };
642: alarm(13);
643: flock($file,$lock_type);
644: alarm(0);
645: };
646: if ($failed) {
647: return undef;
648: } else {
649: return 1;
650: }
651: }
652:
1.5 www 653: # ---------------------------------------------------------- Append Environment
654:
655: sub appenv {
1.949 raeburn 656: my ($newenv,$roles) = @_;
657: if (ref($newenv) eq 'HASH') {
658: foreach my $key (keys(%{$newenv})) {
659: my $refused = 0;
660: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
661: $refused = 1;
662: if (ref($roles) eq 'ARRAY') {
663: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
664: if (grep(/^\Q$role\E$/,@{$roles})) {
665: $refused = 0;
666: }
667: }
668: }
669: if ($refused) {
670: &logthis("<font color=\"blue\">WARNING: ".
671: "Attempt to modify environment ".$key." to ".$newenv->{$key}
672: .'</font>');
673: delete($newenv->{$key});
674: } else {
675: $env{$key}=$newenv->{$key};
676: }
677: }
678: my $opened = open(my $env_file,'+<',$env{'user.environment'});
679: if ($opened
680: && &timed_flock($env_file,LOCK_EX)
681: &&
682: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
683: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
684: while (my ($key,$value) = each(%{$newenv})) {
685: $disk_env{$key} = $value;
686: }
687: untie(%disk_env);
1.35 www 688: }
1.191 harris41 689: }
1.56 www 690: return 'ok';
691: }
692: # ----------------------------------------------------- Delete from Environment
693:
694: sub delenv {
1.1104 raeburn 695: my ($delthis,$regexp,$roles) = @_;
696: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
697: my $refused = 1;
698: if (ref($roles) eq 'ARRAY') {
699: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
700: if (grep(/^\Q$role\E$/,@{$roles})) {
701: $refused = 0;
702: }
703: }
704: if ($refused) {
705: &logthis("<font color=\"blue\">WARNING: ".
706: "Attempt to delete from environment ".$delthis);
707: return 'error';
708: }
1.56 www 709: }
1.917 albertel 710: my $opened = open(my $env_file,'+<',$env{'user.environment'});
711: if ($opened
1.915 albertel 712: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 713: &&
714: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
715: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 716: foreach my $key (keys(%disk_env)) {
1.987 raeburn 717: if ($regexp) {
718: if ($key=~/^$delthis/) {
719: delete($env{$key});
720: delete($disk_env{$key});
721: }
722: } else {
723: if ($key=~/^\Q$delthis\E/) {
724: delete($env{$key});
725: delete($disk_env{$key});
726: }
727: }
1.448 albertel 728: }
1.783 albertel 729: untie(%disk_env);
1.5 www 730: }
731: return 'ok';
1.369 albertel 732: }
733:
1.790 albertel 734: sub get_env_multiple {
735: my ($name) = @_;
736: my @values;
737: if (defined($env{$name})) {
738: # exists is it an array
739: if (ref($env{$name})) {
740: @values=@{ $env{$name} };
741: } else {
742: $values[0]=$env{$name};
743: }
744: }
745: return(@values);
746: }
747:
1.958 www 748: # ------------------------------------------------------------------- Locking
749:
750: sub set_lock {
751: my ($text)=@_;
752: $locknum++;
753: my $id=$$.'-'.$locknum;
754: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
755: 'session.lock.'.$id => $text});
756: return $id;
757: }
758:
759: sub get_locks {
760: my $num=0;
761: my %texts=();
762: foreach my $lock (split(/\,/,$env{'session.locks'})) {
763: if ($lock=~/\w/) {
764: $num++;
765: $texts{$lock}=$env{'session.lock.'.$lock};
766: }
767: }
768: return ($num,%texts);
769: }
770:
771: sub remove_lock {
772: my ($id)=@_;
773: my $newlocks='';
774: foreach my $lock (split(/\,/,$env{'session.locks'})) {
775: if (($lock=~/\w/) && ($lock ne $id)) {
776: $newlocks.=','.$lock;
777: }
778: }
779: &appenv({'session.locks' => $newlocks});
780: &delenv('session.lock.'.$id);
781: }
782:
783: sub remove_all_locks {
784: my $activelocks=$env{'session.locks'};
785: foreach my $lock (split(/\,/,$env{'session.locks'})) {
786: if ($lock=~/\w/) {
787: &remove_lock($lock);
788: }
789: }
790: }
791:
792:
1.369 albertel 793: # ------------------------------------------ Find out current server userload
794: sub userload {
795: my $numusers=0;
796: {
797: opendir(LONIDS,$perlvar{'lonIDsDir'});
798: my $filename;
799: my $curtime=time;
800: while ($filename=readdir(LONIDS)) {
1.925 albertel 801: next if ($filename eq '.' || $filename eq '..');
802: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 803: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 804: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 805: }
806: closedir(LONIDS);
807: }
808: my $userloadpercent=0;
809: my $maxuserload=$perlvar{'lonUserLoadLim'};
810: if ($maxuserload) {
1.371 albertel 811: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 812: }
1.372 albertel 813: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 814: return $userloadpercent;
1.283 www 815: }
816:
1.1 albertel 817: # ------------------------------ Find server with least workload from spare.tab
1.11 www 818:
1.1 albertel 819: sub spareserver {
1.1083 raeburn 820: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 821: my $spare_server;
1.370 albertel 822: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 823: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
824: : $userloadpercent;
1.1083 raeburn 825: my ($uint_dom,$remotesessions);
826: if (($udom ne '') && (&domain($udom) ne '')) {
827: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
828: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
829: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
830: $remotesessions = $udomdefaults{'remotesessions'};
831: }
1.1123 raeburn 832: my $spareshash = &this_host_spares($udom);
833: if (ref($spareshash) eq 'HASH') {
834: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
835: foreach my $try_server (@{ $spareshash->{'primary'} }) {
836: if ($uint_dom) {
837: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
838: $try_server));
839: }
840: ($spare_server, $lowest_load) =
841: &compare_server_load($try_server, $spare_server, $lowest_load);
842: }
1.1083 raeburn 843: }
1.784 albertel 844:
1.1123 raeburn 845: my $found_server = ($spare_server ne '' && $lowest_load < 100);
846:
847: if (!$found_server) {
848: if (ref($spareshash->{'default'}) eq 'ARRAY') {
849: foreach my $try_server (@{ $spareshash->{'default'} }) {
850: if ($uint_dom) {
851: next unless (&spare_can_host($udom,$uint_dom,
852: $remotesessions,$try_server));
853: }
854: ($spare_server, $lowest_load) =
855: &compare_server_load($try_server, $spare_server, $lowest_load);
856: }
857: }
858: }
1.784 albertel 859: }
860:
861: if (!$want_server_name) {
1.968 raeburn 862: my $protocol = 'http';
863: if ($protocol{$spare_server} eq 'https') {
864: $protocol = $protocol{$spare_server};
865: }
1.1001 raeburn 866: if (defined($spare_server)) {
867: my $hostname = &hostname($spare_server);
1.1083 raeburn 868: if (defined($hostname)) {
1.1001 raeburn 869: $spare_server = $protocol.'://'.$hostname;
870: }
871: }
1.784 albertel 872: }
873: return $spare_server;
874: }
875:
876: sub compare_server_load {
877: my ($try_server, $spare_server, $lowest_load) = @_;
878:
879: my $loadans = &reply('load', $try_server);
880: my $userloadans = &reply('userload',$try_server);
881:
882: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 883: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 884: }
885:
886: my $load;
887: if ($loadans =~ /\d/) {
888: if ($userloadans =~ /\d/) {
889: #both are numbers, pick the bigger one
890: $load = ($loadans > $userloadans) ? $loadans
891: : $userloadans;
1.411 albertel 892: } else {
1.784 albertel 893: $load = $loadans;
1.411 albertel 894: }
1.784 albertel 895: } else {
896: $load = $userloadans;
897: }
898:
899: if (($load =~ /\d/) && ($load < $lowest_load)) {
900: $spare_server = $try_server;
901: $lowest_load = $load;
1.370 albertel 902: }
1.784 albertel 903: return ($spare_server,$lowest_load);
1.202 matthew 904: }
1.914 albertel 905:
906: # --------------------------- ask offload servers if user already has a session
907: sub find_existing_session {
908: my ($udom,$uname) = @_;
1.1123 raeburn 909: my $spareshash = &this_host_spares($udom);
910: if (ref($spareshash) eq 'HASH') {
911: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
912: foreach my $try_server (@{ $spareshash->{'primary'} }) {
913: return $try_server if (&has_user_session($try_server, $udom, $uname));
914: }
915: }
916: if (ref($spareshash->{'default'}) eq 'ARRAY') {
917: foreach my $try_server (@{ $spareshash->{'default'} }) {
918: return $try_server if (&has_user_session($try_server, $udom, $uname));
919: }
920: }
1.914 albertel 921: }
922: return;
923: }
924:
925: # -------------------------------- ask if server already has a session for user
926: sub has_user_session {
927: my ($lonid,$udom,$uname) = @_;
928: my $result = &reply(join(':','userhassession',
929: map {&escape($_)} ($udom,$uname)),$lonid);
930: return 1 if ($result eq 'ok');
931:
932: return 0;
933: }
934:
1.1076 raeburn 935: # --------- determine least loaded server in a user's domain which allows login
936:
937: sub choose_server {
1.1115 raeburn 938: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 939: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 940: my %servers = &get_servers($udom);
1.1076 raeburn 941: my $lowest_load = 30000;
1.1151 raeburn 942: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 943: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 944: my $loginvia;
945: if ($checkloginvia) {
946: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 947: if ($loginvia) {
948: my ($server,$path) = split(/:/,$loginvia);
949: ($login_host, $lowest_load) =
950: &compare_server_load($server, $login_host, $lowest_load);
951: if ($login_host eq $server) {
952: $portal_path = $path;
1.1151 raeburn 953: $isredirect = 1;
1.1116 raeburn 954: }
955: } else {
956: ($login_host, $lowest_load) =
957: &compare_server_load($lonhost, $login_host, $lowest_load);
958: if ($login_host eq $lonhost) {
959: $portal_path = '';
1.1151 raeburn 960: $isredirect = '';
1.1116 raeburn 961: }
962: }
963: } else {
1.1076 raeburn 964: ($login_host, $lowest_load) =
1.1116 raeburn 965: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 966: }
967: }
968: if ($login_host ne '') {
1.1116 raeburn 969: $hostname = &hostname($login_host);
1.1076 raeburn 970: }
1.1151 raeburn 971: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 972: }
973:
1.202 matthew 974: # --------------------------------------------- Try to change a user's password
975:
976: sub changepass {
1.799 raeburn 977: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 978: $currentpass = &escape($currentpass);
979: $newpass = &escape($newpass);
1.1030 raeburn 980: my $lonhost = $perlvar{'lonHostID'};
981: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 982: $server);
983: if (! $answer) {
984: &logthis("No reply on password change request to $server ".
985: "by $uname in domain $udom.");
986: } elsif ($answer =~ "^ok") {
987: &logthis("$uname in $udom successfully changed their password ".
988: "on $server.");
989: } elsif ($answer =~ "^pwchange_failure") {
990: &logthis("$uname in $udom was unable to change their password ".
991: "on $server. The action was blocked by either lcpasswd ".
992: "or pwchange");
993: } elsif ($answer =~ "^non_authorized") {
994: &logthis("$uname in $udom did not get their password correct when ".
995: "attempting to change it on $server.");
996: } elsif ($answer =~ "^auth_mode_error") {
997: &logthis("$uname in $udom attempted to change their password despite ".
998: "not being locally or internally authenticated on $server.");
999: } elsif ($answer =~ "^unknown_user") {
1000: &logthis("$uname in $udom attempted to change their password ".
1001: "on $server but were unable to because $server is not ".
1002: "their home server.");
1003: } elsif ($answer =~ "^refused") {
1004: &logthis("$server refused to change $uname in $udom password because ".
1005: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1006: } elsif ($answer =~ "invalid_client") {
1007: &logthis("$server refused to change $uname in $udom password because ".
1008: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1009: }
1010: return $answer;
1.1 albertel 1011: }
1012:
1.169 harris41 1013: # ----------------------- Try to determine user's current authentication scheme
1014:
1015: sub queryauthenticate {
1016: my ($uname,$udom)=@_;
1.456 albertel 1017: my $uhome=&homeserver($uname,$udom);
1018: if (!$uhome) {
1019: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1020: return 'no_host';
1021: }
1022: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1023: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1024: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1025: }
1.456 albertel 1026: return $answer;
1.169 harris41 1027: }
1028:
1.1 albertel 1029: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1030:
1.1 albertel 1031: sub authenticate {
1.1073 raeburn 1032: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1033: $upass=&escape($upass);
1034: $uname= &LONCAPA::clean_username($uname);
1.836 www 1035: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1036: my $newhome;
1.836 www 1037: if ((!$uhome) || ($uhome eq 'no_host')) {
1038: # Maybe the machine was offline and only re-appeared again recently?
1039: &reconlonc();
1040: # One more
1.952 raeburn 1041: $uhome=&homeserver($uname,$udom,1);
1042: if (($uhome eq 'no_host') && $checkdefauth) {
1043: if (defined(&domain($udom,'primary'))) {
1044: $newhome=&domain($udom,'primary');
1045: }
1046: if ($newhome ne '') {
1047: $uhome = $newhome;
1048: }
1049: }
1.836 www 1050: if ((!$uhome) || ($uhome eq 'no_host')) {
1051: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1052: return 'no_host';
1053: }
1.1 albertel 1054: }
1.1073 raeburn 1055: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1056: if ($answer eq 'authorized') {
1.952 raeburn 1057: if ($newhome) {
1058: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1059: return 'no_account_on_host';
1060: } else {
1061: &logthis("User $uname at $udom authorized by $uhome");
1062: return $uhome;
1063: }
1.471 albertel 1064: }
1065: if ($answer eq 'non_authorized') {
1066: &logthis("User $uname at $udom rejected by $uhome");
1067: return 'no_host';
1.9 www 1068: }
1.471 albertel 1069: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1070: return 'no_host';
1071: }
1072:
1.1073 raeburn 1073: sub can_host_session {
1.1074 raeburn 1074: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1075: my $canhost = 1;
1.1074 raeburn 1076: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1077: if (ref($remotesessions) eq 'HASH') {
1078: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1079: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1080: $canhost = 0;
1081: } else {
1082: $canhost = 1;
1083: }
1084: }
1085: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1086: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1087: $canhost = 1;
1088: } else {
1089: $canhost = 0;
1090: }
1091: }
1092: if ($canhost) {
1093: if ($remotesessions->{'version'} ne '') {
1094: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1095: if ($reqmajor ne '' && $reqminor ne '') {
1096: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1097: my $major = $1;
1098: my $minor = $2;
1099: if (($major < $reqmajor ) ||
1100: (($major == $reqmajor) && ($minor < $reqminor))) {
1101: $canhost = 0;
1102: }
1103: } else {
1104: $canhost = 0;
1105: }
1106: }
1107: }
1108: }
1109: }
1110: if ($canhost) {
1111: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1112: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1113: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1114: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1115: if (($uint_dom ne '') &&
1116: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1117: $canhost = 0;
1118: } else {
1119: $canhost = 1;
1120: }
1121: }
1122: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1123: if (($uint_dom ne '') &&
1124: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1125: $canhost = 1;
1126: } else {
1127: $canhost = 0;
1128: }
1129: }
1130: }
1131: }
1132: return $canhost;
1133: }
1134:
1.1083 raeburn 1135: sub spare_can_host {
1136: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1137: my $canhost=1;
1138: my @intdoms;
1139: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1140: if (ref($internet_names) eq 'ARRAY') {
1141: @intdoms = @{$internet_names};
1142: }
1143: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1144: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1145: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1146: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1147: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1148: $canhost = &can_host_session($udom,$try_server,$remoterev,
1149: $remotesessions,
1150: $defdomdefaults{'hostedsessions'});
1151: }
1152: return $canhost;
1153: }
1154:
1.1123 raeburn 1155: sub this_host_spares {
1156: my ($dom) = @_;
1.1126 raeburn 1157: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1158: my @hosts = ¤t_machine_ids();
1159: foreach my $lonhost (@hosts) {
1160: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1161: $dom_in_use = $dom;
1162: $lonhost_in_use = $lonhost;
1.1123 raeburn 1163: last;
1164: }
1165: }
1.1126 raeburn 1166: if ($dom_in_use ne '') {
1167: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1168: }
1169: if (ref($result) ne 'HASH') {
1170: $lonhost_in_use = $perlvar{'lonHostID'};
1171: $dom_in_use = &host_domain($lonhost_in_use);
1172: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1173: if (ref($result) ne 'HASH') {
1174: $result = \%spareid;
1175: }
1176: }
1177: return $result;
1178: }
1179:
1180: sub spares_for_offload {
1181: my ($dom_in_use,$lonhost_in_use) = @_;
1182: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1183: if (defined($cached)) {
1184: return $result;
1185: } else {
1.1126 raeburn 1186: my $cachetime = 60*60*24;
1187: my %domconfig =
1188: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1189: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1190: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1191: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1192: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1193: }
1194: }
1195: }
1196: }
1.1126 raeburn 1197: return;
1.1123 raeburn 1198: }
1199:
1.1129 raeburn 1200: sub get_lonbalancer_config {
1201: my ($servers) = @_;
1202: my ($currbalancer,$currtargets);
1203: if (ref($servers) eq 'HASH') {
1204: foreach my $server (keys(%{$servers})) {
1205: my %what = (
1206: spareid => 1,
1207: perlvar => 1,
1208: );
1209: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1210: if ($result eq 'ok') {
1211: if (ref($returnhash) eq 'HASH') {
1212: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1213: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1214: $currbalancer = $server;
1215: $currtargets = {};
1216: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1217: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1218: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1219: }
1220: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1221: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1222: }
1223: }
1224: last;
1225: }
1226: }
1227: }
1228: }
1229: }
1230: }
1231: return ($currbalancer,$currtargets);
1232: }
1233:
1234: sub check_loadbalancing {
1235: my ($uname,$udom) = @_;
1236: my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
1237: $offloadto,$otherserver);
1238: my $lonhost = $perlvar{'lonHostID'};
1239: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1240: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1241: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1242: my $serverhomedom = &host_domain($lonhost);
1243:
1244: my $cachetime = 60*60*24;
1245:
1246: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1247: $dom_in_use = $udom;
1248: $homeintdom = 1;
1249: } else {
1250: $dom_in_use = $serverhomedom;
1251: }
1252: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1253: unless (defined($cached)) {
1254: my %domconfig =
1255: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1256: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1257: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1258: }
1259: }
1260: if (ref($result) eq 'HASH') {
1261: my $currbalancer = $result->{'lonhost'};
1262: my $currtargets = $result->{'targets'};
1263: my $currrules = $result->{'rules'};
1264: if ($currbalancer ne '') {
1265: my @hosts = ¤t_machine_ids();
1266: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1267: $is_balancer = 1;
1268: }
1269: }
1270: if ($is_balancer) {
1271: if (ref($currrules) eq 'HASH') {
1272: if ($homeintdom) {
1273: if ($uname ne '') {
1274: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1275: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1276: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1277: $rule_in_effect = $currrules->{'_LC_author'};
1278: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1279: $rule_in_effect = $currrules->{'_LC_adv'}
1280: }
1281: }
1282: if ($rule_in_effect eq '') {
1283: my %userenv = &userenvironment($udom,$uname,'inststatus');
1284: if ($userenv{'inststatus'} ne '') {
1285: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1286: my ($othertitle,$usertypes,$types) =
1287: &Apache::loncommon::sorted_inst_types($udom);
1288: if (ref($types) eq 'ARRAY') {
1289: foreach my $type (@{$types}) {
1290: if (grep(/^\Q$type\E$/,@statuses)) {
1291: if (exists($currrules->{$type})) {
1292: $rule_in_effect = $currrules->{$type};
1293: }
1294: }
1295: }
1296: }
1297: } else {
1298: if (exists($currrules->{'default'})) {
1299: $rule_in_effect = $currrules->{'default'};
1300: }
1301: }
1302: }
1303: } else {
1304: if (exists($currrules->{'default'})) {
1305: $rule_in_effect = $currrules->{'default'};
1306: }
1307: }
1308: } else {
1309: if ($currrules->{'_LC_external'} ne '') {
1310: $rule_in_effect = $currrules->{'_LC_external'};
1311: }
1312: }
1313: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1314: $uname,$udom);
1315: }
1316: }
1317: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1318: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1319: unless (defined($cached)) {
1320: my %domconfig =
1321: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1322: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1323: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1324: }
1325: }
1326: if (ref($result) eq 'HASH') {
1327: my $currbalancer = $result->{'lonhost'};
1328: my $currtargets = $result->{'targets'};
1329: my $currrules = $result->{'rules'};
1330:
1331: if ($currbalancer eq $lonhost) {
1332: $is_balancer = 1;
1333: if (ref($currrules) eq 'HASH') {
1334: if ($currrules->{'_LC_internetdom'} ne '') {
1335: $rule_in_effect = $currrules->{'_LC_internetdom'};
1336: }
1337: }
1338: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1339: $uname,$udom);
1340: }
1341: } else {
1342: if ($perlvar{'lonBalancer'} eq 'yes') {
1343: $is_balancer = 1;
1344: $offloadto = &this_host_spares($dom_in_use);
1345: }
1346: }
1347: } else {
1348: if ($perlvar{'lonBalancer'} eq 'yes') {
1349: $is_balancer = 1;
1350: $offloadto = &this_host_spares($dom_in_use);
1351: }
1352: }
1353: my $lowest_load = 30000;
1354: if (ref($offloadto) eq 'HASH') {
1355: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1356: foreach my $try_server (@{$offloadto->{'primary'}}) {
1357: ($otherserver,$lowest_load) =
1358: &compare_server_load($try_server,$otherserver,$lowest_load);
1359: }
1360: }
1361: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1362:
1363: if (!$found_server) {
1364: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1365: foreach my $try_server (@{$offloadto->{'default'}}) {
1366: ($otherserver,$lowest_load) =
1367: &compare_server_load($try_server,$otherserver,$lowest_load);
1368: }
1369: }
1370: }
1371: } elsif (ref($offloadto) eq 'ARRAY') {
1372: if (@{$offloadto} == 1) {
1373: $otherserver = $offloadto->[0];
1374: } elsif (@{$offloadto} > 1) {
1375: foreach my $try_server (@{$offloadto}) {
1376: ($otherserver,$lowest_load) =
1377: &compare_server_load($try_server,$otherserver,$lowest_load);
1378: }
1379: }
1380: }
1381: return ($is_balancer,$otherserver);
1382: }
1383:
1384: sub get_loadbalancer_targets {
1385: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1386: my $offloadto;
1387: if ($rule_in_effect eq '') {
1388: $offloadto = $currtargets;
1389: } else {
1390: if ($rule_in_effect eq 'homeserver') {
1391: my $homeserver = &homeserver($uname,$udom);
1392: if ($homeserver ne 'no_host') {
1393: $offloadto = [$homeserver];
1394: }
1395: } elsif ($rule_in_effect eq 'externalbalancer') {
1396: my %domconfig =
1397: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1398: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1399: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1400: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1401: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1402: }
1403: }
1404: } else {
1405: my %servers = &dom_servers($udom);
1406: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1407: if (&hostname($remotebalancer) ne '') {
1408: $offloadto = [$remotebalancer];
1409: }
1410: }
1411: } elsif (&hostname($rule_in_effect) ne '') {
1412: $offloadto = [$rule_in_effect];
1413: }
1414: }
1415: return $offloadto;
1416: }
1417:
1.1127 raeburn 1418: sub internet_dom_servers {
1419: my ($dom) = @_;
1420: my (%uniqservers,%servers);
1421: my $primaryserver = &hostname(&domain($dom,'primary'));
1422: my @machinedoms = &machine_domains($primaryserver);
1423: foreach my $mdom (@machinedoms) {
1424: my %currservers = %servers;
1425: my %server = &get_servers($mdom);
1426: %servers = (%currservers,%server);
1427: }
1428: my %by_hostname;
1429: foreach my $id (keys(%servers)) {
1430: push(@{$by_hostname{$servers{$id}}},$id);
1431: }
1432: foreach my $hostname (sort(keys(%by_hostname))) {
1433: if (@{$by_hostname{$hostname}} > 1) {
1434: my $match = 0;
1435: foreach my $id (@{$by_hostname{$hostname}}) {
1436: if (&host_domain($id) eq $dom) {
1437: $uniqservers{$id} = $hostname;
1438: $match = 1;
1439: }
1440: }
1441: unless ($match) {
1442: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1443: }
1444: } else {
1445: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1446: }
1447: }
1448: return %uniqservers;
1449: }
1450:
1.1 albertel 1451: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1452:
1.599 albertel 1453: my %homecache;
1.1 albertel 1454: sub homeserver {
1.230 stredwic 1455: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1456: my $index="$uname:$udom";
1.426 albertel 1457:
1.599 albertel 1458: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1459:
1460: my %servers = &get_servers($udom,'library');
1461: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1462: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1463: exists($badServerCache{$tryserver}));
1.841 albertel 1464:
1465: my $answer=reply("home:$udom:$uname",$tryserver);
1466: if ($answer eq 'found') {
1467: delete($badServerCache{$tryserver});
1468: return $homecache{$index}=$tryserver;
1469: } elsif ($answer eq 'no_host') {
1470: $badServerCache{$tryserver}=1;
1471: }
1.1 albertel 1472: }
1473: return 'no_host';
1.70 www 1474: }
1475:
1476: # ------------------------------------- Find the usernames behind a list of IDs
1477:
1478: sub idget {
1479: my ($udom,@ids)=@_;
1480: my %returnhash=();
1481:
1.841 albertel 1482: my %servers = &get_servers($udom,'library');
1483: foreach my $tryserver (keys(%servers)) {
1484: my $idlist=join('&',@ids);
1485: $idlist=~tr/A-Z/a-z/;
1486: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1487: my @answer=();
1488: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1489: @answer=split(/\&/,$reply);
1490: } ;
1491: my $i;
1492: for ($i=0;$i<=$#ids;$i++) {
1493: if ($answer[$i]) {
1494: $returnhash{$ids[$i]}=$answer[$i];
1495: }
1496: }
1497: }
1.70 www 1498: return %returnhash;
1499: }
1500:
1501: # ------------------------------------- Find the IDs behind a list of usernames
1502:
1503: sub idrget {
1504: my ($udom,@unames)=@_;
1505: my %returnhash=();
1.800 albertel 1506: foreach my $uname (@unames) {
1507: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1508: }
1.70 www 1509: return %returnhash;
1510: }
1511:
1512: # ------------------------------- Store away a list of names and associated IDs
1513:
1514: sub idput {
1515: my ($udom,%ids)=@_;
1516: my %servers=();
1.800 albertel 1517: foreach my $uname (keys(%ids)) {
1518: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1519: my $uhom=&homeserver($uname,$udom);
1.70 www 1520: if ($uhom ne 'no_host') {
1.800 albertel 1521: my $id=&escape($ids{$uname});
1.70 www 1522: $id=~tr/A-Z/a-z/;
1.800 albertel 1523: my $esc_unam=&escape($uname);
1.70 www 1524: if ($servers{$uhom}) {
1.800 albertel 1525: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1526: } else {
1.800 albertel 1527: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1528: }
1529: }
1.191 harris41 1530: }
1.800 albertel 1531: foreach my $server (keys(%servers)) {
1532: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1533: }
1.344 www 1534: }
1535:
1.1023 raeburn 1536: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1537: sub dump_dom {
1.1023 raeburn 1538: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1539: if (!$udom) {
1540: $udom=$env{'user.domain'};
1541: }
1542: my %returnhash;
1.1023 raeburn 1543: if ($udom) {
1544: my $uname = &get_domainconfiguser($udom);
1545: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1546: }
1547: return %returnhash;
1548: }
1549:
1.1023 raeburn 1550: # ------------------------------------------ get items from domain db files
1.806 raeburn 1551:
1552: sub get_dom {
1.860 raeburn 1553: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1554: my $items='';
1555: foreach my $item (@$storearr) {
1556: $items.=&escape($item).'&';
1557: }
1558: $items=~s/\&$//;
1.860 raeburn 1559: if (!$udom) {
1560: $udom=$env{'user.domain'};
1561: if (defined(&domain($udom,'primary'))) {
1562: $uhome=&domain($udom,'primary');
1563: } else {
1.874 albertel 1564: undef($uhome);
1.860 raeburn 1565: }
1566: } else {
1567: if (!$uhome) {
1568: if (defined(&domain($udom,'primary'))) {
1569: $uhome=&domain($udom,'primary');
1570: }
1571: }
1572: }
1573: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1574: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1575: my %returnhash;
1.875 albertel 1576: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1577: return %returnhash;
1578: }
1.806 raeburn 1579: my @pairs=split(/\&/,$rep);
1580: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1581: return @pairs;
1582: }
1583: my $i=0;
1584: foreach my $item (@$storearr) {
1585: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1586: $i++;
1587: }
1588: return %returnhash;
1589: } else {
1.880 banghart 1590: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1591: }
1592: }
1593:
1594: # -------------------------------------------- put items in domain db files
1595:
1596: sub put_dom {
1.860 raeburn 1597: my ($namespace,$storehash,$udom,$uhome)=@_;
1598: if (!$udom) {
1599: $udom=$env{'user.domain'};
1600: if (defined(&domain($udom,'primary'))) {
1601: $uhome=&domain($udom,'primary');
1602: } else {
1.874 albertel 1603: undef($uhome);
1.860 raeburn 1604: }
1605: } else {
1606: if (!$uhome) {
1607: if (defined(&domain($udom,'primary'))) {
1608: $uhome=&domain($udom,'primary');
1609: }
1610: }
1611: }
1612: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1613: my $items='';
1614: foreach my $item (keys(%$storehash)) {
1615: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1616: }
1617: $items=~s/\&$//;
1618: return &reply("putdom:$udom:$namespace:$items",$uhome);
1619: } else {
1.860 raeburn 1620: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1621: }
1622: }
1623:
1.1023 raeburn 1624: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1625: sub newput_dom {
1.1023 raeburn 1626: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1627: my $result;
1628: if (!$udom) {
1629: $udom=$env{'user.domain'};
1630: }
1.1023 raeburn 1631: if ($udom) {
1632: my $uname = &get_domainconfiguser($udom);
1633: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1634: }
1635: return $result;
1636: }
1637:
1.1023 raeburn 1638: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1639: sub del_dom {
1.1023 raeburn 1640: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1641: if (ref($storearr) eq 'ARRAY') {
1642: if (!$udom) {
1643: $udom=$env{'user.domain'};
1644: }
1.1023 raeburn 1645: if ($udom) {
1646: my $uname = &get_domainconfiguser($udom);
1647: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1648: }
1649: }
1650: }
1651:
1.1023 raeburn 1652: # ----------------------------------construct domainconfig user for a domain
1653: sub get_domainconfiguser {
1654: my ($udom) = @_;
1655: return $udom.'-domainconfig';
1656: }
1657:
1.837 raeburn 1658: sub retrieve_inst_usertypes {
1659: my ($udom) = @_;
1660: my (%returnhash,@order);
1.989 raeburn 1661: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1662: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1663: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1664: %returnhash = %{$domdefs{'inststatustypes'}};
1665: @order = @{$domdefs{'inststatusorder'}};
1666: } else {
1667: if (defined(&domain($udom,'primary'))) {
1668: my $uhome=&domain($udom,'primary');
1669: my $rep=&reply("inst_usertypes:$udom",$uhome);
1670: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1671: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1672: return (\%returnhash,\@order);
1673: }
1674: my ($hashitems,$orderitems) = split(/:/,$rep);
1675: my @pairs=split(/\&/,$hashitems);
1676: foreach my $item (@pairs) {
1677: my ($key,$value)=split(/=/,$item,2);
1678: $key = &unescape($key);
1679: next if ($key =~ /^error: 2 /);
1680: $returnhash{$key}=&thaw_unescape($value);
1681: }
1682: my @esc_order = split(/\&/,$orderitems);
1683: foreach my $item (@esc_order) {
1684: push(@order,&unescape($item));
1685: }
1686: } else {
1687: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1688: }
1689: }
1690: return (\%returnhash,\@order);
1691: }
1692:
1.868 raeburn 1693: sub is_domainimage {
1694: my ($url) = @_;
1695: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1696: if (&domain($1) ne '') {
1697: return '1';
1698: }
1699: }
1700: return;
1701: }
1702:
1.899 raeburn 1703: sub inst_directory_query {
1704: my ($srch) = @_;
1705: my $udom = $srch->{'srchdomain'};
1706: my %results;
1707: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1708: my $outcome;
1.899 raeburn 1709: if ($homeserver ne '') {
1.904 albertel 1710: my $queryid=&reply("querysend:instdirsearch:".
1711: &escape($srch->{'srchby'}).':'.
1712: &escape($srch->{'srchterm'}).':'.
1713: &escape($srch->{'srchtype'}),$homeserver);
1714: my $host=&hostname($homeserver);
1715: if ($queryid !~/^\Q$host\E\_/) {
1716: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1717: return;
1718: }
1719: my $response = &get_query_reply($queryid);
1720: my $maxtries = 5;
1721: my $tries = 1;
1722: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1723: $response = &get_query_reply($queryid);
1724: $tries ++;
1725: }
1726:
1727: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1728: if ($response eq 'unavailable') {
1729: $outcome = $response;
1730: } else {
1731: $outcome = 'ok';
1732: my @matches = split(/\n/,$response);
1733: foreach my $match (@matches) {
1734: my ($key,$value) = split(/=/,$match);
1735: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1736: }
1.899 raeburn 1737: }
1738: }
1739: }
1.909 raeburn 1740: return ($outcome,%results);
1.899 raeburn 1741: }
1742:
1743: sub usersearch {
1744: my ($srch) = @_;
1745: my $dom = $srch->{'srchdomain'};
1746: my %results;
1747: my %libserv = &all_library();
1748: my $query = 'usersearch';
1749: foreach my $tryserver (keys(%libserv)) {
1750: if (&host_domain($tryserver) eq $dom) {
1751: my $host=&hostname($tryserver);
1752: my $queryid=
1.911 raeburn 1753: &reply("querysend:".&escape($query).':'.
1754: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1755: &escape($srch->{'srchtype'}).':'.
1756: &escape($srch->{'srchterm'}),$tryserver);
1757: if ($queryid !~/^\Q$host\E\_/) {
1758: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1759: next;
1.899 raeburn 1760: }
1761: my $reply = &get_query_reply($queryid);
1762: my $maxtries = 1;
1763: my $tries = 1;
1764: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1765: $reply = &get_query_reply($queryid);
1766: $tries ++;
1767: }
1768: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1769: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1770: } else {
1.911 raeburn 1771: my @matches;
1772: if ($reply =~ /\n/) {
1773: @matches = split(/\n/,$reply);
1774: } else {
1775: @matches = split(/\&/,$reply);
1776: }
1.899 raeburn 1777: foreach my $match (@matches) {
1778: my ($uname,$udom,%userhash);
1.911 raeburn 1779: foreach my $entry (split(/:/,$match)) {
1780: my ($key,$value) =
1781: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1782: $userhash{$key} = $value;
1783: if ($key eq 'username') {
1784: $uname = $value;
1785: } elsif ($key eq 'domain') {
1786: $udom = $value;
1.911 raeburn 1787: }
1.899 raeburn 1788: }
1789: $results{$uname.':'.$udom} = \%userhash;
1790: }
1791: }
1792: }
1793: }
1794: return %results;
1795: }
1796:
1.912 raeburn 1797: sub get_instuser {
1798: my ($udom,$uname,$id) = @_;
1799: my $homeserver = &domain($udom,'primary');
1800: my ($outcome,%results);
1801: if ($homeserver ne '') {
1802: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1803: &escape($id).':'.&escape($udom),$homeserver);
1804: my $host=&hostname($homeserver);
1805: if ($queryid !~/^\Q$host\E\_/) {
1806: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1807: return;
1808: }
1809: my $response = &get_query_reply($queryid);
1810: my $maxtries = 5;
1811: my $tries = 1;
1812: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1813: $response = &get_query_reply($queryid);
1814: $tries ++;
1815: }
1816: if (!&error($response) && $response ne 'refused') {
1817: if ($response eq 'unavailable') {
1818: $outcome = $response;
1819: } else {
1820: $outcome = 'ok';
1821: my @matches = split(/\n/,$response);
1822: foreach my $match (@matches) {
1823: my ($key,$value) = split(/=/,$match);
1824: $results{&unescape($key)} = &thaw_unescape($value);
1825: }
1826: }
1827: }
1828: }
1829: my %userinfo;
1830: if (ref($results{$uname}) eq 'HASH') {
1831: %userinfo = %{$results{$uname}};
1832: }
1833: return ($outcome,%userinfo);
1834: }
1835:
1836: sub inst_rulecheck {
1.923 raeburn 1837: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1838: my %returnhash;
1839: if ($udom ne '') {
1840: if (ref($rules) eq 'ARRAY') {
1841: @{$rules} = map {&escape($_);} (@{$rules});
1842: my $rulestr = join(':',@{$rules});
1843: my $homeserver=&domain($udom,'primary');
1844: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1845: my $response;
1846: if ($item eq 'username') {
1847: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1848: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1849: $homeserver));
1.923 raeburn 1850: } elsif ($item eq 'id') {
1851: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1852: ':'.&escape($id).':'.$rulestr,
1853: $homeserver));
1.945 raeburn 1854: } elsif ($item eq 'selfcreate') {
1855: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1856: &escape($udom).':'.&escape($uname).
1857: ':'.$rulestr,$homeserver));
1.923 raeburn 1858: }
1.912 raeburn 1859: if ($response ne 'refused') {
1860: my @pairs=split(/\&/,$response);
1861: foreach my $item (@pairs) {
1862: my ($key,$value)=split(/=/,$item,2);
1863: $key = &unescape($key);
1864: next if ($key =~ /^error: 2 /);
1865: $returnhash{$key}=&thaw_unescape($value);
1866: }
1867: }
1868: }
1869: }
1870: }
1871: return %returnhash;
1872: }
1873:
1874: sub inst_userrules {
1.923 raeburn 1875: my ($udom,$check) = @_;
1.912 raeburn 1876: my (%ruleshash,@ruleorder);
1877: if ($udom ne '') {
1878: my $homeserver=&domain($udom,'primary');
1879: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1880: my $response;
1881: if ($check eq 'id') {
1882: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1883: $homeserver);
1.943 raeburn 1884: } elsif ($check eq 'email') {
1885: $response=&reply('instemailrules:'.&escape($udom),
1886: $homeserver);
1.923 raeburn 1887: } else {
1888: $response=&reply('instuserrules:'.&escape($udom),
1889: $homeserver);
1890: }
1.912 raeburn 1891: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1892: ($response ne 'unknown_cmd') &&
1.912 raeburn 1893: ($response ne 'no_such_host')) {
1894: my ($hashitems,$orderitems) = split(/:/,$response);
1895: my @pairs=split(/\&/,$hashitems);
1896: foreach my $item (@pairs) {
1897: my ($key,$value)=split(/=/,$item,2);
1898: $key = &unescape($key);
1899: next if ($key =~ /^error: 2 /);
1900: $ruleshash{$key}=&thaw_unescape($value);
1901: }
1902: my @esc_order = split(/\&/,$orderitems);
1903: foreach my $item (@esc_order) {
1904: push(@ruleorder,&unescape($item));
1905: }
1906: }
1907: }
1908: }
1909: return (\%ruleshash,\@ruleorder);
1910: }
1911:
1.976 raeburn 1912: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1913:
1914: sub get_domain_defaults {
1915: my ($domain) = @_;
1916: my $cachetime = 60*60*24;
1917: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1918: if (defined($cached)) {
1919: if (ref($result) eq 'HASH') {
1920: return %{$result};
1921: }
1922: }
1923: my %domdefaults;
1924: my %domconfig =
1.989 raeburn 1925: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1926: 'requestcourses','inststatus',
1.1073 raeburn 1927: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1928: if (ref($domconfig{'defaults'}) eq 'HASH') {
1929: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1930: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1931: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1932: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1933: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 1934: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 1935: } else {
1936: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1937: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1938: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1939: }
1.976 raeburn 1940: if (ref($domconfig{'quotas'}) eq 'HASH') {
1941: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1942: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1943: } else {
1944: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1945: }
1946: my @usertools = ('aboutme','blog','portfolio');
1947: foreach my $item (@usertools) {
1948: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1949: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1950: }
1951: }
1952: }
1.985 raeburn 1953: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1954: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1955: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1956: }
1957: }
1.989 raeburn 1958: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1959: foreach my $item ('inststatustypes','inststatusorder') {
1960: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1961: }
1962: }
1.1047 raeburn 1963: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1964: foreach my $item ('canuse_pdfforms') {
1965: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1966: }
1967: }
1.1073 raeburn 1968: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1969: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1970: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1971: }
1972: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1973: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1974: }
1975: }
1.943 raeburn 1976: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1977: $cachetime);
1978: return %domdefaults;
1979: }
1980:
1.344 www 1981: # --------------------------------------------------- Assign a key to a student
1982:
1983: sub assign_access_key {
1.364 www 1984: #
1985: # a valid key looks like uname:udom#comments
1986: # comments are being appended
1987: #
1.498 www 1988: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1989: $kdom=
1.620 albertel 1990: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1991: $knum=
1.620 albertel 1992: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1993: $cdom=
1.620 albertel 1994: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1995: $cnum=
1.620 albertel 1996: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1997: $udom=$env{'user.name'} unless (defined($udom));
1998: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1999: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2000: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2001: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2002: # assigned to this person
2003: # - this should not happen,
1.345 www 2004: # unless something went wrong
2005: # the first time around
2006: # ready to assign
1.364 www 2007: $logentry=$1.'; '.$logentry;
1.496 www 2008: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2009: $kdom,$knum) eq 'ok') {
1.345 www 2010: # key now belongs to user
1.346 www 2011: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2012: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2013: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2014: return 'ok';
2015: } else {
2016: return
2017: 'error: Count not permanently assign key, will need to be re-entered later.';
2018: }
2019: } else {
2020: return 'error: Could not assign key, try again later.';
2021: }
1.364 www 2022: } elsif (!$existing{$ckey}) {
1.345 www 2023: # the key does not exist
2024: return 'error: The key does not exist';
2025: } else {
2026: # the key is somebody else's
2027: return 'error: The key is already in use';
2028: }
1.344 www 2029: }
2030:
1.364 www 2031: # ------------------------------------------ put an additional comment on a key
2032:
2033: sub comment_access_key {
2034: #
2035: # a valid key looks like uname:udom#comments
2036: # comments are being appended
2037: #
2038: my ($ckey,$cdom,$cnum,$logentry)=@_;
2039: $cdom=
1.620 albertel 2040: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2041: $cnum=
1.620 albertel 2042: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2043: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2044: if ($existing{$ckey}) {
2045: $existing{$ckey}.='; '.$logentry;
2046: # ready to assign
1.367 www 2047: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2048: $cdom,$cnum) eq 'ok') {
2049: return 'ok';
2050: } else {
2051: return 'error: Count not store comment.';
2052: }
2053: } else {
2054: # the key does not exist
2055: return 'error: The key does not exist';
2056: }
2057: }
2058:
1.344 www 2059: # ------------------------------------------------------ Generate a set of keys
2060:
2061: sub generate_access_keys {
1.364 www 2062: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2063: $cdom=
1.620 albertel 2064: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2065: $cnum=
1.620 albertel 2066: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2067: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2068: unless (($cdom) && ($cnum)) { return 0; }
2069: if ($number>10000) { return 0; }
2070: sleep(2); # make sure don't get same seed twice
2071: srand(time()^($$+($$<<15))); # from "Programming Perl"
2072: my $total=0;
2073: for (my $i=1;$i<=$number;$i++) {
2074: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2075: sprintf("%lx",int(100000*rand)).'-'.
2076: sprintf("%lx",int(100000*rand));
2077: $newkey=~s/1/g/g; # folks mix up 1 and l
2078: $newkey=~s/0/h/g; # and also 0 and O
2079: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2080: if ($existing{$newkey}) {
2081: $i--;
2082: } else {
1.364 www 2083: if (&put('accesskeys',
2084: { $newkey => '# generated '.localtime().
1.620 albertel 2085: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2086: '; '.$logentry },
2087: $cdom,$cnum) eq 'ok') {
1.344 www 2088: $total++;
2089: }
2090: }
2091: }
1.620 albertel 2092: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2093: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2094: return $total;
2095: }
2096:
2097: # ------------------------------------------------------- Validate an accesskey
2098:
2099: sub validate_access_key {
2100: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2101: $cdom=
1.620 albertel 2102: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2103: $cnum=
1.620 albertel 2104: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2105: $udom=$env{'user.domain'} unless (defined($udom));
2106: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2107: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2108: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2109: }
2110:
2111: # ------------------------------------- Find the section of student in a course
1.652 albertel 2112: sub devalidate_getsection_cache {
2113: my ($udom,$unam,$courseid)=@_;
2114: my $hashid="$udom:$unam:$courseid";
2115: &devalidate_cache_new('getsection',$hashid);
2116: }
1.298 matthew 2117:
1.815 albertel 2118: sub courseid_to_courseurl {
2119: my ($courseid) = @_;
2120: #already url style courseid
2121: return $courseid if ($courseid =~ m{^/});
2122:
2123: if (exists($env{'course.'.$courseid.'.num'})) {
2124: my $cnum = $env{'course.'.$courseid.'.num'};
2125: my $cdom = $env{'course.'.$courseid.'.domain'};
2126: return "/$cdom/$cnum";
2127: }
2128:
2129: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2130: if (exists($courseinfo{'num'})) {
2131: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2132: }
2133:
2134: return undef;
2135: }
2136:
1.298 matthew 2137: sub getsection {
2138: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2139: my $cachetime=1800;
1.551 albertel 2140:
2141: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2142: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2143: if (defined($cached)) { return $result; }
2144:
1.298 matthew 2145: my %Pending;
2146: my %Expired;
2147: #
2148: # Each role can either have not started yet (pending), be active,
2149: # or have expired.
2150: #
2151: # If there is an active role, we are done.
2152: #
2153: # If there is more than one role which has not started yet,
2154: # choose the one which will start sooner
2155: # If there is one role which has not started yet, return it.
2156: #
2157: # If there is more than one expired role, choose the one which ended last.
2158: # If there is a role which has expired, return it.
2159: #
1.815 albertel 2160: $courseid = &courseid_to_courseurl($courseid);
1.1086 raeburn 2161: my $extra = &freeze_escape({'skipcheck' => 1});
2162: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817 raeburn 2163: foreach my $key (keys(%roleshash)) {
1.479 albertel 2164: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2165: my $section=$1;
2166: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2167: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2168: my $now=time;
1.548 albertel 2169: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2170: $Expired{$end}=$section;
2171: next;
2172: }
1.548 albertel 2173: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2174: $Pending{$start}=$section;
2175: next;
2176: }
1.599 albertel 2177: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2178: }
2179: #
2180: # Presumedly there will be few matching roles from the above
2181: # loop and the sorting time will be negligible.
2182: if (scalar(keys(%Pending))) {
2183: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2184: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2185: }
2186: if (scalar(keys(%Expired))) {
2187: my @sorted = sort {$a <=> $b} keys(%Expired);
2188: my $time = pop(@sorted);
1.599 albertel 2189: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2190: }
1.599 albertel 2191: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2192: }
1.70 www 2193:
1.599 albertel 2194: sub save_cache {
2195: &purge_remembered();
1.722 albertel 2196: #&Apache::loncommon::validate_page();
1.620 albertel 2197: undef(%env);
1.780 albertel 2198: undef($env_loaded);
1.599 albertel 2199: }
1.452 albertel 2200:
1.599 albertel 2201: my $to_remember=-1;
2202: my %remembered;
2203: my %accessed;
2204: my $kicks=0;
2205: my $hits=0;
1.849 albertel 2206: sub make_key {
2207: my ($name,$id) = @_;
1.872 albertel 2208: if (length($id) > 65
2209: && length(&escape($id)) > 200) {
2210: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2211: }
1.849 albertel 2212: return &escape($name.':'.$id);
2213: }
2214:
1.599 albertel 2215: sub devalidate_cache_new {
2216: my ($name,$id,$debug) = @_;
2217: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2218: $id=&make_key($name,$id);
1.599 albertel 2219: $memcache->delete($id);
2220: delete($remembered{$id});
2221: delete($accessed{$id});
2222: }
2223:
2224: sub is_cached_new {
2225: my ($name,$id,$debug) = @_;
1.849 albertel 2226: $id=&make_key($name,$id);
1.599 albertel 2227: if (exists($remembered{$id})) {
1.1133 foxr 2228: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2229: $accessed{$id}=[&gettimeofday()];
2230: $hits++;
2231: return ($remembered{$id},1);
2232: }
2233: my $value = $memcache->get($id);
2234: if (!(defined($value))) {
2235: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2236: return (undef,undef);
1.416 albertel 2237: }
1.599 albertel 2238: if ($value eq '__undef__') {
2239: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2240: $value=undef;
2241: }
2242: &make_room($id,$value,$debug);
2243: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2244: return ($value,1);
2245: }
2246:
2247: sub do_cache_new {
2248: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2249: $id=&make_key($name,$id);
1.599 albertel 2250: my $setvalue=$value;
2251: if (!defined($setvalue)) {
2252: $setvalue='__undef__';
2253: }
1.623 albertel 2254: if (!defined($time) ) {
2255: $time=600;
2256: }
1.599 albertel 2257: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2258: my $result = $memcache->set($id,$setvalue,$time);
2259: if (! $result) {
1.872 albertel 2260: &logthis("caching of id -> $id failed");
1.910 albertel 2261: $memcache->disconnect_all();
1.872 albertel 2262: }
1.600 albertel 2263: # need to make a copy of $value
1.919 albertel 2264: &make_room($id,$value,$debug);
1.599 albertel 2265: return $value;
2266: }
2267:
2268: sub make_room {
2269: my ($id,$value,$debug)=@_;
1.919 albertel 2270:
2271: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2272: : $value;
1.599 albertel 2273: if ($to_remember<0) { return; }
2274: $accessed{$id}=[&gettimeofday()];
2275: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2276: my $to_kick;
2277: my $max_time=0;
2278: foreach my $other (keys(%accessed)) {
2279: if (&tv_interval($accessed{$other}) > $max_time) {
2280: $to_kick=$other;
2281: $max_time=&tv_interval($accessed{$other});
2282: }
2283: }
2284: delete($remembered{$to_kick});
2285: delete($accessed{$to_kick});
2286: $kicks++;
2287: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2288: return;
2289: }
2290:
1.599 albertel 2291: sub purge_remembered {
1.604 albertel 2292: #&logthis("Tossing ".scalar(keys(%remembered)));
2293: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2294: undef(%remembered);
2295: undef(%accessed);
1.428 albertel 2296: }
1.70 www 2297: # ------------------------------------- Read an entry from a user's environment
2298:
2299: sub userenvironment {
2300: my ($udom,$unam,@what)=@_;
1.976 raeburn 2301: my $items;
2302: foreach my $item (@what) {
2303: $items.=&escape($item).'&';
2304: }
2305: $items=~s/\&$//;
1.70 www 2306: my %returnhash=();
1.1009 raeburn 2307: my $uhome = &homeserver($unam,$udom);
2308: unless ($uhome eq 'no_host') {
2309: my @answer=split(/\&/,
2310: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2311: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2312: return %returnhash;
2313: }
1.1009 raeburn 2314: my $i;
2315: for ($i=0;$i<=$#what;$i++) {
2316: $returnhash{$what[$i]}=&unescape($answer[$i]);
2317: }
1.70 www 2318: }
2319: return %returnhash;
1.1 albertel 2320: }
2321:
1.617 albertel 2322: # ---------------------------------------------------------- Get a studentphoto
2323: sub studentphoto {
2324: my ($udom,$unam,$ext) = @_;
2325: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2326: if (defined($env{'request.course.id'})) {
1.708 raeburn 2327: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2328: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2329: return(&retrievestudentphoto($udom,$unam,$ext));
2330: } else {
2331: my ($result,$perm_reqd)=
1.707 albertel 2332: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2333: if ($result eq 'ok') {
2334: if (!($perm_reqd eq 'yes')) {
2335: return(&retrievestudentphoto($udom,$unam,$ext));
2336: }
2337: }
2338: }
2339: }
2340: } else {
2341: my ($result,$perm_reqd) =
1.707 albertel 2342: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2343: if ($result eq 'ok') {
2344: if (!($perm_reqd eq 'yes')) {
2345: return(&retrievestudentphoto($udom,$unam,$ext));
2346: }
2347: }
2348: }
2349: return '/adm/lonKaputt/lonlogo_broken.gif';
2350: }
2351:
2352: sub retrievestudentphoto {
2353: my ($udom,$unam,$ext,$type) = @_;
2354: my $home=&Apache::lonnet::homeserver($unam,$udom);
2355: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2356: if ($ret eq 'ok') {
2357: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2358: if ($type eq 'thumbnail') {
2359: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2360: }
2361: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2362: return $tokenurl;
2363: } else {
2364: if ($type eq 'thumbnail') {
2365: return '/adm/lonKaputt/genericstudent_tn.gif';
2366: } else {
2367: return '/adm/lonKaputt/lonlogo_broken.gif';
2368: }
1.617 albertel 2369: }
2370: }
2371:
1.263 www 2372: # -------------------------------------------------------------------- New chat
2373:
2374: sub chatsend {
1.724 raeburn 2375: my ($newentry,$anon,$group)=@_;
1.620 albertel 2376: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2377: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2378: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2379: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2380: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2381: &escape($newentry)).':'.$group,$chome);
1.292 www 2382: }
2383:
2384: # ------------------------------------------ Find current version of a resource
2385:
2386: sub getversion {
2387: my $fname=&clutter(shift);
2388: unless ($fname=~/^\/res\//) { return -1; }
2389: return ¤tversion(&filelocation('',$fname));
2390: }
2391:
2392: sub currentversion {
2393: my $fname=shift;
2394: my $author=$fname;
2395: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2396: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2397: my $home=&homeserver($uname,$udom);
1.292 www 2398: if ($home eq 'no_host') {
2399: return -1;
2400: }
1.1112 www 2401: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2402: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2403: return -1;
2404: }
1.1112 www 2405: return $answer;
1.263 www 2406: }
2407:
1.1111 www 2408: #
2409: # Return special version number of resource if set by override, empty otherwise
2410: #
2411: sub usedversion {
2412: my $fname=shift;
2413: unless ($fname) { $fname=$env{'request.uri'}; }
2414: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2415: if ($urlversion) { return $urlversion; }
2416: return '';
2417: }
2418:
1.1 albertel 2419: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2420:
1.1 albertel 2421: sub subscribe {
2422: my $fname=shift;
1.761 raeburn 2423: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2424: $fname=~s/[\n\r]//g;
1.1 albertel 2425: my $author=$fname;
2426: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2427: my ($udom,$uname)=split(/\//,$author);
2428: my $home=homeserver($uname,$udom);
1.335 albertel 2429: if ($home eq 'no_host') {
2430: return 'not_found';
1.1 albertel 2431: }
2432: my $answer=reply("sub:$fname",$home);
1.64 www 2433: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2434: $answer.=' by '.$home;
2435: }
1.1 albertel 2436: return $answer;
2437: }
2438:
1.8 www 2439: # -------------------------------------------------------------- Replicate file
2440:
2441: sub repcopy {
2442: my $filename=shift;
1.23 www 2443: $filename=~s/\/+/\//g;
1.1142 raeburn 2444: my $londocroot = $perlvar{'lonDocRoot'};
2445: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
2446: if ($filename=~m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
2447: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2448: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2449: return &repcopy_userfile($filename);
2450: }
1.532 albertel 2451: $filename=~s/[\n\r]//g;
1.8 www 2452: my $transname="$filename.in.transfer";
1.828 www 2453: # FIXME: this should flock
1.607 raeburn 2454: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2455: my $remoteurl=subscribe($filename);
1.64 www 2456: if ($remoteurl =~ /^con_lost by/) {
2457: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2458: return 'unavailable';
1.8 www 2459: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2460: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2461: return 'not_found';
1.64 www 2462: } elsif ($remoteurl =~ /^rejected by/) {
2463: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2464: return 'forbidden';
1.20 www 2465: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2466: return 'ok';
1.8 www 2467: } else {
1.290 www 2468: my $author=$filename;
2469: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2470: my ($udom,$uname)=split(/\//,$author);
2471: my $home=homeserver($uname,$udom);
2472: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2473: my @parts=split(/\//,$filename);
2474: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2475: if ($path ne "$londocroot/res") {
1.8 www 2476: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2477: return 'bad_request';
1.8 www 2478: }
2479: my $count;
2480: for ($count=5;$count<$#parts;$count++) {
2481: $path.="/$parts[$count]";
2482: if ((-e $path)!=1) {
2483: mkdir($path,0777);
2484: }
2485: }
2486: my $ua=new LWP::UserAgent;
2487: my $request=new HTTP::Request('GET',"$remoteurl");
2488: my $response=$ua->request($request,$transname);
2489: if ($response->is_error()) {
2490: unlink($transname);
2491: my $message=$response->status_line;
1.672 albertel 2492: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2493: ." LWP get: $message: $filename</font>");
1.607 raeburn 2494: return 'unavailable';
1.8 www 2495: } else {
1.16 www 2496: if ($remoteurl!~/\.meta$/) {
2497: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2498: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2499: if ($mresponse->is_error()) {
2500: unlink($filename.'.meta');
2501: &logthis(
1.672 albertel 2502: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2503: }
2504: }
1.8 www 2505: rename($transname,$filename);
1.607 raeburn 2506: return 'ok';
1.8 www 2507: }
1.290 www 2508: }
1.8 www 2509: }
1.330 www 2510: }
2511:
2512: # ------------------------------------------------ Get server side include body
2513: sub ssi_body {
1.381 albertel 2514: my ($filelink,%form)=@_;
1.606 matthew 2515: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2516: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2517: }
1.953 www 2518: my $output='';
2519: my $response;
1.980 raeburn 2520: if ($filelink=~/^https?\:/) {
1.954 raeburn 2521: ($output,$response)=&externalssi($filelink);
1.953 www 2522: } else {
1.1004 droeschl 2523: $filelink .= $filelink=~/\?/ ? '&' : '?';
2524: $filelink .= 'inhibitmenu=yes';
1.953 www 2525: ($output,$response)=&ssi($filelink,%form);
2526: }
1.778 albertel 2527: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2528: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2529: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2530: if (wantarray) {
2531: return ($output, $response);
2532: } else {
2533: return $output;
2534: }
1.8 www 2535: }
2536:
1.15 www 2537: # --------------------------------------------------------- Server Side Include
2538:
1.782 albertel 2539: sub absolute_url {
2540: my ($host_name) = @_;
2541: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2542: if ($host_name eq '') {
2543: $host_name = $ENV{'SERVER_NAME'};
2544: }
2545: return $protocol.$host_name;
2546: }
2547:
1.942 foxr 2548: #
2549: # Server side include.
2550: # Parameters:
2551: # fn Possibly encrypted resource name/id.
2552: # form Hash that describes how the rendering should be done
2553: # and other things.
1.944 foxr 2554: # Returns:
1.950 raeburn 2555: # Scalar context: The content of the response.
2556: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2557: #
1.15 www 2558: sub ssi {
2559:
1.944 foxr 2560: my ($fn,%form)=@_;
1.15 www 2561: my $ua=new LWP::UserAgent;
1.23 www 2562: my $request;
1.711 albertel 2563:
2564: $form{'no_update_last_known'}=1;
1.895 albertel 2565: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2566: if (%form) {
1.782 albertel 2567: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2568: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2569: } else {
1.782 albertel 2570: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2571: }
2572:
1.15 www 2573: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2574: my $response=$ua->request($request);
2575:
1.944 foxr 2576: if (wantarray) {
2577: return ($response->content, $response);
2578: } else {
2579: return $response->content;
1.942 foxr 2580: }
1.324 www 2581: }
2582:
2583: sub externalssi {
2584: my ($url)=@_;
2585: my $ua=new LWP::UserAgent;
2586: my $request=new HTTP::Request('GET',$url);
2587: my $response=$ua->request($request);
1.954 raeburn 2588: if (wantarray) {
2589: return ($response->content, $response);
2590: } else {
2591: return $response->content;
2592: }
1.15 www 2593: }
1.254 www 2594:
1.492 albertel 2595: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2596:
2597: sub allowuploaded {
2598: my ($srcurl,$url)=@_;
2599: $url=&clutter(&declutter($url));
2600: my $dir=$url;
2601: $dir=~s/\/[^\/]+$//;
2602: my %httpref=();
2603: my $httpurl=&hreflocation('',$url);
2604: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2605: &Apache::lonnet::appenv(\%httpref);
1.254 www 2606: }
1.477 raeburn 2607:
1.478 albertel 2608: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2609: # input: action, courseID, current domain, intended
1.637 raeburn 2610: # path to file, source of file, instruction to parse file for objects,
2611: # ref to hash for embedded objects,
2612: # ref to hash for codebase of java objects.
1.1095 raeburn 2613: # reference to scalar to accommodate mime type determined
2614: # from File::MMagic if $parser = parse.
1.637 raeburn 2615: #
1.485 raeburn 2616: # output: url to file (if action was uploaddoc),
2617: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2618: #
1.478 albertel 2619: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2620: # course.
1.477 raeburn 2621: #
1.478 albertel 2622: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2623: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2624: # course's home server.
1.477 raeburn 2625: #
1.478 albertel 2626: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2627: # be copied from $source (current location) to
2628: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2629: # and will then be copied to
2630: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2631: # course's home server.
1.485 raeburn 2632: #
1.481 raeburn 2633: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2634: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2635: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2636: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2637: # in course's home server.
1.637 raeburn 2638: #
1.477 raeburn 2639:
2640: sub process_coursefile {
1.1095 raeburn 2641: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2642: $mimetype)=@_;
1.477 raeburn 2643: my $fetchresult;
1.638 albertel 2644: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2645: if ($action eq 'propagate') {
1.638 albertel 2646: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2647: $home);
1.481 raeburn 2648: } else {
1.477 raeburn 2649: my $fpath = '';
2650: my $fname = $file;
1.478 albertel 2651: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2652: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2653: my $filepath = &build_filepath($fpath);
1.481 raeburn 2654: if ($action eq 'copy') {
2655: if ($source eq '') {
2656: $fetchresult = 'no source file';
2657: return $fetchresult;
2658: } else {
2659: my $destination = $filepath.'/'.$fname;
2660: rename($source,$destination);
2661: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2662: $home);
1.481 raeburn 2663: }
2664: } elsif ($action eq 'uploaddoc') {
2665: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2666: print $fh $env{'form.'.$source};
1.481 raeburn 2667: close($fh);
1.637 raeburn 2668: if ($parser eq 'parse') {
1.1024 raeburn 2669: my $mm = new File::MMagic;
1.1095 raeburn 2670: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2671: if ($type eq 'text/html') {
1.1024 raeburn 2672: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2673: unless ($parse_result eq 'ok') {
2674: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2675: }
1.637 raeburn 2676: }
1.1095 raeburn 2677: if (ref($mimetype)) {
2678: $$mimetype = $type;
2679: }
1.637 raeburn 2680: }
1.477 raeburn 2681: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2682: $home);
1.481 raeburn 2683: if ($fetchresult eq 'ok') {
2684: return '/uploaded/'.$fpath.'/'.$fname;
2685: } else {
2686: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2687: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2688: return '/adm/notfound.html';
2689: }
1.477 raeburn 2690: }
2691: }
1.485 raeburn 2692: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2693: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2694: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2695: }
2696: return $fetchresult;
2697: }
2698:
1.637 raeburn 2699: sub build_filepath {
2700: my ($fpath) = @_;
2701: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2702: unless ($fpath eq '') {
2703: my @parts=split('/',$fpath);
2704: foreach my $part (@parts) {
2705: $filepath.= '/'.$part;
2706: if ((-e $filepath)!=1) {
2707: mkdir($filepath,0777);
2708: }
2709: }
2710: }
2711: return $filepath;
2712: }
2713:
2714: sub store_edited_file {
1.638 albertel 2715: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2716: my $file = $primary_url;
2717: $file =~ s#^/uploaded/$docudom/$docuname/##;
2718: my $fpath = '';
2719: my $fname = $file;
2720: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2721: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2722: my $filepath = &build_filepath($fpath);
2723: open(my $fh,'>'.$filepath.'/'.$fname);
2724: print $fh $content;
2725: close($fh);
1.638 albertel 2726: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2727: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2728: $home);
1.637 raeburn 2729: if ($$fetchresult eq 'ok') {
2730: return '/uploaded/'.$fpath.'/'.$fname;
2731: } else {
1.638 albertel 2732: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2733: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2734: return '/adm/notfound.html';
2735: }
2736: }
2737:
1.531 albertel 2738: sub clean_filename {
1.831 albertel 2739: my ($fname,$args)=@_;
1.315 www 2740: # Replace Windows backslashes by forward slashes
1.257 www 2741: $fname=~s/\\/\//g;
1.831 albertel 2742: if (!$args->{'keep_path'}) {
2743: # Get rid of everything but the actual filename
2744: $fname=~s/^.*\/([^\/]+)$/$1/;
2745: }
1.315 www 2746: # Replace spaces by underscores
2747: $fname=~s/\s+/\_/g;
2748: # Replace all other weird characters by nothing
1.831 albertel 2749: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2750: # Replace all .\d. sequences with _\d. so they no longer look like version
2751: # numbers
2752: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2753: return $fname;
2754: }
1.1051 raeburn 2755: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2756: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2757: # image with the same aspect ratio as the original, but with dimensions which do
2758: # not exceed $resizewidth and $resizeheight.
2759:
1.984 neumanie 2760: sub resizeImage {
1.1051 raeburn 2761: my ($img_path,$resizewidth,$resizeheight) = @_;
2762: my $ima = Image::Magick->new;
2763: my $resized;
2764: if (-e $img_path) {
2765: $ima->Read($img_path);
2766: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2767: my $width = $ima->Get('width');
2768: my $height = $ima->Get('height');
2769: if ($width > $resizewidth) {
2770: my $factor = $width/$resizewidth;
2771: my $newheight = $height/$factor;
2772: $ima->Scale(width=>$resizewidth,height=>$newheight);
2773: $resized = 1;
2774: }
2775: }
2776: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2777: my $width = $ima->Get('width');
2778: my $height = $ima->Get('height');
2779: if ($height > $resizeheight) {
2780: my $factor = $height/$resizeheight;
2781: my $newwidth = $width/$factor;
2782: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2783: $resized = 1;
2784: }
2785: }
2786: if ($resized) {
2787: $ima->Write($img_path);
2788: }
2789: }
2790: return;
1.977 amueller 2791: }
2792:
1.608 albertel 2793: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2794: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 2795: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 2796: # $context - possible values: coursedoc, existingfile, overwrite,
2797: # canceloverwrite, or ''.
2798: # if 'coursedoc': upload to the current course
2799: # if 'existingfile': write file to tmp/overwrites directory
2800: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2801: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2802: # $subdir - directory in userfile to store the file into
1.858 raeburn 2803: # $parser - instruction to parse file for objects ($parser = parse)
2804: # $allfiles - reference to hash for embedded objects
2805: # $codebase - reference to hash for codebase of java objects
2806: # $desuname - username for permanent storage of uploaded file
2807: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2808: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2809: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2810: # $resizewidth - width (pixels) to which to resize uploaded image
2811: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 2812: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 2813: # from File::MMagic.
1.858 raeburn 2814: #
1.686 albertel 2815: # output: url of file in userspace, or error: <message>
2816: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2817:
1.531 albertel 2818: sub userfileupload {
1.1090 raeburn 2819: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 2820: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2821: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2822: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2823: $fname=&clean_filename($fname);
1.1090 raeburn 2824: # See if there is anything left
1.257 www 2825: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 2826: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2827: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2828: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2829: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2830: my $now = time;
1.1090 raeburn 2831: my $filepath;
1.1095 raeburn 2832: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 2833: $filepath = 'tmp/helprequests/'.$now;
2834: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2835: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2836: '_'.$env{'user.domain'}.'/pending';
2837: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2838: my ($docuname,$docudom);
2839: if ($destudom) {
2840: $docudom = $destudom;
2841: } else {
2842: $docudom = $env{'user.domain'};
2843: }
2844: if ($destuname) {
2845: $docuname = $destuname;
2846: } else {
2847: $docuname = $env{'user.name'};
2848: }
2849: if (exists($env{'form.group'})) {
2850: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2851: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2852: }
2853: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2854: if ($context eq 'canceloverwrite') {
2855: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2856: if (-e $tempfile) {
2857: my @info = stat($tempfile);
2858: if ($info[9] eq $env{'form.timestamp'}) {
2859: unlink($tempfile);
2860: }
2861: }
2862: return;
1.523 raeburn 2863: }
2864: }
1.1090 raeburn 2865: # Create the directory if not present
1.741 raeburn 2866: my @parts=split(/\//,$filepath);
2867: my $fullpath = $perlvar{'lonDaemons'};
2868: for (my $i=0;$i<@parts;$i++) {
2869: $fullpath .= '/'.$parts[$i];
2870: if ((-e $fullpath)!=1) {
2871: mkdir($fullpath,0777);
2872: }
2873: }
2874: open(my $fh,'>'.$fullpath.'/'.$fname);
2875: print $fh $env{'form.'.$formname};
2876: close($fh);
1.1090 raeburn 2877: if ($context eq 'existingfile') {
2878: my @info = stat($fullpath.'/'.$fname);
2879: return ($fullpath.'/'.$fname,$info[9]);
2880: } else {
2881: return $fullpath.'/'.$fname;
2882: }
1.523 raeburn 2883: }
1.995 raeburn 2884: if ($subdir eq 'scantron') {
2885: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 2886: } else {
1.995 raeburn 2887: $fname="$subdir/$fname";
2888: }
1.1090 raeburn 2889: if ($context eq 'coursedoc') {
1.638 albertel 2890: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2891: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2892: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2893: return &finishuserfileupload($docuname,$docudom,
2894: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2895: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 2896: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2897: } else {
1.620 albertel 2898: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2899: return &process_coursefile('uploaddoc',$docuname,$docudom,
2900: $fname,$formname,$parser,
1.1095 raeburn 2901: $allfiles,$codebase,$mimetype);
1.481 raeburn 2902: }
1.719 banghart 2903: } elsif (defined($destuname)) {
2904: my $docuname=$destuname;
2905: my $docudom=$destudom;
1.860 raeburn 2906: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2907: $parser,$allfiles,$codebase,
1.1051 raeburn 2908: $thumbwidth,$thumbheight,
1.1095 raeburn 2909: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2910: } else {
1.638 albertel 2911: my $docuname=$env{'user.name'};
2912: my $docudom=$env{'user.domain'};
1.714 raeburn 2913: if (exists($env{'form.group'})) {
2914: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2915: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2916: }
1.860 raeburn 2917: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2918: $parser,$allfiles,$codebase,
1.1051 raeburn 2919: $thumbwidth,$thumbheight,
1.1095 raeburn 2920: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2921: }
1.271 www 2922: }
2923:
2924: sub finishuserfileupload {
1.860 raeburn 2925: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 2926: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2927: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2928: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2929:
1.860 raeburn 2930: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2931: $file=$fname;
2932: if ($fname=~m|/|) {
2933: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2934: $path.=$fnamepath.'/';
2935: }
1.259 www 2936: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2937: my $count;
2938: for ($count=4;$count<=$#parts;$count++) {
2939: $filepath.="/$parts[$count]";
2940: if ((-e $filepath)!=1) {
2941: mkdir($filepath,0777);
2942: }
2943: }
1.984 neumanie 2944:
1.258 www 2945: # Save the file
2946: {
1.701 albertel 2947: if (!open(FH,'>'.$filepath.'/'.$file)) {
2948: &logthis('Failed to create '.$filepath.'/'.$file);
2949: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2950: return '/adm/notfound.html';
2951: }
1.1090 raeburn 2952: if ($context eq 'overwrite') {
1.1117 foxr 2953: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 2954: my $target = $filepath.'/'.$file;
2955: if (-e $source) {
2956: my @info = stat($source);
2957: if ($info[9] eq $env{'form.timestamp'}) {
2958: unless (&File::Copy::move($source,$target)) {
2959: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2960: return "Moving from $source failed";
2961: }
2962: } else {
2963: return "Temporary file: $source had unexpected date/time for last modification";
2964: }
2965: } else {
2966: return "Temporary file: $source missing";
2967: }
2968: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2969: &logthis('Failed to write to '.$filepath.'/'.$file);
2970: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2971: return '/adm/notfound.html';
2972: }
1.570 albertel 2973: close(FH);
1.1051 raeburn 2974: if ($resizewidth && $resizeheight) {
2975: my $mm = new File::MMagic;
2976: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2977: if ($mime_type =~ m{^image/}) {
2978: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2979: }
1.977 amueller 2980: }
1.258 www 2981: }
1.1152 raeburn 2982: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
2983: if (ref($mimetype)) {
2984: if ($$mimetype eq '') {
2985: my $mm = new File::MMagic;
2986: my $type = $mm->checktype_filename($filepath.'/'.$file);
2987: $$mimetype = $type;
2988: }
2989: }
2990: }
1.637 raeburn 2991: if ($parser eq 'parse') {
1.1152 raeburn 2992: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 2993: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2994: $allfiles,$codebase);
2995: unless ($parse_result eq 'ok') {
2996: &logthis('Failed to parse '.$filepath.$file.
2997: ' for embedded media: '.$parse_result);
2998: }
1.637 raeburn 2999: }
3000: }
1.860 raeburn 3001: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3002: my $input = $filepath.'/'.$file;
3003: my $output = $filepath.'/'.'tn-'.$file;
3004: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3005: system("convert -sample $thumbsize $input $output");
3006: if (-e $filepath.'/'.'tn-'.$file) {
3007: $fetchthumb = 1;
3008: }
3009: }
1.858 raeburn 3010:
1.259 www 3011: # Notify homeserver to grep it
3012: #
1.984 neumanie 3013: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3014: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3015: if ($fetchresult eq 'ok') {
1.860 raeburn 3016: if ($fetchthumb) {
3017: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3018: if ($thumbresult ne 'ok') {
3019: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3020: $docuhome.': '.$thumbresult);
3021: }
3022: }
1.259 www 3023: #
1.258 www 3024: # Return the URL to it
1.494 albertel 3025: return '/uploaded/'.$path.$file;
1.263 www 3026: } else {
1.494 albertel 3027: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3028: ': '.$fetchresult);
1.263 www 3029: return '/adm/notfound.html';
1.858 raeburn 3030: }
1.493 albertel 3031: }
3032:
1.637 raeburn 3033: sub extract_embedded_items {
1.961 raeburn 3034: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3035: my @state = ();
3036: my %javafiles = (
3037: codebase => '',
3038: code => '',
3039: archive => ''
3040: );
3041: my %mediafiles = (
3042: src => '',
3043: movie => '',
3044: );
1.648 raeburn 3045: my $p;
3046: if ($content) {
3047: $p = HTML::LCParser->new($content);
3048: } else {
1.961 raeburn 3049: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3050: }
1.641 albertel 3051: while (my $t=$p->get_token()) {
1.640 albertel 3052: if ($t->[0] eq 'S') {
3053: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3054: push(@state, $tagname);
1.648 raeburn 3055: if (lc($tagname) eq 'allow') {
3056: &add_filetype($allfiles,$attr->{'src'},'src');
3057: }
1.640 albertel 3058: if (lc($tagname) eq 'img') {
3059: &add_filetype($allfiles,$attr->{'src'},'src');
3060: }
1.886 albertel 3061: if (lc($tagname) eq 'a') {
3062: &add_filetype($allfiles,$attr->{'href'},'href');
3063: }
1.645 raeburn 3064: if (lc($tagname) eq 'script') {
3065: if ($attr->{'archive'} =~ /\.jar$/i) {
3066: &add_filetype($allfiles,$attr->{'archive'},'archive');
3067: } else {
3068: &add_filetype($allfiles,$attr->{'src'},'src');
3069: }
3070: }
3071: if (lc($tagname) eq 'link') {
3072: if (lc($attr->{'rel'}) eq 'stylesheet') {
3073: &add_filetype($allfiles,$attr->{'href'},'href');
3074: }
3075: }
1.640 albertel 3076: if (lc($tagname) eq 'object' ||
3077: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3078: foreach my $item (keys(%javafiles)) {
3079: $javafiles{$item} = '';
3080: }
3081: }
3082: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3083: my $name = lc($attr->{'name'});
3084: foreach my $item (keys(%javafiles)) {
3085: if ($name eq $item) {
3086: $javafiles{$item} = $attr->{'value'};
3087: last;
3088: }
3089: }
3090: foreach my $item (keys(%mediafiles)) {
3091: if ($name eq $item) {
3092: &add_filetype($allfiles, $attr->{'value'}, 'value');
3093: last;
3094: }
3095: }
3096: }
3097: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3098: foreach my $item (keys(%javafiles)) {
3099: if ($attr->{$item}) {
3100: $javafiles{$item} = $attr->{$item};
3101: last;
3102: }
3103: }
3104: foreach my $item (keys(%mediafiles)) {
3105: if ($attr->{$item}) {
3106: &add_filetype($allfiles,$attr->{$item},$item);
3107: last;
3108: }
3109: }
3110: }
3111: } elsif ($t->[0] eq 'E') {
3112: my ($tagname) = ($t->[1]);
3113: if ($javafiles{'codebase'} ne '') {
3114: $javafiles{'codebase'} .= '/';
3115: }
3116: if (lc($tagname) eq 'applet' ||
3117: lc($tagname) eq 'object' ||
3118: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3119: ) {
3120: foreach my $item (keys(%javafiles)) {
3121: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3122: my $file=$javafiles{'codebase'}.$javafiles{$item};
3123: &add_filetype($allfiles,$file,$item);
3124: }
3125: }
3126: }
3127: pop @state;
3128: }
3129: }
1.637 raeburn 3130: return 'ok';
3131: }
3132:
1.639 albertel 3133: sub add_filetype {
3134: my ($allfiles,$file,$type)=@_;
3135: if (exists($allfiles->{$file})) {
3136: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3137: push(@{$allfiles->{$file}}, &escape($type));
3138: }
3139: } else {
3140: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3141: }
3142: }
3143:
1.493 albertel 3144: sub removeuploadedurl {
1.984 neumanie 3145: my ($url)=@_;
3146: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3147: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3148: }
3149:
3150: sub removeuserfile {
3151: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3152: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3153: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3154: if ($result eq 'ok') {
1.798 raeburn 3155: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3156: my $metafile = $fname.'.meta';
3157: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3158: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3159: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3160: my $sqlresult =
1.823 albertel 3161: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3162: 'portfolio_metadata',$group,
3163: 'delete');
1.798 raeburn 3164: }
3165: }
3166: return $result;
1.257 www 3167: }
1.15 www 3168:
1.530 albertel 3169: sub mkdiruserfile {
3170: my ($docuname,$docudom,$dir)=@_;
3171: my $home=&homeserver($docuname,$docudom);
3172: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3173: }
3174:
1.531 albertel 3175: sub renameuserfile {
3176: my ($docuname,$docudom,$old,$new)=@_;
3177: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3178: my $result = &reply("renameuserfile:$docudom:$docuname:".
3179: &escape("$old").':'.&escape("$new"),$home);
3180: if ($result eq 'ok') {
3181: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3182: my $oldmeta = $old.'.meta';
3183: my $newmeta = $new.'.meta';
3184: my $metaresult =
3185: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3186: my $url = "/uploaded/$docudom/$docuname/$old";
3187: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3188: my $sqlresult =
1.823 albertel 3189: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3190: 'portfolio_metadata',$group,
3191: 'delete');
1.798 raeburn 3192: }
3193: }
3194: return $result;
1.531 albertel 3195: }
3196:
1.14 www 3197: # ------------------------------------------------------------------------- Log
3198:
3199: sub log {
3200: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3201: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3202: }
3203:
3204: # ------------------------------------------------------------------ Course Log
1.352 www 3205: #
3206: # This routine flushes several buffers of non-mission-critical nature
3207: #
1.157 www 3208:
3209: sub flushcourselogs {
1.352 www 3210: &logthis('Flushing log buffers');
3211: #
3212: # course logs
3213: # This is a log of all transactions in a course, which can be used
3214: # for data mining purposes
3215: #
3216: # It also collects the courseid database, which lists last transaction
3217: # times and course titles for all courseids
3218: #
3219: my %courseidbuffer=();
1.921 raeburn 3220: foreach my $crsid (keys(%courselogs)) {
1.352 www 3221: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3222: &escape($courselogs{$crsid}),
3223: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3224: delete $courselogs{$crsid};
3225: } else {
3226: &logthis('Failed to flush log buffer for '.$crsid);
3227: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3228: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3229: " exceeded maximum size, deleting.</font>");
3230: delete $courselogs{$crsid};
3231: }
1.352 www 3232: }
1.920 raeburn 3233: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3234: 'description' => $coursedescrbuf{$crsid},
3235: 'inst_code' => $courseinstcodebuf{$crsid},
3236: 'type' => $coursetypebuf{$crsid},
3237: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3238: };
1.191 harris41 3239: }
1.352 www 3240: #
3241: # Write course id database (reverse lookup) to homeserver of courses
3242: # Is used in pickcourse
3243: #
1.840 albertel 3244: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3245: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3246: $courseidbuffer{$crs_home},
3247: $crs_home,'timeonly');
1.352 www 3248: }
3249: #
3250: # File accesses
3251: # Writes to the dynamic metadata of resources to get hit counts, etc.
3252: #
1.449 matthew 3253: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3254: if ($entry =~ /___count$/) {
3255: my ($dom,$name);
1.807 albertel 3256: ($dom,$name,undef)=
1.811 albertel 3257: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3258: if (! defined($dom) || $dom eq '' ||
3259: ! defined($name) || $name eq '') {
1.620 albertel 3260: my $cid = $env{'request.course.id'};
3261: $dom = $env{'request.'.$cid.'.domain'};
3262: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3263: }
1.450 matthew 3264: my $value = $accesshash{$entry};
3265: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3266: my %temphash=($url => $value);
1.449 matthew 3267: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3268: if ($result eq 'ok') {
3269: delete $accesshash{$entry};
3270: }
3271: } else {
1.811 albertel 3272: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3273: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3274: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3275: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3276: delete $accesshash{$entry};
3277: }
1.185 www 3278: }
1.191 harris41 3279: }
1.352 www 3280: #
3281: # Roles
3282: # Reverse lookup of user roles for course faculty/staff and co-authorship
3283: #
1.800 albertel 3284: foreach my $entry (keys(%userrolehash)) {
1.351 www 3285: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3286: split(/\:/,$entry);
3287: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3288: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3289: $rudom,$runame) eq 'ok') {
3290: delete $userrolehash{$entry};
3291: }
3292: }
1.662 raeburn 3293: #
3294: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3295: #
3296: my %domrolebuffer = ();
1.1000 raeburn 3297: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3298: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3299: if ($domrolebuffer{$rudom}) {
3300: $domrolebuffer{$rudom}.='&'.&escape($entry).
3301: '='.&escape($domainrolehash{$entry});
3302: } else {
3303: $domrolebuffer{$rudom}.=&escape($entry).
3304: '='.&escape($domainrolehash{$entry});
3305: }
3306: delete $domainrolehash{$entry};
3307: }
3308: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3309: my %servers = &get_servers($dom,'library');
3310: foreach my $tryserver (keys(%servers)) {
3311: unless (&reply('domroleput:'.$dom.':'.
3312: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3313: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3314: }
1.662 raeburn 3315: }
3316: }
1.186 www 3317: $dumpcount++;
1.157 www 3318: }
3319:
3320: sub courselog {
3321: my $what=shift;
1.158 www 3322: $what=time.':'.$what;
1.620 albertel 3323: unless ($env{'request.course.id'}) { return ''; }
3324: $coursedombuf{$env{'request.course.id'}}=
3325: $env{'course.'.$env{'request.course.id'}.'.domain'};
3326: $coursenumbuf{$env{'request.course.id'}}=
3327: $env{'course.'.$env{'request.course.id'}.'.num'};
3328: $coursehombuf{$env{'request.course.id'}}=
3329: $env{'course.'.$env{'request.course.id'}.'.home'};
3330: $coursedescrbuf{$env{'request.course.id'}}=
3331: $env{'course.'.$env{'request.course.id'}.'.description'};
3332: $courseinstcodebuf{$env{'request.course.id'}}=
3333: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3334: $courseownerbuf{$env{'request.course.id'}}=
3335: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3336: $coursetypebuf{$env{'request.course.id'}}=
3337: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3338: if (defined $courselogs{$env{'request.course.id'}}) {
3339: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3340: } else {
1.620 albertel 3341: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3342: }
1.620 albertel 3343: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3344: &flushcourselogs();
3345: }
1.158 www 3346: }
3347:
3348: sub courseacclog {
3349: my $fnsymb=shift;
1.620 albertel 3350: unless ($env{'request.course.id'}) { return ''; }
3351: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3352: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3353: $what.=':POST';
1.583 matthew 3354: # FIXME: Probably ought to escape things....
1.800 albertel 3355: foreach my $key (keys(%env)) {
3356: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3357: my $formitem = $1;
3358: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3359: $what.=':'.$formitem.'='.$env{$key};
3360: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3361: $what.=':'.$formitem.'='.$env{$key};
3362: }
1.158 www 3363: }
1.191 harris41 3364: }
1.583 matthew 3365: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3366: # FIXME: We should not be depending on a form parameter that someone
3367: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3368: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3369: $what.= ':POST';
3370: # FIXME: Probably ought to escape things....
3371: foreach my $element ('courseexp','crsfulltext','crsrelated',
3372: 'crsdiscuss') {
1.620 albertel 3373: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3374: }
3375: }
1.158 www 3376: }
3377: &courselog($what);
1.149 www 3378: }
3379:
1.185 www 3380: sub countacc {
3381: my $url=&declutter(shift);
1.458 matthew 3382: return if (! defined($url) || $url eq '');
1.620 albertel 3383: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3384: #
3385: # Mark that this url was used in this course
3386: #
1.620 albertel 3387: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3388: #
3389: # Increase the access count for this resource in this child process
3390: #
1.281 www 3391: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3392: $accesshash{$key}++;
1.185 www 3393: }
1.349 www 3394:
1.361 www 3395: sub linklog {
3396: my ($from,$to)=@_;
3397: $from=&declutter($from);
3398: $to=&declutter($to);
3399: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3400: $accesshash{$to.'___'.$from.'___goto'}=1;
3401: }
1.1160 www 3402:
3403: sub statslog {
3404: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3405: if ($users<2) { return; }
3406: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3407: 'course' => $env{'request.course.id'},
3408: 'sections' => '"all"',
3409: 'num_students' => $users,
3410: 'part' => $part,
3411: 'symb' => $symb,
3412: 'mean_tries' => $av_attempts,
3413: 'deg_of_diff' => $degdiff});
3414: foreach my $key (keys(%dynstore)) {
3415: $accesshash{$key}=$dynstore{$key};
3416: }
3417: }
1.361 www 3418:
1.349 www 3419: sub userrolelog {
3420: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 3421: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 3422: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 3423: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 3424: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 3425: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3426: $userrolehash
3427: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3428: =$tend.':'.$tstart;
1.662 raeburn 3429: }
1.898 albertel 3430: if (($env{'request.role'} =~ /dc\./) &&
3431: (($trole=~/^au/) || ($trole=~/^in/) ||
3432: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 3433: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3434: ($trole=~/^co/))) {
1.898 albertel 3435: $userrolehash
3436: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3437: =$tend.':'.$tstart;
3438: }
1.662 raeburn 3439: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3440: ($trole=~/^li/) || ($trole=~/^li/) ||
3441: ($trole=~/^au/) || ($trole=~/^dg/) ||
3442: ($trole=~/^sc/)) {
3443: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3444: $domainrolehash
3445: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3446: = $tend.':'.$tstart;
3447: }
1.351 www 3448: }
3449:
1.957 raeburn 3450: sub courserolelog {
3451: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3452: if (($trole eq 'cc') || ($trole eq 'in') ||
3453: ($trole eq 'ep') || ($trole eq 'ad') ||
3454: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 3455: ($trole=~/^cr/) || ($trole eq 'gr') ||
3456: ($trole eq 'co')) {
1.957 raeburn 3457: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3458: my $cdom = $1;
3459: my $cnum = $2;
3460: my $sec = $3;
3461: my $namespace = 'rolelog';
3462: my %storehash = (
3463: role => $trole,
3464: start => $tstart,
3465: end => $tend,
3466: selfenroll => $selfenroll,
3467: context => $context,
3468: );
3469: if ($trole eq 'gr') {
3470: $namespace = 'groupslog';
3471: $storehash{'group'} = $sec;
3472: } else {
3473: $storehash{'section'} = $sec;
3474: }
3475: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 3476: if (($trole ne 'st') || ($sec ne '')) {
3477: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3478: }
1.957 raeburn 3479: }
3480: }
3481: return;
3482: }
3483:
1.351 www 3484: sub get_course_adv_roles {
1.948 raeburn 3485: my ($cid,$codes) = @_;
1.620 albertel 3486: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3487: my %coursehash=&coursedescription($cid);
1.988 raeburn 3488: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3489: my %nothide=();
1.800 albertel 3490: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3491: if ($user !~ /:/) {
3492: $nothide{join(':',split(/[\@]/,$user))}=1;
3493: } else {
3494: $nothide{$user}=1;
3495: }
1.470 www 3496: }
1.351 www 3497: my %returnhash=();
3498: my %dumphash=
3499: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3500: my $now=time;
1.997 raeburn 3501: my %privileged;
1.1000 raeburn 3502: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3503: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3504: if (($tstart) && ($tstart<0)) { next; }
3505: if (($tend) && ($tend<$now)) { next; }
3506: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3507: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3508: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3509: unless (ref($privileged{$domain}) eq 'HASH') {
3510: my %dompersonnel =
1.998 raeburn 3511: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3512: $privileged{$domain} = {};
3513: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3514: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3515: foreach my $user (keys(%{$dompersonnel{$server}})) {
3516: my ($trole,$uname,$udom) = split(/:/,$user);
3517: $privileged{$udom}{$uname} = 1;
3518: }
3519: }
3520: }
3521: }
3522: if ((exists($privileged{$domain}{$username})) &&
3523: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3524: if ($role eq 'cr') { next; }
1.948 raeburn 3525: if ($codes) {
3526: if ($section) { $role .= ':'.$section; }
3527: if ($returnhash{$role}) {
3528: $returnhash{$role}.=','.$username.':'.$domain;
3529: } else {
3530: $returnhash{$role}=$username.':'.$domain;
3531: }
1.351 www 3532: } else {
1.988 raeburn 3533: my $key=&plaintext($role,$crstype);
1.973 bisitz 3534: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3535: if ($returnhash{$key}) {
3536: $returnhash{$key}.=','.$username.':'.$domain;
3537: } else {
3538: $returnhash{$key}=$username.':'.$domain;
3539: }
1.351 www 3540: }
1.948 raeburn 3541: }
1.400 www 3542: return %returnhash;
3543: }
3544:
3545: sub get_my_roles {
1.937 raeburn 3546: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3547: unless (defined($uname)) { $uname=$env{'user.name'}; }
3548: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3549: my (%dumphash,%nothide);
1.1086 raeburn 3550: if ($context eq 'userroles') {
3551: my $extra = &freeze_escape({'skipcheck' => 1});
3552: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858 raeburn 3553: } else {
3554: %dumphash=
1.400 www 3555: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3556: if ($hidepriv) {
3557: my %coursehash=&coursedescription($udom.'_'.$uname);
3558: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3559: if ($user !~ /:/) {
3560: $nothide{join(':',split(/[\@]/,$user))} = 1;
3561: } else {
3562: $nothide{$user} = 1;
3563: }
3564: }
3565: }
1.858 raeburn 3566: }
1.400 www 3567: my %returnhash=();
3568: my $now=time;
1.999 raeburn 3569: my %privileged;
1.800 albertel 3570: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3571: my ($role,$tend,$tstart);
3572: if ($context eq 'userroles') {
1.1149 raeburn 3573: next if ($entry =~ /^rolesdef/);
1.867 raeburn 3574: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3575: } else {
3576: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3577: }
1.400 www 3578: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3579: my $status = 'active';
1.939 raeburn 3580: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3581: $status = 'previous';
3582: }
3583: if (($tstart) && ($now<$tstart)) {
3584: $status = 'future';
3585: }
3586: if (ref($types) eq 'ARRAY') {
3587: if (!grep(/^\Q$status\E$/,@{$types})) {
3588: next;
3589: }
3590: } else {
3591: if ($status ne 'active') {
3592: next;
3593: }
3594: }
1.867 raeburn 3595: my ($rolecode,$username,$domain,$section,$area);
3596: if ($context eq 'userroles') {
3597: ($area,$rolecode) = split(/_/,$entry);
3598: (undef,$domain,$username,$section) = split(/\//,$area);
3599: } else {
3600: ($role,$username,$domain,$section) = split(/\:/,$entry);
3601: }
1.832 raeburn 3602: if (ref($roledoms) eq 'ARRAY') {
3603: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3604: next;
3605: }
3606: }
3607: if (ref($roles) eq 'ARRAY') {
3608: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3609: if ($role =~ /^cr\//) {
3610: if (!grep(/^cr$/,@{$roles})) {
3611: next;
3612: }
1.1104 raeburn 3613: } elsif ($role =~ /^gr\//) {
3614: if (!grep(/^gr$/,@{$roles})) {
3615: next;
3616: }
1.922 raeburn 3617: } else {
3618: next;
3619: }
1.832 raeburn 3620: }
1.867 raeburn 3621: }
1.937 raeburn 3622: if ($hidepriv) {
1.999 raeburn 3623: if ($context eq 'userroles') {
3624: if ((&privileged($username,$domain)) &&
3625: (!$nothide{$username.':'.$domain})) {
3626: next;
3627: }
3628: } else {
3629: unless (ref($privileged{$domain}) eq 'HASH') {
3630: my %dompersonnel =
3631: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3632: $privileged{$domain} = {};
3633: if (keys(%dompersonnel)) {
3634: foreach my $server (keys(%dompersonnel)) {
3635: if (ref($dompersonnel{$server}) eq 'HASH') {
3636: foreach my $user (keys(%{$dompersonnel{$server}})) {
3637: my ($trole,$uname,$udom) = split(/:/,$user);
3638: $privileged{$udom}{$uname} = $trole;
3639: }
3640: }
3641: }
3642: }
3643: }
3644: if (exists($privileged{$domain}{$username})) {
3645: if (!$nothide{$username.':'.$domain}) {
3646: next;
3647: }
3648: }
1.937 raeburn 3649: }
3650: }
1.933 raeburn 3651: if ($withsec) {
3652: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3653: $tstart.':'.$tend;
3654: } else {
3655: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3656: }
1.832 raeburn 3657: }
1.373 www 3658: return %returnhash;
1.399 www 3659: }
3660:
3661: # ----------------------------------------------------- Frontpage Announcements
3662: #
3663: #
3664:
3665: sub postannounce {
3666: my ($server,$text)=@_;
1.844 albertel 3667: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3668: unless ($text=~/\w/) { $text=''; }
3669: return &reply('setannounce:'.&escape($text),$server);
3670: }
3671:
3672: sub getannounce {
1.448 albertel 3673:
3674: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3675: my $announcement='';
1.800 albertel 3676: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3677: close($fh);
1.399 www 3678: if ($announcement=~/\w/) {
3679: return
3680: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3681: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3682: } else {
3683: return '';
3684: }
3685: } else {
3686: return '';
3687: }
1.351 www 3688: }
1.353 www 3689:
3690: # ---------------------------------------------------------- Course ID routines
3691: # Deal with domain's nohist_courseid.db files
3692: #
3693:
3694: sub courseidput {
1.921 raeburn 3695: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3696: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3697: my $outcome;
3698: if ($caller eq 'timeonly') {
3699: my $cids = '';
3700: foreach my $item (keys(%$storehash)) {
3701: $cids.=&escape($item).'&';
3702: }
3703: $cids=~s/\&$//;
3704: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3705: $coursehome);
3706: } else {
3707: my $items = '';
3708: foreach my $item (keys(%$storehash)) {
3709: $items.= &escape($item).'='.
3710: &freeze_escape($$storehash{$item}).'&';
3711: }
3712: $items=~s/\&$//;
3713: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3714: $coursehome);
1.918 raeburn 3715: }
3716: if ($outcome eq 'unknown_cmd') {
3717: my $what;
3718: foreach my $cid (keys(%$storehash)) {
3719: $what .= &escape($cid).'=';
1.921 raeburn 3720: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3721: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3722: }
3723: $what =~ s/\:$/&/;
3724: }
3725: $what =~ s/\&$//;
3726: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3727: } else {
3728: return $outcome;
3729: }
1.353 www 3730: }
3731:
3732: sub courseiddump {
1.921 raeburn 3733: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3734: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3735: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3736: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3737: my $as_hash = 1;
3738: my %returnhash;
3739: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3740: my %libserv = &all_library();
3741: foreach my $tryserver (keys(%libserv)) {
3742: if ( ( $hostidflag == 1
3743: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3744: || (!defined($hostidflag)) ) {
3745:
1.918 raeburn 3746: if (($domfilter eq '') ||
3747: (&host_domain($tryserver) eq $domfilter)) {
3748: my $rep =
3749: &reply('courseiddump:'.&host_domain($tryserver).':'.
3750: $sincefilter.':'.&escape($descfilter).':'.
3751: &escape($instcodefilter).':'.&escape($ownerfilter).
3752: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3753: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3754: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3755: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3756: &escape($cc_clone).':'.$cloneonly.':'.
3757: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071 raeburn 3758: &escape($creationcontext).':'.$domcloner,
3759: $tryserver);
1.918 raeburn 3760: my @pairs=split(/\&/,$rep);
3761: foreach my $item (@pairs) {
3762: my ($key,$value)=split(/\=/,$item,2);
3763: $key = &unescape($key);
3764: next if ($key =~ /^error: 2 /);
3765: my $result = &thaw_unescape($value);
3766: if (ref($result) eq 'HASH') {
3767: $returnhash{$key}=$result;
3768: } else {
1.921 raeburn 3769: my @responses = split(/:/,$value);
3770: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3771: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3772: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3773: }
1.1008 raeburn 3774: }
1.353 www 3775: }
3776: }
3777: }
3778: }
3779: return %returnhash;
3780: }
3781:
1.1055 raeburn 3782: sub courselastaccess {
3783: my ($cdom,$cnum,$hostidref) = @_;
3784: my %returnhash;
3785: if ($cdom && $cnum) {
3786: my $chome = &homeserver($cnum,$cdom);
3787: if ($chome ne 'no_host') {
3788: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3789: &extract_lastaccess(\%returnhash,$rep);
3790: }
3791: } else {
3792: if (!$cdom) { $cdom=''; }
3793: my %libserv = &all_library();
3794: foreach my $tryserver (keys(%libserv)) {
3795: if (ref($hostidref) eq 'ARRAY') {
3796: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3797: }
3798: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3799: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3800: &extract_lastaccess(\%returnhash,$rep);
3801: }
3802: }
3803: }
3804: return %returnhash;
3805: }
3806:
3807: sub extract_lastaccess {
3808: my ($returnhash,$rep) = @_;
3809: if (ref($returnhash) eq 'HASH') {
3810: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3811: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3812: $rep eq '') {
3813: my @pairs=split(/\&/,$rep);
3814: foreach my $item (@pairs) {
3815: my ($key,$value)=split(/\=/,$item,2);
3816: $key = &unescape($key);
3817: next if ($key =~ /^error: 2 /);
3818: $returnhash->{$key} = &thaw_unescape($value);
3819: }
3820: }
3821: }
3822: return;
3823: }
3824:
1.658 raeburn 3825: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3826:
3827: sub dcmailput {
1.685 raeburn 3828: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3829: my $status = &Apache::lonnet::critical(
1.740 www 3830: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3831: &escape($message),$server);
1.662 raeburn 3832: return $status;
3833: }
3834:
1.658 raeburn 3835: sub dcmaildump {
3836: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3837: my %returnhash=();
1.846 albertel 3838:
3839: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3840: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3841: &escape($enddate).':';
3842: my @esc_senders=map { &escape($_)} @$senders;
3843: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3844: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3845: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3846: if (($key) && ($value)) {
3847: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3848: }
3849: }
3850: }
3851: return %returnhash;
3852: }
1.662 raeburn 3853: # ---------------------------------------------------------- Domain roles
3854:
3855: sub get_domain_roles {
3856: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3857: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3858: $startdate = '.';
3859: }
1.1018 raeburn 3860: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3861: $enddate = '.';
3862: }
1.922 raeburn 3863: my $rolelist;
3864: if (ref($roles) eq 'ARRAY') {
3865: $rolelist = join(':',@{$roles});
3866: }
1.662 raeburn 3867: my %personnel = ();
1.841 albertel 3868:
3869: my %servers = &get_servers($dom,'library');
3870: foreach my $tryserver (keys(%servers)) {
3871: %{$personnel{$tryserver}}=();
3872: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3873: &escape($startdate).':'.
3874: &escape($enddate).':'.
3875: &escape($rolelist), $tryserver))) {
3876: my ($key,$value) = split(/\=/,$line,2);
3877: if (($key) && ($value)) {
3878: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3879: }
3880: }
1.662 raeburn 3881: }
3882: return %personnel;
3883: }
1.658 raeburn 3884:
1.1057 www 3885: # ----------------------------------------------------------- Interval timing
1.149 www 3886:
1.1153 www 3887: {
3888: # Caches needed for speedup of navmaps
3889: # We don't want to cache this for very long at all (5 seconds at most)
3890: #
3891: # The user for whom we cache
3892: my $cachedkey='';
3893: # The cached times for this user
3894: my %cachedtimes=();
3895: # When this was last done
3896: my $cachedtime=();
3897:
3898: sub load_all_first_access {
1.1154 raeburn 3899: my ($uname,$udom)=@_;
1.1156 www 3900: if (($cachedkey eq $uname.':'.$udom) &&
1.1154 raeburn 3901: (abs($cachedtime-time)<5)) {
3902: return;
3903: }
3904: $cachedtime=time;
3905: $cachedkey=$uname.':'.$udom;
3906: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 3907: }
3908:
1.504 albertel 3909: sub get_first_access {
1.1162 ! raeburn 3910: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 3911: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3912: if ($argsymb) { $symb=$argsymb; }
3913: my ($map,$id,$res)=&decode_symb($symb);
1.1162 ! raeburn 3914: if ($argmap) { $map = $argmap; }
1.926 albertel 3915: if ($type eq 'course') {
3916: $res='course';
3917: } elsif ($type eq 'map') {
1.588 albertel 3918: $res=&symbread($map);
3919: } else {
3920: $res=$symb;
3921: }
1.1153 www 3922: &load_all_first_access($uname,$udom);
3923: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 3924: }
3925:
3926: sub set_first_access {
1.1162 ! raeburn 3927: my ($type,$interval)=@_;
1.790 albertel 3928: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3929: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3930: if ($type eq 'course') {
3931: $res='course';
3932: } elsif ($type eq 'map') {
1.588 albertel 3933: $res=&symbread($map);
3934: } else {
3935: $res=$symb;
3936: }
1.1153 www 3937: $cachedkey='';
1.1162 ! raeburn 3938: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 3939: if (!$firstaccess) {
1.1162 ! raeburn 3940: my $start = time;
! 3941: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
! 3942: $udom,$uname);
! 3943: if ($putres eq 'ok') {
! 3944: &put('timerinterval',{"$courseid\0$res"=>$interval},
! 3945: $udom,$uname);
! 3946: &appenv(
! 3947: {
! 3948: 'course.'.$courseid.'.firstaccess.'.$res => $start,
! 3949: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
! 3950: }
! 3951: );
! 3952: }
! 3953: return $putres;
1.505 albertel 3954: }
3955: return 'already_set';
1.504 albertel 3956: }
1.1153 www 3957: }
1.110 www 3958: # --------------------------------------------- Set Expire Date for Spreadsheet
3959:
3960: sub expirespread {
3961: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3962: my $cid=$env{'request.course.id'};
1.110 www 3963: if ($cid) {
3964: my $now=time;
3965: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3966: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3967: $env{'course.'.$cid.'.num'}.
1.110 www 3968: ':nohist_expirationdates:'.
3969: &escape($key).'='.$now,
1.620 albertel 3970: $env{'course.'.$cid.'.home'})
1.110 www 3971: }
3972: return 'ok';
1.14 www 3973: }
3974:
1.109 www 3975: # ----------------------------------------------------- Devalidate Spreadsheets
3976:
3977: sub devalidate {
1.325 www 3978: my ($symb,$uname,$udom)=@_;
1.620 albertel 3979: my $cid=$env{'request.course.id'};
1.109 www 3980: if ($cid) {
1.391 matthew 3981: # delete the stored spreadsheets for
3982: # - the student level sheet of this user in course's homespace
3983: # - the assessment level sheet for this resource
3984: # for this user in user's homespace
1.553 albertel 3985: # - current conditional state info
1.325 www 3986: my $key=$uname.':'.$udom.':';
1.109 www 3987: my $status=
1.299 matthew 3988: &del('nohist_calculatedsheets',
1.391 matthew 3989: [$key.'studentcalc:'],
1.620 albertel 3990: $env{'course.'.$cid.'.domain'},
3991: $env{'course.'.$cid.'.num'})
1.133 albertel 3992: .' '.
3993: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3994: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3995: unless ($status eq 'ok ok') {
3996: &logthis('Could not devalidate spreadsheet '.
1.325 www 3997: $uname.' at '.$udom.' for '.
1.109 www 3998: $symb.': '.$status);
1.133 albertel 3999: }
1.553 albertel 4000: &delenv('user.state.'.$cid);
1.109 www 4001: }
4002: }
4003:
1.265 albertel 4004: sub get_scalar {
4005: my ($string,$end) = @_;
4006: my $value;
4007: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4008: $value = $1;
4009: } elsif ($$string =~ s/^([^&]*?)&//) {
4010: $value = $1;
4011: }
4012: return &unescape($value);
4013: }
4014:
4015: sub array2str {
4016: my (@array) = @_;
4017: my $result=&arrayref2str(\@array);
4018: $result=~s/^__ARRAY_REF__//;
4019: $result=~s/__END_ARRAY_REF__$//;
4020: return $result;
4021: }
4022:
1.204 albertel 4023: sub arrayref2str {
4024: my ($arrayref) = @_;
1.265 albertel 4025: my $result='__ARRAY_REF__';
1.204 albertel 4026: foreach my $elem (@$arrayref) {
1.265 albertel 4027: if(ref($elem) eq 'ARRAY') {
4028: $result.=&arrayref2str($elem).'&';
4029: } elsif(ref($elem) eq 'HASH') {
4030: $result.=&hashref2str($elem).'&';
4031: } elsif(ref($elem)) {
4032: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4033: } else {
4034: $result.=&escape($elem).'&';
4035: }
4036: }
4037: $result=~s/\&$//;
1.265 albertel 4038: $result .= '__END_ARRAY_REF__';
1.204 albertel 4039: return $result;
4040: }
4041:
1.168 albertel 4042: sub hash2str {
1.204 albertel 4043: my (%hash) = @_;
4044: my $result=&hashref2str(\%hash);
1.265 albertel 4045: $result=~s/^__HASH_REF__//;
4046: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4047: return $result;
4048: }
4049:
4050: sub hashref2str {
4051: my ($hashref)=@_;
1.265 albertel 4052: my $result='__HASH_REF__';
1.800 albertel 4053: foreach my $key (sort(keys(%$hashref))) {
4054: if (ref($key) eq 'ARRAY') {
4055: $result.=&arrayref2str($key).'=';
4056: } elsif (ref($key) eq 'HASH') {
4057: $result.=&hashref2str($key).'=';
4058: } elsif (ref($key)) {
1.265 albertel 4059: $result.='=';
1.800 albertel 4060: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4061: } else {
1.1132 raeburn 4062: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4063: }
4064:
1.800 albertel 4065: if(ref($hashref->{$key}) eq 'ARRAY') {
4066: $result.=&arrayref2str($hashref->{$key}).'&';
4067: } elsif(ref($hashref->{$key}) eq 'HASH') {
4068: $result.=&hashref2str($hashref->{$key}).'&';
4069: } elsif(ref($hashref->{$key})) {
1.265 albertel 4070: $result.='&';
1.800 albertel 4071: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4072: } else {
1.800 albertel 4073: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4074: }
4075: }
1.168 albertel 4076: $result=~s/\&$//;
1.265 albertel 4077: $result .= '__END_HASH_REF__';
1.168 albertel 4078: return $result;
4079: }
4080:
4081: sub str2hash {
1.265 albertel 4082: my ($string)=@_;
4083: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4084: return %$hash;
4085: }
4086:
4087: sub str2hashref {
1.168 albertel 4088: my ($string) = @_;
1.265 albertel 4089:
4090: my %hash;
4091:
4092: if($string !~ /^__HASH_REF__/) {
4093: if (! ($string eq '' || !defined($string))) {
4094: $hash{'error'}='Not hash reference';
4095: }
4096: return (\%hash, $string);
4097: }
4098:
4099: $string =~ s/^__HASH_REF__//;
4100:
4101: while($string !~ /^__END_HASH_REF__/) {
4102: #key
4103: my $key='';
4104: if($string =~ /^__HASH_REF__/) {
4105: ($key, $string)=&str2hashref($string);
4106: if(defined($key->{'error'})) {
4107: $hash{'error'}='Bad data';
4108: return (\%hash, $string);
4109: }
4110: } elsif($string =~ /^__ARRAY_REF__/) {
4111: ($key, $string)=&str2arrayref($string);
4112: if($key->[0] eq 'Array reference error') {
4113: $hash{'error'}='Bad data';
4114: return (\%hash, $string);
4115: }
4116: } else {
4117: $string =~ s/^(.*?)=//;
1.267 albertel 4118: $key=&unescape($1);
1.265 albertel 4119: }
4120: $string =~ s/^=//;
4121:
4122: #value
4123: my $value='';
4124: if($string =~ /^__HASH_REF__/) {
4125: ($value, $string)=&str2hashref($string);
4126: if(defined($value->{'error'})) {
4127: $hash{'error'}='Bad data';
4128: return (\%hash, $string);
4129: }
4130: } elsif($string =~ /^__ARRAY_REF__/) {
4131: ($value, $string)=&str2arrayref($string);
4132: if($value->[0] eq 'Array reference error') {
4133: $hash{'error'}='Bad data';
4134: return (\%hash, $string);
4135: }
4136: } else {
4137: $value=&get_scalar(\$string,'__END_HASH_REF__');
4138: }
4139: $string =~ s/^&//;
4140:
4141: $hash{$key}=$value;
1.204 albertel 4142: }
1.265 albertel 4143:
4144: $string =~ s/^__END_HASH_REF__//;
4145:
4146: return (\%hash, $string);
1.204 albertel 4147: }
4148:
4149: sub str2array {
1.265 albertel 4150: my ($string)=@_;
4151: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4152: return @$array;
4153: }
4154:
4155: sub str2arrayref {
1.204 albertel 4156: my ($string) = @_;
1.265 albertel 4157: my @array;
4158:
4159: if($string !~ /^__ARRAY_REF__/) {
4160: if (! ($string eq '' || !defined($string))) {
4161: $array[0]='Array reference error';
4162: }
4163: return (\@array, $string);
4164: }
4165:
4166: $string =~ s/^__ARRAY_REF__//;
4167:
4168: while($string !~ /^__END_ARRAY_REF__/) {
4169: my $value='';
4170: if($string =~ /^__HASH_REF__/) {
4171: ($value, $string)=&str2hashref($string);
4172: if(defined($value->{'error'})) {
4173: $array[0] ='Array reference error';
4174: return (\@array, $string);
4175: }
4176: } elsif($string =~ /^__ARRAY_REF__/) {
4177: ($value, $string)=&str2arrayref($string);
4178: if($value->[0] eq 'Array reference error') {
4179: $array[0] ='Array reference error';
4180: return (\@array, $string);
4181: }
4182: } else {
4183: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4184: }
4185: $string =~ s/^&//;
4186:
4187: push(@array, $value);
1.191 harris41 4188: }
1.265 albertel 4189:
4190: $string =~ s/^__END_ARRAY_REF__//;
4191:
4192: return (\@array, $string);
1.168 albertel 4193: }
4194:
1.167 albertel 4195: # -------------------------------------------------------------------Temp Store
4196:
1.168 albertel 4197: sub tmpreset {
4198: my ($symb,$namespace,$domain,$stuname) = @_;
4199: if (!$symb) {
4200: $symb=&symbread();
1.620 albertel 4201: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4202: }
4203: $symb=escape($symb);
4204:
1.620 albertel 4205: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4206: $namespace=~s/\//\_/g;
4207: $namespace=~s/\W//g;
4208:
1.620 albertel 4209: if (!$domain) { $domain=$env{'user.domain'}; }
4210: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4211: if ($domain eq 'public' && $stuname eq 'public') {
4212: $stuname=$ENV{'REMOTE_ADDR'};
4213: }
1.1117 foxr 4214: my $path=LONCAPA::tempdir();
1.168 albertel 4215: my %hash;
4216: if (tie(%hash,'GDBM_File',
4217: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4218: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4219: foreach my $key (keys(%hash)) {
1.180 albertel 4220: if ($key=~ /:$symb/) {
1.168 albertel 4221: delete($hash{$key});
4222: }
4223: }
4224: }
4225: }
4226:
1.167 albertel 4227: sub tmpstore {
1.168 albertel 4228: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4229:
4230: if (!$symb) {
4231: $symb=&symbread();
1.620 albertel 4232: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4233: }
4234: $symb=escape($symb);
4235:
4236: if (!$namespace) {
4237: # I don't think we would ever want to store this for a course.
4238: # it seems this will only be used if we don't have a course.
1.620 albertel 4239: #$namespace=$env{'request.course.id'};
1.168 albertel 4240: #if (!$namespace) {
1.620 albertel 4241: $namespace=$env{'request.state'};
1.168 albertel 4242: #}
4243: }
4244: $namespace=~s/\//\_/g;
4245: $namespace=~s/\W//g;
1.620 albertel 4246: if (!$domain) { $domain=$env{'user.domain'}; }
4247: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4248: if ($domain eq 'public' && $stuname eq 'public') {
4249: $stuname=$ENV{'REMOTE_ADDR'};
4250: }
1.168 albertel 4251: my $now=time;
4252: my %hash;
1.1117 foxr 4253: my $path=LONCAPA::tempdir();
1.168 albertel 4254: if (tie(%hash,'GDBM_File',
4255: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4256: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4257: $hash{"version:$symb"}++;
4258: my $version=$hash{"version:$symb"};
4259: my $allkeys='';
4260: foreach my $key (keys(%$storehash)) {
4261: $allkeys.=$key.':';
1.591 albertel 4262: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4263: }
4264: $hash{"$version:$symb:timestamp"}=$now;
4265: $allkeys.='timestamp';
4266: $hash{"$version:keys:$symb"}=$allkeys;
4267: if (untie(%hash)) {
4268: return 'ok';
4269: } else {
4270: return "error:$!";
4271: }
4272: } else {
4273: return "error:$!";
4274: }
4275: }
1.167 albertel 4276:
1.168 albertel 4277: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4278:
1.168 albertel 4279: sub tmprestore {
4280: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4281:
1.168 albertel 4282: if (!$symb) {
4283: $symb=&symbread();
1.620 albertel 4284: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4285: }
4286: $symb=escape($symb);
4287:
1.620 albertel 4288: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4289:
1.620 albertel 4290: if (!$domain) { $domain=$env{'user.domain'}; }
4291: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4292: if ($domain eq 'public' && $stuname eq 'public') {
4293: $stuname=$ENV{'REMOTE_ADDR'};
4294: }
1.168 albertel 4295: my %returnhash;
4296: $namespace=~s/\//\_/g;
4297: $namespace=~s/\W//g;
4298: my %hash;
1.1117 foxr 4299: my $path=LONCAPA::tempdir();
1.168 albertel 4300: if (tie(%hash,'GDBM_File',
4301: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4302: &GDBM_READER(),0640)) {
1.168 albertel 4303: my $version=$hash{"version:$symb"};
4304: $returnhash{'version'}=$version;
4305: my $scope;
4306: for ($scope=1;$scope<=$version;$scope++) {
4307: my $vkeys=$hash{"$scope:keys:$symb"};
4308: my @keys=split(/:/,$vkeys);
4309: my $key;
4310: $returnhash{"$scope:keys"}=$vkeys;
4311: foreach $key (@keys) {
1.591 albertel 4312: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4313: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4314: }
4315: }
1.168 albertel 4316: if (!(untie(%hash))) {
4317: return "error:$!";
4318: }
4319: } else {
4320: return "error:$!";
4321: }
4322: return %returnhash;
1.167 albertel 4323: }
4324:
1.9 www 4325: # ----------------------------------------------------------------------- Store
4326:
4327: sub store {
1.124 www 4328: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4329: my $home='';
4330:
1.168 albertel 4331: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4332:
1.213 www 4333: $symb=&symbclean($symb);
1.122 albertel 4334: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4335:
1.620 albertel 4336: if (!$domain) { $domain=$env{'user.domain'}; }
4337: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4338:
4339: &devalidate($symb,$stuname,$domain);
1.109 www 4340:
4341: $symb=escape($symb);
1.187 www 4342: if (!$namespace) {
1.620 albertel 4343: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4344: return '';
4345: }
4346: }
1.620 albertel 4347: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4348:
4349: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4350: $$storehash{'host'}=$perlvar{'lonHostID'};
4351:
1.12 www 4352: my $namevalue='';
1.800 albertel 4353: foreach my $key (keys(%$storehash)) {
4354: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4355: }
1.12 www 4356: $namevalue=~s/\&$//;
1.187 www 4357: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4358: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4359: }
4360:
1.47 www 4361: # -------------------------------------------------------------- Critical Store
4362:
4363: sub cstore {
1.124 www 4364: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4365: my $home='';
4366:
1.168 albertel 4367: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4368:
1.213 www 4369: $symb=&symbclean($symb);
1.122 albertel 4370: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4371:
1.620 albertel 4372: if (!$domain) { $domain=$env{'user.domain'}; }
4373: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4374:
4375: &devalidate($symb,$stuname,$domain);
1.109 www 4376:
4377: $symb=escape($symb);
1.187 www 4378: if (!$namespace) {
1.620 albertel 4379: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4380: return '';
4381: }
4382: }
1.620 albertel 4383: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4384:
4385: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4386: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4387:
1.47 www 4388: my $namevalue='';
1.800 albertel 4389: foreach my $key (keys(%$storehash)) {
4390: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4391: }
1.47 www 4392: $namevalue=~s/\&$//;
1.187 www 4393: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4394: return critical
4395: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4396: }
4397:
1.9 www 4398: # --------------------------------------------------------------------- Restore
4399:
4400: sub restore {
1.124 www 4401: my ($symb,$namespace,$domain,$stuname) = @_;
4402: my $home='';
4403:
1.168 albertel 4404: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4405:
1.122 albertel 4406: if (!$symb) {
4407: unless ($symb=escape(&symbread())) { return ''; }
4408: } else {
1.213 www 4409: $symb=&escape(&symbclean($symb));
1.122 albertel 4410: }
1.188 www 4411: if (!$namespace) {
1.620 albertel 4412: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4413: return '';
4414: }
4415: }
1.620 albertel 4416: if (!$domain) { $domain=$env{'user.domain'}; }
4417: if (!$stuname) { $stuname=$env{'user.name'}; }
4418: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4419: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4420:
1.12 www 4421: my %returnhash=();
1.800 albertel 4422: foreach my $line (split(/\&/,$answer)) {
4423: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4424: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4425: }
1.75 www 4426: my $version;
4427: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4428: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4429: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4430: }
1.75 www 4431: }
1.13 www 4432: return %returnhash;
1.34 www 4433: }
4434:
4435: # ---------------------------------------------------------- Course Description
1.1118 foxr 4436: #
4437: #
1.34 www 4438:
4439: sub coursedescription {
1.731 albertel 4440: my ($courseid,$args)=@_;
1.34 www 4441: $courseid=~s/^\///;
1.49 www 4442: $courseid=~s/\_/\//g;
1.34 www 4443: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4444: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4445: my $normalid=$cdomain.'_'.$cnum;
4446: # need to always cache even if we get errors otherwise we keep
4447: # trying and trying and trying to get the course description.
4448: my %envhash=();
4449: my %returnhash=();
1.731 albertel 4450:
4451: my $expiretime=600;
4452: if ($env{'request.course.id'} eq $normalid) {
4453: $expiretime=120;
4454: }
4455:
4456: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4457: if (!$args->{'freshen_cache'}
4458: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4459: foreach my $key (keys(%env)) {
4460: next if ($key !~ /^\Q$prefix\E(.*)/);
4461: my ($setting) = $1;
4462: $returnhash{$setting} = $env{$key};
4463: }
4464: return %returnhash;
4465: }
4466:
1.1118 foxr 4467: # get the data again
4468:
1.731 albertel 4469: if (!$args->{'one_time'}) {
4470: $envhash{'course.'.$normalid.'.last_cache'}=time;
4471: }
1.811 albertel 4472:
1.34 www 4473: if ($chome ne 'no_host') {
1.302 albertel 4474: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4475: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4476: my $username = $env{'user.name'}; # Defult username
4477: if(defined $args->{'user'}) {
4478: $username = $args->{'user'};
4479: }
1.129 albertel 4480: $returnhash{'home'}= $chome;
4481: $returnhash{'domain'} = $cdomain;
4482: $returnhash{'num'} = $cnum;
1.741 raeburn 4483: if (!defined($returnhash{'type'})) {
4484: $returnhash{'type'} = 'Course';
4485: }
1.130 albertel 4486: while (my ($name,$value) = each %returnhash) {
1.53 www 4487: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4488: }
1.270 www 4489: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4490: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4491: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4492: $envhash{'course.'.$normalid.'.home'}=$chome;
4493: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4494: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4495: }
4496: }
1.731 albertel 4497: if (!$args->{'one_time'}) {
1.949 raeburn 4498: &appenv(\%envhash);
1.731 albertel 4499: }
1.302 albertel 4500: return %returnhash;
1.461 www 4501: }
4502:
1.1080 raeburn 4503: sub update_released_required {
4504: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4505: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4506: $cid = $env{'request.course.id'};
4507: $cdom = $env{'course.'.$cid.'.domain'};
4508: $cnum = $env{'course.'.$cid.'.num'};
4509: $chome = $env{'course.'.$cid.'.home'};
4510: }
4511: if ($needsrelease) {
4512: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4513: my $needsupdate;
4514: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4515: $needsupdate = 1;
4516: } else {
4517: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4518: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4519: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4520: $needsupdate = 1;
4521: }
4522: }
4523: if ($needsupdate) {
4524: my %needshash = (
4525: 'internal.releaserequired' => $needsrelease,
4526: );
4527: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4528: if ($putresult eq 'ok') {
4529: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4530: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4531: if (ref($crsinfo{$cid}) eq 'HASH') {
4532: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4533: &courseidput($cdom,\%crsinfo,$chome,'notime');
4534: }
4535: }
4536: }
4537: }
4538: return;
4539: }
4540:
1.461 www 4541: # -------------------------------------------------See if a user is privileged
4542:
4543: sub privileged {
4544: my ($username,$domain)=@_;
4545: my $rolesdump=&reply("dump:$domain:$username:roles",
4546: &homeserver($username,$domain));
1.1033 raeburn 4547: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4548: ($rolesdump =~ /^error:/)) {
4549: return 0;
4550: }
1.461 www 4551: my $now=time;
4552: if ($rolesdump ne '') {
1.800 albertel 4553: foreach my $entry (split(/&/,$rolesdump)) {
4554: if ($entry!~/^rolesdef_/) {
4555: my ($area,$role)=split(/=/,$entry);
1.461 www 4556: $area=~s/\_\w\w$//;
4557: my ($trole,$tend,$tstart)=split(/_/,$role);
4558: if (($trole eq 'dc') || ($trole eq 'su')) {
4559: my $active=1;
4560: if ($tend) {
4561: if ($tend<$now) { $active=0; }
4562: }
4563: if ($tstart) {
4564: if ($tstart>$now) { $active=0; }
4565: }
4566: if ($active) { return 1; }
4567: }
4568: }
4569: }
4570: }
4571: return 0;
1.9 www 4572: }
1.1 albertel 4573:
1.103 harris41 4574: # -------------------------------------------------------- Get user privileges
1.11 www 4575:
4576: sub rolesinit {
4577: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4578: my $now=time;
4579: my %userroles = ('user.login.time' => $now);
1.1086 raeburn 4580: my $extra = &freeze_escape({'skipcheck' => 1});
1.1078 raeburn 4581: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4582: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1078 raeburn 4583: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4584: return \%userroles;
4585: }
1.1162 ! raeburn 4586: my %firstaccess = &dump('firstaccesstimes',$domain,$username);
! 4587: my %timerinterval = &dump('timerinterval',$domain,$username);
! 4588: my (%coursetimerstarts,%firstaccchk,%firstaccenv,
! 4589: %coursetimerintervals,%timerintchk,%timerintenv);
! 4590: foreach my $key (keys(%firstaccess)) {
! 4591: my ($cid,$rest) = split(/\0/,$key);
! 4592: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
! 4593: }
! 4594: foreach my $key (keys(%timerinterval)) {
! 4595: my ($cid,$rest) = split(/\0/,$key);
! 4596: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
! 4597: }
1.11 www 4598: my %allroles=();
1.1162 ! raeburn 4599: my %allgroups=();
1.11 www 4600:
4601: if ($rolesdump ne '') {
1.800 albertel 4602: foreach my $entry (split(/&/,$rolesdump)) {
4603: if ($entry!~/^rolesdef_/) {
4604: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4605: $area=~s/\_\w\w$//;
1.678 raeburn 4606: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4607: if ($role=~/^cr/) {
1.807 albertel 4608: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4609: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4610: ($tend,$tstart)=split('_',$trest);
4611: } else {
4612: $trole=$role;
4613: }
1.678 raeburn 4614: } elsif ($role =~ m|^gr/|) {
4615: ($trole,$tend,$tstart) = split(/_/,$role);
1.1104 raeburn 4616: next if ($tstart eq '-1');
1.678 raeburn 4617: ($trole,$group_privs) = split(/\//,$trole);
4618: $group_privs = &unescape($group_privs);
1.587 albertel 4619: } else {
4620: ($trole,$tend,$tstart)=split(/_/,$role);
4621: }
1.743 albertel 4622: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4623: $username);
4624: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4625: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4626: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4627: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4628: my $spec=$trole.'.'.$area;
4629: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4630: if ($trole =~ /^cr\//) {
1.567 raeburn 4631: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4632: } elsif ($trole eq 'gr') {
4633: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4634: } else {
1.567 raeburn 4635: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4636: }
1.1162 ! raeburn 4637: if ($trole ne 'gr') {
! 4638: my $cid = $tdomain.'_'.$trest;
! 4639: unless ($firstaccchk{$cid}) {
! 4640: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
! 4641: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
! 4642: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
! 4643: $coursetimerstarts{$cid}{$item};
! 4644: }
! 4645: }
! 4646: $firstaccchk{$cid} = 1;
! 4647: }
! 4648: unless ($timerintchk{$cid}) {
! 4649: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
! 4650: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
! 4651: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
! 4652: $coursetimerintervals{$cid}{$item};
! 4653: }
! 4654: }
! 4655: $timerintchk{$cid} = 1;
! 4656: }
! 4657: }
1.12 www 4658: }
1.662 raeburn 4659: }
1.191 harris41 4660: }
1.743 albertel 4661: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4662: $userroles{'user.adv'} = $adv;
4663: $userroles{'user.author'} = $author;
1.620 albertel 4664: $env{'user.adv'}=$adv;
1.11 www 4665: }
1.1162 ! raeburn 4666: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 4667: }
4668:
1.567 raeburn 4669: sub set_arearole {
4670: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4671: # log the associated role with the area
4672: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4673: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4674: }
4675:
4676: sub custom_roleprivs {
4677: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4678: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4679: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4680: if (&hostname($homsvr) ne '') {
1.567 raeburn 4681: my ($rdummy,$roledef)=
4682: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4683: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4684: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4685: if (defined($syspriv)) {
1.1043 raeburn 4686: if ($trest =~ /^$match_community$/) {
4687: $syspriv =~ s/bre\&S//;
4688: }
1.567 raeburn 4689: $$allroles{'cm./'}.=':'.$syspriv;
4690: $$allroles{$spec.'./'}.=':'.$syspriv;
4691: }
4692: if ($tdomain ne '') {
4693: if (defined($dompriv)) {
4694: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4695: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4696: }
4697: if (($trest ne '') && (defined($coursepriv))) {
4698: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4699: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4700: }
4701: }
4702: }
4703: }
4704: }
4705:
1.678 raeburn 4706: sub group_roleprivs {
4707: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4708: my $access = 1;
4709: my $now = time;
4710: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4711: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4712: if ($access) {
1.811 albertel 4713: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4714: $$allgroups{$course}{$group} .=':'.$group_privs;
4715: }
4716: }
1.567 raeburn 4717:
4718: sub standard_roleprivs {
4719: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4720: if (defined($pr{$trole.':s'})) {
4721: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4722: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4723: }
4724: if ($tdomain ne '') {
4725: if (defined($pr{$trole.':d'})) {
4726: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4727: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4728: }
4729: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4730: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4731: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4732: }
4733: }
4734: }
4735:
4736: sub set_userprivs {
1.1064 raeburn 4737: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4738: my $author=0;
4739: my $adv=0;
1.678 raeburn 4740: my %grouproles = ();
4741: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4742: my @groupkeys;
1.1000 raeburn 4743: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4744: push(@groupkeys,$role);
4745: }
4746: if (ref($groups_roles) eq 'HASH') {
4747: foreach my $key (keys(%{$groups_roles})) {
4748: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4749: push(@groupkeys,$key);
4750: }
4751: }
4752: }
4753: if (@groupkeys > 0) {
4754: foreach my $role (@groupkeys) {
4755: my ($trole,$area,$sec,$extendedarea);
4756: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4757: $trole = $1;
4758: $area = $2;
4759: $sec = $3;
4760: $extendedarea = $area.$sec;
4761: if (exists($$allgroups{$area})) {
4762: foreach my $group (keys(%{$$allgroups{$area}})) {
4763: my $spec = $trole.'.'.$extendedarea;
4764: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4765: $$allgroups{$area}{$group};
1.1064 raeburn 4766: }
1.678 raeburn 4767: }
4768: }
4769: }
4770: }
4771: }
1.800 albertel 4772: foreach my $group (keys(%grouproles)) {
4773: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4774: }
1.800 albertel 4775: foreach my $role (keys(%{$allroles})) {
4776: my %thesepriv;
1.941 raeburn 4777: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4778: foreach my $item (split(/:/,$$allroles{$role})) {
4779: if ($item ne '') {
4780: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4781: if ($restrictions eq '') {
4782: $thesepriv{$privilege}='F';
4783: } elsif ($thesepriv{$privilege} ne 'F') {
4784: $thesepriv{$privilege}.=$restrictions;
4785: }
4786: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4787: }
4788: }
4789: my $thesestr='';
1.1104 raeburn 4790: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 4791: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4792: }
4793: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4794: }
4795: return ($author,$adv);
4796: }
4797:
1.994 raeburn 4798: sub role_status {
1.1104 raeburn 4799: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4800: my @pwhere = ();
4801: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4802: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4803: unless (!defined($$role) || $$role eq '') {
4804: $$where=join('.',@pwhere);
4805: $$trolecode=$$role.'.'.$$where;
4806: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4807: $$tstatus='is';
1.1104 raeburn 4808: if ($$tstart && $$tstart>$update) {
1.994 raeburn 4809: $$tstatus='future';
1.1034 raeburn 4810: if ($$tstart<$now) {
4811: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4812: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4813: my (%allroles,%allgroups,$group_privs,
4814: %groups_roles,@rolecodes);
1.1002 raeburn 4815: my %userroles = (
4816: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4817: );
1.1064 raeburn 4818: @rolecodes = ('cm');
1.1002 raeburn 4819: my $spec=$$role.'.'.$$where;
4820: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4821: if ($$role =~ /^cr\//) {
4822: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4823: push(@rolecodes,'cr');
1.1002 raeburn 4824: } elsif ($$role eq 'gr') {
1.1064 raeburn 4825: push(@rolecodes,$$role);
1.1002 raeburn 4826: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4827: $env{'user.name'});
1.1064 raeburn 4828: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4829: (undef,my $group_privs) = split(/\//,$trole);
4830: $group_privs = &unescape($group_privs);
4831: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4832: 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 4833: &get_groups_roles($tdomain,$trest,
4834: \%course_roles,\@rolecodes,
4835: \%groups_roles);
1.1002 raeburn 4836: } else {
1.1064 raeburn 4837: push(@rolecodes,$$role);
1.1002 raeburn 4838: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4839: }
1.1064 raeburn 4840: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4841: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4842: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4843: }
4844: }
1.1034 raeburn 4845: $$tstatus = 'is';
1.1002 raeburn 4846: }
1.994 raeburn 4847: }
4848: if ($$tend) {
1.1104 raeburn 4849: if ($$tend<$update) {
1.994 raeburn 4850: $$tstatus='expired';
4851: } elsif ($$tend<$now) {
4852: $$tstatus='will_not';
4853: }
4854: }
4855: }
4856: }
4857: }
4858:
1.1104 raeburn 4859: sub get_groups_roles {
4860: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4861: return unless((ref($cdom_courseroles) eq 'HASH') &&
4862: (ref($rolecodes) eq 'ARRAY') &&
4863: (ref($groups_roles) eq 'HASH'));
4864: if (keys(%{$cdom_courseroles}) > 0) {
4865: my ($cnum) = ($rest =~ /^($match_courseid)/);
4866: if ($cdom ne '' && $cnum ne '') {
4867: foreach my $key (keys(%{$cdom_courseroles})) {
4868: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4869: my $crsrole = $1;
4870: my $crssec = $2;
4871: if ($crsrole =~ /^cr/) {
4872: unless (grep(/^cr$/,@{$rolecodes})) {
4873: push(@{$rolecodes},'cr');
4874: }
4875: } else {
4876: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4877: push(@{$rolecodes},$crsrole);
4878: }
4879: }
4880: my $rolekey = "$crsrole./$cdom/$cnum";
4881: if ($crssec ne '') {
4882: $rolekey .= "/$crssec";
4883: }
4884: $rolekey .= './';
4885: $groups_roles->{$rolekey} = $rolecodes;
4886: }
4887: }
4888: }
4889: }
4890: return;
4891: }
4892:
4893: sub delete_env_groupprivs {
4894: my ($where,$courseroles,$possroles) = @_;
4895: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4896: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4897: unless (ref($courseroles->{$udom}) eq 'HASH') {
4898: %{$courseroles->{$udom}} =
4899: &get_my_roles('','','userroles',['active'],
4900: $possroles,[$udom],1);
4901: }
4902: if (ref($courseroles->{$udom}) eq 'HASH') {
4903: foreach my $item (keys(%{$courseroles->{$udom}})) {
4904: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4905: my $area = '/'.$cdom.'/'.$cnum;
4906: my $privkey = "user.priv.$crsrole.$area";
4907: if ($crssec ne '') {
4908: $privkey .= '/'.$crssec;
4909: }
4910: $privkey .= ".$area/$group";
4911: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4912: }
4913: }
4914: return;
4915: }
4916:
1.994 raeburn 4917: sub check_adhoc_privs {
1.1104 raeburn 4918: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4919: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4920: if ($env{$cckey}) {
4921: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 4922: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4923: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 4924: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4925: }
4926: } else {
1.1088 raeburn 4927: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4928: }
4929: }
4930:
4931: sub set_adhoc_privileges {
4932: # role can be cc or ca
1.1088 raeburn 4933: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 4934: my $area = '/'.$dcdom.'/'.$pickedcourse;
4935: my $spec = $role.'.'.$area;
4936: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4937: $env{'user.name'});
4938: my %ccrole = ();
4939: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4940: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4941: &appenv(\%userroles,[$role,'cm']);
4942: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 4943: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4944: &appenv( {'request.role' => $spec,
4945: 'request.role.domain' => $dcdom,
4946: 'request.course.sec' => ''
4947: }
4948: );
4949: my $tadv=0;
4950: if (&allowed('adv') eq 'F') { $tadv=1; }
4951: &appenv({'request.role.adv' => $tadv});
4952: }
1.994 raeburn 4953: }
4954:
1.12 www 4955: # --------------------------------------------------------------- get interface
4956:
4957: sub get {
1.131 albertel 4958: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4959: my $items='';
1.800 albertel 4960: foreach my $item (@$storearr) {
4961: $items.=&escape($item).'&';
1.191 harris41 4962: }
1.12 www 4963: $items=~s/\&$//;
1.620 albertel 4964: if (!$udomain) { $udomain=$env{'user.domain'}; }
4965: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4966: my $uhome=&homeserver($uname,$udomain);
4967:
1.133 albertel 4968: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4969: my @pairs=split(/\&/,$rep);
1.273 albertel 4970: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4971: return @pairs;
4972: }
1.15 www 4973: my %returnhash=();
1.42 www 4974: my $i=0;
1.800 albertel 4975: foreach my $item (@$storearr) {
4976: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4977: $i++;
1.191 harris41 4978: }
1.15 www 4979: return %returnhash;
1.27 www 4980: }
4981:
4982: # --------------------------------------------------------------- del interface
4983:
4984: sub del {
1.133 albertel 4985: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4986: my $items='';
1.800 albertel 4987: foreach my $item (@$storearr) {
4988: $items.=&escape($item).'&';
1.191 harris41 4989: }
1.984 neumanie 4990:
1.27 www 4991: $items=~s/\&$//;
1.620 albertel 4992: if (!$udomain) { $udomain=$env{'user.domain'}; }
4993: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4994: my $uhome=&homeserver($uname,$udomain);
4995: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4996: }
4997:
4998: # -------------------------------------------------------------- dump interface
4999:
5000: sub dump {
1.1086 raeburn 5001: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755 albertel 5002: if (!$udomain) { $udomain=$env{'user.domain'}; }
5003: if (!$uname) { $uname=$env{'user.name'}; }
5004: my $uhome=&homeserver($uname,$udomain);
5005: if ($regexp) {
5006: $regexp=&escape($regexp);
5007: } else {
5008: $regexp='.';
5009: }
1.1086 raeburn 5010: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755 albertel 5011: my @pairs=split(/\&/,$rep);
5012: my %returnhash=();
1.1098 foxr 5013: if (!($rep =~ /^error/ )) {
5014: foreach my $item (@pairs) {
5015: my ($key,$value)=split(/=/,$item,2);
5016: $key = &unescape($key);
5017: next if ($key =~ /^error: 2 /);
5018: $returnhash{$key}=&thaw_unescape($value);
5019: }
1.755 albertel 5020: }
5021: return %returnhash;
1.407 www 5022: }
5023:
1.1098 foxr 5024:
1.717 albertel 5025: # --------------------------------------------------------- dumpstore interface
5026:
5027: sub dumpstore {
5028: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 5029: if (!$udomain) { $udomain=$env{'user.domain'}; }
5030: if (!$uname) { $uname=$env{'user.name'}; }
5031: my $uhome=&homeserver($uname,$udomain);
5032: if ($regexp) {
5033: $regexp=&escape($regexp);
5034: } else {
5035: $regexp='.';
5036: }
5037: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
5038: my @pairs=split(/\&/,$rep);
5039: my %returnhash=();
5040: foreach my $item (@pairs) {
5041: my ($key,$value)=split(/=/,$item,2);
5042: next if ($key =~ /^error: 2 /);
5043: $returnhash{$key}=&thaw_unescape($value);
5044: }
5045: return %returnhash;
1.717 albertel 5046: }
5047:
1.407 www 5048: # -------------------------------------------------------------- keys interface
5049:
5050: sub getkeys {
5051: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5052: if (!$udomain) { $udomain=$env{'user.domain'}; }
5053: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5054: my $uhome=&homeserver($uname,$udomain);
5055: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5056: my @keyarray=();
1.800 albertel 5057: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5058: next if ($key =~ /^error: 2 /);
1.800 albertel 5059: push(@keyarray,&unescape($key));
1.407 www 5060: }
5061: return @keyarray;
1.318 matthew 5062: }
5063:
1.319 matthew 5064: # --------------------------------------------------------------- currentdump
5065: sub currentdump {
1.328 matthew 5066: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5067: $courseid = $env{'request.course.id'} if (! defined($courseid));
5068: $sdom = $env{'user.domain'} if (! defined($sdom));
5069: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5070: my $uhome = &homeserver($sname,$sdom);
5071: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 5072: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5073: #
1.318 matthew 5074: my %returnhash=();
1.319 matthew 5075: #
5076: if ($rep eq "unknown_cmd") {
5077: # an old lond will not know currentdump
5078: # Do a dump and make it look like a currentdump
1.822 albertel 5079: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5080: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5081: my %hash = @tmp;
5082: @tmp=();
1.424 matthew 5083: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5084: } else {
5085: my @pairs=split(/\&/,$rep);
1.800 albertel 5086: foreach my $pair (@pairs) {
5087: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5088: my ($symb,$param) = split(/:/,$key);
5089: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5090: &thaw_unescape($value);
1.319 matthew 5091: }
1.191 harris41 5092: }
1.12 www 5093: return %returnhash;
1.424 matthew 5094: }
5095:
5096: sub convert_dump_to_currentdump{
5097: my %hash = %{shift()};
5098: my %returnhash;
5099: # Code ripped from lond, essentially. The only difference
5100: # here is the unescaping done by lonnet::dump(). Conceivably
5101: # we might run in to problems with parameter names =~ /^v\./
5102: while (my ($key,$value) = each(%hash)) {
5103: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5104: $symb = &unescape($symb);
5105: $param = &unescape($param);
1.424 matthew 5106: next if ($v eq 'version' || $symb eq 'keys');
5107: next if (exists($returnhash{$symb}) &&
5108: exists($returnhash{$symb}->{$param}) &&
5109: $returnhash{$symb}->{'v.'.$param} > $v);
5110: $returnhash{$symb}->{$param}=$value;
5111: $returnhash{$symb}->{'v.'.$param}=$v;
5112: }
5113: #
5114: # Remove all of the keys in the hashes which keep track of
5115: # the version of the parameter.
5116: while (my ($symb,$param_hash) = each(%returnhash)) {
5117: # use a foreach because we are going to delete from the hash.
5118: foreach my $key (keys(%$param_hash)) {
5119: delete($param_hash->{$key}) if ($key =~ /^v\./);
5120: }
5121: }
5122: return \%returnhash;
1.12 www 5123: }
5124:
1.627 albertel 5125: # ------------------------------------------------------ critical inc interface
5126:
5127: sub cinc {
5128: return &inc(@_,'critical');
5129: }
5130:
1.449 matthew 5131: # --------------------------------------------------------------- inc interface
5132:
5133: sub inc {
1.627 albertel 5134: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5135: if (!$udomain) { $udomain=$env{'user.domain'}; }
5136: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5137: my $uhome=&homeserver($uname,$udomain);
5138: my $items='';
5139: if (! ref($store)) {
5140: # got a single value, so use that instead
5141: $items = &escape($store).'=&';
5142: } elsif (ref($store) eq 'SCALAR') {
5143: $items = &escape($$store).'=&';
5144: } elsif (ref($store) eq 'ARRAY') {
5145: $items = join('=&',map {&escape($_);} @{$store});
5146: } elsif (ref($store) eq 'HASH') {
5147: while (my($key,$value) = each(%{$store})) {
5148: $items.= &escape($key).'='.&escape($value).'&';
5149: }
5150: }
5151: $items=~s/\&$//;
1.627 albertel 5152: if ($critical) {
5153: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5154: } else {
5155: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5156: }
1.449 matthew 5157: }
5158:
1.12 www 5159: # --------------------------------------------------------------- put interface
5160:
5161: sub put {
1.134 albertel 5162: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5163: if (!$udomain) { $udomain=$env{'user.domain'}; }
5164: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5165: my $uhome=&homeserver($uname,$udomain);
1.12 www 5166: my $items='';
1.800 albertel 5167: foreach my $item (keys(%$storehash)) {
5168: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5169: }
1.12 www 5170: $items=~s/\&$//;
1.134 albertel 5171: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5172: }
5173:
1.631 albertel 5174: # ------------------------------------------------------------ newput interface
5175:
5176: sub newput {
5177: my ($namespace,$storehash,$udomain,$uname)=@_;
5178: if (!$udomain) { $udomain=$env{'user.domain'}; }
5179: if (!$uname) { $uname=$env{'user.name'}; }
5180: my $uhome=&homeserver($uname,$udomain);
5181: my $items='';
5182: foreach my $key (keys(%$storehash)) {
5183: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5184: }
5185: $items=~s/\&$//;
5186: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5187: }
5188:
5189: # --------------------------------------------------------- putstore interface
5190:
1.524 raeburn 5191: sub putstore {
1.715 albertel 5192: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5193: if (!$udomain) { $udomain=$env{'user.domain'}; }
5194: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5195: my $uhome=&homeserver($uname,$udomain);
5196: my $items='';
1.715 albertel 5197: foreach my $key (keys(%$storehash)) {
5198: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5199: }
1.715 albertel 5200: $items=~s/\&$//;
1.716 albertel 5201: my $esc_symb=&escape($symb);
5202: my $esc_v=&escape($version);
1.715 albertel 5203: my $reply =
1.716 albertel 5204: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5205: $uhome);
5206: if ($reply eq 'unknown_cmd') {
1.716 albertel 5207: # gfall back to way things use to be done
1.715 albertel 5208: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5209: $uname);
1.524 raeburn 5210: }
1.715 albertel 5211: return $reply;
5212: }
5213:
5214: sub old_putstore {
1.716 albertel 5215: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5216: if (!$udomain) { $udomain=$env{'user.domain'}; }
5217: if (!$uname) { $uname=$env{'user.name'}; }
5218: my $uhome=&homeserver($uname,$udomain);
5219: my %newstorehash;
1.800 albertel 5220: foreach my $item (keys(%$storehash)) {
5221: my $key = $version.':'.&escape($symb).':'.$item;
5222: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5223: }
5224: my $items='';
5225: my %allitems = ();
1.800 albertel 5226: foreach my $item (keys(%newstorehash)) {
5227: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5228: my $key = $1.':keys:'.$2;
5229: $allitems{$key} .= $3.':';
5230: }
1.800 albertel 5231: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5232: }
1.800 albertel 5233: foreach my $item (keys(%allitems)) {
5234: $allitems{$item} =~ s/\:$//;
5235: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5236: }
5237: $items=~s/\&$//;
5238: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5239: }
5240:
1.47 www 5241: # ------------------------------------------------------ critical put interface
5242:
5243: sub cput {
1.134 albertel 5244: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5245: if (!$udomain) { $udomain=$env{'user.domain'}; }
5246: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5247: my $uhome=&homeserver($uname,$udomain);
1.47 www 5248: my $items='';
1.800 albertel 5249: foreach my $item (keys(%$storehash)) {
5250: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5251: }
1.47 www 5252: $items=~s/\&$//;
1.134 albertel 5253: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5254: }
5255:
5256: # -------------------------------------------------------------- eget interface
5257:
5258: sub eget {
1.133 albertel 5259: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5260: my $items='';
1.800 albertel 5261: foreach my $item (@$storearr) {
5262: $items.=&escape($item).'&';
1.191 harris41 5263: }
1.12 www 5264: $items=~s/\&$//;
1.620 albertel 5265: if (!$udomain) { $udomain=$env{'user.domain'}; }
5266: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5267: my $uhome=&homeserver($uname,$udomain);
5268: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5269: my @pairs=split(/\&/,$rep);
5270: my %returnhash=();
1.42 www 5271: my $i=0;
1.800 albertel 5272: foreach my $item (@$storearr) {
5273: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5274: $i++;
1.191 harris41 5275: }
1.12 www 5276: return %returnhash;
5277: }
5278:
1.667 albertel 5279: # ------------------------------------------------------------ tmpput interface
5280: sub tmpput {
1.802 raeburn 5281: my ($storehash,$server,$context)=@_;
1.667 albertel 5282: my $items='';
1.800 albertel 5283: foreach my $item (keys(%$storehash)) {
5284: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5285: }
5286: $items=~s/\&$//;
1.802 raeburn 5287: if (defined($context)) {
5288: $items .= ':'.&escape($context);
5289: }
1.667 albertel 5290: return &reply("tmpput:$items",$server);
5291: }
5292:
5293: # ------------------------------------------------------------ tmpget interface
5294: sub tmpget {
1.688 albertel 5295: my ($token,$server)=@_;
5296: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5297: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5298: my %returnhash;
5299: foreach my $item (split(/\&/,$rep)) {
5300: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5301: next if ($key =~ /^error: 2 /);
1.667 albertel 5302: $returnhash{&unescape($key)}=&thaw_unescape($value);
5303: }
5304: return %returnhash;
5305: }
5306:
1.1113 raeburn 5307: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5308: sub tmpdel {
5309: my ($token,$server)=@_;
5310: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5311: return &reply("tmpdel:$token",$server);
5312: }
5313:
1.765 albertel 5314: # -------------------------------------------------- portfolio access checking
5315:
5316: sub portfolio_access {
1.766 albertel 5317: my ($requrl) = @_;
1.765 albertel 5318: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5319: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 5320: if ($result) {
5321: my %setters;
5322: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5323: my ($startblock,$endblock) =
5324: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5325: if ($startblock && $endblock) {
5326: return 'B';
5327: }
5328: } else {
5329: my ($startblock,$endblock) =
5330: &Apache::loncommon::blockcheck(\%setters,'port');
5331: if ($startblock && $endblock) {
5332: return 'B';
5333: }
5334: }
5335: }
1.765 albertel 5336: if ($result eq 'ok') {
1.766 albertel 5337: return 'F';
1.765 albertel 5338: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 5339: return 'A';
1.765 albertel 5340: }
1.766 albertel 5341: return '';
1.765 albertel 5342: }
5343:
5344: sub get_portfolio_access {
1.767 albertel 5345: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5346:
5347: if (!ref($access_hash)) {
5348: my $current_perms = &get_portfile_permissions($udom,$unum);
5349: my %access_controls = &get_access_controls($current_perms,$group,
5350: $file_name);
5351: $access_hash = $access_controls{$file_name};
5352: }
5353:
1.765 albertel 5354: my ($public,$guest,@domains,@users,@courses,@groups);
5355: my $now = time;
5356: if (ref($access_hash) eq 'HASH') {
5357: foreach my $key (keys(%{$access_hash})) {
5358: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5359: if ($start > $now) {
5360: next;
5361: }
5362: if ($end && $end<$now) {
5363: next;
5364: }
5365: if ($scope eq 'public') {
5366: $public = $key;
5367: last;
5368: } elsif ($scope eq 'guest') {
5369: $guest = $key;
5370: } elsif ($scope eq 'domains') {
5371: push(@domains,$key);
5372: } elsif ($scope eq 'users') {
5373: push(@users,$key);
5374: } elsif ($scope eq 'course') {
5375: push(@courses,$key);
5376: } elsif ($scope eq 'group') {
5377: push(@groups,$key);
5378: }
5379: }
5380: if ($public) {
5381: return 'ok';
5382: }
5383: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5384: if ($guest) {
5385: return $guest;
5386: }
5387: } else {
5388: if (@domains > 0) {
5389: foreach my $domkey (@domains) {
5390: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5391: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5392: return 'ok';
5393: }
5394: }
5395: }
5396: }
5397: if (@users > 0) {
5398: foreach my $userkey (@users) {
1.865 raeburn 5399: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5400: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5401: if (ref($item) eq 'HASH') {
5402: if (($item->{'uname'} eq $env{'user.name'}) &&
5403: ($item->{'udom'} eq $env{'user.domain'})) {
5404: return 'ok';
5405: }
5406: }
5407: }
5408: }
1.765 albertel 5409: }
5410: }
5411: my %roleshash;
5412: my @courses_and_groups = @courses;
5413: push(@courses_and_groups,@groups);
5414: if (@courses_and_groups > 0) {
5415: my (%allgroups,%allroles);
5416: my ($start,$end,$role,$sec,$group);
5417: foreach my $envkey (%env) {
1.1060 raeburn 5418: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5419: my $cid = $2.'_'.$3;
5420: if ($1 eq 'gr') {
5421: $group = $4;
5422: $allgroups{$cid}{$group} = $env{$envkey};
5423: } else {
5424: if ($4 eq '') {
5425: $sec = 'none';
5426: } else {
5427: $sec = $4;
5428: }
5429: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5430: }
1.811 albertel 5431: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5432: my $cid = $2.'_'.$3;
5433: if ($4 eq '') {
5434: $sec = 'none';
5435: } else {
5436: $sec = $4;
5437: }
5438: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5439: }
5440: }
5441: if (keys(%allroles) == 0) {
5442: return;
5443: }
5444: foreach my $key (@courses_and_groups) {
5445: my %content = %{$$access_hash{$key}};
5446: my $cnum = $content{'number'};
5447: my $cdom = $content{'domain'};
5448: my $cid = $cdom.'_'.$cnum;
5449: if (!exists($allroles{$cid})) {
5450: next;
5451: }
5452: foreach my $role_id (keys(%{$content{'roles'}})) {
5453: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5454: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5455: my @status = @{$content{'roles'}{$role_id}{'access'}};
5456: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5457: foreach my $role (keys(%{$allroles{$cid}})) {
5458: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5459: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5460: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5461: if (grep/^all$/,@sections) {
5462: return 'ok';
5463: } else {
5464: if (grep/^$sec$/,@sections) {
5465: return 'ok';
5466: }
5467: }
5468: }
5469: }
5470: if (keys(%{$allgroups{$cid}}) == 0) {
5471: if (grep/^none$/,@groups) {
5472: return 'ok';
5473: }
5474: } else {
5475: if (grep/^all$/,@groups) {
5476: return 'ok';
5477: }
5478: foreach my $group (keys(%{$allgroups{$cid}})) {
5479: if (grep/^$group$/,@groups) {
5480: return 'ok';
5481: }
5482: }
5483: }
5484: }
5485: }
5486: }
5487: }
5488: }
5489: if ($guest) {
5490: return $guest;
5491: }
5492: }
5493: }
5494: return;
5495: }
5496:
5497: sub course_group_datechecker {
5498: my ($dates,$now,$status) = @_;
5499: my ($start,$end) = split(/\./,$dates);
5500: if (!$start && !$end) {
5501: return 'ok';
5502: }
5503: if (grep/^active$/,@{$status}) {
5504: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5505: return 'ok';
5506: }
5507: }
5508: if (grep/^previous$/,@{$status}) {
5509: if ($end > $now ) {
5510: return 'ok';
5511: }
5512: }
5513: if (grep/^future$/,@{$status}) {
5514: if ($start > $now) {
5515: return 'ok';
5516: }
5517: }
5518: return;
5519: }
5520:
5521: sub parse_portfolio_url {
5522: my ($url) = @_;
5523:
5524: my ($type,$udom,$unum,$group,$file_name);
5525:
1.823 albertel 5526: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5527: $type = 1;
5528: $udom = $1;
5529: $unum = $2;
5530: $file_name = $3;
1.823 albertel 5531: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5532: $type = 2;
5533: $udom = $1;
5534: $unum = $2;
5535: $group = $3;
5536: $file_name = $3.'/'.$4;
5537: }
5538: if (wantarray) {
5539: return ($type,$udom,$unum,$file_name,$group);
5540: }
5541: return $type;
5542: }
5543:
5544: sub is_portfolio_url {
5545: my ($url) = @_;
5546: return scalar(&parse_portfolio_url($url));
5547: }
5548:
1.798 raeburn 5549: sub is_portfolio_file {
5550: my ($file) = @_;
1.820 raeburn 5551: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5552: return 1;
5553: }
5554: return;
5555: }
5556:
1.976 raeburn 5557: sub usertools_access {
1.1084 raeburn 5558: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 5559: my ($access,%tools);
5560: if ($context eq '') {
5561: $context = 'tools';
5562: }
5563: if ($context eq 'requestcourses') {
5564: %tools = (
5565: official => 1,
5566: unofficial => 1,
1.1006 raeburn 5567: community => 1,
1.985 raeburn 5568: );
5569: } else {
5570: %tools = (
5571: aboutme => 1,
5572: blog => 1,
5573: portfolio => 1,
5574: );
5575: }
1.976 raeburn 5576: return if (!defined($tools{$tool}));
5577:
5578: if ((!defined($udom)) || (!defined($uname))) {
5579: $udom = $env{'user.domain'};
5580: $uname = $env{'user.name'};
5581: }
5582:
1.978 raeburn 5583: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5584: if ($action ne 'reload') {
1.985 raeburn 5585: if ($context eq 'requestcourses') {
5586: return $env{'environment.canrequest.'.$tool};
5587: } else {
5588: return $env{'environment.availabletools.'.$tool};
5589: }
5590: }
1.976 raeburn 5591: }
5592:
5593: my ($toolstatus,$inststatus);
5594:
1.985 raeburn 5595: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5596: ($action ne 'reload')) {
5597: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5598: $inststatus = $env{'environment.inststatus'};
5599: } else {
1.1084 raeburn 5600: if (ref($userenvref) eq 'HASH') {
5601: $toolstatus = $userenvref->{$context.'.'.$tool};
5602: $inststatus = $userenvref->{'inststatus'};
5603: } else {
5604: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5605: $toolstatus = $userenv{$context.'.'.$tool};
5606: $inststatus = $userenv{'inststatus'};
5607: }
1.976 raeburn 5608: }
5609:
5610: if ($toolstatus ne '') {
5611: if ($toolstatus) {
5612: $access = 1;
5613: } else {
5614: $access = 0;
5615: }
5616: return $access;
5617: }
5618:
1.1084 raeburn 5619: my ($is_adv,%domdef);
5620: if (ref($is_advref) eq 'HASH') {
5621: $is_adv = $is_advref->{'is_adv'};
5622: } else {
5623: $is_adv = &is_advanced_user($udom,$uname);
5624: }
5625: if (ref($domdefref) eq 'HASH') {
5626: %domdef = %{$domdefref};
5627: } else {
5628: %domdef = &get_domain_defaults($udom);
5629: }
1.976 raeburn 5630: if (ref($domdef{$tool}) eq 'HASH') {
5631: if ($is_adv) {
5632: if ($domdef{$tool}{'_LC_adv'} ne '') {
5633: if ($domdef{$tool}{'_LC_adv'}) {
5634: $access = 1;
5635: } else {
5636: $access = 0;
5637: }
5638: return $access;
5639: }
5640: }
5641: if ($inststatus ne '') {
5642: my ($hasaccess,$hasnoaccess);
5643: foreach my $affiliation (split(/:/,$inststatus)) {
5644: if ($domdef{$tool}{$affiliation} ne '') {
5645: if ($domdef{$tool}{$affiliation}) {
5646: $hasaccess = 1;
5647: } else {
5648: $hasnoaccess = 1;
5649: }
5650: }
5651: }
5652: if ($hasaccess || $hasnoaccess) {
5653: if ($hasaccess) {
5654: $access = 1;
5655: } elsif ($hasnoaccess) {
5656: $access = 0;
5657: }
5658: return $access;
5659: }
5660: } else {
5661: if ($domdef{$tool}{'default'} ne '') {
5662: if ($domdef{$tool}{'default'}) {
5663: $access = 1;
5664: } elsif ($domdef{$tool}{'default'} == 0) {
5665: $access = 0;
5666: }
5667: return $access;
5668: }
5669: }
5670: } else {
1.985 raeburn 5671: if ($context eq 'tools') {
5672: $access = 1;
5673: } else {
5674: $access = 0;
5675: }
1.976 raeburn 5676: return $access;
5677: }
5678: }
5679:
1.1050 raeburn 5680: sub is_course_owner {
5681: my ($cdom,$cnum,$udom,$uname) = @_;
5682: if (($udom eq '') || ($uname eq '')) {
5683: $udom = $env{'user.domain'};
5684: $uname = $env{'user.name'};
5685: }
5686: unless (($udom eq '') || ($uname eq '')) {
5687: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5688: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5689: return 1;
5690: } else {
5691: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5692: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5693: return 1;
5694: }
5695: }
5696: }
5697: }
5698: return;
5699: }
5700:
1.976 raeburn 5701: sub is_advanced_user {
5702: my ($udom,$uname) = @_;
1.1085 raeburn 5703: if ($udom ne '' && $uname ne '') {
5704: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 5705: if (wantarray) {
5706: return ($env{'user.adv'},$env{'user.author'});
5707: } else {
5708: return $env{'user.adv'};
5709: }
1.1085 raeburn 5710: }
5711: }
1.976 raeburn 5712: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5713: my %allroles;
1.1128 raeburn 5714: my ($is_adv,$is_author);
1.976 raeburn 5715: foreach my $role (keys(%roleshash)) {
5716: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5717: my $area = '/'.$tdomain.'/'.$trest;
5718: if ($sec ne '') {
5719: $area .= '/'.$sec;
5720: }
5721: if (($area ne '') && ($trole ne '')) {
5722: my $spec=$trole.'.'.$area;
5723: if ($trole =~ /^cr\//) {
5724: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5725: } elsif ($trole ne 'gr') {
5726: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5727: }
1.1128 raeburn 5728: if ($trole eq 'au') {
5729: $is_author = 1;
5730: }
1.976 raeburn 5731: }
5732: }
5733: foreach my $role (keys(%allroles)) {
5734: last if ($is_adv);
5735: foreach my $item (split(/:/,$allroles{$role})) {
5736: if ($item ne '') {
5737: my ($privilege,$restrictions)=split(/&/,$item);
5738: if ($privilege eq 'adv') {
5739: $is_adv = 1;
5740: last;
5741: }
5742: }
5743: }
5744: }
1.1128 raeburn 5745: if (wantarray) {
5746: return ($is_adv,$is_author);
5747: }
1.976 raeburn 5748: return $is_adv;
5749: }
1.798 raeburn 5750:
1.1035 raeburn 5751: sub check_can_request {
1.1036 raeburn 5752: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5753: my $canreq = 0;
5754: my ($types,$typename) = &Apache::loncommon::course_types();
5755: my @options = ('approval','validate','autolimit');
5756: my $optregex = join('|',@options);
5757: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5758: foreach my $type (@{$types}) {
5759: if (&usertools_access($env{'user.name'},
5760: $env{'user.domain'},
5761: $type,undef,'requestcourses')) {
5762: $canreq ++;
1.1036 raeburn 5763: if (ref($request_domains) eq 'HASH') {
5764: push(@{$request_domains->{$type}},$env{'user.domain'});
5765: }
1.1035 raeburn 5766: if ($dom eq $env{'user.domain'}) {
5767: $can_request->{$type} = 1;
5768: }
5769: }
5770: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5771: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5772: if (@curr > 0) {
1.1036 raeburn 5773: foreach my $item (@curr) {
5774: if (ref($request_domains) eq 'HASH') {
5775: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5776: if ($otherdom ne '') {
5777: if (ref($request_domains->{$type}) eq 'ARRAY') {
5778: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5779: push(@{$request_domains->{$type}},$otherdom);
5780: }
5781: } else {
5782: push(@{$request_domains->{$type}},$otherdom);
5783: }
5784: }
5785: }
5786: }
5787: unless($dom eq $env{'user.domain'}) {
5788: $canreq ++;
1.1035 raeburn 5789: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5790: $can_request->{$type} = 1;
5791: }
5792: }
5793: }
5794: }
5795: }
5796: }
5797: return $canreq;
5798: }
5799:
1.341 www 5800: # ---------------------------------------------- Custom access rule evaluation
5801:
5802: sub customaccess {
5803: my ($priv,$uri)=@_;
1.807 albertel 5804: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5805: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5806: $udom = &LONCAPA::clean_domain($udom);
5807: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5808: my $access=0;
1.800 albertel 5809: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5810: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5811: if ($type eq 'user') {
5812: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5813: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5814: if ($tdom) {
5815: if ($tdom ne $env{'user.domain'}) { next; }
5816: }
1.896 albertel 5817: if ($tuname) {
5818: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5819: }
5820: $access=($effect eq 'allow');
5821: last;
5822: }
5823: } else {
5824: if ($role) {
5825: if ($role ne $urole) { next; }
5826: }
5827: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5828: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5829: if ($tdom) {
5830: if ($tdom ne $udom) { next; }
5831: }
5832: if ($tcrs) {
5833: if ($tcrs ne $ucrs) { next; }
5834: }
5835: if ($tsec) {
5836: if ($tsec ne $usec) { next; }
5837: }
5838: $access=($effect eq 'allow');
5839: last;
5840: }
5841: if ($realm eq '' && $role eq '') {
5842: $access=($effect eq 'allow');
5843: }
1.402 bowersj2 5844: }
1.341 www 5845: }
5846: return $access;
5847: }
5848:
1.103 harris41 5849: # ------------------------------------------------- Check for a user privilege
1.12 www 5850:
5851: sub allowed {
1.810 raeburn 5852: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5853: my $ver_orguri=$uri;
1.439 www 5854: $uri=&deversion($uri);
1.152 www 5855: my $orguri=$uri;
1.52 www 5856: $uri=&declutter($uri);
1.809 raeburn 5857:
1.810 raeburn 5858: if ($priv eq 'evb') {
5859: # Evade communication block restrictions for specified role in a course
5860: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5861: return $1;
5862: } else {
5863: return;
5864: }
5865: }
5866:
1.620 albertel 5867: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5868: # Free bre access to adm and meta resources
1.775 albertel 5869: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5870: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5871: && ($priv eq 'bre')) {
1.14 www 5872: return 'F';
1.159 www 5873: }
5874:
1.545 banghart 5875: # Free bre access to user's own portfolio contents
1.714 raeburn 5876: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5877: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5878: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5879: my %setters;
5880: my ($startblock,$endblock) =
5881: &Apache::loncommon::blockcheck(\%setters,'port');
5882: if ($startblock && $endblock) {
5883: return 'B';
5884: } else {
5885: return 'F';
5886: }
1.545 banghart 5887: }
5888:
1.762 raeburn 5889: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5890: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5891: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5892: if (exists($env{'request.course.id'})) {
5893: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5894: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5895: if (($domain eq $cdom) && ($name eq $cnum)) {
5896: my $courseprivid=$env{'request.course.id'};
5897: $courseprivid=~s/\_/\//;
5898: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5899: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5900: return $1;
1.762 raeburn 5901: } else {
5902: if ($env{'request.course.sec'}) {
5903: $courseprivid.='/'.$env{'request.course.sec'};
5904: }
5905: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5906: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5907: return $2;
5908: }
1.714 raeburn 5909: }
5910: }
5911: }
5912: }
5913:
1.159 www 5914: # Free bre to public access
5915:
5916: if ($priv eq 'bre') {
1.238 www 5917: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5918: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5919: return 'F';
5920: }
1.238 www 5921: if ($copyright eq 'priv') {
5922: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5923: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5924: return '';
5925: }
5926: }
5927: if ($copyright eq 'domain') {
5928: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5929: unless (($env{'user.domain'} eq $1) ||
5930: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5931: return '';
5932: }
1.262 matthew 5933: }
1.620 albertel 5934: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5935: # Library role, so allow browsing of resources in this domain.
5936: return 'F';
1.238 www 5937: }
1.341 www 5938: if ($copyright eq 'custom') {
5939: unless (&customaccess($priv,$uri)) { return ''; }
5940: }
1.14 www 5941: }
1.264 matthew 5942: # Domain coordinator is trying to create a course
1.620 albertel 5943: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5944: # uri is the requested domain in this case.
5945: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5946: # a role of dc for the domain in question.
1.620 albertel 5947: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5948: }
1.29 www 5949:
1.52 www 5950: my $thisallowed='';
5951: my $statecond=0;
5952: my $courseprivid='';
5953:
1.1039 raeburn 5954: my $ownaccess;
1.1043 raeburn 5955: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5956: if (($priv eq 'bro') && ($env{'user.author'})) {
5957: if ($uri eq '') {
5958: $ownaccess = 1;
5959: } else {
5960: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5961: my $udom = $env{'user.domain'};
5962: my $uname = $env{'user.name'};
5963: if ($uri =~ m{^\Q$udom\E/?$}) {
5964: $ownaccess = 1;
1.1040 raeburn 5965: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5966: unless ($uri =~ m{\.\./}) {
5967: $ownaccess = 1;
5968: }
5969: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5970: my $now = time;
5971: if ($uri =~ m{^([^/]+)/?$}) {
5972: my $adom = $1;
5973: foreach my $key (keys(%env)) {
1.1042 raeburn 5974: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5975: my ($start,$end) = split('.',$env{$key});
5976: if (($now >= $start) && (!$end || $end < $now)) {
5977: $ownaccess = 1;
5978: last;
5979: }
5980: }
5981: }
5982: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5983: my $adom = $1;
5984: my $aname = $2;
1.1042 raeburn 5985: foreach my $role ('ca','aa') {
5986: if ($env{"user.role.$role./$adom/$aname"}) {
5987: my ($start,$end) =
5988: split('.',$env{"user.role.$role./$adom/$aname"});
5989: if (($now >= $start) && (!$end || $end < $now)) {
5990: $ownaccess = 1;
5991: last;
5992: }
1.1039 raeburn 5993: }
5994: }
5995: }
5996: }
5997: }
5998: }
5999: }
6000:
1.52 www 6001: # Course
6002:
1.620 albertel 6003: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6004: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6005: $thisallowed.=$1;
6006: }
1.52 www 6007: }
1.29 www 6008:
1.52 www 6009: # Domain
6010:
1.620 albertel 6011: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6012: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6013: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6014: $thisallowed.=$1;
6015: }
1.12 www 6016: }
1.52 www 6017:
1.1141 raeburn 6018: # User who is not author or co-author might still be able to edit
6019: # resource of an author in the domain (e.g., if Domain Coordinator).
6020: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6021: (&allowed('mdc',$env{'request.course.id'}))) {
6022: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6023: $thisallowed.=$1;
6024: }
6025: }
6026:
1.52 www 6027: # Course: uri itself is a course
1.66 www 6028: my $courseuri=$uri;
6029: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6030: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6031:
1.620 albertel 6032: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6033: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6034: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6035: $thisallowed.=$1;
6036: }
1.12 www 6037: }
1.29 www 6038:
1.665 albertel 6039: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6040: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6041: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6042: $thisallowed='';
1.671 raeburn 6043: my ($match)=&is_on_map($uri);
6044: if ($match) {
6045: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6046: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 ! raeburn 6047: my @blockers = &has_comm_blocking($priv,$symb,$uri);
! 6048: if (@blockers > 0) {
! 6049: $thisallowed = 'B';
! 6050: } else {
! 6051: $thisallowed.=$1;
! 6052: }
1.671 raeburn 6053: }
6054: } else {
1.705 albertel 6055: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6056: if ($refuri) {
6057: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6058: $thisallowed='F';
1.671 raeburn 6059: } else {
6060: $refuri=&declutter($refuri);
6061: my ($match) = &is_on_map($refuri);
6062: if ($match) {
1.1162 ! raeburn 6063: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
! 6064: if (@blockers > 0) {
! 6065: $thisallowed = 'B';
! 6066: } else {
! 6067: $thisallowed='F';
! 6068: }
1.671 raeburn 6069: }
1.669 raeburn 6070: }
1.671 raeburn 6071: }
6072: }
1.314 www 6073: }
1.492 albertel 6074:
1.766 albertel 6075: if ($priv eq 'bre'
6076: && $thisallowed ne 'F'
6077: && $thisallowed ne '2'
6078: && &is_portfolio_url($uri)) {
6079: $thisallowed = &portfolio_access($uri);
6080: }
6081:
1.52 www 6082: # Full access at system, domain or course-wide level? Exit.
1.29 www 6083: if ($thisallowed=~/F/) {
6084: return 'F';
6085: }
6086:
1.52 www 6087: # If this is generating or modifying users, exit with special codes
1.29 www 6088:
1.643 www 6089: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6090: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6091: my ($audom,$auname)=split('/',$uri);
1.643 www 6092: # no author name given, so this just checks on the general right to make a co-author in this domain
6093: unless ($auname) { return $thisallowed; }
6094: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6095: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6096: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6097: ($audom ne $env{'request.role.domain'}))) { return ''; }
6098: }
1.52 www 6099: return $thisallowed;
6100: }
6101: #
1.103 harris41 6102: # Gathered so far: system, domain and course wide privileges
1.52 www 6103: #
6104: # Course: See if uri or referer is an individual resource that is part of
6105: # the course
6106:
1.620 albertel 6107: if ($env{'request.course.id'}) {
1.232 www 6108:
1.620 albertel 6109: $courseprivid=$env{'request.course.id'};
6110: if ($env{'request.course.sec'}) {
6111: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6112: }
6113: $courseprivid=~s/\_/\//;
6114: my $checkreferer=1;
1.232 www 6115: my ($match,$cond)=&is_on_map($uri);
6116: if ($match) {
6117: $statecond=$cond;
1.620 albertel 6118: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6119: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 ! raeburn 6120: my $value = $1;
! 6121: if ($priv eq 'bre') {
! 6122: my @blockers = &has_comm_blocking($priv,$symb,$uri);
! 6123: if (@blockers > 0) {
! 6124: $thisallowed = 'B';
! 6125: } else {
! 6126: $thisallowed.=$value;
! 6127: }
! 6128: } else {
! 6129: $thisallowed.=$value;
! 6130: }
1.52 www 6131: $checkreferer=0;
6132: }
1.29 www 6133: }
1.83 www 6134:
1.148 www 6135: if ($checkreferer) {
1.620 albertel 6136: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6137: unless ($refuri) {
1.800 albertel 6138: foreach my $key (keys(%env)) {
6139: if ($key=~/^httpref\..*\*/) {
6140: my $pattern=$key;
1.156 www 6141: $pattern=~s/^httpref\.\/res\///;
1.148 www 6142: $pattern=~s/\*/\[\^\/\]\+/g;
6143: $pattern=~s/\//\\\//g;
1.152 www 6144: if ($orguri=~/$pattern/) {
1.800 albertel 6145: $refuri=$env{$key};
1.148 www 6146: }
6147: }
1.191 harris41 6148: }
1.148 www 6149: }
1.232 www 6150:
1.148 www 6151: if ($refuri) {
1.152 www 6152: $refuri=&declutter($refuri);
1.232 www 6153: my ($match,$cond)=&is_on_map($refuri);
6154: if ($match) {
6155: my $refstatecond=$cond;
1.620 albertel 6156: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6157: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 ! raeburn 6158: my $value = $1;
! 6159: if ($priv eq 'bre') {
! 6160: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
! 6161: if (@blockers > 0) {
! 6162: $thisallowed = 'B';
! 6163: } else {
! 6164: $thisallowed.=$value;
! 6165: }
! 6166: } else {
! 6167: $thisallowed.=$value;
! 6168: }
1.53 www 6169: $uri=$refuri;
6170: $statecond=$refstatecond;
1.52 www 6171: }
6172: }
1.148 www 6173: }
1.29 www 6174: }
1.52 www 6175: }
1.29 www 6176:
1.52 www 6177: #
1.103 harris41 6178: # Gathered now: all privileges that could apply, and condition number
1.52 www 6179: #
6180: #
6181: # Full or no access?
6182: #
1.29 www 6183:
1.52 www 6184: if ($thisallowed=~/F/) {
6185: return 'F';
6186: }
1.29 www 6187:
1.52 www 6188: unless ($thisallowed) {
6189: return '';
6190: }
1.29 www 6191:
1.52 www 6192: # Restrictions exist, deal with them
6193: #
6194: # C:according to course preferences
6195: # R:according to resource settings
6196: # L:unless locked
6197: # X:according to user session state
6198: #
6199:
6200: # Possibly locked functionality, check all courses
1.54 www 6201: # Locks might take effect only after 10 minutes cache expiration for other
6202: # courses, and 2 minutes for current course
1.52 www 6203:
6204: my $envkey;
6205: if ($thisallowed=~/L/) {
1.1000 raeburn 6206: foreach $envkey (keys(%env)) {
1.54 www 6207: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6208: my $courseid=$2;
6209: my $roleid=$1.'.'.$2;
1.92 www 6210: $courseid=~s/^\///;
1.54 www 6211: my $expiretime=600;
1.620 albertel 6212: if ($env{'request.role'} eq $roleid) {
1.54 www 6213: $expiretime=120;
6214: }
6215: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6216: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6217: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6218: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6219: }
1.620 albertel 6220: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6221: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6222: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6223: &log($env{'user.domain'},$env{'user.name'},
6224: $env{'user.home'},
1.57 www 6225: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6226: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6227: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6228: return '';
6229: }
6230: }
1.620 albertel 6231: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6232: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6233: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6234: &log($env{'user.domain'},$env{'user.name'},
6235: $env{'user.home'},
1.57 www 6236: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6237: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6238: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6239: return '';
6240: }
6241: }
6242: }
1.29 www 6243: }
1.52 www 6244: }
6245:
6246: #
6247: # Rest of the restrictions depend on selected course
6248: #
6249:
1.620 albertel 6250: unless ($env{'request.course.id'}) {
1.766 albertel 6251: if ($thisallowed eq 'A') {
6252: return 'A';
1.814 raeburn 6253: } elsif ($thisallowed eq 'B') {
6254: return 'B';
1.766 albertel 6255: } else {
6256: return '1';
6257: }
1.52 www 6258: }
1.29 www 6259:
1.52 www 6260: #
6261: # Now user is definitely in a course
6262: #
1.53 www 6263:
6264:
6265: # Course preferences
6266:
6267: if ($thisallowed=~/C/) {
1.620 albertel 6268: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6269: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6270: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6271: =~/\Q$rolecode\E/) {
1.1103 raeburn 6272: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6273: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6274: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6275: $env{'request.course.id'});
6276: }
1.237 www 6277: return '';
6278: }
6279:
1.620 albertel 6280: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6281: =~/\Q$unamedom\E/) {
1.1103 raeburn 6282: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6283: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6284: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6285: $env{'request.course.id'});
6286: }
1.54 www 6287: return '';
6288: }
1.53 www 6289: }
6290:
6291: # Resource preferences
6292:
6293: if ($thisallowed=~/R/) {
1.620 albertel 6294: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6295: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6296: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6297: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6298: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6299: }
6300: return '';
1.54 www 6301: }
1.53 www 6302: }
1.30 www 6303:
1.246 www 6304: # Restricted by state or randomout?
1.30 www 6305:
1.52 www 6306: if ($thisallowed=~/X/) {
1.620 albertel 6307: if ($env{'acc.randomout'}) {
1.579 albertel 6308: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 6309: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 6310: return '';
6311: }
1.247 www 6312: }
6313: if (&condval($statecond)) {
1.52 www 6314: return '2';
6315: } else {
6316: return '';
6317: }
6318: }
1.30 www 6319:
1.766 albertel 6320: if ($thisallowed eq 'A') {
6321: return 'A';
1.814 raeburn 6322: } elsif ($thisallowed eq 'B') {
6323: return 'B';
1.766 albertel 6324: }
1.52 www 6325: return 'F';
1.232 www 6326: }
1.1162 ! raeburn 6327:
! 6328: sub get_comm_blocks {
! 6329: my ($cdom,$cnum) = @_;
! 6330: if ($cdom eq '' || $cnum eq '') {
! 6331: return unless ($env{'request.course.id'});
! 6332: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
! 6333: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
! 6334: }
! 6335: my %commblocks;
! 6336: my $hashid=$cdom.'_'.$cnum;
! 6337: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
! 6338: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
! 6339: %commblocks = %{$blocksref};
! 6340: } else {
! 6341: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
! 6342: my $cachetime = 600;
! 6343: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
! 6344: }
! 6345: return %commblocks;
! 6346: }
! 6347:
! 6348: sub has_comm_blocking {
! 6349: my ($priv,$symb,$uri,$blocks) = @_;
! 6350: return unless ($env{'request.course.id'});
! 6351: return unless ($priv eq 'bre');
! 6352: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
! 6353: my %commblocks;
! 6354: if (ref($blocks) eq 'HASH') {
! 6355: %commblocks = %{$blocks};
! 6356: } else {
! 6357: %commblocks = &get_comm_blocks();
! 6358: }
! 6359: return unless (keys(%commblocks) > 0);
! 6360: if (!$symb) { $symb=&symbread($uri,1); }
! 6361: my ($map,$resid,undef)=&decode_symb($symb);
! 6362: my %tocheck = (
! 6363: maps => $map,
! 6364: resources => $symb,
! 6365: );
! 6366: my @blockers;
! 6367: my $now = time;
! 6368: foreach my $block (keys(%commblocks)) {
! 6369: if ($block =~ /^(\d+)____(\d+)$/) {
! 6370: my ($start,$end) = ($1,$2);
! 6371: if ($start <= $now && $end >= $now) {
! 6372: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
! 6373: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
! 6374: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
! 6375: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
! 6376: unless (grep(/^\Q$block\E$/,@blockers)) {
! 6377: push(@blockers,$block);
! 6378: }
! 6379: }
! 6380: }
! 6381: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
! 6382: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
! 6383: unless (grep(/^\Q$block\E$/,@blockers)) {
! 6384: push(@blockers,$block);
! 6385: }
! 6386: }
! 6387: }
! 6388: }
! 6389: }
! 6390: }
! 6391: } elsif ($block =~ /^firstaccess____(.+)$/) {
! 6392: my $item = $1;
! 6393: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
! 6394: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
! 6395: my $check_interval;
! 6396: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
! 6397: my @interval;
! 6398: my $type = 'map';
! 6399: if ($item eq 'course') {
! 6400: $type = 'course';
! 6401: @interval=&EXT("resource.0.interval");
! 6402: } else {
! 6403: if ($item =~ /___\d+___/) {
! 6404: $type = 'resource';
! 6405: @interval=&EXT("resource.0.interval",$item);
! 6406: } else {
! 6407: my $mapsymb = &symbread($item,1);
! 6408: if ($mapsymb) {
! 6409: my $navmap = Apache::lonnavmaps::navmap->new();
! 6410: if (ref($navmap)) {
! 6411: my $mapres = $navmap->getBySymb($mapsymb);
! 6412: my @resources = $mapres->retrieveResources($mapres,undef,0,1);
! 6413: foreach my $res (@resources) {
! 6414: my $symb = $res->symb();
! 6415: next if ($symb eq $mapsymb);
! 6416: if ($symb ne '') {
! 6417: @interval=&EXT("resource.0.interval",$symb);
! 6418: last;
! 6419: }
! 6420: }
! 6421: }
! 6422: }
! 6423: }
! 6424: }
! 6425: if ($interval[0] =~ /\d+/) {
! 6426: my $first_access;
! 6427: if ($type eq 'resource') {
! 6428: $first_access=&get_first_access($interval[1],$item);
! 6429: } elsif ($type eq 'map') {
! 6430: $first_access=&get_first_access($interval[1],undef,$item);
! 6431: } else {
! 6432: $first_access=&get_first_access($interval[1]);
! 6433: }
! 6434: if ($first_access) {
! 6435: my $timesup = $first_access+$interval[0];
! 6436: if ($timesup > $now) {
! 6437: unless (grep(/^\Q$block\E$/,@blockers)) {
! 6438: push(@blockers,$block);
! 6439: }
! 6440: }
! 6441: }
! 6442: }
! 6443: }
! 6444: }
! 6445: }
! 6446: }
! 6447: }
! 6448: return @blockers;
! 6449: }
! 6450:
! 6451: sub check_docs_block {
! 6452: my ($docsblock,$tocheck) =@_;
! 6453: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
! 6454: return;
! 6455: }
! 6456: if (ref($docsblock->{'maps'}) eq 'HASH') {
! 6457: if ($tocheck->{'maps'}) {
! 6458: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
! 6459: return 1;
! 6460: }
! 6461: }
! 6462: }
! 6463: if (ref($docsblock->{'resources'}) eq 'HASH') {
! 6464: if ($tocheck->{'resources'}) {
! 6465: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
! 6466: return 1;
! 6467: }
! 6468: }
! 6469: }
! 6470: return;
! 6471: }
! 6472:
1.1133 foxr 6473: #
6474: # Removes the versino from a URI and
6475: # splits it in to its filename and path to the filename.
6476: # Seems like File::Basename could have done this more clearly.
6477: # Parameters:
6478: # $uri - input URI
6479: # Returns:
6480: # Two element list consisting of
6481: # $pathname - the URI up to and excluding the trailing /
6482: # $filename - The part of the URI following the last /
6483: # NOTE:
6484: # Another realization of this is simply:
6485: # use File::Basename;
6486: # ...
6487: # $uri = shift;
6488: # $filename = basename($uri);
6489: # $path = dirname($uri);
6490: # return ($filename, $path);
6491: #
6492: # The implementation below is probably faster however.
6493: #
1.710 albertel 6494: sub split_uri_for_cond {
6495: my $uri=&deversion(&declutter(shift));
6496: my @uriparts=split(/\//,$uri);
6497: my $filename=pop(@uriparts);
6498: my $pathname=join('/',@uriparts);
6499: return ($pathname,$filename);
6500: }
1.232 www 6501: # --------------------------------------------------- Is a resource on the map?
6502:
6503: sub is_on_map {
1.710 albertel 6504: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 6505: #Trying to find the conditional for the file
1.620 albertel 6506: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 6507: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 6508: if ($match) {
1.289 bowersj2 6509: return (1,$1);
6510: } else {
1.434 www 6511: return (0,0);
1.289 bowersj2 6512: }
1.12 www 6513: }
6514:
1.427 www 6515: # --------------------------------------------------------- Get symb from alias
6516:
6517: sub get_symb_from_alias {
6518: my $symb=shift;
6519: my ($map,$resid,$url)=&decode_symb($symb);
6520: # Already is a symb
6521: if ($url) { return $symb; }
6522: # Must be an alias
6523: my $aliassymb='';
6524: my %bighash;
1.620 albertel 6525: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 6526: &GDBM_READER(),0640)) {
6527: my $rid=$bighash{'mapalias_'.$symb};
6528: if ($rid) {
6529: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 6530: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6531: $resid,$bighash{'src_'.$rid});
1.427 www 6532: }
6533: untie %bighash;
6534: }
6535: return $aliassymb;
6536: }
6537:
1.12 www 6538: # ----------------------------------------------------------------- Define Role
6539:
6540: sub definerole {
6541: if (allowed('mcr','/')) {
6542: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 6543: foreach my $role (split(':',$sysrole)) {
6544: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6545: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6546: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6547: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6548: return "refused:s:$crole&$cqual";
6549: }
6550: }
1.191 harris41 6551: }
1.800 albertel 6552: foreach my $role (split(':',$domrole)) {
6553: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6554: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6555: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6556: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 6557: return "refused:d:$crole&$cqual";
6558: }
6559: }
1.191 harris41 6560: }
1.800 albertel 6561: foreach my $role (split(':',$courole)) {
6562: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6563: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6564: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6565: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6566: return "refused:c:$crole&$cqual";
6567: }
6568: }
1.191 harris41 6569: }
1.620 albertel 6570: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6571: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6572: "rolesdef_$rolename=".
6573: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 6574: return reply($command,$env{'user.home'});
1.12 www 6575: } else {
6576: return 'refused';
6577: }
1.105 harris41 6578: }
6579:
6580: # ---------------- Make a metadata query against the network of library servers
6581:
6582: sub metadata_query {
1.244 matthew 6583: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 6584: my %rhash;
1.845 albertel 6585: my %libserv = &all_library();
1.244 matthew 6586: my @server_list = (defined($server_array) ? @$server_array
6587: : keys(%libserv) );
6588: for my $server (@server_list) {
1.118 harris41 6589: unless ($custom or $customshow) {
6590: my $reply=&reply("querysend:".&escape($query),$server);
6591: $rhash{$server}=$reply;
6592: }
6593: else {
6594: my $reply=&reply("querysend:".&escape($query).':'.
6595: &escape($custom).':'.&escape($customshow),
6596: $server);
6597: $rhash{$server}=$reply;
6598: }
1.112 harris41 6599: }
1.118 harris41 6600: return \%rhash;
1.240 www 6601: }
6602:
6603: # ----------------------------------------- Send log queries and wait for reply
6604:
6605: sub log_query {
6606: my ($uname,$udom,$query,%filters)=@_;
6607: my $uhome=&homeserver($uname,$udom);
6608: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 6609: my $uhost=&hostname($uhome);
1.800 albertel 6610: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 6611: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6612: $uhome);
1.479 albertel 6613: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 6614: return get_query_reply($queryid);
6615: }
6616:
1.818 raeburn 6617: # -------------------------- Update MySQL table for portfolio file
6618:
6619: sub update_portfolio_table {
1.821 raeburn 6620: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 6621: if ($group ne '') {
6622: $file_name =~s /^\Q$group\E//;
6623: }
1.818 raeburn 6624: my $homeserver = &homeserver($uname,$udom);
6625: my $queryid=
1.821 raeburn 6626: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6627: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 6628: my $reply = &get_query_reply($queryid);
6629: return $reply;
6630: }
6631:
1.899 raeburn 6632: # -------------------------- Update MySQL allusers table
6633:
6634: sub update_allusers_table {
6635: my ($uname,$udom,$names) = @_;
6636: my $homeserver = &homeserver($uname,$udom);
6637: my $queryid=
6638: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6639: 'lastname='.&escape($names->{'lastname'}).'%%'.
6640: 'firstname='.&escape($names->{'firstname'}).'%%'.
6641: 'middlename='.&escape($names->{'middlename'}).'%%'.
6642: 'generation='.&escape($names->{'generation'}).'%%'.
6643: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6644: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 6645: return;
1.899 raeburn 6646: }
6647:
1.508 raeburn 6648: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 6649:
6650: sub fetch_enrollment_query {
1.511 raeburn 6651: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 6652: my $homeserver;
1.547 raeburn 6653: my $maxtries = 1;
1.508 raeburn 6654: if ($context eq 'automated') {
6655: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 6656: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 6657: } else {
6658: $homeserver = &homeserver($cnum,$dom);
6659: }
1.838 albertel 6660: my $host=&hostname($homeserver);
1.506 raeburn 6661: my $cmd = '';
1.1000 raeburn 6662: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 6663: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 6664: }
6665: $cmd =~ s/%%$//;
6666: $cmd = &escape($cmd);
6667: my $query = 'fetchenrollment';
1.620 albertel 6668: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 6669: unless ($queryid=~/^\Q$host\E\_/) {
6670: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6671: return 'error: '.$queryid;
6672: }
1.506 raeburn 6673: my $reply = &get_query_reply($queryid);
1.547 raeburn 6674: my $tries = 1;
6675: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6676: $reply = &get_query_reply($queryid);
6677: $tries ++;
6678: }
1.526 raeburn 6679: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 6680: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 6681: } else {
1.901 albertel 6682: my @responses = split(/:/,$reply);
1.515 raeburn 6683: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 6684: foreach my $line (@responses) {
6685: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 6686: $$replyref{$key} = $value;
6687: }
6688: } else {
1.1117 foxr 6689: my $pathname = LONCAPA::tempdir();
1.800 albertel 6690: foreach my $line (@responses) {
6691: my ($key,$value) = split(/=/,$line);
1.506 raeburn 6692: $$replyref{$key} = $value;
6693: if ($value > 0) {
1.800 albertel 6694: foreach my $item (@{$$affiliatesref{$key}}) {
6695: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 6696: my $destname = $pathname.'/'.$filename;
6697: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 6698: if ($xml_classlist =~ /^error/) {
6699: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6700: } else {
1.506 raeburn 6701: if ( open(FILE,">$destname") ) {
6702: print FILE &unescape($xml_classlist);
6703: close(FILE);
1.526 raeburn 6704: } else {
6705: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6706: }
6707: }
6708: }
6709: }
6710: }
6711: }
6712: return 'ok';
6713: }
6714: return 'error';
6715: }
6716:
1.242 www 6717: sub get_query_reply {
6718: my $queryid=shift;
1.1117 foxr 6719: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 6720: my $reply='';
6721: for (1..100) {
6722: sleep 2;
6723: if (-e $replyfile.'.end') {
1.448 albertel 6724: if (open(my $fh,$replyfile)) {
1.904 albertel 6725: $reply = join('',<$fh>);
6726: close($fh);
1.240 www 6727: } else { return 'error: reply_file_error'; }
1.242 www 6728: return &unescape($reply);
6729: }
1.240 www 6730: }
1.242 www 6731: return 'timeout:'.$queryid;
1.240 www 6732: }
6733:
6734: sub courselog_query {
1.241 www 6735: #
6736: # possible filters:
6737: # url: url or symb
6738: # username
6739: # domain
6740: # action: view, submit, grade
6741: # start: timestamp
6742: # end: timestamp
6743: #
1.240 www 6744: my (%filters)=@_;
1.620 albertel 6745: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6746: if ($filters{'url'}) {
6747: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6748: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6749: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6750: }
1.620 albertel 6751: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6752: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6753: return &log_query($cname,$cdom,'courselog',%filters);
6754: }
6755:
6756: sub userlog_query {
1.858 raeburn 6757: #
6758: # possible filters:
6759: # action: log check role
6760: # start: timestamp
6761: # end: timestamp
6762: #
1.240 www 6763: my ($uname,$udom,%filters)=@_;
6764: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6765: }
6766:
1.506 raeburn 6767: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6768:
6769: sub auto_run {
1.508 raeburn 6770: my ($cnum,$cdom) = @_;
1.876 raeburn 6771: my $response = 0;
6772: my $settings;
6773: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6774: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6775: $settings = $domconfig{'autoenroll'};
6776: if ($settings->{'run'} eq '1') {
6777: $response = 1;
6778: }
6779: } else {
1.934 raeburn 6780: my $homeserver;
6781: if (&is_course($cdom,$cnum)) {
6782: $homeserver = &homeserver($cnum,$cdom);
6783: } else {
6784: $homeserver = &domain($cdom,'primary');
6785: }
6786: if ($homeserver ne 'no_host') {
6787: $response = &reply('autorun:'.$cdom,$homeserver);
6788: }
1.876 raeburn 6789: }
1.506 raeburn 6790: return $response;
6791: }
1.776 albertel 6792:
1.506 raeburn 6793: sub auto_get_sections {
1.508 raeburn 6794: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6795: my $homeserver;
6796: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6797: $homeserver = &homeserver($cnum,$cdom);
6798: }
6799: if (!defined($homeserver)) {
6800: if ($cdom =~ /^$match_domain$/) {
6801: $homeserver = &domain($cdom,'primary');
6802: }
6803: }
6804: my @secs;
6805: if (defined($homeserver)) {
6806: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6807: unless ($response eq 'refused') {
6808: @secs = split(/:/,$response);
6809: }
1.506 raeburn 6810: }
6811: return @secs;
6812: }
1.776 albertel 6813:
1.506 raeburn 6814: sub auto_new_course {
1.1099 raeburn 6815: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6816: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 6817: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6818: return $response;
6819: }
1.776 albertel 6820:
1.506 raeburn 6821: sub auto_validate_courseID {
1.508 raeburn 6822: my ($cnum,$cdom,$inst_course_id) = @_;
6823: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6824: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6825: return $response;
6826: }
1.776 albertel 6827:
1.1007 raeburn 6828: sub auto_validate_instcode {
1.1020 raeburn 6829: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6830: my ($homeserver,$response);
6831: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6832: $homeserver = &homeserver($cnum,$cdom);
6833: }
6834: if (!defined($homeserver)) {
6835: if ($cdom =~ /^$match_domain$/) {
6836: $homeserver = &domain($cdom,'primary');
6837: }
6838: }
1.1065 raeburn 6839: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6840: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6841: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6842: return ($outcome,$description);
1.1007 raeburn 6843: }
6844:
1.506 raeburn 6845: sub auto_create_password {
1.873 raeburn 6846: my ($cnum,$cdom,$authparam,$udom) = @_;
6847: my ($homeserver,$response);
1.506 raeburn 6848: my $create_passwd = 0;
6849: my $authchk = '';
1.873 raeburn 6850: if ($udom =~ /^$match_domain$/) {
6851: $homeserver = &domain($udom,'primary');
6852: }
6853: if ($homeserver eq '') {
6854: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6855: $homeserver = &homeserver($cnum,$cdom);
6856: }
6857: }
6858: if ($homeserver eq '') {
6859: $authchk = 'nodomain';
1.506 raeburn 6860: } else {
1.873 raeburn 6861: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6862: if ($response eq 'refused') {
6863: $authchk = 'refused';
6864: } else {
1.901 albertel 6865: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6866: }
1.506 raeburn 6867: }
6868: return ($authparam,$create_passwd,$authchk);
6869: }
6870:
1.706 raeburn 6871: sub auto_photo_permission {
6872: my ($cnum,$cdom,$students) = @_;
6873: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6874: my ($outcome,$perm_reqd,$conditions) =
6875: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6876: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6877: return (undef,undef);
6878: }
1.706 raeburn 6879: return ($outcome,$perm_reqd,$conditions);
6880: }
6881:
6882: sub auto_checkphotos {
6883: my ($uname,$udom,$pid) = @_;
6884: my $homeserver = &homeserver($uname,$udom);
6885: my ($result,$resulttype);
6886: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6887: &escape($uname).':'.&escape($pid),
6888: $homeserver));
1.709 albertel 6889: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6890: return (undef,undef);
6891: }
1.706 raeburn 6892: if ($outcome) {
6893: ($result,$resulttype) = split(/:/,$outcome);
6894: }
6895: return ($result,$resulttype);
6896: }
6897:
6898: sub auto_photochoice {
6899: my ($cnum,$cdom) = @_;
6900: my $homeserver = &homeserver($cnum,$cdom);
6901: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6902: &escape($cdom),
6903: $homeserver)));
1.709 albertel 6904: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6905: return (undef,undef);
6906: }
1.706 raeburn 6907: return ($update,$comment);
6908: }
6909:
6910: sub auto_photoupdate {
6911: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6912: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6913: my $host=&hostname($homeserver);
1.706 raeburn 6914: my $cmd = '';
6915: my $maxtries = 1;
1.800 albertel 6916: foreach my $affiliate (keys(%{$affiliatesref})) {
6917: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6918: }
6919: $cmd =~ s/%%$//;
6920: $cmd = &escape($cmd);
6921: my $query = 'institutionalphotos';
6922: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6923: unless ($queryid=~/^\Q$host\E\_/) {
6924: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6925: return 'error: '.$queryid;
6926: }
6927: my $reply = &get_query_reply($queryid);
6928: my $tries = 1;
6929: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6930: $reply = &get_query_reply($queryid);
6931: $tries ++;
6932: }
6933: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6934: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6935: } else {
6936: my @responses = split(/:/,$reply);
6937: my $outcome = shift(@responses);
6938: foreach my $item (@responses) {
6939: my ($key,$value) = split(/=/,$item);
6940: $$photo{$key} = $value;
6941: }
6942: return $outcome;
6943: }
6944: return 'error';
6945: }
6946:
1.521 raeburn 6947: sub auto_instcode_format {
1.793 albertel 6948: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6949: $cat_order) = @_;
1.521 raeburn 6950: my $courses = '';
1.772 raeburn 6951: my @homeservers;
1.521 raeburn 6952: if ($caller eq 'global') {
1.841 albertel 6953: my %servers = &get_servers($codedom,'library');
6954: foreach my $tryserver (keys(%servers)) {
6955: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6956: push(@homeservers,$tryserver);
6957: }
1.584 raeburn 6958: }
1.1022 raeburn 6959: } elsif ($caller eq 'requests') {
6960: if ($codedom =~ /^$match_domain$/) {
6961: my $chome = &domain($codedom,'primary');
6962: unless ($chome eq 'no_host') {
6963: push(@homeservers,$chome);
6964: }
6965: }
1.521 raeburn 6966: } else {
1.772 raeburn 6967: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6968: }
1.793 albertel 6969: foreach my $code (keys(%{$instcodes})) {
6970: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6971: }
6972: chop($courses);
1.772 raeburn 6973: my $ok_response = 0;
6974: my $response;
6975: while (@homeservers > 0 && $ok_response == 0) {
6976: my $server = shift(@homeservers);
6977: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6978: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6979: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6980: split(/:/,$response);
1.772 raeburn 6981: %{$codes} = (%{$codes},&str2hash($codes_str));
6982: push(@{$codetitles},&str2array($codetitles_str));
6983: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6984: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6985: $ok_response = 1;
6986: }
6987: }
6988: if ($ok_response) {
1.521 raeburn 6989: return 'ok';
1.772 raeburn 6990: } else {
6991: return $response;
1.521 raeburn 6992: }
6993: }
6994:
1.792 raeburn 6995: sub auto_instcode_defaults {
6996: my ($domain,$returnhash,$code_order) = @_;
6997: my @homeservers;
1.841 albertel 6998:
6999: my %servers = &get_servers($domain,'library');
7000: foreach my $tryserver (keys(%servers)) {
7001: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7002: push(@homeservers,$tryserver);
7003: }
1.792 raeburn 7004: }
1.841 albertel 7005:
1.792 raeburn 7006: my $response;
1.841 albertel 7007: foreach my $server (@homeservers) {
1.792 raeburn 7008: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7009: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7010:
7011: foreach my $pair (split(/\&/,$response)) {
7012: my ($name,$value)=split(/\=/,$pair);
7013: if ($name eq 'code_order') {
7014: @{$code_order} = split(/\&/,&unescape($value));
7015: } else {
7016: $returnhash->{&unescape($name)}=&unescape($value);
7017: }
7018: }
7019: return 'ok';
1.792 raeburn 7020: }
1.841 albertel 7021:
7022: return $response;
1.1003 raeburn 7023: }
7024:
7025: sub auto_possible_instcodes {
1.1007 raeburn 7026: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7027: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7028: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7029: return;
7030: }
1.1003 raeburn 7031: my (@homeservers,$uhome);
7032: if (defined(&domain($domain,'primary'))) {
7033: $uhome=&domain($domain,'primary');
7034: push(@homeservers,&domain($domain,'primary'));
7035: } else {
7036: my %servers = &get_servers($domain,'library');
7037: foreach my $tryserver (keys(%servers)) {
7038: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7039: push(@homeservers,$tryserver);
7040: }
7041: }
7042: }
7043: my $response;
7044: foreach my $server (@homeservers) {
7045: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7046: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7047: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7048: split(':',$response);
7049: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7050: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7051: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7052: my ($name,$value)=split('=',$item);
7053: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7054: }
7055: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7056: my ($name,$value)=split('=',$item);
7057: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7058: }
7059: return 'ok';
7060: }
7061: return $response;
7062: }
1.792 raeburn 7063:
1.1010 raeburn 7064: sub auto_courserequest_checks {
7065: my ($dom) = @_;
1.1020 raeburn 7066: my ($homeserver,%validations);
7067: if ($dom =~ /^$match_domain$/) {
7068: $homeserver = &domain($dom,'primary');
7069: }
7070: unless ($homeserver eq 'no_host') {
7071: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7072: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7073: my @items = split(/&/,$response);
7074: foreach my $item (@items) {
7075: my ($key,$value) = split('=',$item);
7076: $validations{&unescape($key)} = &thaw_unescape($value);
7077: }
7078: }
7079: }
1.1010 raeburn 7080: return %validations;
7081: }
7082:
1.1020 raeburn 7083: sub auto_courserequest_validation {
7084: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7085: my ($homeserver,$response);
7086: if ($dom =~ /^$match_domain$/) {
7087: $homeserver = &domain($dom,'primary');
7088: }
7089: unless ($homeserver eq 'no_host') {
1.1021 raeburn 7090:
1.1020 raeburn 7091: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7092: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 7093: ':'.&escape($instcode).':'.&escape($instseclist),
7094: $homeserver));
7095: }
7096: return $response;
7097: }
7098:
1.777 albertel 7099: sub auto_validate_class_sec {
1.918 raeburn 7100: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7101: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7102: my $ownerlist;
7103: if (ref($owners) eq 'ARRAY') {
7104: $ownerlist = join(',',@{$owners});
7105: } else {
7106: $ownerlist = $owners;
7107: }
1.773 raeburn 7108: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7109: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7110: return $response;
7111: }
7112:
1.679 raeburn 7113: # ------------------------------------------------------- Course Group routines
7114:
7115: sub get_coursegroups {
1.809 raeburn 7116: my ($cdom,$cnum,$group,$namespace) = @_;
7117: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7118: }
7119:
1.679 raeburn 7120: sub modify_coursegroup {
7121: my ($cdom,$cnum,$groupsettings) = @_;
7122: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7123: }
7124:
1.809 raeburn 7125: sub toggle_coursegroup_status {
7126: my ($cdom,$cnum,$group,$action) = @_;
7127: my ($from_namespace,$to_namespace);
7128: if ($action eq 'delete') {
7129: $from_namespace = 'coursegroups';
7130: $to_namespace = 'deleted_groups';
7131: } else {
7132: $from_namespace = 'deleted_groups';
7133: $to_namespace = 'coursegroups';
7134: }
7135: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7136: if (my $tmp = &error(%curr_group)) {
7137: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7138: return ('read error',$tmp);
7139: } else {
7140: my %savedsettings = %curr_group;
1.809 raeburn 7141: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7142: my $deloutcome;
7143: if ($result eq 'ok') {
1.809 raeburn 7144: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7145: } else {
7146: return ('write error',$result);
7147: }
7148: if ($deloutcome eq 'ok') {
7149: return 'ok';
7150: } else {
7151: return ('delete error',$deloutcome);
7152: }
7153: }
7154: }
7155:
1.679 raeburn 7156: sub modify_group_roles {
1.957 raeburn 7157: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7158: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7159: my $role = 'gr/'.&escape($userprivs);
7160: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7161: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7162: if ($result eq 'ok') {
7163: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7164: }
1.679 raeburn 7165: return $result;
7166: }
7167:
7168: sub modify_coursegroup_membership {
7169: my ($cdom,$cnum,$membership) = @_;
7170: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7171: return $result;
7172: }
7173:
1.682 raeburn 7174: sub get_active_groups {
7175: my ($udom,$uname,$cdom,$cnum) = @_;
7176: my $now = time;
7177: my %groups = ();
7178: foreach my $key (keys(%env)) {
1.811 albertel 7179: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7180: my ($start,$end) = split(/\./,$env{$key});
7181: if (($end!=0) && ($end<$now)) { next; }
7182: if (($start!=0) && ($start>$now)) { next; }
7183: if ($1 eq $cdom && $2 eq $cnum) {
7184: $groups{$3} = $env{$key} ;
7185: }
7186: }
7187: }
7188: return %groups;
7189: }
7190:
1.683 raeburn 7191: sub get_group_membership {
7192: my ($cdom,$cnum,$group) = @_;
7193: return(&dump('groupmembership',$cdom,$cnum,$group));
7194: }
7195:
7196: sub get_users_groups {
7197: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 7198: my @usersgroups;
1.683 raeburn 7199: my $cachetime=1800;
7200:
7201: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 7202: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7203: if (defined($cached)) {
1.734 albertel 7204: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 7205: } else {
7206: $grouplist = '';
1.816 raeburn 7207: my $courseurl = &courseid_to_courseurl($courseid);
1.1086 raeburn 7208: my $extra = &freeze_escape({'skipcheck' => 1});
7209: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817 raeburn 7210: my $access_end = $env{'course.'.$courseid.
7211: '.default_enrollment_end_date'};
7212: my $now = time;
7213: foreach my $key (keys(%roleshash)) {
7214: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7215: my $group = $1;
7216: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7217: my $start = $2;
7218: my $end = $1;
7219: if ($start == -1) { next; } # deleted from group
7220: if (($start!=0) && ($start>$now)) { next; }
7221: if (($end!=0) && ($end<$now)) {
7222: if ($access_end && $access_end < $now) {
7223: if ($access_end - $end < 86400) {
7224: push(@usersgroups,$group);
1.733 raeburn 7225: }
7226: }
1.817 raeburn 7227: next;
1.733 raeburn 7228: }
1.817 raeburn 7229: push(@usersgroups,$group);
1.683 raeburn 7230: }
7231: }
7232: }
1.817 raeburn 7233: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7234: $grouplist = join(':',@usersgroups);
7235: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 7236: }
1.733 raeburn 7237: return @usersgroups;
1.683 raeburn 7238: }
7239:
7240: sub devalidate_getgroups_cache {
7241: my ($udom,$uname,$cdom,$cnum)=@_;
7242: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 7243:
1.683 raeburn 7244: my $hashid="$udom:$uname:$courseid";
7245: &devalidate_cache_new('getgroups',$hashid);
7246: }
7247:
1.12 www 7248: # ------------------------------------------------------------------ Plain Text
7249:
7250: sub plaintext {
1.988 raeburn 7251: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 7252: if ($short =~ m{^cr/}) {
1.758 albertel 7253: return (split('/',$short))[-1];
7254: }
1.742 raeburn 7255: if (!defined($cid)) {
7256: $cid = $env{'request.course.id'};
7257: }
7258: my %rolenames = (
1.1008 raeburn 7259: Course => 'std',
7260: Community => 'alt1',
1.742 raeburn 7261: );
1.1037 raeburn 7262: if ($cid ne '') {
7263: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
7264: unless ($forcedefault) {
7265: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
7266: &Apache::lonlocal::mt_escape(\$roletext);
7267: return &Apache::lonlocal::mt($roletext);
7268: }
7269: }
7270: }
7271: if ((defined($type)) && (defined($rolenames{$type})) &&
7272: (defined($rolenames{$type})) &&
7273: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 7274: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 7275: } elsif ($cid ne '') {
7276: my $crstype = $env{'course.'.$cid.'.type'};
7277: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7278: (defined($prp{$short}{$rolenames{$crstype}}))) {
7279: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7280: }
1.742 raeburn 7281: }
1.1037 raeburn 7282: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 7283: }
7284:
7285: # ----------------------------------------------------------------- Assign Role
7286:
7287: sub assignrole {
1.957 raeburn 7288: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7289: $context)=@_;
1.21 www 7290: my $mrole;
7291: if ($role =~ /^cr\//) {
1.393 www 7292: my $cwosec=$url;
1.811 albertel 7293: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 7294: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 7295: my $refused = 1;
7296: if ($context eq 'requestcourses') {
7297: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7298: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7299: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7300: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7301: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7302: if ($crsenv{'internal.courseowner'} eq
7303: $env{'user.name'}.':'.$env{'user.domain'}) {
7304: $refused = '';
7305: }
7306: }
7307: }
7308: }
7309: }
7310: if ($refused) {
7311: &logthis('Refused custom assignrole: '.
7312: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7313: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7314: return 'refused';
7315: }
1.104 www 7316: }
1.21 www 7317: $mrole='cr';
1.678 raeburn 7318: } elsif ($role =~ /^gr\//) {
7319: my $cwogrp=$url;
1.811 albertel 7320: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 7321: unless (&allowed('mdg',$cwogrp)) {
7322: &logthis('Refused group assignrole: '.
7323: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7324: $env{'user.name'}.' at '.$env{'user.domain'});
7325: return 'refused';
7326: }
7327: $mrole='gr';
1.21 www 7328: } else {
1.82 www 7329: my $cwosec=$url;
1.811 albertel 7330: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 7331: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7332: my $refused;
7333: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7334: if (!(&allowed('c'.$role,$url))) {
7335: $refused = 1;
7336: }
7337: } else {
7338: $refused = 1;
7339: }
1.947 raeburn 7340: if ($refused) {
1.1045 raeburn 7341: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7342: if (!$selfenroll && $context eq 'course') {
7343: my %crsenv;
7344: if ($role eq 'cc' || $role eq 'co') {
7345: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7346: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7347: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7348: if ($crsenv{'internal.courseowner'} eq
7349: $env{'user.name'}.':'.$env{'user.domain'}) {
7350: $refused = '';
7351: }
7352: }
7353: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7354: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7355: if ($crsenv{'internal.courseowner'} eq
7356: $env{'user.name'}.':'.$env{'user.domain'}) {
7357: $refused = '';
7358: }
7359: }
7360: }
7361: }
7362: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 7363: $refused = '';
1.1017 raeburn 7364: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 7365: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 7366: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 7367: my $wrongcc;
7368: if ($cnum =~ /^$match_community$/) {
7369: $wrongcc = 1 if ($role eq 'cc');
7370: } else {
7371: $wrongcc = 1 if ($role eq 'co');
7372: }
7373: unless ($wrongcc) {
7374: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7375: if ($crsenv{'internal.courseowner'} eq
7376: $env{'user.name'}.':'.$env{'user.domain'}) {
7377: $refused = '';
7378: }
1.1017 raeburn 7379: }
7380: }
7381: }
7382: if ($refused) {
1.947 raeburn 7383: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7384: ' '.$role.' '.$end.' '.$start.' by '.
7385: $env{'user.name'}.' at '.$env{'user.domain'});
7386: return 'refused';
7387: }
1.932 raeburn 7388: }
1.1131 raeburn 7389: } elsif ($role eq 'au') {
7390: if ($url ne '/'.$udom.'/') {
7391: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
7392: ' to assign author role for '.$uname.':'.$udom.
7393: ' in domain: '.$url.' refused (wrong domain).');
7394: return 'refused';
7395: }
1.104 www 7396: }
1.21 www 7397: $mrole=$role;
7398: }
1.620 albertel 7399: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7400: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 7401: if ($end) { $command.='_'.$end; }
1.21 www 7402: if ($start) {
7403: if ($end) {
1.81 www 7404: $command.='_'.$start;
1.21 www 7405: } else {
1.81 www 7406: $command.='_0_'.$start;
1.21 www 7407: }
7408: }
1.739 raeburn 7409: my $origstart = $start;
7410: my $origend = $end;
1.957 raeburn 7411: my $delflag;
1.357 www 7412: # actually delete
7413: if ($deleteflag) {
1.373 www 7414: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 7415: # modify command to delete the role
1.620 albertel 7416: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 7417: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 7418: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 7419: # set start and finish to negative values for userrolelog
7420: $start=-1;
7421: $end=-1;
1.957 raeburn 7422: $delflag = 1;
1.357 www 7423: }
7424: }
7425: # send command
1.349 www 7426: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 7427: # log new user role if status is ok
1.349 www 7428: if ($answer eq 'ok') {
1.663 raeburn 7429: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 7430: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 7431: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 7432: unless ($role =~ /^gr/) {
7433: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 7434: $origstart,$selfenroll,$context);
1.739 raeburn 7435: }
1.1053 raeburn 7436: if ($role eq 'cc') {
7437: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7438: }
1.349 www 7439: }
7440: return $answer;
1.169 harris41 7441: }
7442:
1.1053 raeburn 7443: sub autoupdate_coowners {
7444: my ($url,$end,$start,$uname,$udom) = @_;
7445: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7446: if (($cdom ne '') && ($cnum ne '')) {
7447: my $now = time;
7448: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7449: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7450: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7451: my $instcode = $coursehash{'internal.coursecode'};
7452: if ($instcode ne '') {
1.1056 raeburn 7453: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7454: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 7455: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 7456: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7457: if ($result eq 'valid') {
7458: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 7459: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7460: push(@newcoowners,$coowner);
7461: }
7462: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7463: push(@newcoowners,$uname.':'.$udom);
7464: }
7465: @newcoowners = sort(@newcoowners);
7466: } else {
7467: push(@newcoowners,$uname.':'.$udom);
7468: }
7469: } else {
7470: if ($coursehash{'internal.co-owners'}) {
7471: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7472: unless ($coowner eq $uname.':'.$udom) {
7473: push(@newcoowners,$coowner);
7474: }
7475: }
7476: unless (@newcoowners > 0) {
7477: $delcoowners = 1;
7478: $coowners = '';
7479: }
7480: }
7481: }
7482: if (@newcoowners || $delcoowners) {
7483: &store_coowners($cdom,$cnum,$coursehash{'home'},
7484: $delcoowners,@newcoowners);
7485: }
7486: }
7487: }
7488: }
7489: }
7490: }
7491: }
7492:
7493: sub store_coowners {
7494: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7495: my $cid = $cdom.'_'.$cnum;
7496: my ($coowners,$delresult,$putresult);
7497: if (@newcoowners) {
7498: $coowners = join(',',@newcoowners);
7499: my %coownershash = (
7500: 'internal.co-owners' => $coowners,
7501: );
7502: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7503: if ($putresult eq 'ok') {
7504: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7505: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7506: }
7507: }
7508: }
7509: if ($delcoowners) {
7510: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7511: if ($delresult eq 'ok') {
7512: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7513: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7514: }
7515: }
7516: }
7517: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7518: my %crsinfo =
7519: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7520: if (ref($crsinfo{$cid}) eq 'HASH') {
7521: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7522: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7523: }
7524: }
7525: }
7526:
1.169 harris41 7527: # -------------------------------------------------- Modify user authentication
1.197 www 7528: # Overrides without validation
7529:
1.169 harris41 7530: sub modifyuserauth {
7531: my ($udom,$uname,$umode,$upass)=@_;
7532: my $uhome=&homeserver($uname,$udom);
1.197 www 7533: unless (&allowed('mau',$udom)) { return 'refused'; }
7534: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 7535: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7536: ' in domain '.$env{'request.role.domain'});
1.169 harris41 7537: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7538: &escape($upass),$uhome);
1.620 albertel 7539: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 7540: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7541: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7542: &log($udom,,$uname,$uhome,
1.620 albertel 7543: 'Authentication changed by '.$env{'user.domain'}.', '.
7544: $env{'user.name'}.', '.$umode.
1.197 www 7545: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 7546: unless ($reply eq 'ok') {
1.197 www 7547: &logthis('Authentication mode error: '.$reply);
1.169 harris41 7548: return 'error: '.$reply;
7549: }
1.170 harris41 7550: return 'ok';
1.80 www 7551: }
7552:
1.81 www 7553: # --------------------------------------------------------------- Modify a user
1.80 www 7554:
1.81 www 7555: sub modifyuser {
1.206 matthew 7556: my ($udom, $uname, $uid,
7557: $umode, $upass, $first,
7558: $middle, $last, $gene,
1.1058 raeburn 7559: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 7560: $udom= &LONCAPA::clean_domain($udom);
7561: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 7562: my $showcandelete = 'none';
7563: if (ref($candelete) eq 'ARRAY') {
7564: if (@{$candelete} > 0) {
7565: $showcandelete = join(', ',@{$candelete});
7566: }
7567: }
1.81 www 7568: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 7569: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 7570: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 7571: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7572: ' desiredhome not specified').
1.620 albertel 7573: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7574: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 7575: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 7576: my $newuser;
7577: if ($uhome eq 'no_host') {
7578: $newuser = 1;
7579: }
1.80 www 7580: # ----------------------------------------------------------------- Create User
1.406 albertel 7581: if (($uhome eq 'no_host') &&
7582: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 7583: my $unhome='';
1.844 albertel 7584: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 7585: $unhome = $desiredhome;
1.620 albertel 7586: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7587: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 7588: } else { # load balancing routine for determining $unhome
1.81 www 7589: my $loadm=10000000;
1.841 albertel 7590: my %servers = &get_servers($udom,'library');
7591: foreach my $tryserver (keys(%servers)) {
7592: my $answer=reply('load',$tryserver);
7593: if (($answer=~/\d+/) && ($answer<$loadm)) {
7594: $loadm=$answer;
7595: $unhome=$tryserver;
7596: }
1.80 www 7597: }
7598: }
7599: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 7600: return 'error: unable to find a home server for '.$uname.
7601: ' in domain '.$udom;
1.80 www 7602: }
7603: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7604: &escape($upass),$unhome);
7605: unless ($reply eq 'ok') {
7606: return 'error: '.$reply;
7607: }
1.230 stredwic 7608: $uhome=&homeserver($uname,$udom,'true');
1.80 www 7609: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 7610: return 'error: unable verify users home machine.';
1.80 www 7611: }
1.209 matthew 7612: } # End of creation of new user
1.80 www 7613: # ---------------------------------------------------------------------- Add ID
7614: if ($uid) {
7615: $uid=~tr/A-Z/a-z/;
7616: my %uidhash=&idrget($udom,$uname);
1.196 www 7617: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7618: && (!$forceid)) {
1.80 www 7619: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 7620: return 'error: user id "'.$uid.'" does not match '.
7621: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 7622: }
7623: } else {
7624: &idput($udom,($uname => $uid));
7625: }
7626: }
7627: # -------------------------------------------------------------- Add names, etc
1.313 matthew 7628: my @tmp=&get('environment',
1.899 raeburn 7629: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 7630: 'permanentemail','inststatus'],
1.134 albertel 7631: $udom,$uname);
1.1075 raeburn 7632: my (%names,%oldnames);
1.313 matthew 7633: if ($tmp[0] =~ m/^error:.*/) {
7634: %names=();
7635: } else {
7636: %names = @tmp;
1.1075 raeburn 7637: %oldnames = %names;
1.313 matthew 7638: }
1.388 www 7639: #
1.1058 raeburn 7640: # If name, email and/or uid are blank (e.g., because an uploaded file
7641: # of users did not contain them), do not overwrite existing values
7642: # unless field is in $candelete array ref.
7643: #
7644:
7645: my @fields = ('firstname','middlename','lastname','generation',
7646: 'permanentemail','id');
7647: my %newvalues;
7648: if (ref($candelete) eq 'ARRAY') {
7649: foreach my $field (@fields) {
7650: if (grep(/^\Q$field\E$/,@{$candelete})) {
7651: if ($field eq 'firstname') {
7652: $names{$field} = $first;
7653: } elsif ($field eq 'middlename') {
7654: $names{$field} = $middle;
7655: } elsif ($field eq 'lastname') {
7656: $names{$field} = $last;
7657: } elsif ($field eq 'generation') {
7658: $names{$field} = $gene;
7659: } elsif ($field eq 'permanentemail') {
7660: $names{$field} = $email;
7661: } elsif ($field eq 'id') {
7662: $names{$field} = $uid;
7663: }
7664: }
7665: }
7666: }
1.388 www 7667: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 7668: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 7669: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 7670: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 7671: if ($email) {
7672: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 7673: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 7674: }
1.899 raeburn 7675: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 7676: if (defined($inststatus)) {
7677: $names{'inststatus'} = '';
7678: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7679: if (ref($usertypes) eq 'HASH') {
7680: my @okstatuses;
7681: foreach my $item (split(/:/,$inststatus)) {
7682: if (defined($usertypes->{$item})) {
7683: push(@okstatuses,$item);
7684: }
7685: }
7686: if (@okstatuses) {
7687: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7688: }
7689: }
7690: }
1.1075 raeburn 7691: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 7692: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 7693: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 7694: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7695: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7696: } else {
7697: $logmsg .= ' during self creation';
7698: }
1.1075 raeburn 7699: my $changed;
7700: if ($newuser) {
7701: $changed = 1;
7702: } else {
7703: foreach my $field (@fields) {
7704: if ($names{$field} ne $oldnames{$field}) {
7705: $changed = 1;
7706: last;
7707: }
7708: }
7709: }
7710: unless ($changed) {
7711: $logmsg = 'No changes in user information needed for: '.$logmsg;
7712: &logthis($logmsg);
7713: return 'ok';
7714: }
7715: my $reply = &put('environment', \%names, $udom,$uname);
7716: if ($reply ne 'ok') {
7717: return 'error: '.$reply;
7718: }
1.1087 raeburn 7719: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7720: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7721: }
1.1075 raeburn 7722: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7723: &devalidate_cache_new('namescache',$uname.':'.$udom);
7724: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7725: &logthis($logmsg);
1.134 albertel 7726: return 'ok';
1.80 www 7727: }
7728:
1.81 www 7729: # -------------------------------------------------------------- Modify student
1.80 www 7730:
1.81 www 7731: sub modifystudent {
7732: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7733: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7734: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7735: if (!$cid) {
1.620 albertel 7736: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7737: return 'not_in_class';
7738: }
1.80 www 7739: }
7740: # --------------------------------------------------------------- Make the user
1.81 www 7741: my $reply=&modifyuser
1.209 matthew 7742: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7743: $desiredhome,$email,$inststatus);
1.80 www 7744: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7745: # This will cause &modify_student_enrollment to get the uid from the
7746: # students environment
7747: $uid = undef if (!$forceid);
1.455 albertel 7748: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7749: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7750: return $reply;
7751: }
7752:
7753: sub modify_student_enrollment {
1.957 raeburn 7754: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7755: my ($cdom,$cnum,$chome);
7756: if (!$cid) {
1.620 albertel 7757: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7758: return 'not_in_class';
7759: }
1.620 albertel 7760: $cdom=$env{'course.'.$cid.'.domain'};
7761: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7762: } else {
7763: ($cdom,$cnum)=split(/_/,$cid);
7764: }
1.620 albertel 7765: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7766: if (!$chome) {
1.457 raeburn 7767: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7768: }
1.455 albertel 7769: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7770: # Make sure the user exists
1.81 www 7771: my $uhome=&homeserver($uname,$udom);
7772: if (($uhome eq '') || ($uhome eq 'no_host')) {
7773: return 'error: no such user';
7774: }
1.297 matthew 7775: # Get student data if we were not given enough information
7776: if (!defined($first) || $first eq '' ||
7777: !defined($last) || $last eq '' ||
7778: !defined($uid) || $uid eq '' ||
7779: !defined($middle) || $middle eq '' ||
7780: !defined($gene) || $gene eq '') {
1.294 matthew 7781: # They did not supply us with enough data to enroll the student, so
7782: # we need to pick up more information.
1.297 matthew 7783: my %tmp = &get('environment',
1.294 matthew 7784: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7785: ,$udom,$uname);
7786:
1.800 albertel 7787: #foreach my $key (keys(%tmp)) {
7788: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7789: #}
1.294 matthew 7790: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7791: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7792: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7793: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7794: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7795: }
1.556 albertel 7796: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 7797: my $user = "$uname:$udom";
7798: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 7799: my $reply=cput('classlist',
1.1148 raeburn 7800: {$user =>
1.515 raeburn 7801: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7802: $cdom,$cnum);
1.1148 raeburn 7803: if (($reply eq 'ok') || ($reply eq 'delayed')) {
7804: &devalidate_getsection_cache($udom,$uname,$cid);
7805: } else {
1.81 www 7806: return 'error: '.$reply;
7807: }
1.297 matthew 7808: # Add student role to user
1.83 www 7809: my $uurl='/'.$cid;
1.81 www 7810: $uurl=~s/\_/\//g;
7811: if ($usec) {
7812: $uurl.='/'.$usec;
7813: }
1.1148 raeburn 7814: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
7815: $selfenroll,$context);
7816: if ($result ne 'ok') {
7817: if ($old_entry{$user} ne '') {
7818: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
7819: } else {
7820: $reply = &del('classlist',[$user],$cdom,$cnum);
7821: }
7822: }
7823: return $result;
1.21 www 7824: }
7825:
1.556 albertel 7826: sub format_name {
7827: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7828: my $name;
7829: if ($first ne 'lastname') {
7830: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7831: } else {
7832: if ($lastname=~/\S/) {
7833: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7834: $name=~s/\s+,/,/;
7835: } else {
7836: $name.= $firstname.' '.$middlename.' '.$generation;
7837: }
7838: }
7839: $name=~s/^\s+//;
7840: $name=~s/\s+$//;
7841: $name=~s/\s+/ /g;
7842: return $name;
7843: }
7844:
1.84 www 7845: # ------------------------------------------------- Write to course preferences
7846:
7847: sub writecoursepref {
7848: my ($courseid,%prefs)=@_;
7849: $courseid=~s/^\///;
7850: $courseid=~s/\_/\//g;
7851: my ($cdomain,$cnum)=split(/\//,$courseid);
7852: my $chome=homeserver($cnum,$cdomain);
7853: if (($chome eq '') || ($chome eq 'no_host')) {
7854: return 'error: no such course';
7855: }
7856: my $cstring='';
1.800 albertel 7857: foreach my $pref (keys(%prefs)) {
7858: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7859: }
1.84 www 7860: $cstring=~s/\&$//;
7861: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7862: }
7863:
7864: # ---------------------------------------------------------- Make/modify course
7865:
7866: sub createcourse {
1.741 raeburn 7867: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7868: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7869: $url=&declutter($url);
7870: my $cid='';
1.1028 raeburn 7871: if ($context eq 'requestcourses') {
7872: my $can_create = 0;
7873: my ($ownername,$ownerdom) = split(':',$course_owner);
7874: if ($udom eq $ownerdom) {
7875: if (&usertools_access($ownername,$ownerdom,$category,undef,
7876: $context)) {
7877: $can_create = 1;
7878: }
7879: } else {
7880: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7881: $category);
7882: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7883: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7884: if (@curr > 0) {
7885: my @options = qw(approval validate autolimit);
7886: my $optregex = join('|',@options);
7887: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7888: $can_create = 1;
7889: }
7890: }
7891: }
7892: }
7893: if ($can_create) {
7894: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7895: unless (&allowed('ccc',$udom)) {
7896: return 'refused';
7897: }
1.1017 raeburn 7898: }
7899: } else {
7900: return 'refused';
7901: }
1.1028 raeburn 7902: } elsif (!&allowed('ccc',$udom)) {
7903: return 'refused';
1.84 www 7904: }
1.1011 raeburn 7905: # --------------------------------------------------------------- Get Unique ID
7906: my $uname;
7907: if ($cnum =~ /^$match_courseid$/) {
7908: my $chome=&homeserver($cnum,$udom,'true');
7909: if (($chome eq '') || ($chome eq 'no_host')) {
7910: $uname = $cnum;
7911: } else {
1.1038 raeburn 7912: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7913: }
7914: } else {
1.1038 raeburn 7915: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7916: }
7917: return $uname if ($uname =~ /^error/);
7918: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7919: if (!defined($course_server)) {
7920: if (defined(&domain($udom,'primary'))) {
7921: $course_server = &domain($udom,'primary');
7922: } else {
7923: $course_server = $env{'user.home'};
7924: }
7925: }
7926: my %host_servers =
7927: &Apache::lonnet::get_servers($udom,'library');
7928: unless ($host_servers{$course_server}) {
7929: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7930: }
1.84 www 7931: # ------------------------------------------------------------- Make the course
7932: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7933: $course_server);
1.84 www 7934: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7935: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7936: if (($uhome eq '') || ($uhome eq 'no_host')) {
7937: return 'error: no such course';
7938: }
1.271 www 7939: # ----------------------------------------------------------------- Course made
1.516 raeburn 7940: # log existence
1.1029 raeburn 7941: my $now = time;
1.918 raeburn 7942: my $newcourse = {
7943: $udom.'_'.$uname => {
1.921 raeburn 7944: description => $description,
7945: inst_code => $inst_code,
7946: owner => $course_owner,
7947: type => $crstype,
1.1029 raeburn 7948: creator => $env{'user.name'}.':'.
7949: $env{'user.domain'},
7950: created => $now,
7951: context => $context,
1.918 raeburn 7952: },
7953: };
1.921 raeburn 7954: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7955: # set toplevel url
1.271 www 7956: my $topurl=$url;
7957: unless ($nonstandard) {
7958: # ------------------------------------------ For standard courses, make top url
7959: my $mapurl=&clutter($url);
1.278 www 7960: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7961: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7962: <map>
7963: <resource id="1" type="start"></resource>
7964: <resource id="2" src="$mapurl"></resource>
7965: <resource id="3" type="finish"></resource>
7966: <link index="1" from="1" to="2"></link>
7967: <link index="2" from="2" to="3"></link>
7968: </map>
7969: ENDINITMAP
7970: $topurl=&declutter(
1.638 albertel 7971: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7972: );
7973: }
7974: # ----------------------------------------------------------- Write preferences
1.84 www 7975: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7976: ('description' => $description,
7977: 'url' => $topurl,
7978: 'internal.creator' => $env{'user.name'}.':'.
7979: $env{'user.domain'},
7980: 'internal.created' => $now,
7981: 'internal.creationcontext' => $context)
7982: );
1.84 www 7983: return '/'.$udom.'/'.$uname;
7984: }
7985:
1.1011 raeburn 7986: # ------------------------------------------------------------------- Create ID
7987: sub generate_coursenum {
1.1038 raeburn 7988: my ($udom,$crstype) = @_;
1.1011 raeburn 7989: my $domdesc = &domain($udom);
7990: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7991: my $first;
7992: if ($crstype eq 'Community') {
7993: $first = '0';
7994: } else {
7995: $first = int(1+rand(9));
7996: }
7997: my $uname=$first.
1.1011 raeburn 7998: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7999: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8000: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8001: # ----------------------------------------------- Make sure that does not exist
8002: my $uhome=&homeserver($uname,$udom,'true');
8003: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8004: if ($crstype eq 'Community') {
8005: $first = '0';
8006: } else {
8007: $first = int(1+rand(9));
8008: }
8009: $uname=$first.
1.1011 raeburn 8010: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8011: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8012: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8013: $uhome=&homeserver($uname,$udom,'true');
8014: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8015: return 'error: unable to generate unique course-ID';
8016: }
8017: }
8018: return $uname;
8019: }
8020:
1.813 albertel 8021: sub is_course {
8022: my ($cdom,$cnum) = @_;
8023: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 8024: undef,'.');
1.813 albertel 8025: if (exists($courses{$cdom.'_'.$cnum})) {
8026: return 1;
8027: }
8028: return 0;
8029: }
8030:
1.1015 raeburn 8031: sub store_userdata {
8032: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8033: my $result;
1.1016 raeburn 8034: if ($datakey ne '') {
1.1013 raeburn 8035: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8036: if ($udom eq '' || $uname eq '') {
8037: $udom = $env{'user.domain'};
8038: $uname = $env{'user.name'};
8039: }
8040: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8041: if (($uhome eq '') || ($uhome eq 'no_host')) {
8042: $result = 'error: no_host';
8043: } else {
8044: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8045: $storehash->{'host'} = $perlvar{'lonHostID'};
8046:
8047: my $namevalue='';
8048: foreach my $key (keys(%{$storehash})) {
8049: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8050: }
8051: $namevalue=~s/\&$//;
1.1105 raeburn 8052: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8053: $namevalue,$uhome);
1.1013 raeburn 8054: }
8055: } else {
8056: $result = 'error: data to store was not a hash reference';
8057: }
8058: } else {
8059: $result= 'error: invalid requestkey';
8060: }
8061: return $result;
8062: }
8063:
1.21 www 8064: # ---------------------------------------------------------- Assign Custom Role
8065:
8066: sub assigncustomrole {
1.957 raeburn 8067: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8068: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8069: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8070: }
8071:
8072: # ----------------------------------------------------------------- Revoke Role
8073:
8074: sub revokerole {
1.957 raeburn 8075: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8076: my $now=time;
1.965 raeburn 8077: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8078: }
8079:
8080: # ---------------------------------------------------------- Revoke Custom Role
8081:
8082: sub revokecustomrole {
1.957 raeburn 8083: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8084: my $now=time;
1.357 www 8085: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8086: $deleteflag,$selfenroll,$context);
1.17 www 8087: }
8088:
1.533 banghart 8089: # ------------------------------------------------------------ Disk usage
1.535 albertel 8090: sub diskusage {
1.955 raeburn 8091: my ($udom,$uname,$directorypath,$getpropath)=@_;
8092: $directorypath =~ s/\/$//;
8093: my $listing=&reply('du2:'.&escape($directorypath).':'
8094: .&escape($getpropath).':'.&escape($uname).':'
8095: .&escape($udom),homeserver($uname,$udom));
8096: if ($listing eq 'unknown_cmd') {
8097: if ($getpropath) {
8098: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8099: }
8100: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8101: }
1.514 albertel 8102: return $listing;
1.512 banghart 8103: }
8104:
1.566 banghart 8105: sub is_locked {
1.1096 raeburn 8106: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8107: my @check;
8108: my $is_locked;
1.1093 raeburn 8109: push (@check,$file_name);
1.613 albertel 8110: my %locked = &get('file_permissions',\@check,
1.620 albertel 8111: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8112: my ($tmp)=keys(%locked);
8113: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8114:
1.566 banghart 8115: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8116: $is_locked = 'false';
8117: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8118: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8119: $is_locked = 'true';
1.1096 raeburn 8120: if (ref($which) eq 'ARRAY') {
8121: push(@{$which},$entry);
8122: } else {
8123: last;
8124: }
1.745 raeburn 8125: }
8126: }
1.566 banghart 8127: } else {
8128: $is_locked = 'false';
8129: }
1.1093 raeburn 8130: return $is_locked;
1.566 banghart 8131: }
8132:
1.759 albertel 8133: sub declutter_portfile {
8134: my ($file) = @_;
1.833 albertel 8135: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 8136: return $file;
8137: }
8138:
1.559 banghart 8139: # ------------------------------------------------------------- Mark as Read Only
8140:
8141: sub mark_as_readonly {
8142: my ($domain,$user,$files,$what) = @_;
1.613 albertel 8143: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8144: my ($tmp)=keys(%current_permissions);
8145: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 8146: foreach my $file (@{$files}) {
1.759 albertel 8147: $file = &declutter_portfile($file);
1.561 banghart 8148: push(@{$current_permissions{$file}},$what);
1.559 banghart 8149: }
1.613 albertel 8150: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8151: return;
8152: }
8153:
1.572 banghart 8154: # ------------------------------------------------------------Save Selected Files
8155:
8156: sub save_selected_files {
8157: my ($user, $path, @files) = @_;
8158: my $filename = $user."savedfiles";
1.573 banghart 8159: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 8160: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 8161: foreach my $file (@files) {
1.620 albertel 8162: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 8163: }
8164: foreach my $file (@other_files) {
1.574 banghart 8165: print (OUT $file."\n");
1.572 banghart 8166: }
1.574 banghart 8167: close (OUT);
1.572 banghart 8168: return 'ok';
8169: }
8170:
1.574 banghart 8171: sub clear_selected_files {
8172: my ($user) = @_;
8173: my $filename = $user."savedfiles";
1.1117 foxr 8174: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 8175: print (OUT undef);
8176: close (OUT);
8177: return ("ok");
8178: }
8179:
1.572 banghart 8180: sub files_in_path {
8181: my ($user, $path) = @_;
8182: my $filename = $user."savedfiles";
8183: my %return_files;
1.1117 foxr 8184: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 8185: while (my $line_in = <IN>) {
1.574 banghart 8186: chomp ($line_in);
8187: my @paths_and_file = split (m!/!, $line_in);
8188: my $file_part = pop (@paths_and_file);
8189: my $path_part = join ('/', @paths_and_file);
1.573 banghart 8190: $path_part.='/';
8191: my $path_and_file = $path_part.$file_part;
8192: if ($path_part eq $path) {
8193: $return_files{$file_part}= 'selected';
8194: }
8195: }
1.574 banghart 8196: close (IN);
8197: return (\%return_files);
1.572 banghart 8198: }
8199:
8200: # called in portfolio select mode, to show files selected NOT in current directory
8201: sub files_not_in_path {
8202: my ($user, $path) = @_;
8203: my $filename = $user."savedfiles";
8204: my @return_files;
8205: my $path_part;
1.1117 foxr 8206: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 8207: while (my $line = <IN>) {
1.572 banghart 8208: #ok, I know it's clunky, but I want it to work
1.800 albertel 8209: my @paths_and_file = split(m|/|, $line);
8210: my $file_part = pop(@paths_and_file);
8211: chomp($file_part);
8212: my $path_part = join('/', @paths_and_file);
1.572 banghart 8213: $path_part .= '/';
8214: my $path_and_file = $path_part.$file_part;
8215: if ($path_part ne $path) {
1.800 albertel 8216: push(@return_files, ($path_and_file));
1.572 banghart 8217: }
8218: }
1.800 albertel 8219: close(OUT);
1.574 banghart 8220: return (@return_files);
1.572 banghart 8221: }
8222:
1.745 raeburn 8223: #----------------------------------------------Get portfolio file permissions
1.629 banghart 8224:
1.745 raeburn 8225: sub get_portfile_permissions {
8226: my ($domain,$user) = @_;
1.613 albertel 8227: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8228: my ($tmp)=keys(%current_permissions);
8229: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8230: return \%current_permissions;
8231: }
8232:
8233: #---------------------------------------------Get portfolio file access controls
8234:
1.749 raeburn 8235: sub get_access_controls {
1.745 raeburn 8236: my ($current_permissions,$group,$file) = @_;
1.769 albertel 8237: my %access;
8238: my $real_file = $file;
8239: $file =~ s/\.meta$//;
1.745 raeburn 8240: if (defined($file)) {
1.749 raeburn 8241: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
8242: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 8243: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 8244: }
8245: }
1.745 raeburn 8246: } else {
1.749 raeburn 8247: foreach my $key (keys(%{$current_permissions})) {
8248: if ($key =~ /\0accesscontrol$/) {
8249: if (defined($group)) {
8250: if ($key !~ m-^\Q$group\E/-) {
8251: next;
8252: }
8253: }
8254: my ($fullpath) = split(/\0/,$key);
8255: if (ref($$current_permissions{$key}) eq 'HASH') {
8256: foreach my $control (keys(%{$$current_permissions{$key}})) {
8257: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
8258: }
8259: }
8260: }
8261: }
8262: }
8263: return %access;
8264: }
8265:
8266: sub modify_access_controls {
8267: my ($file_name,$changes,$domain,$user)=@_;
8268: my ($outcome,$deloutcome);
8269: my %store_permissions;
8270: my %new_values;
8271: my %new_control;
8272: my %translation;
8273: my @deletions = ();
8274: my $now = time;
8275: if (exists($$changes{'activate'})) {
8276: if (ref($$changes{'activate'}) eq 'HASH') {
8277: my @newitems = sort(keys(%{$$changes{'activate'}}));
8278: my $numnew = scalar(@newitems);
8279: for (my $i=0; $i<$numnew; $i++) {
8280: my $newkey = $newitems[$i];
8281: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 8282: if ($newkey =~ /^\d+:/) {
8283: $newkey =~ s/^(\d+)/$newid/;
8284: $translation{$1} = $newid;
8285: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
8286: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
8287: $translation{$1} = $newid;
8288: }
1.749 raeburn 8289: $new_values{$file_name."\0".$newkey} =
8290: $$changes{'activate'}{$newitems[$i]};
8291: $new_control{$newkey} = $now;
8292: }
8293: }
8294: }
8295: my %todelete;
8296: my %changed_items;
8297: foreach my $action ('delete','update') {
8298: if (exists($$changes{$action})) {
8299: if (ref($$changes{$action}) eq 'HASH') {
8300: foreach my $key (keys(%{$$changes{$action}})) {
8301: my ($itemnum) = ($key =~ /^([^:]+):/);
8302: if ($action eq 'delete') {
8303: $todelete{$itemnum} = 1;
8304: } else {
8305: $changed_items{$itemnum} = $key;
8306: }
8307: }
1.745 raeburn 8308: }
8309: }
1.749 raeburn 8310: }
8311: # get lock on access controls for file.
8312: my $lockhash = {
8313: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8314: ':'.$env{'user.domain'},
8315: };
8316: my $tries = 0;
8317: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8318:
8319: while (($gotlock ne 'ok') && $tries <3) {
8320: $tries ++;
8321: sleep 1;
8322: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8323: }
8324: if ($gotlock eq 'ok') {
8325: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8326: my ($tmp)=keys(%curr_permissions);
8327: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8328: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8329: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8330: if (ref($curr_controls) eq 'HASH') {
8331: foreach my $control_item (keys(%{$curr_controls})) {
8332: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8333: if (defined($todelete{$itemnum})) {
8334: push(@deletions,$file_name."\0".$control_item);
8335: } else {
8336: if (defined($changed_items{$itemnum})) {
8337: $new_control{$changed_items{$itemnum}} = $now;
8338: push(@deletions,$file_name."\0".$control_item);
8339: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8340: } else {
8341: $new_control{$control_item} = $$curr_controls{$control_item};
8342: }
8343: }
1.745 raeburn 8344: }
8345: }
8346: }
1.970 raeburn 8347: my ($group);
8348: if (&is_course($domain,$user)) {
8349: ($group,my $file) = split(/\//,$file_name,2);
8350: }
1.749 raeburn 8351: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8352: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8353: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8354: # remove lock
8355: my @del_lock = ($file_name."\0".'locked_access_records');
8356: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 8357: my $sqlresult =
1.970 raeburn 8358: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 8359: $group);
1.749 raeburn 8360: } else {
8361: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 8362: }
1.749 raeburn 8363: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 8364: }
8365:
1.827 raeburn 8366: sub make_public_indefinitely {
8367: my ($requrl) = @_;
8368: my $now = time;
8369: my $action = 'activate';
8370: my $aclnum = 0;
8371: if (&is_portfolio_url($requrl)) {
8372: my (undef,$udom,$unum,$file_name,$group) =
8373: &parse_portfolio_url($requrl);
8374: my $current_perms = &get_portfile_permissions($udom,$unum);
8375: my %access_controls = &get_access_controls($current_perms,
8376: $group,$file_name);
8377: foreach my $key (keys(%{$access_controls{$file_name}})) {
8378: my ($num,$scope,$end,$start) =
8379: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8380: if ($scope eq 'public') {
8381: if ($start <= $now && $end == 0) {
8382: $action = 'none';
8383: } else {
8384: $action = 'update';
8385: $aclnum = $num;
8386: }
8387: last;
8388: }
8389: }
8390: if ($action eq 'none') {
8391: return 'ok';
8392: } else {
8393: my %changes;
8394: my $newend = 0;
8395: my $newstart = $now;
8396: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8397: $changes{$action}{$newkey} = {
8398: type => 'public',
8399: time => {
8400: start => $newstart,
8401: end => $newend,
8402: },
8403: };
8404: my ($outcome,$deloutcome,$new_values,$translation) =
8405: &modify_access_controls($file_name,\%changes,$udom,$unum);
8406: return $outcome;
8407: }
8408: } else {
8409: return 'invalid';
8410: }
8411: }
8412:
1.745 raeburn 8413: #------------------------------------------------------Get Marked as Read Only
8414:
8415: sub get_marked_as_readonly {
8416: my ($domain,$user,$what,$group) = @_;
8417: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 8418: my @readonly_files;
1.629 banghart 8419: my $cmp1=$what;
8420: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 8421: while (my ($file_name,$value) = each(%{$current_permissions})) {
8422: if (defined($group)) {
8423: if ($file_name !~ m-^\Q$group\E/-) {
8424: next;
8425: }
8426: }
1.561 banghart 8427: if (ref($value) eq "ARRAY"){
8428: foreach my $stored_what (@{$value}) {
1.629 banghart 8429: my $cmp2=$stored_what;
1.759 albertel 8430: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 8431: $cmp2=join('',@{$stored_what});
1.745 raeburn 8432: }
1.629 banghart 8433: if ($cmp1 eq $cmp2) {
1.561 banghart 8434: push(@readonly_files, $file_name);
1.745 raeburn 8435: last;
1.563 banghart 8436: } elsif (!defined($what)) {
8437: push(@readonly_files, $file_name);
1.745 raeburn 8438: last;
1.561 banghart 8439: }
8440: }
1.745 raeburn 8441: }
1.561 banghart 8442: }
8443: return @readonly_files;
8444: }
1.577 banghart 8445: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 8446:
1.577 banghart 8447: sub get_marked_as_readonly_hash {
1.745 raeburn 8448: my ($current_permissions,$group,$what) = @_;
1.577 banghart 8449: my %readonly_files;
1.745 raeburn 8450: while (my ($file_name,$value) = each(%{$current_permissions})) {
8451: if (defined($group)) {
8452: if ($file_name !~ m-^\Q$group\E/-) {
8453: next;
8454: }
8455: }
1.577 banghart 8456: if (ref($value) eq "ARRAY"){
8457: foreach my $stored_what (@{$value}) {
1.745 raeburn 8458: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 8459: foreach my $lock_descriptor(@{$stored_what}) {
8460: if ($lock_descriptor eq 'graded') {
8461: $readonly_files{$file_name} = 'graded';
8462: } elsif ($lock_descriptor eq 'handback') {
8463: $readonly_files{$file_name} = 'handback';
8464: } else {
8465: if (!exists($readonly_files{$file_name})) {
8466: $readonly_files{$file_name} = 'locked';
8467: }
8468: }
1.745 raeburn 8469: }
1.750 banghart 8470: }
1.577 banghart 8471: }
8472: }
8473: }
8474: return %readonly_files;
8475: }
1.559 banghart 8476: # ------------------------------------------------------------ Unmark as Read Only
8477:
8478: sub unmark_as_readonly {
1.629 banghart 8479: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8480: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 8481: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 8482: $file_name = &declutter_portfile($file_name);
1.634 albertel 8483: my $symb_crs = $what;
8484: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 8485: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 8486: my ($tmp)=keys(%current_permissions);
8487: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8488: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 8489: foreach my $file (@readonly_files) {
1.759 albertel 8490: my $clean_file = &declutter_portfile($file);
8491: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 8492: my $current_locks = $current_permissions{$file};
1.563 banghart 8493: my @new_locks;
8494: my @del_keys;
8495: if (ref($current_locks) eq "ARRAY"){
8496: foreach my $locker (@{$current_locks}) {
1.632 albertel 8497: my $compare=$locker;
1.749 raeburn 8498: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 8499: $compare=join('',@{$locker});
1.746 raeburn 8500: if ($compare ne $symb_crs) {
8501: push(@new_locks, $locker);
8502: }
1.563 banghart 8503: }
8504: }
1.650 albertel 8505: if (scalar(@new_locks) > 0) {
1.563 banghart 8506: $current_permissions{$file} = \@new_locks;
8507: } else {
8508: push(@del_keys, $file);
1.613 albertel 8509: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 8510: delete($current_permissions{$file});
1.563 banghart 8511: }
8512: }
1.561 banghart 8513: }
1.613 albertel 8514: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8515: return;
8516: }
1.512 banghart 8517:
1.17 www 8518: # ------------------------------------------------------------ Directory lister
8519:
8520: sub dirlist {
1.955 raeburn 8521: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 8522: $uri=~s/^\///;
8523: $uri=~s/\/$//;
1.253 stredwic 8524: my ($udom, $uname);
1.955 raeburn 8525: if ($getuserdir) {
1.253 stredwic 8526: $udom = $userdomain;
8527: $uname = $username;
1.955 raeburn 8528: } else {
8529: (undef,$udom,$uname)=split(/\//,$uri);
8530: if(defined($userdomain)) {
8531: $udom = $userdomain;
8532: }
8533: if(defined($username)) {
8534: $uname = $username;
8535: }
1.253 stredwic 8536: }
1.955 raeburn 8537: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 8538:
1.955 raeburn 8539: $dirRoot = $perlvar{'lonDocRoot'};
8540: if (defined($getpropath)) {
8541: $dirRoot = &propath($udom,$uname);
1.253 stredwic 8542: $dirRoot =~ s/\/$//;
1.955 raeburn 8543: } elsif (defined($getuserdir)) {
8544: my $subdir=$uname.'__';
8545: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8546: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8547: ."/$udom/$subdir/$uname";
8548: } elsif (defined($alternateRoot)) {
8549: $dirRoot = $alternateRoot;
1.751 banghart 8550: }
1.253 stredwic 8551:
8552: if($udom) {
8553: if($uname) {
1.1135 raeburn 8554: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 8555: if ($uhome eq 'no_host') {
8556: return ([],'no_host');
8557: }
1.955 raeburn 8558: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 8559: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 8560: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 8561: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8562: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 8563: } else {
8564: @listing_results = map { &unescape($_); } split(/:/,$listing);
8565: }
1.605 matthew 8566: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8567: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 8568: @listing_results = split(/:/,$listing);
8569: } else {
8570: @listing_results = map { &unescape($_); } split(/:/,$listing);
8571: }
1.1135 raeburn 8572: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 8573: ($listing eq 'rejected') || ($listing eq 'refused') ||
8574: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8575: return ([],$listing);
8576: } else {
8577: return (\@listing_results);
1.1135 raeburn 8578: }
1.955 raeburn 8579: } elsif(!$alternateRoot) {
1.1136 raeburn 8580: my (%allusers,%listerror);
1.841 albertel 8581: my %servers = &get_servers($udom,'library');
1.955 raeburn 8582: foreach my $tryserver (keys(%servers)) {
8583: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8584: &escape($udom),$tryserver);
8585: if ($listing eq 'unknown_cmd') {
8586: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8587: $udom, $tryserver);
8588: } else {
8589: @listing_results = map { &unescape($_); } split(/:/,$listing);
8590: }
1.841 albertel 8591: if ($listing eq 'unknown_cmd') {
8592: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8593: $udom, $tryserver);
8594: @listing_results = split(/:/,$listing);
8595: } else {
8596: @listing_results =
8597: map { &unescape($_); } split(/:/,$listing);
8598: }
1.1136 raeburn 8599: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8600: ($listing eq 'rejected') || ($listing eq 'refused') ||
8601: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8602: $listerror{$tryserver} = $listing;
8603: } else {
1.841 albertel 8604: foreach my $line (@listing_results) {
8605: my ($entry) = split(/&/,$line,2);
8606: $allusers{$entry} = 1;
8607: }
8608: }
1.253 stredwic 8609: }
1.1136 raeburn 8610: my @alluserslist=();
1.800 albertel 8611: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 8612: push(@alluserslist,$user.'&user');
1.253 stredwic 8613: }
1.1136 raeburn 8614: return (\@alluserslist);
1.253 stredwic 8615: } else {
1.1136 raeburn 8616: return ([],'missing username');
1.253 stredwic 8617: }
1.955 raeburn 8618: } elsif(!defined($getpropath)) {
1.1136 raeburn 8619: my $path = $perlvar{'lonDocRoot'}.'/res/';
8620: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
8621: return (\@all_domains);
1.955 raeburn 8622: } else {
1.1136 raeburn 8623: return ([],'missing domain');
1.275 stredwic 8624: }
8625: }
8626:
8627: # --------------------------------------------- GetFileTimestamp
8628: # This function utilizes dirlist and returns the date stamp for
8629: # when it was last modified. It will also return an error of -1
8630: # if an error occurs
8631:
8632: sub GetFileTimestamp {
1.955 raeburn 8633: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 8634: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8635: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 8636: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
8637: undef,$getuserdir);
8638: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8639: return -1;
8640: }
8641: if (ref($fileref) eq 'ARRAY') {
8642: my @stats = split('&',$fileref->[0]);
1.375 matthew 8643: # @stats contains first the filename, then the stat output
8644: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 8645: } else {
8646: return -1;
1.253 stredwic 8647: }
1.26 www 8648: }
8649:
1.712 albertel 8650: sub stat_file {
8651: my ($uri) = @_;
1.787 albertel 8652: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 8653:
1.955 raeburn 8654: my ($udom,$uname,$file);
1.712 albertel 8655: if ($uri =~ m-^/(uploaded|editupload)/-) {
8656: ($udom,$uname,$file) =
1.811 albertel 8657: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 8658: $file = 'userfiles/'.$file;
8659: }
8660: if ($uri =~ m-^/res/-) {
8661: ($udom,$uname) =
1.807 albertel 8662: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 8663: $file = $uri;
8664: }
8665:
8666: if (!$udom || !$uname || !$file) {
8667: # unable to handle the uri
8668: return ();
8669: }
1.956 raeburn 8670: my $getpropath;
8671: if ($file =~ /^userfiles\//) {
8672: $getpropath = 1;
8673: }
1.1136 raeburn 8674: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
8675: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8676: return ();
8677: } else {
8678: if (ref($listref) eq 'ARRAY') {
8679: my @stats = split('&',$listref->[0]);
8680: shift(@stats); #filename is first
8681: return @stats;
8682: }
1.712 albertel 8683: }
8684: return ();
8685: }
8686:
1.26 www 8687: # -------------------------------------------------------- Value of a Condition
8688:
1.713 albertel 8689: # gets the value of a specific preevaluated condition
8690: # stored in the string $env{user.state.<cid>}
8691: # or looks up a condition reference in the bighash and if if hasn't
8692: # already been evaluated recurses into docondval to get the value of
8693: # the condition, then memoizing it to
8694: # $env{user.state.<cid>.<condition>}
1.40 www 8695: sub directcondval {
8696: my $number=shift;
1.620 albertel 8697: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 8698: &Apache::lonuserstate::evalstate();
8699: }
1.713 albertel 8700: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8701: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8702: } elsif ($number =~ /^_/) {
8703: my $sub_condition;
8704: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8705: &GDBM_READER(),0640)) {
8706: $sub_condition=$bighash{'conditions'.$number};
8707: untie(%bighash);
8708: }
8709: my $value = &docondval($sub_condition);
1.949 raeburn 8710: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 8711: return $value;
8712: }
1.620 albertel 8713: if ($env{'user.state.'.$env{'request.course.id'}}) {
8714: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 8715: } else {
8716: return 2;
8717: }
8718: }
8719:
1.713 albertel 8720: # get the collection of conditions for this resource
1.26 www 8721: sub condval {
8722: my $condidx=shift;
1.54 www 8723: my $allpathcond='';
1.713 albertel 8724: foreach my $cond (split(/\|/,$condidx)) {
8725: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8726: $allpathcond.=
8727: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8728: }
1.191 harris41 8729: }
1.54 www 8730: $allpathcond=~s/\|$//;
1.713 albertel 8731: return &docondval($allpathcond);
8732: }
8733:
8734: #evaluates an expression of conditions
8735: sub docondval {
8736: my ($allpathcond) = @_;
8737: my $result=0;
8738: if ($env{'request.course.id'}
8739: && defined($allpathcond)) {
8740: my $operand='|';
8741: my @stack;
8742: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8743: if ($chunk eq '(') {
8744: push @stack,($operand,$result);
8745: } elsif ($chunk eq ')') {
8746: my $before=pop @stack;
8747: if (pop @stack eq '&') {
8748: $result=$result>$before?$before:$result;
8749: } else {
8750: $result=$result>$before?$result:$before;
8751: }
8752: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8753: $operand=$chunk;
8754: } else {
8755: my $new=directcondval($chunk);
8756: if ($operand eq '&') {
8757: $result=$result>$new?$new:$result;
8758: } else {
8759: $result=$result>$new?$result:$new;
8760: }
8761: }
8762: }
1.26 www 8763: }
8764: return $result;
1.421 albertel 8765: }
8766:
8767: # ---------------------------------------------------- Devalidate courseresdata
8768:
8769: sub devalidatecourseresdata {
8770: my ($coursenum,$coursedomain)=@_;
8771: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8772: &devalidate_cache_new('courseres',$hashid);
1.28 www 8773: }
8774:
1.763 www 8775:
1.200 www 8776: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8777: #
8778: # Parameters:
8779: # $coursenum - Number of the course.
8780: # $coursedomain - Domain at which the course was created.
8781: # Returns:
8782: # A hash of the course parameters along (I think) with timestamps
8783: # and version info.
1.877 foxr 8784:
1.624 albertel 8785: sub get_courseresdata {
8786: my ($coursenum,$coursedomain)=@_;
1.200 www 8787: my $coursehom=&homeserver($coursenum,$coursedomain);
8788: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8789: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8790: my %dumpreply;
1.417 albertel 8791: unless (defined($cached)) {
1.624 albertel 8792: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 8793: $result=\%dumpreply;
1.251 albertel 8794: my ($tmp) = keys(%dumpreply);
8795: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 8796: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 8797: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8798: return $tmp;
1.416 albertel 8799: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8800: $result=undef;
1.599 albertel 8801: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8802: }
8803: }
1.624 albertel 8804: return $result;
8805: }
8806:
1.633 albertel 8807: sub devalidateuserresdata {
8808: my ($uname,$udom)=@_;
8809: my $hashid="$udom:$uname";
8810: &devalidate_cache_new('userres',$hashid);
8811: }
8812:
1.624 albertel 8813: sub get_userresdata {
8814: my ($uname,$udom)=@_;
8815: #most student don\'t have any data set, check if there is some data
8816: if (&EXT_cache_status($udom,$uname)) { return undef; }
8817:
8818: my $hashid="$udom:$uname";
8819: my ($result,$cached)=&is_cached_new('userres',$hashid);
8820: if (!defined($cached)) {
8821: my %resourcedata=&dump('resourcedata',$udom,$uname);
8822: $result=\%resourcedata;
8823: &do_cache_new('userres',$hashid,$result,600);
8824: }
8825: my ($tmp)=keys(%$result);
8826: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8827: return $result;
8828: }
8829: #error 2 occurs when the .db doesn't exist
8830: if ($tmp!~/error: 2 /) {
1.672 albertel 8831: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8832: " Trying to get resource data for ".
8833: $uname." at ".$udom.": ".
8834: $tmp."</font>");
8835: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8836: #&EXT_cache_set($udom,$uname);
8837: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8838: undef($tmp); # not really an error so don't send it back
1.624 albertel 8839: }
8840: return $tmp;
8841: }
1.879 foxr 8842: #----------------------------------------------- resdata - return resource data
8843: # Purpose:
8844: # Return resource data for either users or for a course.
8845: # Parameters:
8846: # $name - Course/user name.
8847: # $domain - Name of the domain the user/course is registered on.
8848: # $type - Type of thing $name is (must be 'course' or 'user'
8849: # @which - Array of names of resources desired.
8850: # Returns:
8851: # The value of the first reasource in @which that is found in the
8852: # resource hash.
8853: # Exceptional Conditions:
8854: # If the $type passed in is not valid (not the string 'course' or
8855: # 'user', an undefined reference is returned.
8856: # If none of the resources are found, an undef is returned
1.624 albertel 8857: sub resdata {
8858: my ($name,$domain,$type,@which)=@_;
8859: my $result;
8860: if ($type eq 'course') {
8861: $result=&get_courseresdata($name,$domain);
8862: } elsif ($type eq 'user') {
8863: $result=&get_userresdata($name,$domain);
8864: }
8865: if (!ref($result)) { return $result; }
1.251 albertel 8866: foreach my $item (@which) {
1.927 albertel 8867: if (defined($result->{$item->[0]})) {
8868: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8869: }
1.250 albertel 8870: }
1.291 albertel 8871: return undef;
1.200 www 8872: }
8873:
1.379 matthew 8874: #
8875: # EXT resource caching routines
8876: #
8877:
8878: sub clear_EXT_cache_status {
1.383 albertel 8879: &delenv('cache.EXT.');
1.379 matthew 8880: }
8881:
8882: sub EXT_cache_status {
8883: my ($target_domain,$target_user) = @_;
1.383 albertel 8884: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8885: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8886: # We know already the user has no data
8887: return 1;
8888: } else {
8889: return 0;
8890: }
8891: }
8892:
8893: sub EXT_cache_set {
8894: my ($target_domain,$target_user) = @_;
1.383 albertel 8895: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8896: #&appenv({$cachename => time});
1.379 matthew 8897: }
8898:
1.28 www 8899: # --------------------------------------------------------- Value of a Variable
1.58 www 8900: sub EXT {
1.715 albertel 8901:
1.395 albertel 8902: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8903: unless ($varname) { return ''; }
1.218 albertel 8904: #get real user name/domain, courseid and symb
8905: my $courseid;
1.359 albertel 8906: my $publicuser;
1.427 www 8907: if ($symbparm) {
8908: $symbparm=&get_symb_from_alias($symbparm);
8909: }
1.218 albertel 8910: if (!($uname && $udom)) {
1.790 albertel 8911: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8912: if (!$symbparm) { $symbparm=$cursymb; }
8913: } else {
1.620 albertel 8914: $courseid=$env{'request.course.id'};
1.218 albertel 8915: }
1.48 www 8916: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8917: my $rest;
1.320 albertel 8918: if (defined($therest[0])) {
1.48 www 8919: $rest=join('.',@therest);
8920: } else {
8921: $rest='';
8922: }
1.320 albertel 8923:
1.57 www 8924: my $qualifierrest=$qualifier;
8925: if ($rest) { $qualifierrest.='.'.$rest; }
8926: my $spacequalifierrest=$space;
8927: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8928: if ($realm eq 'user') {
1.48 www 8929: # --------------------------------------------------------------- user.resource
8930: if ($space eq 'resource') {
1.651 albertel 8931: if ( (defined($Apache::lonhomework::parsing_a_problem)
8932: || defined($Apache::lonhomework::parsing_a_task))
8933: &&
1.744 albertel 8934: ($symbparm eq &symbread()) ) {
8935: # if we are in the middle of processing the resource the
8936: # get the value we are planning on committing
8937: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8938: return $Apache::lonhomework::results{$qualifierrest};
8939: } else {
8940: return $Apache::lonhomework::history{$qualifierrest};
8941: }
1.335 albertel 8942: } else {
1.359 albertel 8943: my %restored;
1.620 albertel 8944: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8945: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8946: } else {
8947: %restored=&restore($symbparm,$courseid,$udom,$uname);
8948: }
1.335 albertel 8949: return $restored{$qualifierrest};
8950: }
1.48 www 8951: # ----------------------------------------------------------------- user.access
8952: } elsif ($space eq 'access') {
1.218 albertel 8953: # FIXME - not supporting calls for a specific user
1.48 www 8954: return &allowed($qualifier,$rest);
8955: # ------------------------------------------ user.preferences, user.environment
8956: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8957: if (($uname eq $env{'user.name'}) &&
8958: ($udom eq $env{'user.domain'})) {
8959: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8960: } else {
1.359 albertel 8961: my %returnhash;
8962: if (!$publicuser) {
8963: %returnhash=&userenvironment($udom,$uname,
8964: $qualifierrest);
8965: }
1.218 albertel 8966: return $returnhash{$qualifierrest};
8967: }
1.48 www 8968: # ----------------------------------------------------------------- user.course
8969: } elsif ($space eq 'course') {
1.218 albertel 8970: # FIXME - not supporting calls for a specific user
1.620 albertel 8971: return $env{join('.',('request.course',$qualifier))};
1.48 www 8972: # ------------------------------------------------------------------- user.role
8973: } elsif ($space eq 'role') {
1.218 albertel 8974: # FIXME - not supporting calls for a specific user
1.620 albertel 8975: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8976: if ($qualifier eq 'value') {
8977: return $role;
8978: } elsif ($qualifier eq 'extent') {
8979: return $where;
8980: }
8981: # ----------------------------------------------------------------- user.domain
8982: } elsif ($space eq 'domain') {
1.218 albertel 8983: return $udom;
1.48 www 8984: # ------------------------------------------------------------------- user.name
8985: } elsif ($space eq 'name') {
1.218 albertel 8986: return $uname;
1.48 www 8987: # ---------------------------------------------------- Any other user namespace
1.29 www 8988: } else {
1.359 albertel 8989: my %reply;
8990: if (!$publicuser) {
8991: %reply=&get($space,[$qualifierrest],$udom,$uname);
8992: }
8993: return $reply{$qualifierrest};
1.48 www 8994: }
1.236 www 8995: } elsif ($realm eq 'query') {
8996: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8997: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8998: [$spacequalifierrest]);
1.620 albertel 8999: return $env{'form.'.$spacequalifierrest};
1.236 www 9000: } elsif ($realm eq 'request') {
1.48 www 9001: # ------------------------------------------------------------- request.browser
9002: if ($space eq 'browser') {
1.1145 bisitz 9003: return $env{'browser.'.$qualifier};
1.57 www 9004: # ------------------------------------------------------------ request.filename
9005: } else {
1.620 albertel 9006: return $env{'request.'.$spacequalifierrest};
1.29 www 9007: }
1.28 www 9008: } elsif ($realm eq 'course') {
1.48 www 9009: # ---------------------------------------------------------- course.description
1.620 albertel 9010: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9011: } elsif ($realm eq 'resource') {
1.165 www 9012:
1.620 albertel 9013: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9014: if (!$symbparm) { $symbparm=&symbread(); }
9015: }
1.693 albertel 9016:
9017: if ($space eq 'title') {
9018: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9019: return &gettitle($symbparm);
9020: }
9021:
9022: if ($space eq 'map') {
9023: my ($map) = &decode_symb($symbparm);
9024: return &symbread($map);
9025: }
1.905 albertel 9026: if ($space eq 'filename') {
9027: if ($symbparm) {
9028: return &clutter((&decode_symb($symbparm))[2]);
9029: }
9030: return &hreflocation('',$env{'request.filename'});
9031: }
1.693 albertel 9032:
9033: my ($section, $group, @groups);
1.593 albertel 9034: my ($courselevelm,$courselevel);
1.539 albertel 9035: if ($symbparm && defined($courseid) &&
1.620 albertel 9036: $courseid eq $env{'request.course.id'}) {
1.165 www 9037:
1.218 albertel 9038: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9039:
1.60 www 9040: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9041: my $symbp=$symbparm;
1.735 albertel 9042: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9043:
9044: my $symbparm=$symbp.'.'.$spacequalifierrest;
9045: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9046:
1.620 albertel 9047: if (($env{'user.name'} eq $uname) &&
9048: ($env{'user.domain'} eq $udom)) {
9049: $section=$env{'request.course.sec'};
1.733 raeburn 9050: @groups = split(/:/,$env{'request.course.groups'});
9051: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9052: } else {
1.539 albertel 9053: if (! defined($usection)) {
1.551 albertel 9054: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9055: } else {
9056: $section = $usection;
9057: }
1.733 raeburn 9058: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9059: }
9060:
9061: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9062: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9063: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9064:
1.593 albertel 9065: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9066: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9067: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9068:
1.60 www 9069: # ----------------------------------------------------------- first, check user
1.624 albertel 9070:
9071: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9072: ([$courselevelr,'resource'],
9073: [$courselevelm,'map' ],
9074: [$courselevel, 'course' ]));
1.931 albertel 9075: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9076:
1.594 albertel 9077: # ------------------------------------------------ second, check some of course
1.684 raeburn 9078: my $coursereply;
1.691 raeburn 9079: if (@groups > 0) {
9080: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9081: $mapparm,$spacequalifierrest);
1.927 albertel 9082: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9083: }
1.96 www 9084:
1.684 raeburn 9085: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9086: $env{'course.'.$courseid.'.domain'},
9087: 'course',
9088: ([$seclevelr, 'resource'],
9089: [$seclevelm, 'map' ],
9090: [$seclevel, 'course' ],
9091: [$courselevelr,'resource']));
9092: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 9093:
1.60 www 9094: # ------------------------------------------------------ third, check map parms
1.218 albertel 9095: my %parmhash=();
9096: my $thisparm='';
9097: if (tie(%parmhash,'GDBM_File',
1.620 albertel 9098: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 9099: &GDBM_READER(),0640)) {
1.218 albertel 9100: $thisparm=$parmhash{$symbparm};
9101: untie(%parmhash);
9102: }
1.927 albertel 9103: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 9104: }
1.594 albertel 9105: # ------------------------------------------ fourth, look in resource metadata
1.71 www 9106:
1.218 albertel 9107: $spacequalifierrest=~s/\./\_/;
1.282 albertel 9108: my $filename;
9109: if (!$symbparm) { $symbparm=&symbread(); }
9110: if ($symbparm) {
1.409 www 9111: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 9112: } else {
1.620 albertel 9113: $filename=$env{'request.filename'};
1.282 albertel 9114: }
9115: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 9116: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 9117: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 9118: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 9119:
1.927 albertel 9120: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 9121: if ($symbparm && defined($courseid) &&
1.620 albertel 9122: $courseid eq $env{'request.course.id'}) {
1.624 albertel 9123: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9124: $env{'course.'.$courseid.'.domain'},
9125: 'course',
1.927 albertel 9126: ([$courselevelm,'map' ],
9127: [$courselevel, 'course']));
9128: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 9129: }
1.145 www 9130: # ------------------------------------------------------------------ Cascade up
1.218 albertel 9131: unless ($space eq '0') {
1.336 albertel 9132: my @parts=split(/_/,$space);
9133: my $id=pop(@parts);
9134: my $part=join('_',@parts);
9135: if ($part eq '') { $part='0'; }
1.927 albertel 9136: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 9137: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 9138: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 9139: }
1.395 albertel 9140: if ($recurse) { return undef; }
9141: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 9142: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 9143: # ---------------------------------------------------- Any other user namespace
9144: } elsif ($realm eq 'environment') {
9145: # ----------------------------------------------------------------- environment
1.620 albertel 9146: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9147: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 9148: } else {
1.770 albertel 9149: if ($uname eq 'anonymous' && $udom eq '') {
9150: return '';
9151: }
1.219 albertel 9152: my %returnhash=&userenvironment($udom,$uname,
9153: $spacequalifierrest);
9154: return $returnhash{$spacequalifierrest};
9155: }
1.28 www 9156: } elsif ($realm eq 'system') {
1.48 www 9157: # ----------------------------------------------------------------- system.time
9158: if ($space eq 'time') {
9159: return time;
9160: }
1.696 albertel 9161: } elsif ($realm eq 'server') {
9162: # ----------------------------------------------------------------- system.time
9163: if ($space eq 'name') {
9164: return $ENV{'SERVER_NAME'};
9165: }
1.28 www 9166: }
1.48 www 9167: return '';
1.61 www 9168: }
9169:
1.927 albertel 9170: sub get_reply {
9171: my ($reply_value) = @_;
1.940 raeburn 9172: if (ref($reply_value) eq 'ARRAY') {
9173: if (wantarray) {
9174: return @$reply_value;
9175: }
9176: return $reply_value->[0];
9177: } else {
9178: return $reply_value;
1.927 albertel 9179: }
9180: }
9181:
1.691 raeburn 9182: sub check_group_parms {
9183: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
9184: my @groupitems = ();
9185: my $resultitem;
1.927 albertel 9186: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 9187: foreach my $group (@{$groups}) {
9188: foreach my $level (@levels) {
1.927 albertel 9189: my $item = $courseid.'.['.$group.'].'.$level->[0];
9190: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 9191: }
9192: }
9193: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
9194: $env{'course.'.$courseid.'.domain'},
9195: 'course',@groupitems);
9196: return $coursereply;
9197: }
9198:
9199: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 9200: my ($courseid,@groups) = @_;
9201: @groups = sort(@groups);
1.691 raeburn 9202: return @groups;
9203: }
9204:
1.395 albertel 9205: sub packages_tab_default {
9206: my ($uri,$varname)=@_;
9207: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 9208:
9209: my (@extension,@specifics,$do_default);
9210: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 9211: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 9212: if ($pack_type eq 'default') {
9213: $do_default=1;
9214: } elsif ($pack_type eq 'extension') {
9215: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 9216: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 9217: # only look at packages defaults for packages that this id is
1.738 albertel 9218: push(@specifics,[$package,$pack_type,$pack_part]);
9219: }
9220: }
9221: # first look for a package that matches the requested part id
9222: foreach my $package (@specifics) {
9223: my (undef,$pack_type,$pack_part)=@{$package};
9224: next if ($pack_part ne $part);
9225: if (defined($packagetab{"$pack_type&$name&default"})) {
9226: return $packagetab{"$pack_type&$name&default"};
9227: }
9228: }
9229: # look for any possible matching non extension_ package
9230: foreach my $package (@specifics) {
9231: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 9232: if (defined($packagetab{"$pack_type&$name&default"})) {
9233: return $packagetab{"$pack_type&$name&default"};
9234: }
1.585 albertel 9235: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 9236: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
9237: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 9238: }
9239: }
1.738 albertel 9240: # look for any posible extension_ match
9241: foreach my $package (@extension) {
9242: my ($package,$pack_type)=@{$package};
9243: if (defined($packagetab{"$pack_type&$name&default"})) {
9244: return $packagetab{"$pack_type&$name&default"};
9245: }
9246: if (defined($packagetab{$package."&$name&default"})) {
9247: return $packagetab{$package."&$name&default"};
9248: }
9249: }
9250: # look for a global default setting
9251: if ($do_default && defined($packagetab{"default&$name&default"})) {
9252: return $packagetab{"default&$name&default"};
9253: }
1.395 albertel 9254: return undef;
9255: }
9256:
1.334 albertel 9257: sub add_prefix_and_part {
9258: my ($prefix,$part)=@_;
9259: my $keyroot;
9260: if (defined($prefix) && $prefix !~ /^__/) {
9261: # prefix that has a part already
9262: $keyroot=$prefix;
9263: } elsif (defined($prefix)) {
9264: # prefix that is missing a part
9265: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
9266: } else {
9267: # no prefix at all
9268: if (defined($part)) { $keyroot='_'.$part; }
9269: }
9270: return $keyroot;
9271: }
9272:
1.71 www 9273: # ---------------------------------------------------------------- Get metadata
9274:
1.599 albertel 9275: my %metaentry;
1.1070 www 9276: my %importedpartids;
1.71 www 9277: sub metadata {
1.176 www 9278: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 9279: $uri=&declutter($uri);
1.288 albertel 9280: # if it is a non metadata possible uri return quickly
1.529 albertel 9281: if (($uri eq '') ||
9282: (($uri =~ m|^/*adm/|) &&
1.698 albertel 9283: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108 raeburn 9284: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 9285: return undef;
9286: }
1.1140 www 9287: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 9288: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 9289: return undef;
1.288 albertel 9290: }
1.73 www 9291: my $filename=$uri;
9292: $uri=~s/\.meta$//;
1.172 www 9293: #
9294: # Is the metadata already cached?
1.177 www 9295: # Look at timestamp of caching
1.172 www 9296: # Everything is cached by the main uri, libraries are never directly cached
9297: #
1.428 albertel 9298: if (!defined($liburi)) {
1.599 albertel 9299: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 9300: if (defined($cached)) { return $result->{':'.$what}; }
9301: }
9302: {
1.1069 www 9303: # Imported parts would go here
1.1070 www 9304: my %importedids=();
9305: my @origfileimportpartids=();
1.1069 www 9306: my $importedparts=0;
1.172 www 9307: #
9308: # Is this a recursive call for a library?
9309: #
1.599 albertel 9310: # if (! exists($metacache{$uri})) {
9311: # $metacache{$uri}={};
9312: # }
1.924 albertel 9313: my $cachetime = 60*60;
1.171 www 9314: if ($liburi) {
9315: $liburi=&declutter($liburi);
9316: $filename=$liburi;
1.401 bowersj2 9317: } else {
1.599 albertel 9318: &devalidate_cache_new('meta',$uri);
9319: undef(%metaentry);
1.401 bowersj2 9320: }
1.140 www 9321: my %metathesekeys=();
1.73 www 9322: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 9323: my $metastring;
1.1140 www 9324: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 9325: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 9326: $metastring =
1.929 albertel 9327: &Apache::lonnet::ssi_body($which,
1.924 albertel 9328: ('grade_target' => 'meta'));
9329: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 9330: } elsif (($uri !~ m -^(editupload)/-) &&
9331: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 9332: my $file=&filelocation('',&clutter($filename));
1.599 albertel 9333: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 9334: $metastring=&getfile($file);
1.489 albertel 9335: }
1.208 albertel 9336: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 9337: my $token;
1.140 www 9338: undef %metathesekeys;
1.71 www 9339: while ($token=$parser->get_token) {
1.339 albertel 9340: if ($token->[0] eq 'S') {
9341: if (defined($token->[2]->{'package'})) {
1.172 www 9342: #
9343: # This is a package - get package info
9344: #
1.339 albertel 9345: my $package=$token->[2]->{'package'};
9346: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9347: if (defined($token->[2]->{'id'})) {
9348: $keyroot.='_'.$token->[2]->{'id'};
9349: }
1.599 albertel 9350: if ($metaentry{':packages'}) {
9351: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 9352: } else {
1.599 albertel 9353: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 9354: }
1.736 albertel 9355: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 9356: my $part=$keyroot;
9357: $part=~s/^\_//;
1.736 albertel 9358: if ($pack_entry=~/^\Q$package\E\&/ ||
9359: $pack_entry=~/^\Q$package\E_0\&/) {
9360: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 9361: # ignore package.tab specified default values
9362: # here &package_tab_default() will fetch those
9363: if ($subp eq 'default') { next; }
1.736 albertel 9364: my $value=$packagetab{$pack_entry};
1.432 albertel 9365: my $unikey;
9366: if ($pack =~ /_0$/) {
9367: $unikey='parameter_0_'.$name;
9368: $part=0;
9369: } else {
9370: $unikey='parameter'.$keyroot.'_'.$name;
9371: }
1.339 albertel 9372: if ($subp eq 'display') {
9373: $value.=' [Part: '.$part.']';
9374: }
1.599 albertel 9375: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 9376: $metathesekeys{$unikey}=1;
1.599 albertel 9377: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9378: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 9379: }
1.599 albertel 9380: if (defined($metaentry{':'.$unikey.'.default'})) {
9381: $metaentry{':'.$unikey}=
9382: $metaentry{':'.$unikey.'.default'};
1.356 albertel 9383: }
1.339 albertel 9384: }
9385: }
9386: } else {
1.172 www 9387: #
9388: # This is not a package - some other kind of start tag
1.339 albertel 9389: #
9390: my $entry=$token->[1];
1.1068 www 9391: my $unikey='';
1.175 www 9392:
1.339 albertel 9393: if ($entry eq 'import') {
1.175 www 9394: #
9395: # Importing a library here
1.339 albertel 9396: #
1.1067 www 9397: my $location=$parser->get_text('/import');
9398: my $dir=$filename;
9399: $dir=~s|[^/]*$||;
9400: $location=&filelocation($dir,$location);
1.1069 www 9401:
1.1068 www 9402: my $importmode=$token->[2]->{'importmode'};
9403: if ($importmode eq 'problem') {
1.1069 www 9404: # Import as problem/response
1.1068 www 9405: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9406: } elsif ($importmode eq 'part') {
9407: # Import as part(s)
1.1069 www 9408: $importedparts=1;
9409: # We need to get the original file and the imported file to get the part order correct
9410: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9411: # Load and inspect original file
1.1070 www 9412: if ($#origfileimportpartids<0) {
9413: undef(%importedpartids);
9414: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9415: my $origfile=&getfile($origfilelocation);
9416: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9417: }
9418:
1.1069 www 9419: # Load and inspect imported file
9420: my $impfile=&getfile($location);
9421: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9422: if ($#impfilepartids>=0) {
9423: # This problem had parts
1.1070 www 9424: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 9425: } else {
9426: # Importing by turning a single problem into a problem part
9427: # It gets the import-tags ID as part-ID
9428: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 9429: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 9430: }
1.1068 www 9431: } else {
9432: # Normal import
9433: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9434: if (defined($token->[2]->{'id'})) {
9435: $unikey.='_'.$token->[2]->{'id'};
9436: }
1.1067 www 9437: }
9438:
1.339 albertel 9439: if ($depthcount<20) {
1.736 albertel 9440: my $metadata =
9441: &metadata($uri,'keys', $location,$unikey,
9442: $depthcount+1);
9443: foreach my $meta (split(',',$metadata)) {
9444: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9445: $metathesekeys{$meta}=1;
1.339 albertel 9446: }
1.1068 www 9447:
9448: }
1.1067 www 9449: } else {
9450: #
9451: # Not importing, some other kind of non-package, non-library start tag
9452: #
9453: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9454: if (defined($token->[2]->{'id'})) {
9455: $unikey.='_'.$token->[2]->{'id'};
9456: }
1.339 albertel 9457: if (defined($token->[2]->{'name'})) {
9458: $unikey.='_'.$token->[2]->{'name'};
9459: }
9460: $metathesekeys{$unikey}=1;
1.736 albertel 9461: foreach my $param (@{$token->[3]}) {
9462: $metaentry{':'.$unikey.'.'.$param} =
9463: $token->[2]->{$param};
1.339 albertel 9464: }
9465: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 9466: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 9467: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9468: # only ws inside the tag, and not in default, so use default
9469: # as value
1.599 albertel 9470: $metaentry{':'.$unikey}=$default;
1.908 albertel 9471: } elsif ( $internaltext =~ /\S/ ) {
9472: # something interesting inside the tag
9473: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 9474: } else {
1.908 albertel 9475: # no interesting values, don't set a default
1.339 albertel 9476: }
1.172 www 9477: # end of not-a-package not-a-library import
1.339 albertel 9478: }
1.172 www 9479: # end of not-a-package start tag
1.339 albertel 9480: }
1.172 www 9481: # the next is the end of "start tag"
1.339 albertel 9482: }
9483: }
1.483 albertel 9484: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 9485: $extension = lc($extension);
9486: if ($extension eq 'htm') { $extension='html'; }
9487:
1.737 albertel 9488: foreach my $key (keys(%packagetab)) {
1.483 albertel 9489: #no specific packages #how's our extension
9490: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 9491: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 9492: \%metathesekeys);
9493: }
1.883 albertel 9494:
9495: if (!exists($metaentry{':packages'})
9496: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 9497: foreach my $key (keys(%packagetab)) {
1.483 albertel 9498: #no specific packages well let's get default then
9499: if ($key!~/^default&/) { next; }
1.488 albertel 9500: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 9501: \%metathesekeys);
9502: }
9503: }
1.338 www 9504: # are there custom rights to evaluate
1.599 albertel 9505: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 9506:
1.338 www 9507: #
9508: # Importing a rights file here
1.339 albertel 9509: #
9510: unless ($depthcount) {
1.599 albertel 9511: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 9512: my $dir=$filename;
9513: $dir=~s|[^/]*$||;
9514: $location=&filelocation($dir,$location);
1.736 albertel 9515: my $rights_metadata =
9516: &metadata($uri,'keys',$location,'_rights',
9517: $depthcount+1);
9518: foreach my $rights (split(',',$rights_metadata)) {
9519: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9520: $metathesekeys{$rights}=1;
1.339 albertel 9521: }
9522: }
9523: }
1.737 albertel 9524: # uniqifiy package listing
9525: my %seen;
9526: my @uniq_packages =
9527: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9528: $metaentry{':packages'} = join(',',@uniq_packages);
9529:
1.1070 www 9530: if ($importedparts) {
9531: # We had imported parts and need to rebuild partorder
9532: $metaentry{':partorder'}='';
9533: $metathesekeys{'partorder'}=1;
9534: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9535: if ($origfileimportpartids[$index] eq 'part') {
9536: # original part, part of the problem
9537: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9538: } else {
9539: # we have imported parts at this position
9540: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9541: }
9542: }
9543: $metaentry{':partorder'}=~s/^\,//;
9544: }
9545:
1.737 albertel 9546: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 9547: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9548: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 9549: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 9550: # this is the end of "was not already recently cached
1.71 www 9551: }
1.599 albertel 9552: return $metaentry{':'.$what};
1.261 albertel 9553: }
9554:
1.488 albertel 9555: sub metadata_create_package_def {
1.483 albertel 9556: my ($uri,$key,$package,$metathesekeys)=@_;
9557: my ($pack,$name,$subp)=split(/\&/,$key);
9558: if ($subp eq 'default') { next; }
9559:
1.599 albertel 9560: if (defined($metaentry{':packages'})) {
9561: $metaentry{':packages'}.=','.$package;
1.483 albertel 9562: } else {
1.599 albertel 9563: $metaentry{':packages'}=$package;
1.483 albertel 9564: }
9565: my $value=$packagetab{$key};
9566: my $unikey;
9567: $unikey='parameter_0_'.$name;
1.599 albertel 9568: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 9569: $$metathesekeys{$unikey}=1;
1.599 albertel 9570: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9571: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 9572: }
1.599 albertel 9573: if (defined($metaentry{':'.$unikey.'.default'})) {
9574: $metaentry{':'.$unikey}=
9575: $metaentry{':'.$unikey.'.default'};
1.483 albertel 9576: }
9577: }
9578:
1.261 albertel 9579: sub metadata_generate_part0 {
9580: my ($metadata,$metacache,$uri) = @_;
9581: my %allnames;
1.737 albertel 9582: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 9583: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 9584: my $part=$$metacache{':'.$metakey.'.part'};
9585: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 9586: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 9587: $allnames{$name}=$part;
9588: }
9589: }
9590: }
9591: foreach my $name (keys(%allnames)) {
9592: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 9593: my $key=":parameter_0_$name";
1.261 albertel 9594: $$metacache{"$key.part"}='0';
9595: $$metacache{"$key.name"}=$name;
1.428 albertel 9596: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 9597: $allnames{$name}.'_'.$name.
9598: '.type'};
1.428 albertel 9599: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 9600: '.display'};
1.644 www 9601: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 9602: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 9603: $$metacache{"$key.display"}=$olddis;
9604: }
1.71 www 9605: }
9606:
1.764 albertel 9607: # ------------------------------------------------------ Devalidate title cache
9608:
9609: sub devalidate_title_cache {
9610: my ($url)=@_;
9611: if (!$env{'request.course.id'}) { return; }
9612: my $symb=&symbread($url);
9613: if (!$symb) { return; }
9614: my $key=$env{'request.course.id'}."\0".$symb;
9615: &devalidate_cache_new('title',$key);
9616: }
9617:
1.1014 droeschl 9618: # ------------------------------------------------- Get the title of a course
9619:
9620: sub current_course_title {
9621: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9622: }
1.301 www 9623: # ------------------------------------------------- Get the title of a resource
9624:
9625: sub gettitle {
9626: my $urlsymb=shift;
9627: my $symb=&symbread($urlsymb);
1.534 albertel 9628: if ($symb) {
1.620 albertel 9629: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 9630: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 9631: if (defined($cached)) {
9632: return $result;
9633: }
1.534 albertel 9634: my ($map,$resid,$url)=&decode_symb($symb);
9635: my $title='';
1.907 albertel 9636: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9637: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9638: } else {
9639: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9640: &GDBM_READER(),0640)) {
9641: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9642: $title=$bighash{'title_'.$mapid.'.'.$resid};
9643: untie(%bighash);
9644: }
1.534 albertel 9645: }
9646: $title=~s/\&colon\;/\:/gs;
9647: if ($title) {
1.1159 www 9648: # Remember both $symb and $title for dynamic metadata
9649: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 9650: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 9651: # Cache this title and then return it
1.599 albertel 9652: return &do_cache_new('title',$key,$title,600);
1.534 albertel 9653: }
9654: $urlsymb=$url;
9655: }
9656: my $title=&metadata($urlsymb,'title');
9657: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9658: return $title;
1.301 www 9659: }
1.613 albertel 9660:
1.614 albertel 9661: sub get_slot {
9662: my ($which,$cnum,$cdom)=@_;
9663: if (!$cnum || !$cdom) {
1.790 albertel 9664: (undef,my $courseid)=&whichuser();
1.620 albertel 9665: $cdom=$env{'course.'.$courseid.'.domain'};
9666: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 9667: }
1.703 albertel 9668: my $key=join("\0",'slots',$cdom,$cnum,$which);
9669: my %slotinfo;
9670: if (exists($remembered{$key})) {
9671: $slotinfo{$which} = $remembered{$key};
9672: } else {
9673: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9674: &Apache::lonhomework::showhash(%slotinfo);
9675: my ($tmp)=keys(%slotinfo);
9676: if ($tmp=~/^error:/) { return (); }
9677: $remembered{$key} = $slotinfo{$which};
9678: }
1.616 albertel 9679: if (ref($slotinfo{$which}) eq 'HASH') {
9680: return %{$slotinfo{$which}};
9681: }
9682: return $slotinfo{$which};
1.614 albertel 9683: }
1.1150 raeburn 9684:
9685: sub get_reservable_slots {
9686: my ($cnum,$cdom,$uname,$udom) = @_;
9687: my $now = time;
9688: my $reservable_info;
9689: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
9690: if (exists($remembered{$key})) {
9691: $reservable_info = $remembered{$key};
9692: } else {
9693: my %resv;
9694: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
9695: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
9696: $reservable_info = \%resv;
9697: $remembered{$key} = $reservable_info;
9698: }
9699: return $reservable_info;
9700: }
9701:
9702: sub get_course_slots {
9703: my ($cnum,$cdom) = @_;
9704: my $hashid=$cnum.':'.$cdom;
9705: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
9706: if (defined($cached)) {
9707: if (ref($result) eq 'HASH') {
9708: return %{$result};
9709: }
9710: } else {
9711: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
9712: my ($tmp) = keys(%slots);
9713: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9714: &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
9715: return %slots;
9716: }
9717: }
9718: return;
9719: }
9720:
9721: sub devalidate_slots_cache {
9722: my ($cnum,$cdom)=@_;
9723: my $hashid=$cnum.':'.$cdom;
9724: &devalidate_cache_new('allslots',$hashid);
9725: }
9726:
1.31 www 9727: # ------------------------------------------------- Update symbolic store links
9728:
9729: sub symblist {
9730: my ($mapname,%newhash)=@_;
1.438 www 9731: $mapname=&deversion(&declutter($mapname));
1.31 www 9732: my %hash;
1.620 albertel 9733: if (($env{'request.course.fn'}) && (%newhash)) {
9734: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9735: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 9736: foreach my $url (keys(%newhash)) {
1.711 albertel 9737: next if ($url eq 'last_known'
9738: && $env{'form.no_update_last_known'});
9739: $hash{declutter($url)}=&encode_symb($mapname,
9740: $newhash{$url}->[1],
9741: $newhash{$url}->[0]);
1.191 harris41 9742: }
1.31 www 9743: if (untie(%hash)) {
9744: return 'ok';
9745: }
9746: }
9747: }
9748: return 'error';
1.212 www 9749: }
9750:
9751: # --------------------------------------------------------------- Verify a symb
9752:
9753: sub symbverify {
1.510 www 9754: my ($symb,$thisurl)=@_;
9755: my $thisfn=$thisurl;
1.439 www 9756: $thisfn=&declutter($thisfn);
1.215 www 9757: # direct jump to resource in page or to a sequence - will construct own symbs
9758: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9759: # check URL part
1.409 www 9760: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 9761:
1.431 www 9762: unless ($url eq $thisfn) { return 0; }
1.213 www 9763:
1.216 www 9764: $symb=&symbclean($symb);
1.510 www 9765: $thisurl=&deversion($thisurl);
1.439 www 9766: $thisfn=&deversion($thisfn);
1.213 www 9767:
9768: my %bighash;
9769: my $okay=0;
1.431 www 9770:
1.620 albertel 9771: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9772: &GDBM_READER(),0640)) {
1.1032 raeburn 9773: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9774: $thisurl =~ s/\?.+$//;
9775: }
1.510 www 9776: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102 raeburn 9777: unless ($ids) {
9778: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9779: $ids=$bighash{$idkey};
1.216 www 9780: }
9781: if ($ids) {
9782: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 9783: foreach my $id (split(/\,/,$ids)) {
9784: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 9785: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9786: $symb =~ s/\?.+$//;
9787: }
1.216 www 9788: if (
9789: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9790: eq $symb) {
1.620 albertel 9791: if (($env{'request.role.adv'}) ||
1.1101 raeburn 9792: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9793: ($thisurl eq '/adm/navmaps')) {
1.582 albertel 9794: $okay=1;
9795: }
9796: }
1.216 www 9797: }
9798: }
1.213 www 9799: untie(%bighash);
9800: }
9801: return $okay;
1.31 www 9802: }
9803:
1.210 www 9804: # --------------------------------------------------------------- Clean-up symb
9805:
9806: sub symbclean {
9807: my $symb=shift;
1.568 albertel 9808: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 9809: # remove version from map
9810: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 9811:
1.210 www 9812: # remove version from URL
9813: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 9814:
1.507 www 9815: # remove wrapper
9816:
1.510 www 9817: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 9818: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 9819: return $symb;
1.409 www 9820: }
9821:
9822: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 9823:
9824: sub encode_symb {
9825: my ($map,$resid,$url)=@_;
9826: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9827: }
1.409 www 9828:
9829: sub decode_symb {
1.568 albertel 9830: my $symb=shift;
9831: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9832: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 9833: return (&fixversion($map),$resid,&fixversion($url));
9834: }
9835:
9836: sub fixversion {
9837: my $fn=shift;
1.609 banghart 9838: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 9839: my %bighash;
9840: my $uri=&clutter($fn);
1.620 albertel 9841: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 9842: # is this cached?
1.599 albertel 9843: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 9844: if (defined($cached)) { return $result; }
9845: # unfortunately not cached, or expired
1.620 albertel 9846: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 9847: &GDBM_READER(),0640)) {
9848: if ($bighash{'version_'.$uri}) {
9849: my $version=$bighash{'version_'.$uri};
1.444 www 9850: unless (($version eq 'mostrecent') ||
9851: ($version==&getversion($uri))) {
1.440 www 9852: $uri=~s/\.(\w+)$/\.$version\.$1/;
9853: }
9854: }
9855: untie %bighash;
1.413 www 9856: }
1.599 albertel 9857: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 9858: }
9859:
9860: sub deversion {
9861: my $url=shift;
9862: $url=~s/\.\d+\.(\w+)$/\.$1/;
9863: return $url;
1.210 www 9864: }
9865:
1.31 www 9866: # ------------------------------------------------------ Return symb list entry
9867:
9868: sub symbread {
1.249 www 9869: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 9870: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 9871: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 9872: # no filename provided? try from environment
1.44 www 9873: unless ($thisfn) {
1.620 albertel 9874: if ($env{'request.symb'}) {
9875: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 9876: }
1.620 albertel 9877: $thisfn=$env{'request.filename'};
1.44 www 9878: }
1.569 albertel 9879: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 9880: # is that filename actually a symb? Verify, clean, and return
9881: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 9882: if (&symbverify($thisfn,$1)) {
1.620 albertel 9883: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 9884: }
1.242 www 9885: }
1.44 www 9886: $thisfn=declutter($thisfn);
1.31 www 9887: my %hash;
1.37 www 9888: my %bighash;
9889: my $syval='';
1.620 albertel 9890: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 9891: my $targetfn = $thisfn;
1.609 banghart 9892: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 9893: $targetfn = 'adm/wrapper/'.$thisfn;
9894: }
1.687 albertel 9895: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9896: $targetfn=$1;
9897: }
1.620 albertel 9898: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9899: &GDBM_READER(),0640)) {
1.481 raeburn 9900: $syval=$hash{$targetfn};
1.37 www 9901: untie(%hash);
9902: }
9903: # ---------------------------------------------------------- There was an entry
9904: if ($syval) {
1.601 albertel 9905: #unless ($syval=~/\_\d+$/) {
1.620 albertel 9906: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 9907: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9908: #return $env{$cache_str}='';
1.601 albertel 9909: #}
9910: #$syval.=$1;
9911: #}
1.37 www 9912: } else {
9913: # ------------------------------------------------------- Was not in symb table
1.620 albertel 9914: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9915: &GDBM_READER(),0640)) {
1.37 www 9916: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 9917: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 9918: unless ($ids) {
9919: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 9920: }
9921: unless ($ids) {
9922: # alias?
9923: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 9924: }
1.37 www 9925: if ($ids) {
9926: # ------------------------------------------------------------------- Has ID(s)
9927: my @possibilities=split(/\,/,$ids);
1.39 www 9928: if ($#possibilities==0) {
9929: # ----------------------------------------------- There is only one possibility
1.37 www 9930: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 9931: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9932: $resid,$thisfn);
1.249 www 9933: } elsif (!$donotrecurse) {
1.39 www 9934: # ------------------------------------------ There is more than one possibility
9935: my $realpossible=0;
1.800 albertel 9936: foreach my $id (@possibilities) {
9937: my $file=$bighash{'src_'.$id};
1.39 www 9938: if (&allowed('bre',$file)) {
1.800 albertel 9939: my ($mapid,$resid)=split(/\./,$id);
1.39 www 9940: if ($bighash{'map_type_'.$mapid} ne 'page') {
9941: $realpossible++;
1.626 albertel 9942: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9943: $resid,$thisfn);
1.39 www 9944: }
9945: }
1.191 harris41 9946: }
1.39 www 9947: if ($realpossible!=1) { $syval=''; }
1.249 www 9948: } else {
9949: $syval='';
1.37 www 9950: }
9951: }
9952: untie(%bighash)
1.481 raeburn 9953: }
1.31 www 9954: }
1.62 www 9955: if ($syval) {
1.620 albertel 9956: return $env{$cache_str}=$syval;
1.62 www 9957: }
1.31 www 9958: }
1.949 raeburn 9959: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9960: return $env{$cache_str}='';
1.31 www 9961: }
9962:
9963: # ---------------------------------------------------------- Return random seed
9964:
1.32 www 9965: sub numval {
9966: my $txt=shift;
9967: $txt=~tr/A-J/0-9/;
9968: $txt=~tr/a-j/0-9/;
9969: $txt=~tr/K-T/0-9/;
9970: $txt=~tr/k-t/0-9/;
9971: $txt=~tr/U-Z/0-5/;
9972: $txt=~tr/u-z/0-5/;
9973: $txt=~s/\D//g;
1.564 albertel 9974: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 9975: return int($txt);
1.368 albertel 9976: }
9977:
1.484 albertel 9978: sub numval2 {
9979: my $txt=shift;
9980: $txt=~tr/A-J/0-9/;
9981: $txt=~tr/a-j/0-9/;
9982: $txt=~tr/K-T/0-9/;
9983: $txt=~tr/k-t/0-9/;
9984: $txt=~tr/U-Z/0-5/;
9985: $txt=~tr/u-z/0-5/;
9986: $txt=~s/\D//g;
9987: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9988: my $total;
9989: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9990: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9991: return int($total);
9992: }
9993:
1.575 albertel 9994: sub numval3 {
9995: use integer;
9996: my $txt=shift;
9997: $txt=~tr/A-J/0-9/;
9998: $txt=~tr/a-j/0-9/;
9999: $txt=~tr/K-T/0-9/;
10000: $txt=~tr/k-t/0-9/;
10001: $txt=~tr/U-Z/0-5/;
10002: $txt=~tr/u-z/0-5/;
10003: $txt=~s/\D//g;
10004: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10005: my $total;
10006: foreach my $val (@txts) { $total+=$val; }
10007: if ($_64bit) { $total=(($total<<32)>>32); }
10008: return $total;
10009: }
10010:
1.675 albertel 10011: sub digest {
10012: my ($data)=@_;
10013: my $digest=&Digest::MD5::md5($data);
10014: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10015: my ($e,$f);
10016: {
10017: use integer;
10018: $e=($a+$b);
10019: $f=($c+$d);
10020: if ($_64bit) {
10021: $e=(($e<<32)>>32);
10022: $f=(($f<<32)>>32);
10023: }
10024: }
10025: if (wantarray) {
10026: return ($e,$f);
10027: } else {
10028: my $g;
10029: {
10030: use integer;
10031: $g=($e+$f);
10032: if ($_64bit) {
10033: $g=(($g<<32)>>32);
10034: }
10035: }
10036: return $g;
10037: }
10038: }
10039:
1.368 albertel 10040: sub latest_rnd_algorithm_id {
1.675 albertel 10041: return '64bit5';
1.366 albertel 10042: }
1.32 www 10043:
1.503 albertel 10044: sub get_rand_alg {
10045: my ($courseid)=@_;
1.790 albertel 10046: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 10047: if ($courseid) {
1.620 albertel 10048: return $env{"course.$courseid.rndseed"};
1.503 albertel 10049: }
10050: return &latest_rnd_algorithm_id();
10051: }
10052:
1.562 albertel 10053: sub validCODE {
10054: my ($CODE)=@_;
10055: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10056: return 0;
10057: }
10058:
1.491 albertel 10059: sub getCODE {
1.620 albertel 10060: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 10061: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10062: defined($Apache::lonhomework::parsing_a_task) ) &&
10063: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 10064: return $Apache::lonhomework::history{'resource.CODE'};
10065: }
10066: return undef;
10067: }
1.1133 foxr 10068: #
10069: # Determines the random seed for a specific context:
10070: #
10071: # parameters:
10072: # symb - in course context the symb for the seed.
10073: # course_id - The course id of the form domain_coursenum.
10074: # domain - Domain for the user.
10075: # course - Course for the user.
10076: # cenv - environment of the course.
10077: #
10078: # NOTE:
10079: # All parameters are picked out of the environment if missing
10080: # or not defined.
10081: # If a symb cannot be determined the current time is used instead.
10082: #
10083: # For a given well defined symb, courside, domain, username,
10084: # and course environment, the seed is reproducible.
10085: #
1.31 www 10086: sub rndseed {
1.1133 foxr 10087: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 10088: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 10089: if (!defined($symb)) {
1.366 albertel 10090: unless ($symb=$wsymb) { return time; }
10091: }
1.1146 foxr 10092: if (!defined $courseid) {
10093: $courseid=$wcourseid;
10094: }
10095: if (!defined $domain) { $domain=$wdomain; }
10096: if (!defined $username) { $username=$wusername }
1.1133 foxr 10097:
10098: my $which;
10099: if (defined($cenv->{'rndseed'})) {
10100: $which = $cenv->{'rndseed'};
10101: } else {
10102: $which =&get_rand_alg($courseid);
10103: }
1.491 albertel 10104: if (defined(&getCODE())) {
1.1133 foxr 10105:
1.675 albertel 10106: if ($which eq '64bit5') {
10107: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10108: } elsif ($which eq '64bit4') {
1.575 albertel 10109: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10110: } else {
10111: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10112: }
1.675 albertel 10113: } elsif ($which eq '64bit5') {
10114: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 10115: } elsif ($which eq '64bit4') {
10116: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 10117: } elsif ($which eq '64bit3') {
10118: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 10119: } elsif ($which eq '64bit2') {
10120: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 10121: } elsif ($which eq '64bit') {
10122: return &rndseed_64bit($symb,$courseid,$domain,$username);
10123: }
10124: return &rndseed_32bit($symb,$courseid,$domain,$username);
10125: }
10126:
10127: sub rndseed_32bit {
10128: my ($symb,$courseid,$domain,$username)=@_;
10129: {
10130: use integer;
10131: my $symbchck=unpack("%32C*",$symb) << 27;
10132: my $symbseed=numval($symb) << 22;
10133: my $namechck=unpack("%32C*",$username) << 17;
10134: my $nameseed=numval($username) << 12;
10135: my $domainseed=unpack("%32C*",$domain) << 7;
10136: my $courseseed=unpack("%32C*",$courseid);
10137: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 10138: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10139: #&logthis("rndseed :$num:$symb");
1.564 albertel 10140: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 10141: return $num;
10142: }
10143: }
10144:
10145: sub rndseed_64bit {
10146: my ($symb,$courseid,$domain,$username)=@_;
10147: {
10148: use integer;
10149: my $symbchck=unpack("%32S*",$symb) << 21;
10150: my $symbseed=numval($symb) << 10;
10151: my $namechck=unpack("%32S*",$username);
10152:
10153: my $nameseed=numval($username) << 21;
10154: my $domainseed=unpack("%32S*",$domain) << 10;
10155: my $courseseed=unpack("%32S*",$courseid);
10156:
10157: my $num1=$symbchck+$symbseed+$namechck;
10158: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10159: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10160: #&logthis("rndseed :$num:$symb");
1.564 albertel 10161: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 10162: return "$num1,$num2";
1.155 albertel 10163: }
1.366 albertel 10164: }
10165:
1.443 albertel 10166: sub rndseed_64bit2 {
10167: my ($symb,$courseid,$domain,$username)=@_;
10168: {
10169: use integer;
10170: # strings need to be an even # of cahracters long, it it is odd the
10171: # last characters gets thrown away
10172: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10173: my $symbseed=numval($symb) << 10;
10174: my $namechck=unpack("%32S*",$username.' ');
10175:
10176: my $nameseed=numval($username) << 21;
1.501 albertel 10177: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10178: my $courseseed=unpack("%32S*",$courseid.' ');
10179:
10180: my $num1=$symbchck+$symbseed+$namechck;
10181: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10182: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10183: #&logthis("rndseed :$num:$symb");
1.803 albertel 10184: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 10185: return "$num1,$num2";
10186: }
10187: }
10188:
10189: sub rndseed_64bit3 {
10190: my ($symb,$courseid,$domain,$username)=@_;
10191: {
10192: use integer;
10193: # strings need to be an even # of cahracters long, it it is odd the
10194: # last characters gets thrown away
10195: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10196: my $symbseed=numval2($symb) << 10;
10197: my $namechck=unpack("%32S*",$username.' ');
10198:
10199: my $nameseed=numval2($username) << 21;
1.443 albertel 10200: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10201: my $courseseed=unpack("%32S*",$courseid.' ');
10202:
10203: my $num1=$symbchck+$symbseed+$namechck;
10204: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10205: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10206: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 10207: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 10208:
1.503 albertel 10209: return "$num1:$num2";
1.443 albertel 10210: }
10211: }
10212:
1.575 albertel 10213: sub rndseed_64bit4 {
10214: my ($symb,$courseid,$domain,$username)=@_;
10215: {
10216: use integer;
10217: # strings need to be an even # of cahracters long, it it is odd the
10218: # last characters gets thrown away
10219: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10220: my $symbseed=numval3($symb) << 10;
10221: my $namechck=unpack("%32S*",$username.' ');
10222:
10223: my $nameseed=numval3($username) << 21;
10224: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10225: my $courseseed=unpack("%32S*",$courseid.' ');
10226:
10227: my $num1=$symbchck+$symbseed+$namechck;
10228: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10229: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10230: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 10231: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 10232:
1.575 albertel 10233: return "$num1:$num2";
10234: }
10235: }
10236:
1.675 albertel 10237: sub rndseed_64bit5 {
10238: my ($symb,$courseid,$domain,$username)=@_;
10239: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10240: return "$num1:$num2";
10241: }
10242:
1.366 albertel 10243: sub rndseed_CODE_64bit {
10244: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 10245: {
1.366 albertel 10246: use integer;
1.443 albertel 10247: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 10248: my $symbseed=numval2($symb);
1.491 albertel 10249: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10250: my $CODEseed=numval(&getCODE());
1.443 albertel 10251: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 10252: my $num1=$symbseed+$CODEchck;
10253: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 10254: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10255: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 10256: if ($_64bit) { $num1=(($num1<<32)>>32); }
10257: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 10258: return "$num1:$num2";
1.366 albertel 10259: }
10260: }
10261:
1.575 albertel 10262: sub rndseed_CODE_64bit4 {
10263: my ($symb,$courseid,$domain,$username)=@_;
10264: {
10265: use integer;
10266: my $symbchck=unpack("%32S*",$symb.' ') << 16;
10267: my $symbseed=numval3($symb);
10268: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10269: my $CODEseed=numval3(&getCODE());
10270: my $courseseed=unpack("%32S*",$courseid.' ');
10271: my $num1=$symbseed+$CODEchck;
10272: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 10273: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10274: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 10275: if ($_64bit) { $num1=(($num1<<32)>>32); }
10276: if ($_64bit) { $num2=(($num2<<32)>>32); }
10277: return "$num1:$num2";
10278: }
10279: }
10280:
1.675 albertel 10281: sub rndseed_CODE_64bit5 {
10282: my ($symb,$courseid,$domain,$username)=@_;
10283: my $code = &getCODE();
10284: my ($num1,$num2)=&digest("$symb,$courseid,$code");
10285: return "$num1:$num2";
10286: }
10287:
1.366 albertel 10288: sub setup_random_from_rndseed {
10289: my ($rndseed)=@_;
1.503 albertel 10290: if ($rndseed =~/([,:])/) {
10291: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 10292: &Math::Random::random_set_seed(abs($num1),abs($num2));
10293: } else {
10294: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 10295: }
1.36 albertel 10296: }
10297:
1.474 albertel 10298: sub latest_receipt_algorithm_id {
1.835 albertel 10299: return 'receipt3';
1.474 albertel 10300: }
10301:
1.480 www 10302: sub recunique {
10303: my $fucourseid=shift;
10304: my $unique;
1.835 albertel 10305: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10306: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 10307: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 10308: } else {
10309: $unique=$perlvar{'lonReceipt'};
10310: }
10311: return unpack("%32C*",$unique);
10312: }
10313:
10314: sub recprefix {
10315: my $fucourseid=shift;
10316: my $prefix;
1.835 albertel 10317: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10318: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 10319: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 10320: } else {
10321: $prefix=$perlvar{'lonHostID'};
10322: }
10323: return unpack("%32C*",$prefix);
10324: }
10325:
1.76 www 10326: sub ireceipt {
1.474 albertel 10327: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 10328:
10329: my $return =&recprefix($fucourseid).'-';
10330:
10331: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10332: $env{'request.state'} eq 'construct') {
10333: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10334: return $return;
10335: }
10336:
1.76 www 10337: my $cuname=unpack("%32C*",$funame);
10338: my $cudom=unpack("%32C*",$fudom);
10339: my $cucourseid=unpack("%32C*",$fucourseid);
10340: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 10341: my $cunique=&recunique($fucourseid);
1.474 albertel 10342: my $cpart=unpack("%32S*",$part);
1.835 albertel 10343: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10344:
1.790 albertel 10345: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 10346:
10347: $return.= ($cunique%$cuname+
10348: $cunique%$cudom+
10349: $cusymb%$cuname+
10350: $cusymb%$cudom+
10351: $cucourseid%$cuname+
10352: $cucourseid%$cudom+
10353: $cpart%$cuname+
10354: $cpart%$cudom);
10355: } else {
10356: $return.= ($cunique%$cuname+
10357: $cunique%$cudom+
10358: $cusymb%$cuname+
10359: $cusymb%$cudom+
10360: $cucourseid%$cuname+
10361: $cucourseid%$cudom);
10362: }
10363: return $return;
1.76 www 10364: }
10365:
10366: sub receipt {
1.474 albertel 10367: my ($part)=@_;
1.790 albertel 10368: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 10369: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 10370: }
1.260 ng 10371:
1.790 albertel 10372: sub whichuser {
10373: my ($passedsymb)=@_;
10374: my ($symb,$courseid,$domain,$name,$publicuser);
10375: if (defined($env{'form.grade_symb'})) {
10376: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10377: my $allowed=&allowed('vgr',$tmp_courseid);
10378: if (!$allowed &&
10379: exists($env{'request.course.sec'}) &&
10380: $env{'request.course.sec'} !~ /^\s*$/) {
10381: $allowed=&allowed('vgr',$tmp_courseid.
10382: '/'.$env{'request.course.sec'});
10383: }
10384: if ($allowed) {
10385: ($symb)=&get_env_multiple('form.grade_symb');
10386: $courseid=$tmp_courseid;
10387: ($domain)=&get_env_multiple('form.grade_domain');
10388: ($name)=&get_env_multiple('form.grade_username');
10389: return ($symb,$courseid,$domain,$name,$publicuser);
10390: }
10391: }
10392: if (!$passedsymb) {
10393: $symb=&symbread();
10394: } else {
10395: $symb=$passedsymb;
10396: }
10397: $courseid=$env{'request.course.id'};
10398: $domain=$env{'user.domain'};
10399: $name=$env{'user.name'};
10400: if ($name eq 'public' && $domain eq 'public') {
10401: if (!defined($env{'form.username'})) {
10402: $env{'form.username'}.=time.rand(10000000);
10403: }
10404: $name.=$env{'form.username'};
10405: }
10406: return ($symb,$courseid,$domain,$name,$publicuser);
10407:
10408: }
10409:
1.36 albertel 10410: # ------------------------------------------------------------ Serves up a file
1.472 albertel 10411: # returns either the contents of the file or
10412: # -1 if the file doesn't exist
1.481 raeburn 10413: #
10414: # if the target is a file that was uploaded via DOCS,
10415: # a check will be made to see if a current copy exists on the local server,
10416: # if it does this will be served, otherwise a copy will be retrieved from
10417: # the home server for the course and stored in /home/httpd/html/userfiles on
10418: # the local server.
1.472 albertel 10419:
1.36 albertel 10420: sub getfile {
1.538 albertel 10421: my ($file) = @_;
1.609 banghart 10422: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 10423: &repcopy($file);
10424: return &readfile($file);
10425: }
10426:
10427: sub repcopy_userfile {
10428: my ($file)=@_;
1.1142 raeburn 10429: my $londocroot = $perlvar{'lonDocRoot'};
10430: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10431: if ($file =~ m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
1.538 albertel 10432: my ($cdom,$cnum,$filename) =
1.811 albertel 10433: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 10434: my $uri="/uploaded/$cdom/$cnum/$filename";
10435: if (-e "$file") {
1.828 www 10436: # we already have a local copy, check it out
1.538 albertel 10437: my @fileinfo = stat($file);
1.828 www 10438: my $rtncode;
10439: my $info;
1.538 albertel 10440: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 10441: if ($lwpresp ne 'ok') {
1.828 www 10442: # there is no such file anymore, even though we had a local copy
1.482 albertel 10443: if ($rtncode eq '404') {
1.538 albertel 10444: unlink($file);
1.482 albertel 10445: }
10446: return -1;
10447: }
10448: if ($info < $fileinfo[9]) {
1.828 www 10449: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 10450: return 'ok';
1.828 www 10451: } else {
10452: # the file is outdated, get rid of it
10453: unlink($file);
1.482 albertel 10454: }
1.828 www 10455: }
10456: # one way or the other, at this point, we don't have the file
10457: # construct the correct path for the file
10458: my @parts = ($cdom,$cnum);
10459: if ($filename =~ m|^(.+)/[^/]+$|) {
10460: push @parts, split(/\//,$1);
10461: }
10462: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10463: foreach my $part (@parts) {
10464: $path .= '/'.$part;
10465: if (!-e $path) {
10466: mkdir($path,0770);
1.482 albertel 10467: }
10468: }
1.828 www 10469: # now the path exists for sure
10470: # get a user agent
10471: my $ua=new LWP::UserAgent;
10472: my $transferfile=$file.'.in.transfer';
10473: # FIXME: this should flock
10474: if (-e $transferfile) { return 'ok'; }
10475: my $request;
10476: $uri=~s/^\///;
1.980 raeburn 10477: my $homeserver = &homeserver($cnum,$cdom);
10478: my $protocol = $protocol{$homeserver};
10479: $protocol = 'http' if ($protocol ne 'https');
10480: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 10481: my $response=$ua->request($request,$transferfile);
10482: # did it work?
10483: if ($response->is_error()) {
10484: unlink($transferfile);
10485: &logthis("Userfile repcopy failed for $uri");
10486: return -1;
10487: }
10488: # worked, rename the transfer file
10489: rename($transferfile,$file);
1.607 raeburn 10490: return 'ok';
1.481 raeburn 10491: }
10492:
1.517 albertel 10493: sub tokenwrapper {
10494: my $uri=shift;
1.980 raeburn 10495: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 10496: $uri=~s|^/||;
1.620 albertel 10497: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 10498: my $token=$1;
1.552 albertel 10499: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10500: if ($udom && $uname && $file) {
10501: $file=~s|(\?\.*)*$||;
1.949 raeburn 10502: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 10503: my $homeserver = &homeserver($uname,$udom);
10504: my $protocol = $protocol{$homeserver};
10505: $protocol = 'http' if ($protocol ne 'https');
10506: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 10507: (($uri=~/\?/)?'&':'?').'token='.$token.
10508: '&tokenissued='.$perlvar{'lonHostID'};
10509: } else {
10510: return '/adm/notfound.html';
10511: }
10512: }
10513:
1.828 www 10514: # call with reqtype HEAD: get last modification time
10515: # call with reqtype GET: get the file contents
10516: # Do not call this with reqtype GET for large files! It loads everything into memory
10517: #
1.481 raeburn 10518: sub getuploaded {
10519: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10520: $uri=~s/^\///;
1.980 raeburn 10521: my $homeserver = &homeserver($cnum,$cdom);
10522: my $protocol = $protocol{$homeserver};
10523: $protocol = 'http' if ($protocol ne 'https');
10524: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 10525: my $ua=new LWP::UserAgent;
10526: my $request=new HTTP::Request($reqtype,$uri);
10527: my $response=$ua->request($request);
10528: $$rtncode = $response->code;
1.482 albertel 10529: if (! $response->is_success()) {
10530: return 'failed';
10531: }
10532: if ($reqtype eq 'HEAD') {
1.486 www 10533: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 10534: } elsif ($reqtype eq 'GET') {
10535: $$info = $response->content;
1.472 albertel 10536: }
1.482 albertel 10537: return 'ok';
1.36 albertel 10538: }
10539:
1.481 raeburn 10540: sub readfile {
10541: my $file = shift;
10542: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10543: my $fh;
10544: open($fh,"<$file");
10545: my $a='';
1.800 albertel 10546: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 10547: return $a;
10548: }
10549:
1.36 albertel 10550: sub filelocation {
1.590 banghart 10551: my ($dir,$file) = @_;
10552: my $location;
10553: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 10554:
10555: if ($file =~ m-^/adm/-) {
10556: $file=~s-^/adm/wrapper/-/-;
10557: $file=~s-^/adm/coursedocs/showdoc/-/-;
10558: }
1.882 albertel 10559:
1.1139 www 10560: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 10561: $location = $file;
1.609 banghart 10562: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 10563: my ($udom,$uname,$filename)=
1.811 albertel 10564: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 10565: my $home=&homeserver($uname,$udom);
10566: my $is_me=0;
10567: my @ids=¤t_machine_ids();
10568: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10569: if ($is_me) {
1.1117 foxr 10570: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 10571: } else {
10572: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10573: $udom.'/'.$uname.'/'.$filename;
10574: }
1.882 albertel 10575: } elsif ($file =~ m-^/adm/-) {
10576: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 10577: } else {
10578: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 10579: $file=~s:^/(res|priv)/:/:;
10580: my $space=$1;
1.590 banghart 10581: if ( !( $file =~ m:^/:) ) {
10582: $location = $dir. '/'.$file;
10583: } else {
1.1142 raeburn 10584: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 10585: }
1.59 albertel 10586: }
1.590 banghart 10587: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 10588: while ($location=~m{/\.\./}) {
10589: if ($location =~ m{/[^/]+/\.\./}) {
10590: $location=~ s{/[^/]+/\.\./}{/}g;
10591: } else {
10592: $location=~ s{/\.\./}{/}g;
10593: }
10594: } #remove dir/..
1.590 banghart 10595: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10596: return $location;
1.46 www 10597: }
1.36 albertel 10598:
1.46 www 10599: sub hreflocation {
10600: my ($dir,$file)=@_;
1.980 raeburn 10601: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 10602: $file=filelocation($dir,$file);
1.700 albertel 10603: } elsif ($file=~m-^/adm/-) {
10604: $file=~s-^/adm/wrapper/-/-;
10605: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 10606: }
10607: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10608: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10609: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 10610: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10611: {/uploaded/$1/$2/}x;
1.46 www 10612: }
1.913 albertel 10613: if ($file=~ m{^/userfiles/}) {
10614: $file =~ s{^/userfiles/}{/uploaded/};
10615: }
1.462 albertel 10616: return $file;
1.465 albertel 10617: }
10618:
1.1139 www 10619:
10620:
10621:
10622:
1.465 albertel 10623: sub current_machine_domains {
1.853 albertel 10624: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10625: }
10626:
10627: sub machine_domains {
10628: my ($hostname) = @_;
1.465 albertel 10629: my @domains;
1.838 albertel 10630: my %hostname = &all_hostnames();
1.465 albertel 10631: while( my($id, $name) = each(%hostname)) {
1.467 matthew 10632: # &logthis("-$id-$name-$hostname-");
1.465 albertel 10633: if ($hostname eq $name) {
1.844 albertel 10634: push(@domains,&host_domain($id));
1.465 albertel 10635: }
10636: }
10637: return @domains;
10638: }
10639:
10640: sub current_machine_ids {
1.853 albertel 10641: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10642: }
10643:
10644: sub machine_ids {
10645: my ($hostname) = @_;
10646: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 10647: my @ids;
1.888 albertel 10648: my %name_to_host = &all_names();
1.889 albertel 10649: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10650: return @{ $name_to_host{$hostname} };
10651: }
10652: return;
1.31 www 10653: }
10654:
1.824 raeburn 10655: sub additional_machine_domains {
10656: my @domains;
10657: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10658: while( my $line = <$fh>) {
10659: $line =~ s/\s//g;
10660: push(@domains,$line);
10661: }
10662: return @domains;
10663: }
10664:
10665: sub default_login_domain {
10666: my $domain = $perlvar{'lonDefDomain'};
10667: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10668: foreach my $posdom (¤t_machine_domains(),
10669: &additional_machine_domains()) {
10670: if (lc($posdom) eq lc($testdomain)) {
10671: $domain=$posdom;
10672: last;
10673: }
10674: }
10675: return $domain;
10676: }
10677:
1.31 www 10678: # ------------------------------------------------------------- Declutters URLs
10679:
10680: sub declutter {
10681: my $thisfn=shift;
1.569 albertel 10682: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 10683: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 10684: $thisfn=~s/^\///;
1.697 albertel 10685: $thisfn=~s|^adm/wrapper/||;
10686: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 10687: $thisfn=~s/^res\///;
1.1032 raeburn 10688: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10689: $thisfn=~s/\?.+$//;
10690: }
1.268 www 10691: return $thisfn;
10692: }
10693:
10694: # ------------------------------------------------------------- Clutter up URLs
10695:
10696: sub clutter {
10697: my $thisfn='/'.&declutter(shift);
1.887 albertel 10698: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 10699: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 10700: $thisfn='/res'.$thisfn;
10701: }
1.1031 raeburn 10702: if ($thisfn !~m|^/adm|) {
10703: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 10704: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 10705: } else {
10706: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10707: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 10708: if ($embstyle eq 'ssi'
10709: || ($embstyle eq 'hdn')
10710: || ($embstyle eq 'rat')
10711: || ($embstyle eq 'prv')
10712: || ($embstyle eq 'ign')) {
10713: #do nothing with these
10714: } elsif (($embstyle eq 'img')
1.695 albertel 10715: || ($embstyle eq 'emb')
10716: || ($embstyle eq 'wrp')) {
10717: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 10718: } elsif ($embstyle eq 'unk'
10719: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 10720: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 10721: } else {
1.718 www 10722: # &logthis("Got a blank emb style");
1.695 albertel 10723: }
1.694 albertel 10724: }
10725: }
1.31 www 10726: return $thisfn;
1.12 www 10727: }
10728:
1.787 albertel 10729: sub clutter_with_no_wrapper {
10730: my $uri = &clutter(shift);
10731: if ($uri =~ m-^/adm/-) {
10732: $uri =~ s-^/adm/wrapper/-/-;
10733: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
10734: }
10735: return $uri;
10736: }
10737:
1.557 albertel 10738: sub freeze_escape {
10739: my ($value)=@_;
10740: if (ref($value)) {
10741: $value=&nfreeze($value);
10742: return '__FROZEN__'.&escape($value);
10743: }
10744: return &escape($value);
10745: }
10746:
1.11 www 10747:
1.557 albertel 10748: sub thaw_unescape {
10749: my ($value)=@_;
10750: if ($value =~ /^__FROZEN__/) {
10751: substr($value,0,10,undef);
10752: $value=&unescape($value);
10753: return &thaw($value);
10754: }
10755: return &unescape($value);
10756: }
10757:
1.436 albertel 10758: sub correct_line_ends {
10759: my ($result)=@_;
10760: $$result =~s/\r\n/\n/mg;
10761: $$result =~s/\r/\n/mg;
1.415 albertel 10762: }
1.1 albertel 10763: # ================================================================ Main Program
10764:
1.184 www 10765: sub goodbye {
1.204 albertel 10766: &logthis("Starting Shut down");
1.443 albertel 10767: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 10768: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 10769: #converted
1.599 albertel 10770: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 10771: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10772: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10773: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 10774: #1.1 only
1.870 albertel 10775: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10776: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10777: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10778: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10779: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 10780: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10781: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 10782: &flushcourselogs();
10783: &logthis("Shutting down");
10784: }
10785:
1.852 albertel 10786: sub get_dns {
1.869 albertel 10787: my ($url,$func,$ignore_cache) = @_;
10788: if (!$ignore_cache) {
10789: my ($content,$cached)=
10790: &Apache::lonnet::is_cached_new('dns',$url);
10791: if ($cached) {
10792: &$func($content);
10793: return;
10794: }
10795: }
10796:
10797: my %alldns;
1.852 albertel 10798: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10799: foreach my $dns (<$config>) {
10800: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 10801: my $line = $1;
10802: my ($host,$protocol) = split(/:/,$line);
10803: if ($protocol ne 'https') {
10804: $protocol = 'http';
10805: }
10806: $alldns{$host} = $protocol;
1.869 albertel 10807: }
10808: while (%alldns) {
10809: my ($dns) = keys(%alldns);
1.852 albertel 10810: my $ua=new LWP::UserAgent;
1.1134 raeburn 10811: $ua->timeout(30);
1.979 raeburn 10812: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 10813: my $response=$ua->request($request);
1.979 raeburn 10814: delete($alldns{$dns});
1.852 albertel 10815: next if ($response->is_error());
10816: my @content = split("\n",$response->content);
1.869 albertel 10817: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 10818: &$func(\@content);
1.869 albertel 10819: return;
1.852 albertel 10820: }
10821: close($config);
1.871 albertel 10822: my $which = (split('/',$url))[3];
10823: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10824: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 10825: my @content = <$config>;
10826: &$func(\@content);
10827: return;
1.852 albertel 10828: }
1.327 albertel 10829: # ------------------------------------------------------------ Read domain file
10830: {
1.852 albertel 10831: my $loaded;
1.846 albertel 10832: my %domain;
10833:
1.852 albertel 10834: sub parse_domain_tab {
10835: my ($lines) = @_;
10836: foreach my $line (@$lines) {
10837: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 10838:
1.846 albertel 10839: chomp($line);
1.852 albertel 10840: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 10841: my %this_domain;
10842: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10843: 'lang_def', 'city', 'longi', 'lati',
10844: 'primary') {
10845: $this_domain{$field} = shift(@elements);
10846: }
10847: $domain{$name} = \%this_domain;
1.852 albertel 10848: }
10849: }
1.864 albertel 10850:
10851: sub reset_domain_info {
10852: undef($loaded);
10853: undef(%domain);
10854: }
10855:
1.852 albertel 10856: sub load_domain_tab {
1.869 albertel 10857: my ($ignore_cache) = @_;
10858: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 10859: my $fh;
10860: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10861: my @lines = <$fh>;
10862: &parse_domain_tab(\@lines);
1.448 albertel 10863: }
1.852 albertel 10864: close($fh);
10865: $loaded = 1;
1.327 albertel 10866: }
1.846 albertel 10867:
10868: sub domain {
1.852 albertel 10869: &load_domain_tab() if (!$loaded);
10870:
1.846 albertel 10871: my ($name,$what) = @_;
10872: return if ( !exists($domain{$name}) );
10873:
10874: if (!$what) {
10875: return $domain{$name}{'description'};
10876: }
10877: return $domain{$name}{$what};
10878: }
1.974 raeburn 10879:
10880: sub domain_info {
10881: &load_domain_tab() if (!$loaded);
10882: return %domain;
10883: }
10884:
1.327 albertel 10885: }
10886:
10887:
1.1 albertel 10888: # ------------------------------------------------------------- Read hosts file
10889: {
1.838 albertel 10890: my %hostname;
1.844 albertel 10891: my %hostdom;
1.845 albertel 10892: my %libserv;
1.852 albertel 10893: my $loaded;
1.888 albertel 10894: my %name_to_host;
1.1074 raeburn 10895: my %internetdom;
1.1107 raeburn 10896: my %LC_dns_serv;
1.852 albertel 10897:
10898: sub parse_hosts_tab {
10899: my ($file) = @_;
10900: foreach my $configline (@$file) {
10901: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 10902: chomp($configline);
10903: if ($configline =~ /^\^/) {
10904: if ($configline =~ /^\^([\w.\-]+)/) {
10905: $LC_dns_serv{$1} = 1;
10906: }
10907: next;
10908: }
1.1074 raeburn 10909: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 10910: $name=~s/\s//g;
10911: if ($id && $domain && $role && $name) {
10912: $hostname{$id}=$name;
1.888 albertel 10913: push(@{$name_to_host{$name}}, $id);
1.852 albertel 10914: $hostdom{$id}=$domain;
10915: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 10916: if (defined($protocol)) {
10917: if ($protocol eq 'https') {
10918: $protocol{$id} = $protocol;
10919: } else {
10920: $protocol{$id} = 'http';
10921: }
1.968 raeburn 10922: } else {
1.969 raeburn 10923: $protocol{$id} = 'http';
1.968 raeburn 10924: }
1.1074 raeburn 10925: if (defined($intdom)) {
10926: $internetdom{$id} = $intdom;
10927: }
1.852 albertel 10928: }
10929: }
10930: }
1.864 albertel 10931:
10932: sub reset_hosts_info {
1.897 albertel 10933: &purge_remembered();
1.864 albertel 10934: &reset_domain_info();
10935: &reset_hosts_ip_info();
1.892 albertel 10936: undef(%name_to_host);
1.864 albertel 10937: undef(%hostname);
10938: undef(%hostdom);
10939: undef(%libserv);
10940: undef($loaded);
10941: }
1.1 albertel 10942:
1.852 albertel 10943: sub load_hosts_tab {
1.869 albertel 10944: my ($ignore_cache) = @_;
10945: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 10946: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10947: my @config = <$config>;
10948: &parse_hosts_tab(\@config);
10949: close($config);
10950: $loaded=1;
1.1 albertel 10951: }
1.852 albertel 10952:
1.838 albertel 10953: sub hostname {
1.852 albertel 10954: &load_hosts_tab() if (!$loaded);
10955:
1.838 albertel 10956: my ($lonid) = @_;
10957: return $hostname{$lonid};
10958: }
1.845 albertel 10959:
1.838 albertel 10960: sub all_hostnames {
1.852 albertel 10961: &load_hosts_tab() if (!$loaded);
10962:
1.838 albertel 10963: return %hostname;
10964: }
1.845 albertel 10965:
1.888 albertel 10966: sub all_names {
10967: &load_hosts_tab() if (!$loaded);
10968:
10969: return %name_to_host;
10970: }
10971:
1.974 raeburn 10972: sub all_host_domain {
10973: &load_hosts_tab() if (!$loaded);
10974: return %hostdom;
10975: }
10976:
1.845 albertel 10977: sub is_library {
1.852 albertel 10978: &load_hosts_tab() if (!$loaded);
10979:
1.845 albertel 10980: return exists($libserv{$_[0]});
10981: }
10982:
10983: sub all_library {
1.852 albertel 10984: &load_hosts_tab() if (!$loaded);
10985:
1.845 albertel 10986: return %libserv;
10987: }
10988:
1.1062 droeschl 10989: sub unique_library {
10990: #2x reverse removes all hostnames that appear more than once
10991: my %unique = reverse &all_library();
10992: return reverse %unique;
10993: }
10994:
1.841 albertel 10995: sub get_servers {
1.852 albertel 10996: &load_hosts_tab() if (!$loaded);
10997:
1.841 albertel 10998: my ($domain,$type) = @_;
10999: my %possible_hosts = ($type eq 'library') ? %libserv
11000: : %hostname;
11001: my %result;
1.842 albertel 11002: if (ref($domain) eq 'ARRAY') {
11003: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 11004: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 11005: $result{$host} = $hostname;
11006: }
11007: }
11008: } else {
11009: while ( my ($host,$hostname) = each(%possible_hosts)) {
11010: if ($hostdom{$host} eq $domain) {
11011: $result{$host} = $hostname;
11012: }
1.841 albertel 11013: }
11014: }
11015: return %result;
11016: }
1.845 albertel 11017:
1.1062 droeschl 11018: sub get_unique_servers {
11019: my %unique = reverse &get_servers(@_);
11020: return reverse %unique;
11021: }
11022:
1.844 albertel 11023: sub host_domain {
1.852 albertel 11024: &load_hosts_tab() if (!$loaded);
11025:
1.844 albertel 11026: my ($lonid) = @_;
11027: return $hostdom{$lonid};
11028: }
11029:
1.841 albertel 11030: sub all_domains {
1.852 albertel 11031: &load_hosts_tab() if (!$loaded);
11032:
1.841 albertel 11033: my %seen;
11034: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11035: return @uniq;
11036: }
1.1074 raeburn 11037:
11038: sub internet_dom {
11039: &load_hosts_tab() if (!$loaded);
11040:
11041: my ($lonid) = @_;
11042: return $internetdom{$lonid};
11043: }
1.1107 raeburn 11044:
11045: sub is_LC_dns {
11046: &load_hosts_tab() if (!$loaded);
11047:
11048: my ($hostname) = @_;
11049: return exists($LC_dns_serv{$hostname});
11050: }
11051:
1.1 albertel 11052: }
11053:
1.847 albertel 11054: {
11055: my %iphost;
1.856 albertel 11056: my %name_to_ip;
11057: my %lonid_to_ip;
1.869 albertel 11058:
1.847 albertel 11059: sub get_hosts_from_ip {
11060: my ($ip) = @_;
11061: my %iphosts = &get_iphost();
11062: if (ref($iphosts{$ip})) {
11063: return @{$iphosts{$ip}};
11064: }
11065: return;
1.839 albertel 11066: }
1.864 albertel 11067:
11068: sub reset_hosts_ip_info {
11069: undef(%iphost);
11070: undef(%name_to_ip);
11071: undef(%lonid_to_ip);
11072: }
1.856 albertel 11073:
11074: sub get_host_ip {
11075: my ($lonid) = @_;
11076: if (exists($lonid_to_ip{$lonid})) {
11077: return $lonid_to_ip{$lonid};
11078: }
11079: my $name=&hostname($lonid);
11080: my $ip = gethostbyname($name);
11081: return if (!$ip || length($ip) ne 4);
11082: $ip=inet_ntoa($ip);
11083: $name_to_ip{$name} = $ip;
11084: $lonid_to_ip{$lonid} = $ip;
11085: return $ip;
11086: }
1.847 albertel 11087:
11088: sub get_iphost {
1.869 albertel 11089: my ($ignore_cache) = @_;
1.894 albertel 11090:
1.869 albertel 11091: if (!$ignore_cache) {
11092: if (%iphost) {
11093: return %iphost;
11094: }
11095: my ($ip_info,$cached)=
11096: &Apache::lonnet::is_cached_new('iphost','iphost');
11097: if ($cached) {
11098: %iphost = %{$ip_info->[0]};
11099: %name_to_ip = %{$ip_info->[1]};
11100: %lonid_to_ip = %{$ip_info->[2]};
11101: return %iphost;
11102: }
11103: }
1.894 albertel 11104:
11105: # get yesterday's info for fallback
11106: my %old_name_to_ip;
11107: my ($ip_info,$cached)=
11108: &Apache::lonnet::is_cached_new('iphost','iphost');
11109: if ($cached) {
11110: %old_name_to_ip = %{$ip_info->[1]};
11111: }
11112:
1.888 albertel 11113: my %name_to_host = &all_names();
11114: foreach my $name (keys(%name_to_host)) {
1.847 albertel 11115: my $ip;
11116: if (!exists($name_to_ip{$name})) {
11117: $ip = gethostbyname($name);
11118: if (!$ip || length($ip) ne 4) {
1.894 albertel 11119: if (defined($old_name_to_ip{$name})) {
11120: $ip = $old_name_to_ip{$name};
11121: &logthis("Can't find $name defaulting to old $ip");
11122: } else {
11123: &logthis("Name $name no IP found");
11124: next;
11125: }
11126: } else {
11127: $ip=inet_ntoa($ip);
1.847 albertel 11128: }
11129: $name_to_ip{$name} = $ip;
11130: } else {
11131: $ip = $name_to_ip{$name};
1.653 albertel 11132: }
1.888 albertel 11133: foreach my $id (@{ $name_to_host{$name} }) {
11134: $lonid_to_ip{$id} = $ip;
11135: }
11136: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 11137: }
1.869 albertel 11138: &Apache::lonnet::do_cache_new('iphost','iphost',
11139: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 11140: 48*60*60);
1.869 albertel 11141:
1.847 albertel 11142: return %iphost;
1.598 albertel 11143: }
11144:
1.992 raeburn 11145: #
11146: # Given a DNS returns the loncapa host name for that DNS
11147: #
11148: sub host_from_dns {
11149: my ($dns) = @_;
11150: my @hosts;
11151: my $ip;
11152:
1.993 raeburn 11153: if (exists($name_to_ip{$dns})) {
1.992 raeburn 11154: $ip = $name_to_ip{$dns};
11155: }
11156: if (!$ip) {
11157: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11158: if (length($ip) == 4) {
11159: $ip = &IO::Socket::inet_ntoa($ip);
11160: }
11161: }
11162: if ($ip) {
11163: @hosts = get_hosts_from_ip($ip);
11164: return $hosts[0];
11165: }
11166: return undef;
1.986 foxr 11167: }
1.992 raeburn 11168:
1.1074 raeburn 11169: sub get_internet_names {
11170: my ($lonid) = @_;
11171: return if ($lonid eq '');
11172: my ($idnref,$cached)=
11173: &Apache::lonnet::is_cached_new('internetnames',$lonid);
11174: if ($cached) {
11175: return $idnref;
11176: }
11177: my $ip = &get_host_ip($lonid);
11178: my @hosts = &get_hosts_from_ip($ip);
11179: my %iphost = &get_iphost();
11180: my (@idns,%seen);
11181: foreach my $id (@hosts) {
11182: my $dom = &host_domain($id);
11183: my $prim_id = &domain($dom,'primary');
11184: my $prim_ip = &get_host_ip($prim_id);
11185: next if ($seen{$prim_ip});
11186: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11187: foreach my $id (@{$iphost{$prim_ip}}) {
11188: my $intdom = &internet_dom($id);
11189: unless (grep(/^\Q$intdom\E$/,@idns)) {
11190: push(@idns,$intdom);
11191: }
11192: }
11193: }
11194: $seen{$prim_ip} = 1;
11195: }
11196: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11197: }
11198:
1.986 foxr 11199: }
11200:
1.1079 raeburn 11201: sub all_loncaparevs {
11202: 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);
11203: }
11204:
1.862 albertel 11205: BEGIN {
11206:
11207: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11208: unless ($readit) {
11209: {
11210: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11211: %perlvar = (%perlvar,%{$configvars});
11212: }
11213:
11214:
1.1 albertel 11215: # ------------------------------------------------------ Read spare server file
11216: {
1.448 albertel 11217: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 11218:
11219: while (my $configline=<$config>) {
11220: chomp($configline);
1.284 matthew 11221: if ($configline) {
1.784 albertel 11222: my ($host,$type) = split(':',$configline,2);
1.785 albertel 11223: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 11224: push(@{ $spareid{$type} }, $host);
1.1 albertel 11225: }
11226: }
1.448 albertel 11227: close($config);
1.1 albertel 11228: }
1.11 www 11229: # ------------------------------------------------------------ Read permissions
11230: {
1.448 albertel 11231: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 11232:
11233: while (my $configline=<$config>) {
1.448 albertel 11234: chomp($configline);
11235: if ($configline) {
11236: my ($role,$perm)=split(/ /,$configline);
11237: if ($perm ne '') { $pr{$role}=$perm; }
11238: }
1.11 www 11239: }
1.448 albertel 11240: close($config);
1.11 www 11241: }
11242:
11243: # -------------------------------------------- Read plain texts for permissions
11244: {
1.448 albertel 11245: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 11246:
11247: while (my $configline=<$config>) {
1.448 albertel 11248: chomp($configline);
11249: if ($configline) {
1.742 raeburn 11250: my ($short,@plain)=split(/:/,$configline);
11251: %{$prp{$short}} = ();
11252: if (@plain > 0) {
11253: $prp{$short}{'std'} = $plain[0];
11254: for (my $i=1; $i<@plain; $i++) {
11255: $prp{$short}{'alt'.$i} = $plain[$i];
11256: }
11257: }
1.448 albertel 11258: }
1.135 www 11259: }
1.448 albertel 11260: close($config);
1.135 www 11261: }
11262:
11263: # ---------------------------------------------------------- Read package table
11264: {
1.448 albertel 11265: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 11266:
11267: while (my $configline=<$config>) {
1.483 albertel 11268: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 11269: chomp($configline);
11270: my ($short,$plain)=split(/:/,$configline);
11271: my ($pack,$name)=split(/\&/,$short);
11272: if ($plain ne '') {
11273: $packagetab{$pack.'&'.$name.'&name'}=$name;
11274: $packagetab{$short}=$plain;
11275: }
1.11 www 11276: }
1.448 albertel 11277: close($config);
1.329 matthew 11278: }
11279:
1.1073 raeburn 11280: # ---------------------------------------------------------- Read loncaparev table
11281: {
11282: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11283: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11284: while (my $configline=<$config>) {
11285: chomp($configline);
11286: my ($hostid,$loncaparev)=split(/:/,$configline);
11287: $loncaparevs{$hostid}=$loncaparev;
11288: }
11289: close($config);
11290: }
11291: }
11292: }
11293:
1.1074 raeburn 11294: # ---------------------------------------------------------- Read serverhostID table
11295: {
11296: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11297: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11298: while (my $configline=<$config>) {
11299: chomp($configline);
11300: my ($name,$id)=split(/:/,$configline);
11301: $serverhomeIDs{$name}=$id;
11302: }
11303: close($config);
11304: }
11305: }
11306: }
11307:
1.1079 raeburn 11308: {
11309: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11310: if (-e $file) {
11311: my $parser = HTML::LCParser->new($file);
11312: while (my $token = $parser->get_token()) {
11313: if ($token->[0] eq 'S') {
11314: my $item = $token->[1];
11315: my $name = $token->[2]{'name'};
11316: my $value = $token->[2]{'value'};
11317: if ($item ne '' && $name ne '' && $value ne '') {
11318: my $release = $parser->get_text();
11319: $release =~ s/(^\s*|\s*$ )//gx;
11320: $needsrelease{$item.':'.$name.':'.$value} = $release;
11321: }
11322: }
11323: }
11324: }
1.1073 raeburn 11325: }
11326:
1.1138 raeburn 11327: # ---------------------------------------------------------- Read managers table
11328: {
11329: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11330: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11331: while (my $configline=<$config>) {
11332: chomp($configline);
11333: next if ($configline =~ /^\#/);
11334: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11335: $managerstab{$configline} = 1;
11336: }
11337: }
11338: close($config);
11339: }
11340: }
11341: }
11342:
1.329 matthew 11343: # ------------- set up temporary directory
11344: {
1.1117 foxr 11345: $tmpdir = LONCAPA::tempdir();
1.329 matthew 11346:
1.11 www 11347: }
11348:
1.794 albertel 11349: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
11350: 'compress_threshold'=> 20_000,
11351: });
1.185 www 11352:
1.281 www 11353: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 11354: $dumpcount=0;
1.958 www 11355: $locknum=0;
1.22 www 11356:
1.163 harris41 11357: &logtouch();
1.672 albertel 11358: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 11359: $readit=1;
1.564 albertel 11360: {
11361: use integer;
11362: my $test=(2**32)+1;
1.568 albertel 11363: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 11364: &logthis(" Detected 64bit platform ($_64bit)");
11365: }
1.195 www 11366: }
1.1 albertel 11367: }
1.179 www 11368:
1.1 albertel 11369: 1;
1.191 harris41 11370: __END__
11371:
1.243 albertel 11372: =pod
11373:
1.191 harris41 11374: =head1 NAME
11375:
1.243 albertel 11376: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 11377:
11378: =head1 SYNOPSIS
11379:
1.243 albertel 11380: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 11381:
11382: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11383:
1.243 albertel 11384: Common parameters:
11385:
11386: =over 4
11387:
11388: =item *
11389:
11390: $uname : an internal username (if $cname expecting a course Id specifically)
11391:
11392: =item *
11393:
11394: $udom : a domain (if $cdom expecting a course's domain specifically)
11395:
11396: =item *
11397:
11398: $symb : a resource instance identifier
11399:
11400: =item *
11401:
11402: $namespace : the name of a .db file that contains the data needed or
11403: being set.
11404:
11405: =back
11406:
1.394 bowersj2 11407: =head1 OVERVIEW
1.191 harris41 11408:
1.394 bowersj2 11409: lonnet provides subroutines which interact with the
11410: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11411: about classes, users, and resources.
1.243 albertel 11412:
11413: For many of these objects you can also use this to store data about
11414: them or modify them in various ways.
1.191 harris41 11415:
1.394 bowersj2 11416: =head2 Symbs
1.191 harris41 11417:
1.394 bowersj2 11418: To identify a specific instance of a resource, LON-CAPA uses symbols
11419: or "symbs"X<symb>. These identifiers are built from the URL of the
11420: map, the resource number of the resource in the map, and the URL of
11421: the resource itself. The latter is somewhat redundant, but might help
11422: if maps change.
11423:
11424: An example is
11425:
11426: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11427:
11428: The respective map entry is
11429:
11430: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11431: title="Problem 2">
11432: </resource>
11433:
11434: Symbs are used by the random number generator, as well as to store and
11435: restore data specific to a certain instance of for example a problem.
11436:
11437: =head2 Storing And Retrieving Data
11438:
11439: X<store()>X<cstore()>X<restore()>Three of the most important functions
11440: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11441: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11442: is is the non-critical message twin of cstore. These functions are for
11443: handlers to store a perl hash to a user's permanent data space in an
11444: easy manner, and to retrieve it again on another call. It is expected
11445: that a handler would use this once at the beginning to retrieve data,
11446: and then again once at the end to send only the new data back.
11447:
11448: The data is stored in the user's data directory on the user's
11449: homeserver under the ID of the course.
11450:
11451: The hash that is returned by restore will have all of the previous
11452: value for all of the elements of the hash.
11453:
11454: Example:
11455:
11456: #creating a hash
11457: my %hash;
11458: $hash{'foo'}='bar';
11459:
11460: #storing it
11461: &Apache::lonnet::cstore(\%hash);
11462:
11463: #changing a value
11464: $hash{'foo'}='notbar';
11465:
11466: #adding a new value
11467: $hash{'bar'}='foo';
11468: &Apache::lonnet::cstore(\%hash);
11469:
11470: #retrieving the hash
11471: my %history=&Apache::lonnet::restore();
11472:
11473: #print the hash
11474: foreach my $key (sort(keys(%history))) {
11475: print("\%history{$key} = $history{$key}");
11476: }
11477:
11478: Will print out:
1.191 harris41 11479:
1.394 bowersj2 11480: %history{1:foo} = bar
11481: %history{1:keys} = foo:timestamp
11482: %history{1:timestamp} = 990455579
11483: %history{2:bar} = foo
11484: %history{2:foo} = notbar
11485: %history{2:keys} = foo:bar:timestamp
11486: %history{2:timestamp} = 990455580
11487: %history{bar} = foo
11488: %history{foo} = notbar
11489: %history{timestamp} = 990455580
11490: %history{version} = 2
11491:
11492: Note that the special hash entries C<keys>, C<version> and
11493: C<timestamp> were added to the hash. C<version> will be equal to the
11494: total number of versions of the data that have been stored. The
11495: C<timestamp> attribute will be the UNIX time the hash was
11496: stored. C<keys> is available in every historical section to list which
11497: keys were added or changed at a specific historical revision of a
11498: hash.
11499:
11500: B<Warning>: do not store the hash that restore returns directly. This
11501: will cause a mess since it will restore the historical keys as if the
11502: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 11503:
1.394 bowersj2 11504: Calling convention:
1.191 harris41 11505:
1.394 bowersj2 11506: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11507: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 11508:
1.394 bowersj2 11509: For more detailed information, see lonnet specific documentation.
1.191 harris41 11510:
1.394 bowersj2 11511: =head1 RETURN MESSAGES
1.191 harris41 11512:
1.394 bowersj2 11513: =over 4
1.191 harris41 11514:
1.394 bowersj2 11515: =item * B<con_lost>: unable to contact remote host
1.191 harris41 11516:
1.394 bowersj2 11517: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11518: when the connection is brought back up
1.191 harris41 11519:
1.394 bowersj2 11520: =item * B<con_failed>: unable to contact remote host and unable to save message
11521: for later delivery
1.191 harris41 11522:
1.967 bisitz 11523: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 11524:
1.394 bowersj2 11525: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 11526: that was requested
1.191 harris41 11527:
1.243 albertel 11528: =back
1.191 harris41 11529:
1.243 albertel 11530: =head1 PUBLIC SUBROUTINES
1.191 harris41 11531:
1.243 albertel 11532: =head2 Session Environment Functions
1.191 harris41 11533:
1.243 albertel 11534: =over 4
1.191 harris41 11535:
1.394 bowersj2 11536: =item *
11537: X<appenv()>
1.949 raeburn 11538: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 11539: the user envirnoment file, and will be restored for each access this
1.620 albertel 11540: user makes during this session, also modifies the %env for the current
1.949 raeburn 11541: process. Optional rolesarrayref - if defined contains a reference to an array
11542: of roles which are exempt from the restriction on modifying user.role entries
11543: in the user's environment.db and in %env.
1.191 harris41 11544:
11545: =item *
1.394 bowersj2 11546: X<delenv()>
1.987 raeburn 11547: B<delenv($delthis,$regexp)>: removes all items from the session
11548: environment file that begin with $delthis. If the
11549: optional second arg - $regexp - is true, $delthis is treated as a
11550: regular expression, otherwise \Q$delthis\E is used.
11551: The values are also deleted from the current processes %env.
1.191 harris41 11552:
1.795 albertel 11553: =item * get_env_multiple($name)
11554:
11555: gets $name from the %env hash, it seemlessly handles the cases where multiple
11556: values may be defined and end up as an array ref.
11557:
11558: returns an array of values
11559:
1.243 albertel 11560: =back
11561:
11562: =head2 User Information
1.191 harris41 11563:
1.243 albertel 11564: =over 4
1.191 harris41 11565:
11566: =item *
1.394 bowersj2 11567: X<queryauthenticate()>
11568: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 11569: authentication scheme
11570:
11571: =item *
1.394 bowersj2 11572: X<authenticate()>
1.1073 raeburn 11573: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 11574: authenticate user from domain's lib servers (first use the current
11575: one). C<$upass> should be the users password.
1.1073 raeburn 11576: $checkdefauth is optional (value is 1 if a check should be made to
11577: authenticate user using default authentication method, and allow
11578: account creation if username does not have account in the domain).
11579: $clientcancheckhost is optional (value is 1 if checking whether the
11580: server can host will occur on the client side in lonauth.pm).
1.191 harris41 11581:
11582: =item *
1.394 bowersj2 11583: X<homeserver()>
11584: B<homeserver($uname,$udom)>: find the server which has
11585: the user's directory and files (there must be only one), this caches
11586: the answer, and also caches if there is a borken connection.
1.191 harris41 11587:
11588: =item *
1.394 bowersj2 11589: X<idget()>
11590: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11591: (IDs are a unique resource in a domain, there must be only 1 ID per
11592: username, and only 1 username per ID in a specific domain) (returns
11593: hash: id=>name,id=>name)
1.191 harris41 11594:
11595: =item *
1.394 bowersj2 11596: X<idrget()>
11597: B<idrget($udom,@unames)>: find the IDs behind a list of
11598: usernames (returns hash: name=>id,name=>id)
1.191 harris41 11599:
11600: =item *
1.394 bowersj2 11601: X<idput()>
11602: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 11603:
11604: =item *
1.394 bowersj2 11605: X<rolesinit()>
11606: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 11607:
11608: =item *
1.551 albertel 11609: X<getsection()>
11610: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 11611: course $cname, return section name/number or '' for "not in course"
11612: and '-1' for "no section"
11613:
11614: =item *
1.394 bowersj2 11615: X<userenvironment()>
11616: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 11617: passed in @what from the requested user's environment, returns a hash
11618:
1.858 raeburn 11619: =item *
11620: X<userlog_query()>
1.859 albertel 11621: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11622: activity.log file. %filters defines filters applied when parsing the
11623: log file. These can be start or end timestamps, or the type of action
11624: - log to look for Login or Logout events, check for Checkin or
11625: Checkout, role for role selection. The response is in the form
11626: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11627: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 11628:
1.243 albertel 11629: =back
11630:
11631: =head2 User Roles
11632:
11633: =over 4
11634:
11635: =item *
11636:
1.810 raeburn 11637: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 11638: F: full access
11639: U,I,K: authentication modes (cxx only)
11640: '': forbidden
11641: 1: user needs to choose course
11642: 2: browse allowed
1.766 albertel 11643: A: passphrase authentication needed
1.243 albertel 11644:
11645: =item *
11646:
11647: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11648: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11649: and course level
11650:
11651: =item *
11652:
1.988 raeburn 11653: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11654: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 11655: $type is Course (default) or Community.
1.988 raeburn 11656: If $forcedefault evaluates to true, text returned will be default
11657: text for $type. Otherwise, if this is a course, the text returned
11658: will be a custom name for the role (if defined in the course's
11659: environment). If no custom name is defined the default is returned.
11660:
1.832 raeburn 11661: =item *
11662:
1.935 raeburn 11663: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 11664: All arguments are optional. Returns a hash of a roles, either for
11665: co-author/assistant author roles for a user's Construction Space
1.906 albertel 11666: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 11667: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11668: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11669: For each key, value is set to colon-separated start and end times for
11670: the role. If no username and domain are specified, will default to
1.934 raeburn 11671: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 11672: of role statuses (active, future or previous), roles
11673: (e.g., cc,in, st etc.) and domains of the roles which can be used
11674: to restrict the list of roles reported. If no array ref is
11675: provided for types, will default to return only active roles.
1.834 albertel 11676:
1.243 albertel 11677: =back
11678:
11679: =head2 User Modification
11680:
11681: =over 4
11682:
11683: =item *
11684:
1.957 raeburn 11685: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 11686: user for the level given by URL. Optional start and end dates (leave empty
11687: string or zero for "no date")
1.191 harris41 11688:
11689: =item *
11690:
1.243 albertel 11691: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11692: change a users, password, possible return values are: ok,
11693: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11694: refused
1.191 harris41 11695:
11696: =item *
11697:
1.243 albertel 11698: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 11699:
11700: =item *
11701:
1.1058 raeburn 11702: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11703: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11704:
11705: will update user information (firstname,middlename,lastname,generation,
11706: permanentemail), and if forceid is true, student/employee ID also.
11707: A user's institutional affiliation(s) can also be updated.
11708: User information fields will not be overwritten with empty entries
11709: unless the field is included in the $candelete array reference.
11710: This array is included when a single user is modified via "Manage Users",
11711: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 11712:
11713: =item *
11714:
1.286 matthew 11715: modifystudent
11716:
1.957 raeburn 11717: modify a student's enrollment and identification information.
1.286 matthew 11718: The course id is resolved based on the current users environment.
11719: This means the envoking user must be a course coordinator or otherwise
11720: associated with a course.
11721:
1.297 matthew 11722: This call is essentially a wrapper for lonnet::modifyuser and
11723: lonnet::modify_student_enrollment
1.286 matthew 11724:
11725: Inputs:
11726:
11727: =over 4
11728:
1.957 raeburn 11729: =item B<$udom> Student's loncapa domain
1.286 matthew 11730:
1.957 raeburn 11731: =item B<$uname> Student's loncapa login name
1.286 matthew 11732:
1.964 bisitz 11733: =item B<$uid> Student/Employee ID
1.286 matthew 11734:
1.957 raeburn 11735: =item B<$umode> Student's authentication mode
1.286 matthew 11736:
1.957 raeburn 11737: =item B<$upass> Student's password
1.286 matthew 11738:
1.957 raeburn 11739: =item B<$first> Student's first name
1.286 matthew 11740:
1.957 raeburn 11741: =item B<$middle> Student's middle name
1.286 matthew 11742:
1.957 raeburn 11743: =item B<$last> Student's last name
1.286 matthew 11744:
1.957 raeburn 11745: =item B<$gene> Student's generation
1.286 matthew 11746:
1.957 raeburn 11747: =item B<$usec> Student's section in course
1.286 matthew 11748:
11749: =item B<$end> Unix time of the roles expiration
11750:
11751: =item B<$start> Unix time of the roles start date
11752:
11753: =item B<$forceid> If defined, allow $uid to be changed
11754:
11755: =item B<$desiredhome> server to use as home server for student
11756:
1.957 raeburn 11757: =item B<$email> Student's permanent e-mail address
11758:
11759: =item B<$type> Type of enrollment (auto or manual)
11760:
1.963 raeburn 11761: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
11762:
11763: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 11764:
1.963 raeburn 11765: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 11766:
1.963 raeburn 11767: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 11768:
1.963 raeburn 11769: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 11770:
1.286 matthew 11771: =back
1.297 matthew 11772:
11773: =item *
11774:
11775: modify_student_enrollment
11776:
11777: Change a students enrollment status in a class. The environment variable
11778: 'role.request.course' must be defined for this function to proceed.
11779:
11780: Inputs:
11781:
11782: =over 4
11783:
11784: =item $udom, students domain
11785:
11786: =item $uname, students name
11787:
11788: =item $uid, students user id
11789:
11790: =item $first, students first name
11791:
11792: =item $middle
11793:
11794: =item $last
11795:
11796: =item $gene
11797:
11798: =item $usec
11799:
11800: =item $end
11801:
11802: =item $start
11803:
1.957 raeburn 11804: =item $type
11805:
11806: =item $locktype
11807:
11808: =item $cid
11809:
11810: =item $selfenroll
11811:
11812: =item $context
11813:
1.297 matthew 11814: =back
11815:
1.191 harris41 11816:
11817: =item *
11818:
1.243 albertel 11819: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11820: custom role; give a custom role to a user for the level given by URL. Specify
11821: name and domain of role author, and role name
1.191 harris41 11822:
11823: =item *
11824:
1.243 albertel 11825: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 11826:
11827: =item *
11828:
1.243 albertel 11829: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11830:
11831: =back
11832:
11833: =head2 Course Infomation
11834:
11835: =over 4
1.191 harris41 11836:
11837: =item *
11838:
1.1118 foxr 11839: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 11840: specified course id, including all environment settings for the
11841: course, the description of the course will be in the hash under the
11842: key 'description'
1.191 harris41 11843:
1.1118 foxr 11844: $options is an optional parameter that if supplied is a hash reference that controls
11845: what how this function works. It has the following key/values:
11846:
11847: =over 4
11848:
11849: =item freshen_cache
11850:
11851: If defined, and the environment cache for the course is valid, it is
11852: returned in the returned hash.
11853:
11854: =item one_time
11855:
11856: If defined, the last cache time is set to _now_
11857:
11858: =item user
11859:
11860: If defined, the supplied username is used instead of the current user.
11861:
11862:
11863: =back
11864:
1.191 harris41 11865: =item *
11866:
1.624 albertel 11867: resdata($name,$domain,$type,@which) : request for current parameter
11868: setting for a specific $type, where $type is either 'course' or 'user',
11869: @what should be a list of parameters to ask about. This routine caches
11870: answers for 5 minutes.
1.243 albertel 11871:
1.877 foxr 11872: =item *
11873:
11874: get_courseresdata($courseid, $domain) : dump the entire course resource
11875: data base, returning a hash that is keyed by the resource name and has
11876: values that are the resource value. I believe that the timestamps and
11877: versions are also returned.
11878:
11879:
1.243 albertel 11880: =back
11881:
11882: =head2 Course Modification
11883:
11884: =over 4
1.191 harris41 11885:
11886: =item *
11887:
1.243 albertel 11888: writecoursepref($courseid,%prefs) : write preferences (environment
11889: database) for a course
1.191 harris41 11890:
11891: =item *
11892:
1.1011 raeburn 11893: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11894:
11895: =item *
11896:
1.1038 raeburn 11897: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 11898:
11899: =back
11900:
11901: =head2 Resource Subroutines
11902:
11903: =over 4
1.191 harris41 11904:
11905: =item *
11906:
1.243 albertel 11907: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 11908:
11909: =item *
11910:
1.243 albertel 11911: repcopy($filename) : subscribes to the requested file, and attempts to
11912: replicate from the owning library server, Might return
1.607 raeburn 11913: 'unavailable', 'not_found', 'forbidden', 'ok', or
11914: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 11915: resource. Expects the local filesystem pathname
11916: (/home/httpd/html/res/....)
11917:
11918: =back
11919:
11920: =head2 Resource Information
11921:
11922: =over 4
1.191 harris41 11923:
11924: =item *
11925:
1.243 albertel 11926: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11927: a vairety of different possible values, $varname should be a request
11928: string, and the other parameters can be used to specify who and what
11929: one is asking about.
11930:
11931: Possible values for $varname are environment.lastname (or other item
11932: from the envirnment hash), user.name (or someother aspect about the
11933: user), resource.0.maxtries (or some other part and parameter of a
11934: resource)
1.204 albertel 11935:
11936: =item *
11937:
1.243 albertel 11938: directcondval($number) : get current value of a condition; reads from a state
11939: string
1.204 albertel 11940:
11941: =item *
11942:
1.243 albertel 11943: condval($condidx) : value of condition index based on state
1.204 albertel 11944:
11945: =item *
11946:
1.243 albertel 11947: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11948: resource's metadata, $what should be either a specific key, or either
11949: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11950: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11951:
11952: this function automatically caches all requests
1.191 harris41 11953:
11954: =item *
11955:
1.243 albertel 11956: metadata_query($query,$custom,$customshow) : make a metadata query against the
11957: network of library servers; returns file handle of where SQL and regex results
11958: will be stored for query
1.191 harris41 11959:
11960: =item *
11961:
1.243 albertel 11962: symbread($filename) : return symbolic list entry (filename argument optional);
11963: returns the data handle
1.191 harris41 11964:
11965: =item *
11966:
1.243 albertel 11967: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 11968: a possible symb for the URL in $thisfn, and if is an encryypted
11969: resource that the user accessed using /enc/ returns a 1 on success, 0
11970: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 11971: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 11972:
1.191 harris41 11973:
11974: =item *
11975:
1.243 albertel 11976: symbclean($symb) : removes versions numbers from a symb, returns the
11977: cleaned symb
1.191 harris41 11978:
11979: =item *
11980:
1.243 albertel 11981: is_on_map($uri) : checks if the $uri is somewhere on the current
11982: course map, user must be in a course for it to work.
1.191 harris41 11983:
11984: =item *
11985:
1.243 albertel 11986: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 11987:
11988: =item *
11989:
1.243 albertel 11990: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11991: a random seed, all arguments are optional, if they aren't sent it uses the
11992: environment to derive them. Note: if symb isn't sent and it can't get one
11993: from &symbread it will use the current time as its return value
1.191 harris41 11994:
11995: =item *
11996:
1.243 albertel 11997: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11998: unfakeable, receipt
1.191 harris41 11999:
12000: =item *
12001:
1.620 albertel 12002: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 12003:
12004: =item *
12005:
1.243 albertel 12006: countacc($url) : count the number of accesses to a given URL
1.191 harris41 12007:
12008: =item *
12009:
1.243 albertel 12010: 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 12011:
12012: =item *
12013:
1.243 albertel 12014: 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 12015:
12016: =item *
12017:
1.243 albertel 12018: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 12019:
12020: =item *
12021:
1.243 albertel 12022: devalidate($symb) : devalidate temporary spreadsheet calculations,
12023: forcing spreadsheet to reevaluate the resource scores next time.
12024:
12025: =back
12026:
12027: =head2 Storing/Retreiving Data
12028:
12029: =over 4
1.191 harris41 12030:
12031: =item *
12032:
1.243 albertel 12033: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12034: for this url; hashref needs to be given and should be a \%hashname; the
12035: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 12036: be derived from the env
1.191 harris41 12037:
12038: =item *
12039:
1.243 albertel 12040: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12041: uses critical subroutine
1.191 harris41 12042:
12043: =item *
12044:
1.243 albertel 12045: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12046: all args are optional
1.191 harris41 12047:
12048: =item *
12049:
1.717 albertel 12050: dumpstore($namespace,$udom,$uname,$regexp,$range) :
12051: dumps the complete (or key matching regexp) namespace into a hash
12052: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12053: normally &store()ed into
12054:
12055: $range should be either an integer '100' (give me the first 100
12056: matching records)
12057: or be two integers sperated by a - with no spaces
12058: '30-50' (give me the 30th through the 50th matching
12059: records)
12060:
12061:
12062: =item *
12063:
12064: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12065: replaces a &store() version of data with a replacement set of data
12066: for a particular resource in a namespace passed in the $storehash hash
12067: reference
12068:
12069: =item *
12070:
1.243 albertel 12071: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12072: works very similar to store/cstore, but all data is stored in a
12073: temporary location and can be reset using tmpreset, $storehash should
12074: be a hash reference, returns nothing on success
1.191 harris41 12075:
12076: =item *
12077:
1.243 albertel 12078: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12079: similar to restore, but all data is stored in a temporary location and
12080: can be reset using tmpreset. Returns a hash of values on success,
12081: error string otherwise.
1.191 harris41 12082:
12083: =item *
12084:
1.243 albertel 12085: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12086: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 12087:
12088: =item *
12089:
1.243 albertel 12090: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12091: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 12092:
12093: =item *
12094:
1.243 albertel 12095: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12096: namesp ($udom and $uname are optional)
1.191 harris41 12097:
12098: =item *
12099:
1.702 albertel 12100: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 12101: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 12102: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 12103:
1.702 albertel 12104: $range should be either an integer '100' (give me the first 100
12105: matching records)
12106: or be two integers sperated by a - with no spaces
12107: '30-50' (give me the 30th through the 50th matching
12108: records)
1.449 matthew 12109: =item *
12110:
12111: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12112: $store can be a scalar, an array reference, or if the amount to be
12113: incremented is > 1, a hash reference.
12114:
12115: ($udom and $uname are optional)
1.191 harris41 12116:
12117: =item *
12118:
1.243 albertel 12119: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12120: ($udom and $uname are optional)
1.191 harris41 12121:
12122: =item *
12123:
1.243 albertel 12124: cput($namespace,$storehash,$udom,$uname) : critical put
12125: ($udom and $uname are optional)
1.191 harris41 12126:
12127: =item *
12128:
1.748 albertel 12129: newput($namespace,$storehash,$udom,$uname) :
12130:
12131: Attempts to store the items in the $storehash, but only if they don't
12132: currently exist, if this succeeds you can be certain that you have
12133: successfully created a new key value pair in the $namespace db.
12134:
12135:
12136: Args:
12137: $namespace: name of database to store values to
12138: $storehash: hashref to store to the db
12139: $udom: (optional) domain of user containing the db
12140: $uname: (optional) name of user caontaining the db
12141:
12142: Returns:
12143: 'ok' -> succeeded in storing all keys of $storehash
12144: 'key_exists: <key>' -> failed to anything out of $storehash, as at
12145: least <key> already existed in the db (other
12146: requested keys may also already exist)
1.967 bisitz 12147: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 12148: 'con_lost' -> unable to contact request server
12149: 'refused' -> action was not allowed by remote machine
12150:
12151:
12152: =item *
12153:
1.243 albertel 12154: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12155: reference filled in from namesp (encrypts the return communication)
12156: ($udom and $uname are optional)
1.191 harris41 12157:
12158: =item *
12159:
1.243 albertel 12160: log($udom,$name,$home,$message) : write to permanent log for user; use
12161: critical subroutine
12162:
1.806 raeburn 12163: =item *
12164:
1.860 raeburn 12165: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12166: array reference filled in from namespace found in domain level on either
12167: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 12168:
12169: =item *
12170:
1.860 raeburn 12171: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
12172: domain level either on specified domain server ($uhome) or primary domain
12173: server ($udom and $uhome are optional)
1.806 raeburn 12174:
1.943 raeburn 12175: =item *
12176:
12177: get_domain_defaults($target_domain) : returns hash with defaults for
12178: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12179: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12180: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12181: Values are retrieved from cache (if current), or from domain's configuration.db
12182: (if available), or lastly from values in lonTabs/dns_domain,tab,
12183: or lonTabs/domain.tab.
12184:
12185: %domdefaults = &get_auth_defaults($target_domain);
12186:
1.243 albertel 12187: =back
12188:
12189: =head2 Network Status Functions
12190:
12191: =over 4
1.191 harris41 12192:
12193: =item *
12194:
1.1137 raeburn 12195: dirlist() : return directory list based on URI (first arg).
12196:
12197: Inputs: 1 required, 5 optional.
12198:
12199: =over
12200:
12201: =item
12202: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12203:
12204: =item
12205: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
12206:
12207: =item
12208: $username - username of user/course to be listed. Extracted from $uri if absent.
12209:
12210: =item
12211: $getpropath - boolean: 1 if prepend path using &propath().
12212:
12213: =item
12214: $getuserdir - boolean: 1 if prepend path for "userfiles".
12215:
12216: =item
12217: $alternateRoot - path to prepend in place of path from $uri.
12218:
12219: =back
12220:
12221: Returns: Array of up to two items.
12222:
12223: =over
12224:
12225: a reference to an array of files/subdirectories
12226:
12227: =over
12228:
12229: Each element in the array of files/subdirectories is a & separated list of
12230: item name and the result of running stat on the item. If dirlist was requested
12231: for a file instead of a directory, the item name will be ''. For a directory
12232: listing, if the item is a metadata file, the element will end &N&M
12233: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12234: default copyright set (1).
12235:
12236: =back
12237:
12238: a scalar containing error condition (if encountered).
12239:
12240: =over
12241:
12242: =item
12243: no_host (no homeserver identified for $username:$domain).
12244:
12245: =item
12246: no_such_host (server contacted for listing not identified as valid host).
12247:
12248: =item
12249: con_lost (connection to remote server failed).
12250:
12251: =item
12252: refused (invalid $username:$domain received on lond side).
12253:
12254: =item
12255: no_such_dir (directory at specified path on lond side does not exist).
12256:
12257: =item
12258: empty (directory at specified path on lond side is empty).
12259:
12260: =over
12261:
12262: This is currently not encountered because the &ls3, &ls2,
12263: &ls (_handler) routines on the lond side do not filter out
12264: . and .. from a directory listing.
12265:
12266: =back
12267:
12268: =back
12269:
12270: =back
1.191 harris41 12271:
12272: =item *
12273:
1.243 albertel 12274: spareserver() : find server with least workload from spare.tab
12275:
1.986 foxr 12276:
12277: =item *
12278:
12279: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12280: if there is no corresponding loncapa host.
12281:
1.243 albertel 12282: =back
12283:
1.986 foxr 12284:
1.243 albertel 12285: =head2 Apache Request
12286:
12287: =over 4
1.191 harris41 12288:
12289: =item *
12290:
1.243 albertel 12291: ssi($url,%hash) : server side include, does a complete request cycle on url to
12292: localhost, posts hash
12293:
12294: =back
12295:
12296: =head2 Data to String to Data
12297:
12298: =over 4
1.191 harris41 12299:
12300: =item *
12301:
1.243 albertel 12302: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12303: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 12304:
12305: =item *
12306:
1.243 albertel 12307: hashref2str($hashref) : convert a hashref into a string complete with
12308: escaping and '=' and '&' separators, supports elements that are
12309: arrayrefs and hashrefs
1.191 harris41 12310:
12311: =item *
12312:
1.243 albertel 12313: arrayref2str($arrayref) : convert an arrayref into a string complete
12314: with escaping and '&' separators, supports elements that are arrayrefs
12315: and hashrefs
1.191 harris41 12316:
12317: =item *
12318:
1.243 albertel 12319: str2hash($string) : convert string to hash using unescaping and
12320: splitting on '=' and '&', supports elements that are arrayrefs and
12321: hashrefs
1.191 harris41 12322:
12323: =item *
12324:
1.243 albertel 12325: str2array($string) : convert string to hash using unescaping and
12326: splitting on '&', supports elements that are arrayrefs and hashrefs
12327:
12328: =back
12329:
12330: =head2 Logging Routines
12331:
12332:
12333: These routines allow one to make log messages in the lonnet.log and
12334: lonnet.perm logfiles.
1.191 harris41 12335:
1.1119 foxr 12336: =over 4
12337:
1.191 harris41 12338: =item *
12339:
1.243 albertel 12340: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 12341:
12342: =item *
12343:
1.243 albertel 12344: logthis() : append message to the normal lonnet.log file, it gets
12345: preiodically rolled over and deleted.
1.191 harris41 12346:
12347: =item *
12348:
1.243 albertel 12349: logperm() : append a permanent message to lonnet.perm.log, this log
12350: file never gets deleted by any automated portion of the system, only
12351: messages of critical importance should go in here.
12352:
1.1119 foxr 12353:
1.243 albertel 12354: =back
12355:
12356: =head2 General File Helper Routines
12357:
12358: =over 4
1.191 harris41 12359:
12360: =item *
12361:
1.481 raeburn 12362: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12363: (a) files in /uploaded
12364: (i) If a local copy of the file exists -
12365: compares modification date of local copy with last-modified date for
12366: definitive version stored on home server for course. If local copy is
12367: stale, requests a new version from the home server and stores it.
12368: If the original has been removed from the home server, then local copy
12369: is unlinked.
12370: (ii) If local copy does not exist -
12371: requests the file from the home server and stores it.
12372:
12373: If $caller is 'uploadrep':
12374: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12375: for request for files originally uploaded via DOCS.
12376: - returns 'ok' if fresh local copy now available, -1 otherwise.
12377:
12378: Otherwise:
12379: This indicates a call from the content generation phase of the request.
12380: - returns the entire contents of the file or -1.
12381:
12382: (b) files in /res
12383: - returns the entire contents of a file or -1;
12384: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 12385:
1.712 albertel 12386:
12387: =item *
12388:
12389: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12390: reference
12391:
12392: returns either a stat() list of data about the file or an empty list
12393: if the file doesn't exist or couldn't find out about it (connection
12394: problems or user unknown)
12395:
1.191 harris41 12396: =item *
12397:
1.243 albertel 12398: filelocation($dir,$file) : returns file system location of a file
12399: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12400: directory that relative $file lookups are to looked in ($dir of /a/dir
12401: and a file of ../bob will become /a/bob)
1.191 harris41 12402:
12403: =item *
12404:
12405: hreflocation($dir,$file) : returns file system location or a URL; same as
12406: filelocation except for hrefs
12407:
12408: =item *
12409:
12410: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12411:
1.243 albertel 12412: =back
12413:
1.608 albertel 12414: =head2 Usererfile file routines (/uploaded*)
12415:
12416: =over 4
12417:
12418: =item *
12419:
12420: userfileupload(): main rotine for putting a file in a user or course's
12421: filespace, arguments are,
12422:
1.620 albertel 12423: formname - required - this is the name of the element in $env where the
1.608 albertel 12424: filename, and the contents of the file to create/modifed exist
1.620 albertel 12425: the filename is in $env{'form.'.$formname.'.filename'} and the
12426: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 12427: context - if coursedoc, store the file in the course of the active role
12428: of the current user;
12429: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12430: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 12431: subdir - required - subdirectory to put the file in under ../userfiles/
12432: if undefined, it will be placed in "unknown"
12433:
12434: (This routine calls clean_filename() to remove any dangerous
12435: characters from the filename, and then calls finuserfileupload() to
12436: complete the transaction)
12437:
12438: returns either the url of the uploaded file (/uploaded/....) if successful
12439: and /adm/notfound.html if unsuccessful
12440:
12441: =item *
12442:
12443: clean_filename(): routine for cleaing a filename up for storage in
12444: userfile space, argument is:
12445:
12446: filename - proposed filename
12447:
12448: returns: the new clean filename
12449:
12450: =item *
12451:
1.1090 raeburn 12452: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 12453: userspace, probably shouldn't be called directly
12454:
12455: docuname: username or courseid of destination for the file
12456: docudom: domain of user/course of destination for the file
12457: formname: same as for userfileupload()
1.1090 raeburn 12458: fname: filename (including subdirectories) for the file
12459: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12460: allfiles: reference to hash used to store objects found by parser
12461: codebase: reference to hash used for codebases of java objects found by parser
12462: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12463: thumbheight: height (pixels) of thumbnail to be created for uploaded image
12464: resizewidth: width to be used to resize image using resizeImage from ImageMagick
12465: resizeheight: height to be used to resize image using resizeImage from ImageMagick
12466: context: if 'overwrite', will move the uploaded file from its temporary location to
12467: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 12468: mimetype: reference to scalar to accommodate mime type determined
12469: from File::MMagic if $parser = parse.
1.608 albertel 12470:
12471: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 12472: and /adm/notfound.html if unsuccessful (or an error message if context
12473: was 'overwrite').
12474:
1.608 albertel 12475:
12476: =item *
12477:
12478: renameuserfile(): renames an existing userfile to a new name
12479:
12480: Args:
12481: docuname: username or courseid of destination for the file
12482: docudom: domain of user/course of destination for the file
12483: old: current file name (including any subdirs under userfiles)
12484: new: desired file name (including any subdirs under userfiles)
12485:
12486: =item *
12487:
12488: mkdiruserfile(): creates a directory is a userfiles dir
12489:
12490: Args:
12491: docuname: username or courseid of destination for the file
12492: docudom: domain of user/course of destination for the file
12493: dir: dir to create (including any subdirs under userfiles)
12494:
12495: =item *
12496:
12497: removeuserfile(): removes a file that exists in userfiles
12498:
12499: Args:
12500: docuname: username or courseid of destination for the file
12501: docudom: domain of user/course of destination for the file
12502: fname: filname to delete (including any subdirs under userfiles)
12503:
12504: =item *
12505:
12506: removeuploadedurl(): convience function for removeuserfile()
12507:
12508: Args:
12509: url: a full /uploaded/... url to delete
12510:
1.747 albertel 12511: =item *
12512:
12513: get_portfile_permissions():
12514: Args:
12515: domain: domain of user or course contain the portfolio files
12516: user: name of user or num of course contain the portfolio files
12517: Returns:
12518: hashref of a dump of the proper file_permissions.db
12519:
12520:
12521: =item *
12522:
12523: get_access_controls():
12524:
12525: Args:
12526: current_permissions: the hash ref returned from get_portfile_permissions()
12527: group: (optional) the group you want the files associated with
12528: file: (optional) the file you want access info on
12529:
12530: Returns:
1.749 raeburn 12531: a hash (keys are file names) of hashes containing
12532: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12533: values are XML containing access control settings (see below)
1.747 albertel 12534:
12535: Internal notes:
12536:
1.749 raeburn 12537: access controls are stored in file_permissions.db as key=value pairs.
12538: key -> path to file/file_name\0uniqueID:scope_end_start
12539: where scope -> public,guest,course,group,domains or users.
12540: end -> UNIX time for end of access (0 -> no end date)
12541: start -> UNIX time for start of access
12542:
12543: value -> XML description of access control
12544: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12545: <start></start>
12546: <end></end>
12547:
12548: <password></password> for scope type = guest
12549:
12550: <domain></domain> for scope type = course or group
12551: <number></number>
12552: <roles id="">
12553: <role></role>
12554: <access></access>
12555: <section></section>
12556: <group></group>
12557: </roles>
12558:
12559: <dom></dom> for scope type = domains
12560:
12561: <users> for scope type = users
12562: <user>
12563: <uname></uname>
12564: <udom></udom>
12565: </user>
12566: </users>
12567: </scope>
12568:
12569: Access data is also aggregated for each file in an additional key=value pair:
12570: key -> path to file/file_name\0accesscontrol
12571: value -> reference to hash
12572: hash contains key = value pairs
12573: where key = uniqueID:scope_end_start
12574: value = UNIX time record was last updated
12575:
12576: Used to improve speed of look-ups of access controls for each file.
12577:
12578: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12579:
12580: modify_access_controls():
12581:
12582: Modifies access controls for a portfolio file
12583: Args
12584: 1. file name
12585: 2. reference to hash of required changes,
12586: 3. domain
12587: 4. username
12588: where domain,username are the domain of the portfolio owner
12589: (either a user or a course)
12590:
12591: Returns:
12592: 1. result of additions or updates ('ok' or 'error', with error message).
12593: 2. result of deletions ('ok' or 'error', with error message).
12594: 3. reference to hash of any new or updated access controls.
12595: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12596: key = integer (inbound ID)
12597: value = uniqueID
1.747 albertel 12598:
1.608 albertel 12599: =back
12600:
1.243 albertel 12601: =head2 HTTP Helper Routines
12602:
12603: =over 4
12604:
1.191 harris41 12605: =item *
12606:
12607: escape() : unpack non-word characters into CGI-compatible hex codes
12608:
12609: =item *
12610:
12611: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12612:
1.243 albertel 12613: =back
12614:
12615: =head1 PRIVATE SUBROUTINES
12616:
12617: =head2 Underlying communication routines (Shouldn't call)
12618:
12619: =over 4
12620:
12621: =item *
12622:
12623: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12624:
12625: =item *
12626:
12627: reply() : uses subreply to send a message to remote machine, logs all failures
12628:
12629: =item *
12630:
12631: critical() : passes a critical message to another server; if cannot
12632: get through then place message in connection buffer directory and
12633: returns con_delayed, if incapable of saving message, returns
12634: con_failed
12635:
12636: =item *
12637:
12638: reconlonc() : tries to reconnect lonc client processes.
12639:
12640: =back
12641:
12642: =head2 Resource Access Logging
12643:
12644: =over 4
12645:
12646: =item *
12647:
12648: flushcourselogs() : flush (save) buffer logs and access logs
12649:
12650: =item *
12651:
12652: courselog($what) : save message for course in hash
12653:
12654: =item *
12655:
12656: courseacclog($what) : save message for course using &courselog(). Perform
12657: special processing for specific resource types (problems, exams, quizzes, etc).
12658:
1.191 harris41 12659: =item *
12660:
12661: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12662: as a PerlChildExitHandler
1.243 albertel 12663:
12664: =back
12665:
12666: =head2 Other
12667:
12668: =over 4
12669:
12670: =item *
12671:
12672: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 12673:
12674: =back
12675:
12676: =cut
1.877 foxr 12677:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>