Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1172.2.8
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1172.2.8! raeburn 4: # $Id: lonnet.pm,v 1.1172.2.7 2012/06/24 18:03:29 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.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'};
1.1172.2.4 raeburn 1239: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1240: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1241: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1242: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1243: my $serverhomedom = &host_domain($lonhost);
1244:
1245: my $cachetime = 60*60*24;
1246:
1247: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1248: $dom_in_use = $udom;
1249: $homeintdom = 1;
1250: } else {
1251: $dom_in_use = $serverhomedom;
1252: }
1253: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1254: unless (defined($cached)) {
1255: my %domconfig =
1256: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1257: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1258: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1259: }
1260: }
1261: if (ref($result) eq 'HASH') {
1262: my $currbalancer = $result->{'lonhost'};
1263: my $currtargets = $result->{'targets'};
1264: my $currrules = $result->{'rules'};
1265: if ($currbalancer ne '') {
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: }
1.1172.2.5 raeburn 1353: if ($is_balancer) {
1354: my $lowest_load = 30000;
1355: if (ref($offloadto) eq 'HASH') {
1356: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1357: foreach my $try_server (@{$offloadto->{'primary'}}) {
1358: ($otherserver,$lowest_load) =
1359: &compare_server_load($try_server,$otherserver,$lowest_load);
1360: }
1.1129 raeburn 1361: }
1.1172.2.5 raeburn 1362: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1363:
1.1172.2.5 raeburn 1364: if (!$found_server) {
1365: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1366: foreach my $try_server (@{$offloadto->{'default'}}) {
1367: ($otherserver,$lowest_load) =
1368: &compare_server_load($try_server,$otherserver,$lowest_load);
1369: }
1370: }
1371: }
1372: } elsif (ref($offloadto) eq 'ARRAY') {
1373: if (@{$offloadto} == 1) {
1374: $otherserver = $offloadto->[0];
1375: } elsif (@{$offloadto} > 1) {
1376: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1377: ($otherserver,$lowest_load) =
1378: &compare_server_load($try_server,$otherserver,$lowest_load);
1379: }
1380: }
1381: }
1.1172.2.5 raeburn 1382: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1383: $is_balancer = 0;
1384: if ($uname ne '' && $udom ne '') {
1385: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1386:
1387: &appenv({'user.loadbalexempt' => $lonhost,
1388: 'user.loadbalcheck.time' => time});
1389: }
1.1129 raeburn 1390: }
1391: }
1392: }
1393: return ($is_balancer,$otherserver);
1394: }
1395:
1396: sub get_loadbalancer_targets {
1397: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1398: my $offloadto;
1.1172.2.4 raeburn 1399: if ($rule_in_effect eq 'none') {
1400: return [$perlvar{'lonHostID'}];
1401: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1402: $offloadto = $currtargets;
1403: } else {
1404: if ($rule_in_effect eq 'homeserver') {
1405: my $homeserver = &homeserver($uname,$udom);
1406: if ($homeserver ne 'no_host') {
1407: $offloadto = [$homeserver];
1408: }
1409: } elsif ($rule_in_effect eq 'externalbalancer') {
1410: my %domconfig =
1411: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1412: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1413: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1414: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1415: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1416: }
1417: }
1418: } else {
1.1172.2.7 raeburn 1419: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1420: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1421: if (&hostname($remotebalancer) ne '') {
1422: $offloadto = [$remotebalancer];
1423: }
1424: }
1425: } elsif (&hostname($rule_in_effect) ne '') {
1426: $offloadto = [$rule_in_effect];
1427: }
1428: }
1429: return $offloadto;
1430: }
1431:
1.1127 raeburn 1432: sub internet_dom_servers {
1433: my ($dom) = @_;
1434: my (%uniqservers,%servers);
1435: my $primaryserver = &hostname(&domain($dom,'primary'));
1436: my @machinedoms = &machine_domains($primaryserver);
1437: foreach my $mdom (@machinedoms) {
1438: my %currservers = %servers;
1439: my %server = &get_servers($mdom);
1440: %servers = (%currservers,%server);
1441: }
1442: my %by_hostname;
1443: foreach my $id (keys(%servers)) {
1444: push(@{$by_hostname{$servers{$id}}},$id);
1445: }
1446: foreach my $hostname (sort(keys(%by_hostname))) {
1447: if (@{$by_hostname{$hostname}} > 1) {
1448: my $match = 0;
1449: foreach my $id (@{$by_hostname{$hostname}}) {
1450: if (&host_domain($id) eq $dom) {
1451: $uniqservers{$id} = $hostname;
1452: $match = 1;
1453: }
1454: }
1455: unless ($match) {
1456: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1457: }
1458: } else {
1459: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1460: }
1461: }
1462: return %uniqservers;
1463: }
1464:
1.1 albertel 1465: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1466:
1.599 albertel 1467: my %homecache;
1.1 albertel 1468: sub homeserver {
1.230 stredwic 1469: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1470: my $index="$uname:$udom";
1.426 albertel 1471:
1.599 albertel 1472: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1473:
1474: my %servers = &get_servers($udom,'library');
1475: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1476: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1477: exists($badServerCache{$tryserver}));
1.841 albertel 1478:
1479: my $answer=reply("home:$udom:$uname",$tryserver);
1480: if ($answer eq 'found') {
1481: delete($badServerCache{$tryserver});
1482: return $homecache{$index}=$tryserver;
1483: } elsif ($answer eq 'no_host') {
1484: $badServerCache{$tryserver}=1;
1485: }
1.1 albertel 1486: }
1487: return 'no_host';
1.70 www 1488: }
1489:
1490: # ------------------------------------- Find the usernames behind a list of IDs
1491:
1492: sub idget {
1493: my ($udom,@ids)=@_;
1494: my %returnhash=();
1495:
1.841 albertel 1496: my %servers = &get_servers($udom,'library');
1497: foreach my $tryserver (keys(%servers)) {
1498: my $idlist=join('&',@ids);
1499: $idlist=~tr/A-Z/a-z/;
1500: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1501: my @answer=();
1502: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1503: @answer=split(/\&/,$reply);
1504: } ;
1505: my $i;
1506: for ($i=0;$i<=$#ids;$i++) {
1507: if ($answer[$i]) {
1508: $returnhash{$ids[$i]}=$answer[$i];
1509: }
1510: }
1511: }
1.70 www 1512: return %returnhash;
1513: }
1514:
1515: # ------------------------------------- Find the IDs behind a list of usernames
1516:
1517: sub idrget {
1518: my ($udom,@unames)=@_;
1519: my %returnhash=();
1.800 albertel 1520: foreach my $uname (@unames) {
1521: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1522: }
1.70 www 1523: return %returnhash;
1524: }
1525:
1526: # ------------------------------- Store away a list of names and associated IDs
1527:
1528: sub idput {
1529: my ($udom,%ids)=@_;
1530: my %servers=();
1.800 albertel 1531: foreach my $uname (keys(%ids)) {
1532: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1533: my $uhom=&homeserver($uname,$udom);
1.70 www 1534: if ($uhom ne 'no_host') {
1.800 albertel 1535: my $id=&escape($ids{$uname});
1.70 www 1536: $id=~tr/A-Z/a-z/;
1.800 albertel 1537: my $esc_unam=&escape($uname);
1.70 www 1538: if ($servers{$uhom}) {
1.800 albertel 1539: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1540: } else {
1.800 albertel 1541: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1542: }
1543: }
1.191 harris41 1544: }
1.800 albertel 1545: foreach my $server (keys(%servers)) {
1546: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1547: }
1.344 www 1548: }
1549:
1.1023 raeburn 1550: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1551: sub dump_dom {
1.1165 droeschl 1552: my ($namespace, $udom, $regexp) = @_;
1553:
1554: $udom ||= $env{'user.domain'};
1555:
1556: return () unless $udom;
1557:
1558: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1559: }
1560:
1.1023 raeburn 1561: # ------------------------------------------ get items from domain db files
1.806 raeburn 1562:
1563: sub get_dom {
1.860 raeburn 1564: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1565: my $items='';
1566: foreach my $item (@$storearr) {
1567: $items.=&escape($item).'&';
1568: }
1569: $items=~s/\&$//;
1.860 raeburn 1570: if (!$udom) {
1571: $udom=$env{'user.domain'};
1572: if (defined(&domain($udom,'primary'))) {
1573: $uhome=&domain($udom,'primary');
1574: } else {
1.874 albertel 1575: undef($uhome);
1.860 raeburn 1576: }
1577: } else {
1578: if (!$uhome) {
1579: if (defined(&domain($udom,'primary'))) {
1580: $uhome=&domain($udom,'primary');
1581: }
1582: }
1583: }
1584: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1585: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1586: my %returnhash;
1.875 albertel 1587: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1588: return %returnhash;
1589: }
1.806 raeburn 1590: my @pairs=split(/\&/,$rep);
1591: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1592: return @pairs;
1593: }
1594: my $i=0;
1595: foreach my $item (@$storearr) {
1596: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1597: $i++;
1598: }
1599: return %returnhash;
1600: } else {
1.880 banghart 1601: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1602: }
1603: }
1604:
1605: # -------------------------------------------- put items in domain db files
1606:
1607: sub put_dom {
1.860 raeburn 1608: my ($namespace,$storehash,$udom,$uhome)=@_;
1609: if (!$udom) {
1610: $udom=$env{'user.domain'};
1611: if (defined(&domain($udom,'primary'))) {
1612: $uhome=&domain($udom,'primary');
1613: } else {
1.874 albertel 1614: undef($uhome);
1.860 raeburn 1615: }
1616: } else {
1617: if (!$uhome) {
1618: if (defined(&domain($udom,'primary'))) {
1619: $uhome=&domain($udom,'primary');
1620: }
1621: }
1622: }
1623: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1624: my $items='';
1625: foreach my $item (keys(%$storehash)) {
1626: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1627: }
1628: $items=~s/\&$//;
1629: return &reply("putdom:$udom:$namespace:$items",$uhome);
1630: } else {
1.860 raeburn 1631: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1632: }
1633: }
1634:
1.1023 raeburn 1635: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1636: sub newput_dom {
1.1023 raeburn 1637: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1638: my $result;
1639: if (!$udom) {
1640: $udom=$env{'user.domain'};
1641: }
1.1023 raeburn 1642: if ($udom) {
1643: my $uname = &get_domainconfiguser($udom);
1644: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1645: }
1646: return $result;
1647: }
1648:
1.1023 raeburn 1649: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1650: sub del_dom {
1.1023 raeburn 1651: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1652: if (ref($storearr) eq 'ARRAY') {
1653: if (!$udom) {
1654: $udom=$env{'user.domain'};
1655: }
1.1023 raeburn 1656: if ($udom) {
1657: my $uname = &get_domainconfiguser($udom);
1658: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1659: }
1660: }
1661: }
1662:
1.1023 raeburn 1663: # ----------------------------------construct domainconfig user for a domain
1664: sub get_domainconfiguser {
1665: my ($udom) = @_;
1666: return $udom.'-domainconfig';
1667: }
1668:
1.837 raeburn 1669: sub retrieve_inst_usertypes {
1670: my ($udom) = @_;
1671: my (%returnhash,@order);
1.989 raeburn 1672: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1673: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1674: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1675: %returnhash = %{$domdefs{'inststatustypes'}};
1676: @order = @{$domdefs{'inststatusorder'}};
1677: } else {
1678: if (defined(&domain($udom,'primary'))) {
1679: my $uhome=&domain($udom,'primary');
1680: my $rep=&reply("inst_usertypes:$udom",$uhome);
1681: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1682: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1683: return (\%returnhash,\@order);
1684: }
1685: my ($hashitems,$orderitems) = split(/:/,$rep);
1686: my @pairs=split(/\&/,$hashitems);
1687: foreach my $item (@pairs) {
1688: my ($key,$value)=split(/=/,$item,2);
1689: $key = &unescape($key);
1690: next if ($key =~ /^error: 2 /);
1691: $returnhash{$key}=&thaw_unescape($value);
1692: }
1693: my @esc_order = split(/\&/,$orderitems);
1694: foreach my $item (@esc_order) {
1695: push(@order,&unescape($item));
1696: }
1697: } else {
1698: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1699: }
1700: }
1701: return (\%returnhash,\@order);
1702: }
1703:
1.868 raeburn 1704: sub is_domainimage {
1705: my ($url) = @_;
1706: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1707: if (&domain($1) ne '') {
1708: return '1';
1709: }
1710: }
1711: return;
1712: }
1713:
1.899 raeburn 1714: sub inst_directory_query {
1715: my ($srch) = @_;
1716: my $udom = $srch->{'srchdomain'};
1717: my %results;
1718: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1719: my $outcome;
1.899 raeburn 1720: if ($homeserver ne '') {
1.904 albertel 1721: my $queryid=&reply("querysend:instdirsearch:".
1722: &escape($srch->{'srchby'}).':'.
1723: &escape($srch->{'srchterm'}).':'.
1724: &escape($srch->{'srchtype'}),$homeserver);
1725: my $host=&hostname($homeserver);
1726: if ($queryid !~/^\Q$host\E\_/) {
1727: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1728: return;
1729: }
1730: my $response = &get_query_reply($queryid);
1731: my $maxtries = 5;
1732: my $tries = 1;
1733: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1734: $response = &get_query_reply($queryid);
1735: $tries ++;
1736: }
1737:
1738: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1739: if ($response eq 'unavailable') {
1740: $outcome = $response;
1741: } else {
1742: $outcome = 'ok';
1743: my @matches = split(/\n/,$response);
1744: foreach my $match (@matches) {
1745: my ($key,$value) = split(/=/,$match);
1746: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1747: }
1.899 raeburn 1748: }
1749: }
1750: }
1.909 raeburn 1751: return ($outcome,%results);
1.899 raeburn 1752: }
1753:
1754: sub usersearch {
1755: my ($srch) = @_;
1756: my $dom = $srch->{'srchdomain'};
1757: my %results;
1758: my %libserv = &all_library();
1759: my $query = 'usersearch';
1760: foreach my $tryserver (keys(%libserv)) {
1761: if (&host_domain($tryserver) eq $dom) {
1762: my $host=&hostname($tryserver);
1763: my $queryid=
1.911 raeburn 1764: &reply("querysend:".&escape($query).':'.
1765: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1766: &escape($srch->{'srchtype'}).':'.
1767: &escape($srch->{'srchterm'}),$tryserver);
1768: if ($queryid !~/^\Q$host\E\_/) {
1769: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1770: next;
1.899 raeburn 1771: }
1772: my $reply = &get_query_reply($queryid);
1773: my $maxtries = 1;
1774: my $tries = 1;
1775: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1776: $reply = &get_query_reply($queryid);
1777: $tries ++;
1778: }
1779: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1780: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1781: } else {
1.911 raeburn 1782: my @matches;
1783: if ($reply =~ /\n/) {
1784: @matches = split(/\n/,$reply);
1785: } else {
1786: @matches = split(/\&/,$reply);
1787: }
1.899 raeburn 1788: foreach my $match (@matches) {
1789: my ($uname,$udom,%userhash);
1.911 raeburn 1790: foreach my $entry (split(/:/,$match)) {
1791: my ($key,$value) =
1792: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1793: $userhash{$key} = $value;
1794: if ($key eq 'username') {
1795: $uname = $value;
1796: } elsif ($key eq 'domain') {
1797: $udom = $value;
1.911 raeburn 1798: }
1.899 raeburn 1799: }
1800: $results{$uname.':'.$udom} = \%userhash;
1801: }
1802: }
1803: }
1804: }
1805: return %results;
1806: }
1807:
1.912 raeburn 1808: sub get_instuser {
1809: my ($udom,$uname,$id) = @_;
1810: my $homeserver = &domain($udom,'primary');
1811: my ($outcome,%results);
1812: if ($homeserver ne '') {
1813: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1814: &escape($id).':'.&escape($udom),$homeserver);
1815: my $host=&hostname($homeserver);
1816: if ($queryid !~/^\Q$host\E\_/) {
1817: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1818: return;
1819: }
1820: my $response = &get_query_reply($queryid);
1821: my $maxtries = 5;
1822: my $tries = 1;
1823: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1824: $response = &get_query_reply($queryid);
1825: $tries ++;
1826: }
1827: if (!&error($response) && $response ne 'refused') {
1828: if ($response eq 'unavailable') {
1829: $outcome = $response;
1830: } else {
1831: $outcome = 'ok';
1832: my @matches = split(/\n/,$response);
1833: foreach my $match (@matches) {
1834: my ($key,$value) = split(/=/,$match);
1835: $results{&unescape($key)} = &thaw_unescape($value);
1836: }
1837: }
1838: }
1839: }
1840: my %userinfo;
1841: if (ref($results{$uname}) eq 'HASH') {
1842: %userinfo = %{$results{$uname}};
1843: }
1844: return ($outcome,%userinfo);
1845: }
1846:
1847: sub inst_rulecheck {
1.923 raeburn 1848: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1849: my %returnhash;
1850: if ($udom ne '') {
1851: if (ref($rules) eq 'ARRAY') {
1852: @{$rules} = map {&escape($_);} (@{$rules});
1853: my $rulestr = join(':',@{$rules});
1854: my $homeserver=&domain($udom,'primary');
1855: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1856: my $response;
1857: if ($item eq 'username') {
1858: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1859: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1860: $homeserver));
1.923 raeburn 1861: } elsif ($item eq 'id') {
1862: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1863: ':'.&escape($id).':'.$rulestr,
1864: $homeserver));
1.945 raeburn 1865: } elsif ($item eq 'selfcreate') {
1866: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1867: &escape($udom).':'.&escape($uname).
1868: ':'.$rulestr,$homeserver));
1.923 raeburn 1869: }
1.912 raeburn 1870: if ($response ne 'refused') {
1871: my @pairs=split(/\&/,$response);
1872: foreach my $item (@pairs) {
1873: my ($key,$value)=split(/=/,$item,2);
1874: $key = &unescape($key);
1875: next if ($key =~ /^error: 2 /);
1876: $returnhash{$key}=&thaw_unescape($value);
1877: }
1878: }
1879: }
1880: }
1881: }
1882: return %returnhash;
1883: }
1884:
1885: sub inst_userrules {
1.923 raeburn 1886: my ($udom,$check) = @_;
1.912 raeburn 1887: my (%ruleshash,@ruleorder);
1888: if ($udom ne '') {
1889: my $homeserver=&domain($udom,'primary');
1890: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1891: my $response;
1892: if ($check eq 'id') {
1893: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1894: $homeserver);
1.943 raeburn 1895: } elsif ($check eq 'email') {
1896: $response=&reply('instemailrules:'.&escape($udom),
1897: $homeserver);
1.923 raeburn 1898: } else {
1899: $response=&reply('instuserrules:'.&escape($udom),
1900: $homeserver);
1901: }
1.912 raeburn 1902: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1903: ($response ne 'unknown_cmd') &&
1.912 raeburn 1904: ($response ne 'no_such_host')) {
1905: my ($hashitems,$orderitems) = split(/:/,$response);
1906: my @pairs=split(/\&/,$hashitems);
1907: foreach my $item (@pairs) {
1908: my ($key,$value)=split(/=/,$item,2);
1909: $key = &unescape($key);
1910: next if ($key =~ /^error: 2 /);
1911: $ruleshash{$key}=&thaw_unescape($value);
1912: }
1913: my @esc_order = split(/\&/,$orderitems);
1914: foreach my $item (@esc_order) {
1915: push(@ruleorder,&unescape($item));
1916: }
1917: }
1918: }
1919: }
1920: return (\%ruleshash,\@ruleorder);
1921: }
1922:
1.976 raeburn 1923: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1924:
1925: sub get_domain_defaults {
1926: my ($domain) = @_;
1927: my $cachetime = 60*60*24;
1928: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1929: if (defined($cached)) {
1930: if (ref($result) eq 'HASH') {
1931: return %{$result};
1932: }
1933: }
1934: my %domdefaults;
1935: my %domconfig =
1.989 raeburn 1936: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1937: 'requestcourses','inststatus',
1.1073 raeburn 1938: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1939: if (ref($domconfig{'defaults'}) eq 'HASH') {
1940: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1941: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1942: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1943: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1944: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 1945: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 1946: } else {
1947: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1948: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1949: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1950: }
1.976 raeburn 1951: if (ref($domconfig{'quotas'}) eq 'HASH') {
1952: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1953: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1954: } else {
1955: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1956: }
1.1172.2.6 raeburn 1957: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 1958: foreach my $item (@usertools) {
1959: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1960: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1961: }
1962: }
1963: }
1.985 raeburn 1964: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1965: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1966: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1967: }
1968: }
1.989 raeburn 1969: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1970: foreach my $item ('inststatustypes','inststatusorder') {
1971: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1972: }
1973: }
1.1047 raeburn 1974: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1975: foreach my $item ('canuse_pdfforms') {
1976: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1977: }
1978: }
1.1073 raeburn 1979: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1980: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1981: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1982: }
1983: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1984: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1985: }
1986: }
1.943 raeburn 1987: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1988: $cachetime);
1989: return %domdefaults;
1990: }
1991:
1.344 www 1992: # --------------------------------------------------- Assign a key to a student
1993:
1994: sub assign_access_key {
1.364 www 1995: #
1996: # a valid key looks like uname:udom#comments
1997: # comments are being appended
1998: #
1.498 www 1999: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2000: $kdom=
1.620 albertel 2001: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2002: $knum=
1.620 albertel 2003: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2004: $cdom=
1.620 albertel 2005: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2006: $cnum=
1.620 albertel 2007: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2008: $udom=$env{'user.name'} unless (defined($udom));
2009: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2010: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2011: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2012: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2013: # assigned to this person
2014: # - this should not happen,
1.345 www 2015: # unless something went wrong
2016: # the first time around
2017: # ready to assign
1.364 www 2018: $logentry=$1.'; '.$logentry;
1.496 www 2019: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2020: $kdom,$knum) eq 'ok') {
1.345 www 2021: # key now belongs to user
1.346 www 2022: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2023: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2024: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2025: return 'ok';
2026: } else {
2027: return
2028: 'error: Count not permanently assign key, will need to be re-entered later.';
2029: }
2030: } else {
2031: return 'error: Could not assign key, try again later.';
2032: }
1.364 www 2033: } elsif (!$existing{$ckey}) {
1.345 www 2034: # the key does not exist
2035: return 'error: The key does not exist';
2036: } else {
2037: # the key is somebody else's
2038: return 'error: The key is already in use';
2039: }
1.344 www 2040: }
2041:
1.364 www 2042: # ------------------------------------------ put an additional comment on a key
2043:
2044: sub comment_access_key {
2045: #
2046: # a valid key looks like uname:udom#comments
2047: # comments are being appended
2048: #
2049: my ($ckey,$cdom,$cnum,$logentry)=@_;
2050: $cdom=
1.620 albertel 2051: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2052: $cnum=
1.620 albertel 2053: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2054: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2055: if ($existing{$ckey}) {
2056: $existing{$ckey}.='; '.$logentry;
2057: # ready to assign
1.367 www 2058: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2059: $cdom,$cnum) eq 'ok') {
2060: return 'ok';
2061: } else {
2062: return 'error: Count not store comment.';
2063: }
2064: } else {
2065: # the key does not exist
2066: return 'error: The key does not exist';
2067: }
2068: }
2069:
1.344 www 2070: # ------------------------------------------------------ Generate a set of keys
2071:
2072: sub generate_access_keys {
1.364 www 2073: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2074: $cdom=
1.620 albertel 2075: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2076: $cnum=
1.620 albertel 2077: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2078: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2079: unless (($cdom) && ($cnum)) { return 0; }
2080: if ($number>10000) { return 0; }
2081: sleep(2); # make sure don't get same seed twice
2082: srand(time()^($$+($$<<15))); # from "Programming Perl"
2083: my $total=0;
2084: for (my $i=1;$i<=$number;$i++) {
2085: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2086: sprintf("%lx",int(100000*rand)).'-'.
2087: sprintf("%lx",int(100000*rand));
2088: $newkey=~s/1/g/g; # folks mix up 1 and l
2089: $newkey=~s/0/h/g; # and also 0 and O
2090: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2091: if ($existing{$newkey}) {
2092: $i--;
2093: } else {
1.364 www 2094: if (&put('accesskeys',
2095: { $newkey => '# generated '.localtime().
1.620 albertel 2096: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2097: '; '.$logentry },
2098: $cdom,$cnum) eq 'ok') {
1.344 www 2099: $total++;
2100: }
2101: }
2102: }
1.620 albertel 2103: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2104: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2105: return $total;
2106: }
2107:
2108: # ------------------------------------------------------- Validate an accesskey
2109:
2110: sub validate_access_key {
2111: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2112: $cdom=
1.620 albertel 2113: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2114: $cnum=
1.620 albertel 2115: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2116: $udom=$env{'user.domain'} unless (defined($udom));
2117: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2118: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2119: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2120: }
2121:
2122: # ------------------------------------- Find the section of student in a course
1.652 albertel 2123: sub devalidate_getsection_cache {
2124: my ($udom,$unam,$courseid)=@_;
2125: my $hashid="$udom:$unam:$courseid";
2126: &devalidate_cache_new('getsection',$hashid);
2127: }
1.298 matthew 2128:
1.815 albertel 2129: sub courseid_to_courseurl {
2130: my ($courseid) = @_;
2131: #already url style courseid
2132: return $courseid if ($courseid =~ m{^/});
2133:
2134: if (exists($env{'course.'.$courseid.'.num'})) {
2135: my $cnum = $env{'course.'.$courseid.'.num'};
2136: my $cdom = $env{'course.'.$courseid.'.domain'};
2137: return "/$cdom/$cnum";
2138: }
2139:
2140: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2141: if (exists($courseinfo{'num'})) {
2142: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2143: }
2144:
2145: return undef;
2146: }
2147:
1.298 matthew 2148: sub getsection {
2149: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2150: my $cachetime=1800;
1.551 albertel 2151:
2152: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2153: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2154: if (defined($cached)) { return $result; }
2155:
1.298 matthew 2156: my %Pending;
2157: my %Expired;
2158: #
2159: # Each role can either have not started yet (pending), be active,
2160: # or have expired.
2161: #
2162: # If there is an active role, we are done.
2163: #
2164: # If there is more than one role which has not started yet,
2165: # choose the one which will start sooner
2166: # If there is one role which has not started yet, return it.
2167: #
2168: # If there is more than one expired role, choose the one which ended last.
2169: # If there is a role which has expired, return it.
2170: #
1.815 albertel 2171: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2172: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2173: foreach my $key (keys(%roleshash)) {
1.479 albertel 2174: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2175: my $section=$1;
2176: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2177: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2178: my $now=time;
1.548 albertel 2179: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2180: $Expired{$end}=$section;
2181: next;
2182: }
1.548 albertel 2183: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2184: $Pending{$start}=$section;
2185: next;
2186: }
1.599 albertel 2187: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2188: }
2189: #
2190: # Presumedly there will be few matching roles from the above
2191: # loop and the sorting time will be negligible.
2192: if (scalar(keys(%Pending))) {
2193: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2194: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2195: }
2196: if (scalar(keys(%Expired))) {
2197: my @sorted = sort {$a <=> $b} keys(%Expired);
2198: my $time = pop(@sorted);
1.599 albertel 2199: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2200: }
1.599 albertel 2201: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2202: }
1.70 www 2203:
1.599 albertel 2204: sub save_cache {
2205: &purge_remembered();
1.722 albertel 2206: #&Apache::loncommon::validate_page();
1.620 albertel 2207: undef(%env);
1.780 albertel 2208: undef($env_loaded);
1.599 albertel 2209: }
1.452 albertel 2210:
1.599 albertel 2211: my $to_remember=-1;
2212: my %remembered;
2213: my %accessed;
2214: my $kicks=0;
2215: my $hits=0;
1.849 albertel 2216: sub make_key {
2217: my ($name,$id) = @_;
1.872 albertel 2218: if (length($id) > 65
2219: && length(&escape($id)) > 200) {
2220: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2221: }
1.849 albertel 2222: return &escape($name.':'.$id);
2223: }
2224:
1.599 albertel 2225: sub devalidate_cache_new {
2226: my ($name,$id,$debug) = @_;
2227: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2228: $id=&make_key($name,$id);
1.599 albertel 2229: $memcache->delete($id);
2230: delete($remembered{$id});
2231: delete($accessed{$id});
2232: }
2233:
2234: sub is_cached_new {
2235: my ($name,$id,$debug) = @_;
1.849 albertel 2236: $id=&make_key($name,$id);
1.599 albertel 2237: if (exists($remembered{$id})) {
1.1133 foxr 2238: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2239: $accessed{$id}=[&gettimeofday()];
2240: $hits++;
2241: return ($remembered{$id},1);
2242: }
2243: my $value = $memcache->get($id);
2244: if (!(defined($value))) {
2245: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2246: return (undef,undef);
1.416 albertel 2247: }
1.599 albertel 2248: if ($value eq '__undef__') {
2249: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2250: $value=undef;
2251: }
2252: &make_room($id,$value,$debug);
2253: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2254: return ($value,1);
2255: }
2256:
2257: sub do_cache_new {
2258: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2259: $id=&make_key($name,$id);
1.599 albertel 2260: my $setvalue=$value;
2261: if (!defined($setvalue)) {
2262: $setvalue='__undef__';
2263: }
1.623 albertel 2264: if (!defined($time) ) {
2265: $time=600;
2266: }
1.599 albertel 2267: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2268: my $result = $memcache->set($id,$setvalue,$time);
2269: if (! $result) {
1.872 albertel 2270: &logthis("caching of id -> $id failed");
1.910 albertel 2271: $memcache->disconnect_all();
1.872 albertel 2272: }
1.600 albertel 2273: # need to make a copy of $value
1.919 albertel 2274: &make_room($id,$value,$debug);
1.599 albertel 2275: return $value;
2276: }
2277:
2278: sub make_room {
2279: my ($id,$value,$debug)=@_;
1.919 albertel 2280:
2281: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2282: : $value;
1.599 albertel 2283: if ($to_remember<0) { return; }
2284: $accessed{$id}=[&gettimeofday()];
2285: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2286: my $to_kick;
2287: my $max_time=0;
2288: foreach my $other (keys(%accessed)) {
2289: if (&tv_interval($accessed{$other}) > $max_time) {
2290: $to_kick=$other;
2291: $max_time=&tv_interval($accessed{$other});
2292: }
2293: }
2294: delete($remembered{$to_kick});
2295: delete($accessed{$to_kick});
2296: $kicks++;
2297: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2298: return;
2299: }
2300:
1.599 albertel 2301: sub purge_remembered {
1.604 albertel 2302: #&logthis("Tossing ".scalar(keys(%remembered)));
2303: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2304: undef(%remembered);
2305: undef(%accessed);
1.428 albertel 2306: }
1.70 www 2307: # ------------------------------------- Read an entry from a user's environment
2308:
2309: sub userenvironment {
2310: my ($udom,$unam,@what)=@_;
1.976 raeburn 2311: my $items;
2312: foreach my $item (@what) {
2313: $items.=&escape($item).'&';
2314: }
2315: $items=~s/\&$//;
1.70 www 2316: my %returnhash=();
1.1009 raeburn 2317: my $uhome = &homeserver($unam,$udom);
2318: unless ($uhome eq 'no_host') {
2319: my @answer=split(/\&/,
2320: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2321: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2322: return %returnhash;
2323: }
1.1009 raeburn 2324: my $i;
2325: for ($i=0;$i<=$#what;$i++) {
2326: $returnhash{$what[$i]}=&unescape($answer[$i]);
2327: }
1.70 www 2328: }
2329: return %returnhash;
1.1 albertel 2330: }
2331:
1.617 albertel 2332: # ---------------------------------------------------------- Get a studentphoto
2333: sub studentphoto {
2334: my ($udom,$unam,$ext) = @_;
2335: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2336: if (defined($env{'request.course.id'})) {
1.708 raeburn 2337: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2338: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2339: return(&retrievestudentphoto($udom,$unam,$ext));
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: }
2350: } else {
2351: my ($result,$perm_reqd) =
1.707 albertel 2352: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2353: if ($result eq 'ok') {
2354: if (!($perm_reqd eq 'yes')) {
2355: return(&retrievestudentphoto($udom,$unam,$ext));
2356: }
2357: }
2358: }
2359: return '/adm/lonKaputt/lonlogo_broken.gif';
2360: }
2361:
2362: sub retrievestudentphoto {
2363: my ($udom,$unam,$ext,$type) = @_;
2364: my $home=&Apache::lonnet::homeserver($unam,$udom);
2365: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2366: if ($ret eq 'ok') {
2367: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2368: if ($type eq 'thumbnail') {
2369: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2370: }
2371: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2372: return $tokenurl;
2373: } else {
2374: if ($type eq 'thumbnail') {
2375: return '/adm/lonKaputt/genericstudent_tn.gif';
2376: } else {
2377: return '/adm/lonKaputt/lonlogo_broken.gif';
2378: }
1.617 albertel 2379: }
2380: }
2381:
1.263 www 2382: # -------------------------------------------------------------------- New chat
2383:
2384: sub chatsend {
1.724 raeburn 2385: my ($newentry,$anon,$group)=@_;
1.620 albertel 2386: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2387: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2388: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2389: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2390: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2391: &escape($newentry)).':'.$group,$chome);
1.292 www 2392: }
2393:
2394: # ------------------------------------------ Find current version of a resource
2395:
2396: sub getversion {
2397: my $fname=&clutter(shift);
2398: unless ($fname=~/^\/res\//) { return -1; }
2399: return ¤tversion(&filelocation('',$fname));
2400: }
2401:
2402: sub currentversion {
2403: my $fname=shift;
2404: my $author=$fname;
2405: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2406: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2407: my $home=&homeserver($uname,$udom);
1.292 www 2408: if ($home eq 'no_host') {
2409: return -1;
2410: }
1.1112 www 2411: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2412: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2413: return -1;
2414: }
1.1112 www 2415: return $answer;
1.263 www 2416: }
2417:
1.1111 www 2418: #
2419: # Return special version number of resource if set by override, empty otherwise
2420: #
2421: sub usedversion {
2422: my $fname=shift;
2423: unless ($fname) { $fname=$env{'request.uri'}; }
2424: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2425: if ($urlversion) { return $urlversion; }
2426: return '';
2427: }
2428:
1.1 albertel 2429: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2430:
1.1 albertel 2431: sub subscribe {
2432: my $fname=shift;
1.761 raeburn 2433: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2434: $fname=~s/[\n\r]//g;
1.1 albertel 2435: my $author=$fname;
2436: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2437: my ($udom,$uname)=split(/\//,$author);
2438: my $home=homeserver($uname,$udom);
1.335 albertel 2439: if ($home eq 'no_host') {
2440: return 'not_found';
1.1 albertel 2441: }
2442: my $answer=reply("sub:$fname",$home);
1.64 www 2443: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2444: $answer.=' by '.$home;
2445: }
1.1 albertel 2446: return $answer;
2447: }
2448:
1.8 www 2449: # -------------------------------------------------------------- Replicate file
2450:
2451: sub repcopy {
2452: my $filename=shift;
1.23 www 2453: $filename=~s/\/+/\//g;
1.1142 raeburn 2454: my $londocroot = $perlvar{'lonDocRoot'};
2455: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2456: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2457: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2458: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2459: return &repcopy_userfile($filename);
2460: }
1.532 albertel 2461: $filename=~s/[\n\r]//g;
1.8 www 2462: my $transname="$filename.in.transfer";
1.828 www 2463: # FIXME: this should flock
1.607 raeburn 2464: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2465: my $remoteurl=subscribe($filename);
1.64 www 2466: if ($remoteurl =~ /^con_lost by/) {
2467: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2468: return 'unavailable';
1.8 www 2469: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2470: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2471: return 'not_found';
1.64 www 2472: } elsif ($remoteurl =~ /^rejected by/) {
2473: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2474: return 'forbidden';
1.20 www 2475: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2476: return 'ok';
1.8 www 2477: } else {
1.290 www 2478: my $author=$filename;
2479: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2480: my ($udom,$uname)=split(/\//,$author);
2481: my $home=homeserver($uname,$udom);
2482: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2483: my @parts=split(/\//,$filename);
2484: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2485: if ($path ne "$londocroot/res") {
1.8 www 2486: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2487: return 'bad_request';
1.8 www 2488: }
2489: my $count;
2490: for ($count=5;$count<$#parts;$count++) {
2491: $path.="/$parts[$count]";
2492: if ((-e $path)!=1) {
2493: mkdir($path,0777);
2494: }
2495: }
2496: my $ua=new LWP::UserAgent;
2497: my $request=new HTTP::Request('GET',"$remoteurl");
2498: my $response=$ua->request($request,$transname);
2499: if ($response->is_error()) {
2500: unlink($transname);
2501: my $message=$response->status_line;
1.672 albertel 2502: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2503: ." LWP get: $message: $filename</font>");
1.607 raeburn 2504: return 'unavailable';
1.8 www 2505: } else {
1.16 www 2506: if ($remoteurl!~/\.meta$/) {
2507: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2508: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2509: if ($mresponse->is_error()) {
2510: unlink($filename.'.meta');
2511: &logthis(
1.672 albertel 2512: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2513: }
2514: }
1.8 www 2515: rename($transname,$filename);
1.607 raeburn 2516: return 'ok';
1.8 www 2517: }
1.290 www 2518: }
1.8 www 2519: }
1.330 www 2520: }
2521:
2522: # ------------------------------------------------ Get server side include body
2523: sub ssi_body {
1.381 albertel 2524: my ($filelink,%form)=@_;
1.606 matthew 2525: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2526: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2527: }
1.953 www 2528: my $output='';
2529: my $response;
1.980 raeburn 2530: if ($filelink=~/^https?\:/) {
1.954 raeburn 2531: ($output,$response)=&externalssi($filelink);
1.953 www 2532: } else {
1.1004 droeschl 2533: $filelink .= $filelink=~/\?/ ? '&' : '?';
2534: $filelink .= 'inhibitmenu=yes';
1.953 www 2535: ($output,$response)=&ssi($filelink,%form);
2536: }
1.778 albertel 2537: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2538: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2539: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2540: if (wantarray) {
2541: return ($output, $response);
2542: } else {
2543: return $output;
2544: }
1.8 www 2545: }
2546:
1.15 www 2547: # --------------------------------------------------------- Server Side Include
2548:
1.782 albertel 2549: sub absolute_url {
2550: my ($host_name) = @_;
2551: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2552: if ($host_name eq '') {
2553: $host_name = $ENV{'SERVER_NAME'};
2554: }
2555: return $protocol.$host_name;
2556: }
2557:
1.942 foxr 2558: #
2559: # Server side include.
2560: # Parameters:
2561: # fn Possibly encrypted resource name/id.
2562: # form Hash that describes how the rendering should be done
2563: # and other things.
1.944 foxr 2564: # Returns:
1.950 raeburn 2565: # Scalar context: The content of the response.
2566: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2567: #
1.15 www 2568: sub ssi {
2569:
1.944 foxr 2570: my ($fn,%form)=@_;
1.15 www 2571: my $ua=new LWP::UserAgent;
1.23 www 2572: my $request;
1.711 albertel 2573:
2574: $form{'no_update_last_known'}=1;
1.895 albertel 2575: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2576: if (%form) {
1.782 albertel 2577: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2578: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2579: } else {
1.782 albertel 2580: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2581: }
2582:
1.15 www 2583: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2 raeburn 2584: my $response= $ua->request($request);
1.944 foxr 2585: if (wantarray) {
1.1172.2.3 raeburn 2586: return ($response->content, $response);
1.944 foxr 2587: } else {
1.1172.2.3 raeburn 2588: return $response->content;
1.942 foxr 2589: }
1.324 www 2590: }
2591:
2592: sub externalssi {
2593: my ($url)=@_;
2594: my $ua=new LWP::UserAgent;
2595: my $request=new HTTP::Request('GET',$url);
2596: my $response=$ua->request($request);
1.954 raeburn 2597: if (wantarray) {
2598: return ($response->content, $response);
2599: } else {
2600: return $response->content;
2601: }
1.15 www 2602: }
1.254 www 2603:
1.492 albertel 2604: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2605:
2606: sub allowuploaded {
2607: my ($srcurl,$url)=@_;
2608: $url=&clutter(&declutter($url));
2609: my $dir=$url;
2610: $dir=~s/\/[^\/]+$//;
2611: my %httpref=();
2612: my $httpurl=&hreflocation('',$url);
2613: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2614: &Apache::lonnet::appenv(\%httpref);
1.254 www 2615: }
1.477 raeburn 2616:
1.478 albertel 2617: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2618: # input: action, courseID, current domain, intended
1.637 raeburn 2619: # path to file, source of file, instruction to parse file for objects,
2620: # ref to hash for embedded objects,
2621: # ref to hash for codebase of java objects.
1.1095 raeburn 2622: # reference to scalar to accommodate mime type determined
2623: # from File::MMagic if $parser = parse.
1.637 raeburn 2624: #
1.485 raeburn 2625: # output: url to file (if action was uploaddoc),
2626: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2627: #
1.478 albertel 2628: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2629: # course.
1.477 raeburn 2630: #
1.478 albertel 2631: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2632: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2633: # course's home server.
1.477 raeburn 2634: #
1.478 albertel 2635: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2636: # be copied from $source (current location) to
2637: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2638: # and will then be copied to
2639: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2640: # course's home server.
1.485 raeburn 2641: #
1.481 raeburn 2642: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2643: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2644: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2645: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2646: # in course's home server.
1.637 raeburn 2647: #
1.477 raeburn 2648:
2649: sub process_coursefile {
1.1095 raeburn 2650: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2651: $mimetype)=@_;
1.477 raeburn 2652: my $fetchresult;
1.638 albertel 2653: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2654: if ($action eq 'propagate') {
1.638 albertel 2655: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2656: $home);
1.481 raeburn 2657: } else {
1.477 raeburn 2658: my $fpath = '';
2659: my $fname = $file;
1.478 albertel 2660: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2661: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2662: my $filepath = &build_filepath($fpath);
1.481 raeburn 2663: if ($action eq 'copy') {
2664: if ($source eq '') {
2665: $fetchresult = 'no source file';
2666: return $fetchresult;
2667: } else {
2668: my $destination = $filepath.'/'.$fname;
2669: rename($source,$destination);
2670: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2671: $home);
1.481 raeburn 2672: }
2673: } elsif ($action eq 'uploaddoc') {
2674: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2675: print $fh $env{'form.'.$source};
1.481 raeburn 2676: close($fh);
1.637 raeburn 2677: if ($parser eq 'parse') {
1.1024 raeburn 2678: my $mm = new File::MMagic;
1.1095 raeburn 2679: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2680: if ($type eq 'text/html') {
1.1024 raeburn 2681: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2682: unless ($parse_result eq 'ok') {
2683: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2684: }
1.637 raeburn 2685: }
1.1095 raeburn 2686: if (ref($mimetype)) {
2687: $$mimetype = $type;
2688: }
1.637 raeburn 2689: }
1.477 raeburn 2690: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2691: $home);
1.481 raeburn 2692: if ($fetchresult eq 'ok') {
2693: return '/uploaded/'.$fpath.'/'.$fname;
2694: } else {
2695: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2696: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2697: return '/adm/notfound.html';
2698: }
1.477 raeburn 2699: }
2700: }
1.485 raeburn 2701: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2702: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2703: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2704: }
2705: return $fetchresult;
2706: }
2707:
1.637 raeburn 2708: sub build_filepath {
2709: my ($fpath) = @_;
2710: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2711: unless ($fpath eq '') {
2712: my @parts=split('/',$fpath);
2713: foreach my $part (@parts) {
2714: $filepath.= '/'.$part;
2715: if ((-e $filepath)!=1) {
2716: mkdir($filepath,0777);
2717: }
2718: }
2719: }
2720: return $filepath;
2721: }
2722:
2723: sub store_edited_file {
1.638 albertel 2724: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2725: my $file = $primary_url;
2726: $file =~ s#^/uploaded/$docudom/$docuname/##;
2727: my $fpath = '';
2728: my $fname = $file;
2729: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2730: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2731: my $filepath = &build_filepath($fpath);
2732: open(my $fh,'>'.$filepath.'/'.$fname);
2733: print $fh $content;
2734: close($fh);
1.638 albertel 2735: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2736: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2737: $home);
1.637 raeburn 2738: if ($$fetchresult eq 'ok') {
2739: return '/uploaded/'.$fpath.'/'.$fname;
2740: } else {
1.638 albertel 2741: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2742: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2743: return '/adm/notfound.html';
2744: }
2745: }
2746:
1.531 albertel 2747: sub clean_filename {
1.831 albertel 2748: my ($fname,$args)=@_;
1.315 www 2749: # Replace Windows backslashes by forward slashes
1.257 www 2750: $fname=~s/\\/\//g;
1.831 albertel 2751: if (!$args->{'keep_path'}) {
2752: # Get rid of everything but the actual filename
2753: $fname=~s/^.*\/([^\/]+)$/$1/;
2754: }
1.315 www 2755: # Replace spaces by underscores
2756: $fname=~s/\s+/\_/g;
2757: # Replace all other weird characters by nothing
1.831 albertel 2758: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2759: # Replace all .\d. sequences with _\d. so they no longer look like version
2760: # numbers
2761: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2762: return $fname;
2763: }
1.1051 raeburn 2764: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2765: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2766: # image with the same aspect ratio as the original, but with dimensions which do
2767: # not exceed $resizewidth and $resizeheight.
2768:
1.984 neumanie 2769: sub resizeImage {
1.1051 raeburn 2770: my ($img_path,$resizewidth,$resizeheight) = @_;
2771: my $ima = Image::Magick->new;
2772: my $resized;
2773: if (-e $img_path) {
2774: $ima->Read($img_path);
2775: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2776: my $width = $ima->Get('width');
2777: my $height = $ima->Get('height');
2778: if ($width > $resizewidth) {
2779: my $factor = $width/$resizewidth;
2780: my $newheight = $height/$factor;
2781: $ima->Scale(width=>$resizewidth,height=>$newheight);
2782: $resized = 1;
2783: }
2784: }
2785: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2786: my $width = $ima->Get('width');
2787: my $height = $ima->Get('height');
2788: if ($height > $resizeheight) {
2789: my $factor = $height/$resizeheight;
2790: my $newwidth = $width/$factor;
2791: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2792: $resized = 1;
2793: }
2794: }
2795: if ($resized) {
2796: $ima->Write($img_path);
2797: }
2798: }
2799: return;
1.977 amueller 2800: }
2801:
1.608 albertel 2802: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2803: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 2804: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 2805: # $context - possible values: coursedoc, existingfile, overwrite,
2806: # canceloverwrite, or ''.
2807: # if 'coursedoc': upload to the current course
2808: # if 'existingfile': write file to tmp/overwrites directory
2809: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2810: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2811: # $subdir - directory in userfile to store the file into
1.858 raeburn 2812: # $parser - instruction to parse file for objects ($parser = parse)
2813: # $allfiles - reference to hash for embedded objects
2814: # $codebase - reference to hash for codebase of java objects
2815: # $desuname - username for permanent storage of uploaded file
2816: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2817: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2818: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2819: # $resizewidth - width (pixels) to which to resize uploaded image
2820: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 2821: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 2822: # from File::MMagic.
1.858 raeburn 2823: #
1.686 albertel 2824: # output: url of file in userspace, or error: <message>
2825: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2826:
1.531 albertel 2827: sub userfileupload {
1.1090 raeburn 2828: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 2829: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2830: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2831: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2832: $fname=&clean_filename($fname);
1.1090 raeburn 2833: # See if there is anything left
1.257 www 2834: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 2835: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2836: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2837: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2838: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2839: my $now = time;
1.1090 raeburn 2840: my $filepath;
1.1095 raeburn 2841: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 2842: $filepath = 'tmp/helprequests/'.$now;
2843: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2844: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2845: '_'.$env{'user.domain'}.'/pending';
2846: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2847: my ($docuname,$docudom);
2848: if ($destudom) {
2849: $docudom = $destudom;
2850: } else {
2851: $docudom = $env{'user.domain'};
2852: }
2853: if ($destuname) {
2854: $docuname = $destuname;
2855: } else {
2856: $docuname = $env{'user.name'};
2857: }
2858: if (exists($env{'form.group'})) {
2859: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2860: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2861: }
2862: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2863: if ($context eq 'canceloverwrite') {
2864: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2865: if (-e $tempfile) {
2866: my @info = stat($tempfile);
2867: if ($info[9] eq $env{'form.timestamp'}) {
2868: unlink($tempfile);
2869: }
2870: }
2871: return;
1.523 raeburn 2872: }
2873: }
1.1090 raeburn 2874: # Create the directory if not present
1.741 raeburn 2875: my @parts=split(/\//,$filepath);
2876: my $fullpath = $perlvar{'lonDaemons'};
2877: for (my $i=0;$i<@parts;$i++) {
2878: $fullpath .= '/'.$parts[$i];
2879: if ((-e $fullpath)!=1) {
2880: mkdir($fullpath,0777);
2881: }
2882: }
2883: open(my $fh,'>'.$fullpath.'/'.$fname);
2884: print $fh $env{'form.'.$formname};
2885: close($fh);
1.1090 raeburn 2886: if ($context eq 'existingfile') {
2887: my @info = stat($fullpath.'/'.$fname);
2888: return ($fullpath.'/'.$fname,$info[9]);
2889: } else {
2890: return $fullpath.'/'.$fname;
2891: }
1.523 raeburn 2892: }
1.995 raeburn 2893: if ($subdir eq 'scantron') {
2894: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 2895: } else {
1.995 raeburn 2896: $fname="$subdir/$fname";
2897: }
1.1090 raeburn 2898: if ($context eq 'coursedoc') {
1.638 albertel 2899: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2900: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2901: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2902: return &finishuserfileupload($docuname,$docudom,
2903: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2904: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 2905: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2906: } else {
1.620 albertel 2907: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2908: return &process_coursefile('uploaddoc',$docuname,$docudom,
2909: $fname,$formname,$parser,
1.1095 raeburn 2910: $allfiles,$codebase,$mimetype);
1.481 raeburn 2911: }
1.719 banghart 2912: } elsif (defined($destuname)) {
2913: my $docuname=$destuname;
2914: my $docudom=$destudom;
1.860 raeburn 2915: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2916: $parser,$allfiles,$codebase,
1.1051 raeburn 2917: $thumbwidth,$thumbheight,
1.1095 raeburn 2918: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2919: } else {
1.638 albertel 2920: my $docuname=$env{'user.name'};
2921: my $docudom=$env{'user.domain'};
1.714 raeburn 2922: if (exists($env{'form.group'})) {
2923: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2924: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2925: }
1.860 raeburn 2926: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2927: $parser,$allfiles,$codebase,
1.1051 raeburn 2928: $thumbwidth,$thumbheight,
1.1095 raeburn 2929: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2930: }
1.271 www 2931: }
2932:
2933: sub finishuserfileupload {
1.860 raeburn 2934: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 2935: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2936: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2937: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2938:
1.860 raeburn 2939: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2940: $file=$fname;
2941: if ($fname=~m|/|) {
2942: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2943: $path.=$fnamepath.'/';
2944: }
1.259 www 2945: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2946: my $count;
2947: for ($count=4;$count<=$#parts;$count++) {
2948: $filepath.="/$parts[$count]";
2949: if ((-e $filepath)!=1) {
2950: mkdir($filepath,0777);
2951: }
2952: }
1.984 neumanie 2953:
1.258 www 2954: # Save the file
2955: {
1.701 albertel 2956: if (!open(FH,'>'.$filepath.'/'.$file)) {
2957: &logthis('Failed to create '.$filepath.'/'.$file);
2958: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2959: return '/adm/notfound.html';
2960: }
1.1090 raeburn 2961: if ($context eq 'overwrite') {
1.1117 foxr 2962: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 2963: my $target = $filepath.'/'.$file;
2964: if (-e $source) {
2965: my @info = stat($source);
2966: if ($info[9] eq $env{'form.timestamp'}) {
2967: unless (&File::Copy::move($source,$target)) {
2968: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2969: return "Moving from $source failed";
2970: }
2971: } else {
2972: return "Temporary file: $source had unexpected date/time for last modification";
2973: }
2974: } else {
2975: return "Temporary file: $source missing";
2976: }
2977: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2978: &logthis('Failed to write to '.$filepath.'/'.$file);
2979: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2980: return '/adm/notfound.html';
2981: }
1.570 albertel 2982: close(FH);
1.1051 raeburn 2983: if ($resizewidth && $resizeheight) {
2984: my $mm = new File::MMagic;
2985: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2986: if ($mime_type =~ m{^image/}) {
2987: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2988: }
1.977 amueller 2989: }
1.258 www 2990: }
1.1152 raeburn 2991: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
2992: if (ref($mimetype)) {
2993: if ($$mimetype eq '') {
2994: my $mm = new File::MMagic;
2995: my $type = $mm->checktype_filename($filepath.'/'.$file);
2996: $$mimetype = $type;
2997: }
2998: }
2999: }
1.637 raeburn 3000: if ($parser eq 'parse') {
1.1152 raeburn 3001: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3002: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3003: $allfiles,$codebase);
3004: unless ($parse_result eq 'ok') {
3005: &logthis('Failed to parse '.$filepath.$file.
3006: ' for embedded media: '.$parse_result);
3007: }
1.637 raeburn 3008: }
3009: }
1.860 raeburn 3010: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3011: my $input = $filepath.'/'.$file;
3012: my $output = $filepath.'/'.'tn-'.$file;
3013: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3014: system("convert -sample $thumbsize $input $output");
3015: if (-e $filepath.'/'.'tn-'.$file) {
3016: $fetchthumb = 1;
3017: }
3018: }
1.858 raeburn 3019:
1.259 www 3020: # Notify homeserver to grep it
3021: #
1.984 neumanie 3022: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3023: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3024: if ($fetchresult eq 'ok') {
1.860 raeburn 3025: if ($fetchthumb) {
3026: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3027: if ($thumbresult ne 'ok') {
3028: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3029: $docuhome.': '.$thumbresult);
3030: }
3031: }
1.259 www 3032: #
1.258 www 3033: # Return the URL to it
1.494 albertel 3034: return '/uploaded/'.$path.$file;
1.263 www 3035: } else {
1.494 albertel 3036: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3037: ': '.$fetchresult);
1.263 www 3038: return '/adm/notfound.html';
1.858 raeburn 3039: }
1.493 albertel 3040: }
3041:
1.637 raeburn 3042: sub extract_embedded_items {
1.961 raeburn 3043: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3044: my @state = ();
1.1164 raeburn 3045: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3046: my %javafiles = (
3047: codebase => '',
3048: code => '',
3049: archive => ''
3050: );
3051: my %mediafiles = (
3052: src => '',
3053: movie => '',
3054: );
1.648 raeburn 3055: my $p;
3056: if ($content) {
3057: $p = HTML::LCParser->new($content);
3058: } else {
1.961 raeburn 3059: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3060: }
1.641 albertel 3061: while (my $t=$p->get_token()) {
1.640 albertel 3062: if ($t->[0] eq 'S') {
3063: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3064: push(@state, $tagname);
1.648 raeburn 3065: if (lc($tagname) eq 'allow') {
3066: &add_filetype($allfiles,$attr->{'src'},'src');
3067: }
1.640 albertel 3068: if (lc($tagname) eq 'img') {
3069: &add_filetype($allfiles,$attr->{'src'},'src');
3070: }
1.886 albertel 3071: if (lc($tagname) eq 'a') {
3072: &add_filetype($allfiles,$attr->{'href'},'href');
3073: }
1.645 raeburn 3074: if (lc($tagname) eq 'script') {
1.1164 raeburn 3075: my $src;
1.645 raeburn 3076: if ($attr->{'archive'} =~ /\.jar$/i) {
3077: &add_filetype($allfiles,$attr->{'archive'},'archive');
3078: } else {
1.1164 raeburn 3079: if ($attr->{'src'} ne '') {
3080: $src = $attr->{'src'};
3081: &add_filetype($allfiles,$src,'src');
3082: }
3083: }
3084: my $text = $p->get_trimmed_text();
3085: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3086: my @swfargs = split(/,/,$1);
3087: foreach my $item (@swfargs) {
3088: $item =~ s/["']//g;
3089: $item =~ s/^\s+//;
3090: $item =~ s/\s+$//;
3091: }
3092: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3093: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3094: push(@{$related{$swfargs[0]}},$swfargs[2]);
3095: } else {
3096: $related{$swfargs[0]} = [$swfargs[2]];
3097: }
3098: }
1.645 raeburn 3099: }
3100: }
3101: if (lc($tagname) eq 'link') {
3102: if (lc($attr->{'rel'}) eq 'stylesheet') {
3103: &add_filetype($allfiles,$attr->{'href'},'href');
3104: }
3105: }
1.640 albertel 3106: if (lc($tagname) eq 'object' ||
3107: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3108: foreach my $item (keys(%javafiles)) {
3109: $javafiles{$item} = '';
3110: }
1.1164 raeburn 3111: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3112: $lastids{lc($tagname)} = $attr->{'id'};
3113: }
1.640 albertel 3114: }
3115: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3116: my $name = lc($attr->{'name'});
3117: foreach my $item (keys(%javafiles)) {
3118: if ($name eq $item) {
3119: $javafiles{$item} = $attr->{'value'};
3120: last;
3121: }
3122: }
1.1164 raeburn 3123: my $pathfrom;
1.640 albertel 3124: foreach my $item (keys(%mediafiles)) {
3125: if ($name eq $item) {
1.1164 raeburn 3126: $pathfrom = $attr->{'value'};
3127: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3128: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3129: last;
3130: }
3131: }
1.1164 raeburn 3132: if ($name eq 'flashvars') {
3133: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3134: }
3135: if ($pathfrom ne '') {
3136: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3137: $pathfrom);
3138: }
1.640 albertel 3139: }
3140: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3141: foreach my $item (keys(%javafiles)) {
3142: if ($attr->{$item}) {
3143: $javafiles{$item} = $attr->{$item};
3144: last;
3145: }
3146: }
3147: foreach my $item (keys(%mediafiles)) {
3148: if ($attr->{$item}) {
3149: &add_filetype($allfiles,$attr->{$item},$item);
3150: last;
3151: }
3152: }
1.1164 raeburn 3153: if (lc($tagname) eq 'embed') {
3154: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3155: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3156: $attr->{'src'});
3157: }
3158: }
1.640 albertel 3159: }
1.1164 raeburn 3160: if ($t->[4] =~ m{/>$}) {
3161: pop(@state);
3162: }
1.640 albertel 3163: } elsif ($t->[0] eq 'E') {
3164: my ($tagname) = ($t->[1]);
3165: if ($javafiles{'codebase'} ne '') {
3166: $javafiles{'codebase'} .= '/';
3167: }
3168: if (lc($tagname) eq 'applet' ||
3169: lc($tagname) eq 'object' ||
3170: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3171: ) {
3172: foreach my $item (keys(%javafiles)) {
3173: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3174: my $file=$javafiles{'codebase'}.$javafiles{$item};
3175: &add_filetype($allfiles,$file,$item);
3176: }
3177: }
3178: }
3179: pop @state;
3180: }
3181: }
1.1164 raeburn 3182: foreach my $id (sort(keys(%flashvars))) {
3183: if ($shockwave{$id} ne '') {
3184: my @pairs = split(/\&/,$flashvars{$id});
3185: foreach my $pair (@pairs) {
3186: my ($key,$value) = split(/\=/,$pair);
3187: if ($key eq 'thumb') {
3188: &add_filetype($allfiles,$value,$key);
3189: } elsif ($key eq 'content') {
3190: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3191: my ($ext) = ($value =~ /\.([^.]+)$/);
3192: if ($ext ne '') {
3193: &add_filetype($allfiles,$path.$value,$ext);
3194: }
3195: }
3196: }
3197: }
3198: }
1.637 raeburn 3199: return 'ok';
3200: }
3201:
1.639 albertel 3202: sub add_filetype {
3203: my ($allfiles,$file,$type)=@_;
3204: if (exists($allfiles->{$file})) {
3205: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3206: push(@{$allfiles->{$file}}, &escape($type));
3207: }
3208: } else {
3209: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3210: }
3211: }
3212:
1.1164 raeburn 3213: sub embedded_dependency {
3214: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3215: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3216: if (($identifier ne '') &&
3217: (ref($related->{$identifier}) eq 'ARRAY') &&
3218: ($pathfrom ne '')) {
3219: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3220: foreach my $dep (@{$related->{$identifier}}) {
3221: &add_filetype($allfiles,$path.$dep,'object');
3222: }
3223: }
3224: }
3225: return;
3226: }
3227:
1.493 albertel 3228: sub removeuploadedurl {
1.984 neumanie 3229: my ($url)=@_;
3230: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3231: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3232: }
3233:
3234: sub removeuserfile {
3235: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3236: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3237: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3238: if ($result eq 'ok') {
1.798 raeburn 3239: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3240: my $metafile = $fname.'.meta';
3241: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3242: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3243: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3244: my $sqlresult =
1.823 albertel 3245: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3246: 'portfolio_metadata',$group,
3247: 'delete');
1.798 raeburn 3248: }
3249: }
3250: return $result;
1.257 www 3251: }
1.15 www 3252:
1.530 albertel 3253: sub mkdiruserfile {
3254: my ($docuname,$docudom,$dir)=@_;
3255: my $home=&homeserver($docuname,$docudom);
3256: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3257: }
3258:
1.531 albertel 3259: sub renameuserfile {
3260: my ($docuname,$docudom,$old,$new)=@_;
3261: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3262: my $result = &reply("renameuserfile:$docudom:$docuname:".
3263: &escape("$old").':'.&escape("$new"),$home);
3264: if ($result eq 'ok') {
3265: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3266: my $oldmeta = $old.'.meta';
3267: my $newmeta = $new.'.meta';
3268: my $metaresult =
3269: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3270: my $url = "/uploaded/$docudom/$docuname/$old";
3271: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3272: my $sqlresult =
1.823 albertel 3273: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3274: 'portfolio_metadata',$group,
3275: 'delete');
1.798 raeburn 3276: }
3277: }
3278: return $result;
1.531 albertel 3279: }
3280:
1.14 www 3281: # ------------------------------------------------------------------------- Log
3282:
3283: sub log {
3284: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3285: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3286: }
3287:
3288: # ------------------------------------------------------------------ Course Log
1.352 www 3289: #
3290: # This routine flushes several buffers of non-mission-critical nature
3291: #
1.157 www 3292:
3293: sub flushcourselogs {
1.352 www 3294: &logthis('Flushing log buffers');
3295: #
3296: # course logs
3297: # This is a log of all transactions in a course, which can be used
3298: # for data mining purposes
3299: #
3300: # It also collects the courseid database, which lists last transaction
3301: # times and course titles for all courseids
3302: #
3303: my %courseidbuffer=();
1.921 raeburn 3304: foreach my $crsid (keys(%courselogs)) {
1.352 www 3305: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3306: &escape($courselogs{$crsid}),
3307: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3308: delete $courselogs{$crsid};
3309: } else {
3310: &logthis('Failed to flush log buffer for '.$crsid);
3311: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3312: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3313: " exceeded maximum size, deleting.</font>");
3314: delete $courselogs{$crsid};
3315: }
1.352 www 3316: }
1.920 raeburn 3317: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3318: 'description' => $coursedescrbuf{$crsid},
3319: 'inst_code' => $courseinstcodebuf{$crsid},
3320: 'type' => $coursetypebuf{$crsid},
3321: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3322: };
1.191 harris41 3323: }
1.352 www 3324: #
3325: # Write course id database (reverse lookup) to homeserver of courses
3326: # Is used in pickcourse
3327: #
1.840 albertel 3328: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3329: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3330: $courseidbuffer{$crs_home},
3331: $crs_home,'timeonly');
1.352 www 3332: }
3333: #
3334: # File accesses
3335: # Writes to the dynamic metadata of resources to get hit counts, etc.
3336: #
1.449 matthew 3337: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3338: if ($entry =~ /___count$/) {
3339: my ($dom,$name);
1.807 albertel 3340: ($dom,$name,undef)=
1.811 albertel 3341: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3342: if (! defined($dom) || $dom eq '' ||
3343: ! defined($name) || $name eq '') {
1.620 albertel 3344: my $cid = $env{'request.course.id'};
3345: $dom = $env{'request.'.$cid.'.domain'};
3346: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3347: }
1.450 matthew 3348: my $value = $accesshash{$entry};
3349: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3350: my %temphash=($url => $value);
1.449 matthew 3351: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3352: if ($result eq 'ok') {
3353: delete $accesshash{$entry};
3354: }
3355: } else {
1.811 albertel 3356: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3357: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3358: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3359: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3360: delete $accesshash{$entry};
3361: }
1.185 www 3362: }
1.191 harris41 3363: }
1.352 www 3364: #
3365: # Roles
3366: # Reverse lookup of user roles for course faculty/staff and co-authorship
3367: #
1.800 albertel 3368: foreach my $entry (keys(%userrolehash)) {
1.351 www 3369: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3370: split(/\:/,$entry);
3371: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3372: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3373: $rudom,$runame) eq 'ok') {
3374: delete $userrolehash{$entry};
3375: }
3376: }
1.662 raeburn 3377: #
3378: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3379: #
3380: my %domrolebuffer = ();
1.1000 raeburn 3381: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3382: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3383: if ($domrolebuffer{$rudom}) {
3384: $domrolebuffer{$rudom}.='&'.&escape($entry).
3385: '='.&escape($domainrolehash{$entry});
3386: } else {
3387: $domrolebuffer{$rudom}.=&escape($entry).
3388: '='.&escape($domainrolehash{$entry});
3389: }
3390: delete $domainrolehash{$entry};
3391: }
3392: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3393: my %servers = &get_servers($dom,'library');
3394: foreach my $tryserver (keys(%servers)) {
3395: unless (&reply('domroleput:'.$dom.':'.
3396: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3397: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3398: }
1.662 raeburn 3399: }
3400: }
1.186 www 3401: $dumpcount++;
1.157 www 3402: }
3403:
3404: sub courselog {
3405: my $what=shift;
1.158 www 3406: $what=time.':'.$what;
1.620 albertel 3407: unless ($env{'request.course.id'}) { return ''; }
3408: $coursedombuf{$env{'request.course.id'}}=
3409: $env{'course.'.$env{'request.course.id'}.'.domain'};
3410: $coursenumbuf{$env{'request.course.id'}}=
3411: $env{'course.'.$env{'request.course.id'}.'.num'};
3412: $coursehombuf{$env{'request.course.id'}}=
3413: $env{'course.'.$env{'request.course.id'}.'.home'};
3414: $coursedescrbuf{$env{'request.course.id'}}=
3415: $env{'course.'.$env{'request.course.id'}.'.description'};
3416: $courseinstcodebuf{$env{'request.course.id'}}=
3417: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3418: $courseownerbuf{$env{'request.course.id'}}=
3419: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3420: $coursetypebuf{$env{'request.course.id'}}=
3421: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3422: if (defined $courselogs{$env{'request.course.id'}}) {
3423: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3424: } else {
1.620 albertel 3425: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3426: }
1.620 albertel 3427: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3428: &flushcourselogs();
3429: }
1.158 www 3430: }
3431:
3432: sub courseacclog {
3433: my $fnsymb=shift;
1.620 albertel 3434: unless ($env{'request.course.id'}) { return ''; }
3435: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3436: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3437: $what.=':POST';
1.583 matthew 3438: # FIXME: Probably ought to escape things....
1.800 albertel 3439: foreach my $key (keys(%env)) {
3440: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3441: my $formitem = $1;
3442: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3443: $what.=':'.$formitem.'='.$env{$key};
3444: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3445: $what.=':'.$formitem.'='.$env{$key};
3446: }
1.158 www 3447: }
1.191 harris41 3448: }
1.583 matthew 3449: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3450: # FIXME: We should not be depending on a form parameter that someone
3451: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3452: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3453: $what.= ':POST';
3454: # FIXME: Probably ought to escape things....
3455: foreach my $element ('courseexp','crsfulltext','crsrelated',
3456: 'crsdiscuss') {
1.620 albertel 3457: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3458: }
3459: }
1.158 www 3460: }
3461: &courselog($what);
1.149 www 3462: }
3463:
1.185 www 3464: sub countacc {
3465: my $url=&declutter(shift);
1.458 matthew 3466: return if (! defined($url) || $url eq '');
1.620 albertel 3467: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3468: #
3469: # Mark that this url was used in this course
3470: #
1.620 albertel 3471: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3472: #
3473: # Increase the access count for this resource in this child process
3474: #
1.281 www 3475: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3476: $accesshash{$key}++;
1.185 www 3477: }
1.349 www 3478:
1.361 www 3479: sub linklog {
3480: my ($from,$to)=@_;
3481: $from=&declutter($from);
3482: $to=&declutter($to);
3483: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3484: $accesshash{$to.'___'.$from.'___goto'}=1;
3485: }
1.1160 www 3486:
3487: sub statslog {
3488: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3489: if ($users<2) { return; }
3490: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3491: 'course' => $env{'request.course.id'},
3492: 'sections' => '"all"',
3493: 'num_students' => $users,
3494: 'part' => $part,
3495: 'symb' => $symb,
3496: 'mean_tries' => $av_attempts,
3497: 'deg_of_diff' => $degdiff});
3498: foreach my $key (keys(%dynstore)) {
3499: $accesshash{$key}=$dynstore{$key};
3500: }
3501: }
1.361 www 3502:
1.349 www 3503: sub userrolelog {
3504: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3505: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3506: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3507: $userrolehash
3508: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3509: =$tend.':'.$tstart;
1.662 raeburn 3510: }
1.1169 droeschl 3511: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3512: $userrolehash
3513: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3514: =$tend.':'.$tstart;
3515: }
1.1169 droeschl 3516: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3517: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3518: $domainrolehash
3519: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3520: = $tend.':'.$tstart;
3521: }
1.351 www 3522: }
3523:
1.957 raeburn 3524: sub courserolelog {
3525: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3526: if (($trole eq 'cc') || ($trole eq 'in') ||
3527: ($trole eq 'ep') || ($trole eq 'ad') ||
3528: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 3529: ($trole=~/^cr/) || ($trole eq 'gr') ||
3530: ($trole eq 'co')) {
1.957 raeburn 3531: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3532: my $cdom = $1;
3533: my $cnum = $2;
3534: my $sec = $3;
3535: my $namespace = 'rolelog';
3536: my %storehash = (
3537: role => $trole,
3538: start => $tstart,
3539: end => $tend,
3540: selfenroll => $selfenroll,
3541: context => $context,
3542: );
3543: if ($trole eq 'gr') {
3544: $namespace = 'groupslog';
3545: $storehash{'group'} = $sec;
3546: } else {
3547: $storehash{'section'} = $sec;
3548: }
3549: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 3550: if (($trole ne 'st') || ($sec ne '')) {
3551: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3552: }
1.957 raeburn 3553: }
3554: }
3555: return;
3556: }
3557:
1.351 www 3558: sub get_course_adv_roles {
1.948 raeburn 3559: my ($cid,$codes) = @_;
1.620 albertel 3560: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3561: my %coursehash=&coursedescription($cid);
1.988 raeburn 3562: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3563: my %nothide=();
1.800 albertel 3564: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3565: if ($user !~ /:/) {
3566: $nothide{join(':',split(/[\@]/,$user))}=1;
3567: } else {
3568: $nothide{$user}=1;
3569: }
1.470 www 3570: }
1.351 www 3571: my %returnhash=();
3572: my %dumphash=
3573: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3574: my $now=time;
1.997 raeburn 3575: my %privileged;
1.1000 raeburn 3576: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3577: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3578: if (($tstart) && ($tstart<0)) { next; }
3579: if (($tend) && ($tend<$now)) { next; }
3580: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3581: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3582: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3583: unless (ref($privileged{$domain}) eq 'HASH') {
3584: my %dompersonnel =
1.998 raeburn 3585: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3586: $privileged{$domain} = {};
3587: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3588: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3589: foreach my $user (keys(%{$dompersonnel{$server}})) {
3590: my ($trole,$uname,$udom) = split(/:/,$user);
3591: $privileged{$udom}{$uname} = 1;
3592: }
3593: }
3594: }
3595: }
3596: if ((exists($privileged{$domain}{$username})) &&
3597: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3598: if ($role eq 'cr') { next; }
1.948 raeburn 3599: if ($codes) {
3600: if ($section) { $role .= ':'.$section; }
3601: if ($returnhash{$role}) {
3602: $returnhash{$role}.=','.$username.':'.$domain;
3603: } else {
3604: $returnhash{$role}=$username.':'.$domain;
3605: }
1.351 www 3606: } else {
1.988 raeburn 3607: my $key=&plaintext($role,$crstype);
1.973 bisitz 3608: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3609: if ($returnhash{$key}) {
3610: $returnhash{$key}.=','.$username.':'.$domain;
3611: } else {
3612: $returnhash{$key}=$username.':'.$domain;
3613: }
1.351 www 3614: }
1.948 raeburn 3615: }
1.400 www 3616: return %returnhash;
3617: }
3618:
3619: sub get_my_roles {
1.937 raeburn 3620: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3621: unless (defined($uname)) { $uname=$env{'user.name'}; }
3622: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3623: my (%dumphash,%nothide);
1.1086 raeburn 3624: if ($context eq 'userroles') {
1.1166 raeburn 3625: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 3626: } else {
3627: %dumphash=
1.400 www 3628: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3629: if ($hidepriv) {
3630: my %coursehash=&coursedescription($udom.'_'.$uname);
3631: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3632: if ($user !~ /:/) {
3633: $nothide{join(':',split(/[\@]/,$user))} = 1;
3634: } else {
3635: $nothide{$user} = 1;
3636: }
3637: }
3638: }
1.858 raeburn 3639: }
1.400 www 3640: my %returnhash=();
3641: my $now=time;
1.999 raeburn 3642: my %privileged;
1.800 albertel 3643: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3644: my ($role,$tend,$tstart);
3645: if ($context eq 'userroles') {
1.1149 raeburn 3646: next if ($entry =~ /^rolesdef/);
1.867 raeburn 3647: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3648: } else {
3649: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3650: }
1.400 www 3651: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3652: my $status = 'active';
1.939 raeburn 3653: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3654: $status = 'previous';
3655: }
3656: if (($tstart) && ($now<$tstart)) {
3657: $status = 'future';
3658: }
3659: if (ref($types) eq 'ARRAY') {
3660: if (!grep(/^\Q$status\E$/,@{$types})) {
3661: next;
3662: }
3663: } else {
3664: if ($status ne 'active') {
3665: next;
3666: }
3667: }
1.867 raeburn 3668: my ($rolecode,$username,$domain,$section,$area);
3669: if ($context eq 'userroles') {
3670: ($area,$rolecode) = split(/_/,$entry);
3671: (undef,$domain,$username,$section) = split(/\//,$area);
3672: } else {
3673: ($role,$username,$domain,$section) = split(/\:/,$entry);
3674: }
1.832 raeburn 3675: if (ref($roledoms) eq 'ARRAY') {
3676: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3677: next;
3678: }
3679: }
3680: if (ref($roles) eq 'ARRAY') {
3681: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3682: if ($role =~ /^cr\//) {
3683: if (!grep(/^cr$/,@{$roles})) {
3684: next;
3685: }
1.1104 raeburn 3686: } elsif ($role =~ /^gr\//) {
3687: if (!grep(/^gr$/,@{$roles})) {
3688: next;
3689: }
1.922 raeburn 3690: } else {
3691: next;
3692: }
1.832 raeburn 3693: }
1.867 raeburn 3694: }
1.937 raeburn 3695: if ($hidepriv) {
1.999 raeburn 3696: if ($context eq 'userroles') {
3697: if ((&privileged($username,$domain)) &&
3698: (!$nothide{$username.':'.$domain})) {
3699: next;
3700: }
3701: } else {
3702: unless (ref($privileged{$domain}) eq 'HASH') {
3703: my %dompersonnel =
3704: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3705: $privileged{$domain} = {};
3706: if (keys(%dompersonnel)) {
3707: foreach my $server (keys(%dompersonnel)) {
3708: if (ref($dompersonnel{$server}) eq 'HASH') {
3709: foreach my $user (keys(%{$dompersonnel{$server}})) {
3710: my ($trole,$uname,$udom) = split(/:/,$user);
3711: $privileged{$udom}{$uname} = $trole;
3712: }
3713: }
3714: }
3715: }
3716: }
3717: if (exists($privileged{$domain}{$username})) {
3718: if (!$nothide{$username.':'.$domain}) {
3719: next;
3720: }
3721: }
1.937 raeburn 3722: }
3723: }
1.933 raeburn 3724: if ($withsec) {
3725: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3726: $tstart.':'.$tend;
3727: } else {
3728: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3729: }
1.832 raeburn 3730: }
1.373 www 3731: return %returnhash;
1.399 www 3732: }
3733:
3734: # ----------------------------------------------------- Frontpage Announcements
3735: #
3736: #
3737:
3738: sub postannounce {
3739: my ($server,$text)=@_;
1.844 albertel 3740: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3741: unless ($text=~/\w/) { $text=''; }
3742: return &reply('setannounce:'.&escape($text),$server);
3743: }
3744:
3745: sub getannounce {
1.448 albertel 3746:
3747: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3748: my $announcement='';
1.800 albertel 3749: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3750: close($fh);
1.399 www 3751: if ($announcement=~/\w/) {
3752: return
3753: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3754: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3755: } else {
3756: return '';
3757: }
3758: } else {
3759: return '';
3760: }
1.351 www 3761: }
1.353 www 3762:
3763: # ---------------------------------------------------------- Course ID routines
3764: # Deal with domain's nohist_courseid.db files
3765: #
3766:
3767: sub courseidput {
1.921 raeburn 3768: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3769: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3770: my $outcome;
3771: if ($caller eq 'timeonly') {
3772: my $cids = '';
3773: foreach my $item (keys(%$storehash)) {
3774: $cids.=&escape($item).'&';
3775: }
3776: $cids=~s/\&$//;
3777: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3778: $coursehome);
3779: } else {
3780: my $items = '';
3781: foreach my $item (keys(%$storehash)) {
3782: $items.= &escape($item).'='.
3783: &freeze_escape($$storehash{$item}).'&';
3784: }
3785: $items=~s/\&$//;
3786: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3787: $coursehome);
1.918 raeburn 3788: }
3789: if ($outcome eq 'unknown_cmd') {
3790: my $what;
3791: foreach my $cid (keys(%$storehash)) {
3792: $what .= &escape($cid).'=';
1.921 raeburn 3793: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3794: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3795: }
3796: $what =~ s/\:$/&/;
3797: }
3798: $what =~ s/\&$//;
3799: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3800: } else {
3801: return $outcome;
3802: }
1.353 www 3803: }
3804:
3805: sub courseiddump {
1.921 raeburn 3806: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3807: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3808: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3809: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3810: my $as_hash = 1;
3811: my %returnhash;
3812: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3813: my %libserv = &all_library();
3814: foreach my $tryserver (keys(%libserv)) {
3815: if ( ( $hostidflag == 1
3816: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3817: || (!defined($hostidflag)) ) {
3818:
1.918 raeburn 3819: if (($domfilter eq '') ||
3820: (&host_domain($tryserver) eq $domfilter)) {
3821: my $rep =
3822: &reply('courseiddump:'.&host_domain($tryserver).':'.
3823: $sincefilter.':'.&escape($descfilter).':'.
3824: &escape($instcodefilter).':'.&escape($ownerfilter).
3825: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3826: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3827: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3828: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3829: &escape($cc_clone).':'.$cloneonly.':'.
3830: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071 raeburn 3831: &escape($creationcontext).':'.$domcloner,
3832: $tryserver);
1.918 raeburn 3833: my @pairs=split(/\&/,$rep);
3834: foreach my $item (@pairs) {
3835: my ($key,$value)=split(/\=/,$item,2);
3836: $key = &unescape($key);
3837: next if ($key =~ /^error: 2 /);
3838: my $result = &thaw_unescape($value);
3839: if (ref($result) eq 'HASH') {
3840: $returnhash{$key}=$result;
3841: } else {
1.921 raeburn 3842: my @responses = split(/:/,$value);
3843: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3844: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3845: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3846: }
1.1008 raeburn 3847: }
1.353 www 3848: }
3849: }
3850: }
3851: }
3852: return %returnhash;
3853: }
3854:
1.1055 raeburn 3855: sub courselastaccess {
3856: my ($cdom,$cnum,$hostidref) = @_;
3857: my %returnhash;
3858: if ($cdom && $cnum) {
3859: my $chome = &homeserver($cnum,$cdom);
3860: if ($chome ne 'no_host') {
3861: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3862: &extract_lastaccess(\%returnhash,$rep);
3863: }
3864: } else {
3865: if (!$cdom) { $cdom=''; }
3866: my %libserv = &all_library();
3867: foreach my $tryserver (keys(%libserv)) {
3868: if (ref($hostidref) eq 'ARRAY') {
3869: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3870: }
3871: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3872: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3873: &extract_lastaccess(\%returnhash,$rep);
3874: }
3875: }
3876: }
3877: return %returnhash;
3878: }
3879:
3880: sub extract_lastaccess {
3881: my ($returnhash,$rep) = @_;
3882: if (ref($returnhash) eq 'HASH') {
3883: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3884: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3885: $rep eq '') {
3886: my @pairs=split(/\&/,$rep);
3887: foreach my $item (@pairs) {
3888: my ($key,$value)=split(/\=/,$item,2);
3889: $key = &unescape($key);
3890: next if ($key =~ /^error: 2 /);
3891: $returnhash->{$key} = &thaw_unescape($value);
3892: }
3893: }
3894: }
3895: return;
3896: }
3897:
1.658 raeburn 3898: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3899:
3900: sub dcmailput {
1.685 raeburn 3901: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3902: my $status = &Apache::lonnet::critical(
1.740 www 3903: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3904: &escape($message),$server);
1.662 raeburn 3905: return $status;
3906: }
3907:
1.658 raeburn 3908: sub dcmaildump {
3909: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3910: my %returnhash=();
1.846 albertel 3911:
3912: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3913: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3914: &escape($enddate).':';
3915: my @esc_senders=map { &escape($_)} @$senders;
3916: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3917: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3918: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3919: if (($key) && ($value)) {
3920: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3921: }
3922: }
3923: }
3924: return %returnhash;
3925: }
1.662 raeburn 3926: # ---------------------------------------------------------- Domain roles
3927:
3928: sub get_domain_roles {
3929: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3930: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3931: $startdate = '.';
3932: }
1.1018 raeburn 3933: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3934: $enddate = '.';
3935: }
1.922 raeburn 3936: my $rolelist;
3937: if (ref($roles) eq 'ARRAY') {
3938: $rolelist = join(':',@{$roles});
3939: }
1.662 raeburn 3940: my %personnel = ();
1.841 albertel 3941:
3942: my %servers = &get_servers($dom,'library');
3943: foreach my $tryserver (keys(%servers)) {
3944: %{$personnel{$tryserver}}=();
3945: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3946: &escape($startdate).':'.
3947: &escape($enddate).':'.
3948: &escape($rolelist), $tryserver))) {
3949: my ($key,$value) = split(/\=/,$line,2);
3950: if (($key) && ($value)) {
3951: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3952: }
3953: }
1.662 raeburn 3954: }
3955: return %personnel;
3956: }
1.658 raeburn 3957:
1.1057 www 3958: # ----------------------------------------------------------- Interval timing
1.149 www 3959:
1.1153 www 3960: {
3961: # Caches needed for speedup of navmaps
3962: # We don't want to cache this for very long at all (5 seconds at most)
3963: #
3964: # The user for whom we cache
3965: my $cachedkey='';
3966: # The cached times for this user
3967: my %cachedtimes=();
3968: # When this was last done
3969: my $cachedtime=();
3970:
3971: sub load_all_first_access {
1.1154 raeburn 3972: my ($uname,$udom)=@_;
1.1156 www 3973: if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2 raeburn 3974: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 3975: return;
3976: }
3977: $cachedtime=time;
3978: $cachedkey=$uname.':'.$udom;
3979: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 3980: }
3981:
1.504 albertel 3982: sub get_first_access {
1.1162 raeburn 3983: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 3984: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3985: if ($argsymb) { $symb=$argsymb; }
3986: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 3987: if ($argmap) { $map = $argmap; }
1.926 albertel 3988: if ($type eq 'course') {
3989: $res='course';
3990: } elsif ($type eq 'map') {
1.588 albertel 3991: $res=&symbread($map);
3992: } else {
3993: $res=$symb;
3994: }
1.1153 www 3995: &load_all_first_access($uname,$udom);
3996: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 3997: }
3998:
3999: sub set_first_access {
1.1162 raeburn 4000: my ($type,$interval)=@_;
1.790 albertel 4001: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4002: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4003: if ($type eq 'course') {
4004: $res='course';
4005: } elsif ($type eq 'map') {
1.588 albertel 4006: $res=&symbread($map);
4007: } else {
4008: $res=$symb;
4009: }
1.1153 www 4010: $cachedkey='';
1.1162 raeburn 4011: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4012: if (!$firstaccess) {
1.1162 raeburn 4013: my $start = time;
4014: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4015: $udom,$uname);
4016: if ($putres eq 'ok') {
4017: &put('timerinterval',{"$courseid\0$res"=>$interval},
4018: $udom,$uname);
4019: &appenv(
4020: {
4021: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4022: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4023: }
4024: );
4025: }
4026: return $putres;
1.505 albertel 4027: }
4028: return 'already_set';
1.504 albertel 4029: }
1.1153 www 4030: }
1.110 www 4031: # --------------------------------------------- Set Expire Date for Spreadsheet
4032:
4033: sub expirespread {
4034: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4035: my $cid=$env{'request.course.id'};
1.110 www 4036: if ($cid) {
4037: my $now=time;
4038: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4039: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4040: $env{'course.'.$cid.'.num'}.
1.110 www 4041: ':nohist_expirationdates:'.
4042: &escape($key).'='.$now,
1.620 albertel 4043: $env{'course.'.$cid.'.home'})
1.110 www 4044: }
4045: return 'ok';
1.14 www 4046: }
4047:
1.109 www 4048: # ----------------------------------------------------- Devalidate Spreadsheets
4049:
4050: sub devalidate {
1.325 www 4051: my ($symb,$uname,$udom)=@_;
1.620 albertel 4052: my $cid=$env{'request.course.id'};
1.109 www 4053: if ($cid) {
1.391 matthew 4054: # delete the stored spreadsheets for
4055: # - the student level sheet of this user in course's homespace
4056: # - the assessment level sheet for this resource
4057: # for this user in user's homespace
1.553 albertel 4058: # - current conditional state info
1.325 www 4059: my $key=$uname.':'.$udom.':';
1.109 www 4060: my $status=
1.299 matthew 4061: &del('nohist_calculatedsheets',
1.391 matthew 4062: [$key.'studentcalc:'],
1.620 albertel 4063: $env{'course.'.$cid.'.domain'},
4064: $env{'course.'.$cid.'.num'})
1.133 albertel 4065: .' '.
4066: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4067: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4068: unless ($status eq 'ok ok') {
4069: &logthis('Could not devalidate spreadsheet '.
1.325 www 4070: $uname.' at '.$udom.' for '.
1.109 www 4071: $symb.': '.$status);
1.133 albertel 4072: }
1.553 albertel 4073: &delenv('user.state.'.$cid);
1.109 www 4074: }
4075: }
4076:
1.265 albertel 4077: sub get_scalar {
4078: my ($string,$end) = @_;
4079: my $value;
4080: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4081: $value = $1;
4082: } elsif ($$string =~ s/^([^&]*?)&//) {
4083: $value = $1;
4084: }
4085: return &unescape($value);
4086: }
4087:
4088: sub array2str {
4089: my (@array) = @_;
4090: my $result=&arrayref2str(\@array);
4091: $result=~s/^__ARRAY_REF__//;
4092: $result=~s/__END_ARRAY_REF__$//;
4093: return $result;
4094: }
4095:
1.204 albertel 4096: sub arrayref2str {
4097: my ($arrayref) = @_;
1.265 albertel 4098: my $result='__ARRAY_REF__';
1.204 albertel 4099: foreach my $elem (@$arrayref) {
1.265 albertel 4100: if(ref($elem) eq 'ARRAY') {
4101: $result.=&arrayref2str($elem).'&';
4102: } elsif(ref($elem) eq 'HASH') {
4103: $result.=&hashref2str($elem).'&';
4104: } elsif(ref($elem)) {
4105: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4106: } else {
4107: $result.=&escape($elem).'&';
4108: }
4109: }
4110: $result=~s/\&$//;
1.265 albertel 4111: $result .= '__END_ARRAY_REF__';
1.204 albertel 4112: return $result;
4113: }
4114:
1.168 albertel 4115: sub hash2str {
1.204 albertel 4116: my (%hash) = @_;
4117: my $result=&hashref2str(\%hash);
1.265 albertel 4118: $result=~s/^__HASH_REF__//;
4119: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4120: return $result;
4121: }
4122:
4123: sub hashref2str {
4124: my ($hashref)=@_;
1.265 albertel 4125: my $result='__HASH_REF__';
1.800 albertel 4126: foreach my $key (sort(keys(%$hashref))) {
4127: if (ref($key) eq 'ARRAY') {
4128: $result.=&arrayref2str($key).'=';
4129: } elsif (ref($key) eq 'HASH') {
4130: $result.=&hashref2str($key).'=';
4131: } elsif (ref($key)) {
1.265 albertel 4132: $result.='=';
1.800 albertel 4133: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4134: } else {
1.1132 raeburn 4135: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4136: }
4137:
1.800 albertel 4138: if(ref($hashref->{$key}) eq 'ARRAY') {
4139: $result.=&arrayref2str($hashref->{$key}).'&';
4140: } elsif(ref($hashref->{$key}) eq 'HASH') {
4141: $result.=&hashref2str($hashref->{$key}).'&';
4142: } elsif(ref($hashref->{$key})) {
1.265 albertel 4143: $result.='&';
1.800 albertel 4144: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4145: } else {
1.800 albertel 4146: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4147: }
4148: }
1.168 albertel 4149: $result=~s/\&$//;
1.265 albertel 4150: $result .= '__END_HASH_REF__';
1.168 albertel 4151: return $result;
4152: }
4153:
4154: sub str2hash {
1.265 albertel 4155: my ($string)=@_;
4156: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4157: return %$hash;
4158: }
4159:
4160: sub str2hashref {
1.168 albertel 4161: my ($string) = @_;
1.265 albertel 4162:
4163: my %hash;
4164:
4165: if($string !~ /^__HASH_REF__/) {
4166: if (! ($string eq '' || !defined($string))) {
4167: $hash{'error'}='Not hash reference';
4168: }
4169: return (\%hash, $string);
4170: }
4171:
4172: $string =~ s/^__HASH_REF__//;
4173:
4174: while($string !~ /^__END_HASH_REF__/) {
4175: #key
4176: my $key='';
4177: if($string =~ /^__HASH_REF__/) {
4178: ($key, $string)=&str2hashref($string);
4179: if(defined($key->{'error'})) {
4180: $hash{'error'}='Bad data';
4181: return (\%hash, $string);
4182: }
4183: } elsif($string =~ /^__ARRAY_REF__/) {
4184: ($key, $string)=&str2arrayref($string);
4185: if($key->[0] eq 'Array reference error') {
4186: $hash{'error'}='Bad data';
4187: return (\%hash, $string);
4188: }
4189: } else {
4190: $string =~ s/^(.*?)=//;
1.267 albertel 4191: $key=&unescape($1);
1.265 albertel 4192: }
4193: $string =~ s/^=//;
4194:
4195: #value
4196: my $value='';
4197: if($string =~ /^__HASH_REF__/) {
4198: ($value, $string)=&str2hashref($string);
4199: if(defined($value->{'error'})) {
4200: $hash{'error'}='Bad data';
4201: return (\%hash, $string);
4202: }
4203: } elsif($string =~ /^__ARRAY_REF__/) {
4204: ($value, $string)=&str2arrayref($string);
4205: if($value->[0] eq 'Array reference error') {
4206: $hash{'error'}='Bad data';
4207: return (\%hash, $string);
4208: }
4209: } else {
4210: $value=&get_scalar(\$string,'__END_HASH_REF__');
4211: }
4212: $string =~ s/^&//;
4213:
4214: $hash{$key}=$value;
1.204 albertel 4215: }
1.265 albertel 4216:
4217: $string =~ s/^__END_HASH_REF__//;
4218:
4219: return (\%hash, $string);
1.204 albertel 4220: }
4221:
4222: sub str2array {
1.265 albertel 4223: my ($string)=@_;
4224: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4225: return @$array;
4226: }
4227:
4228: sub str2arrayref {
1.204 albertel 4229: my ($string) = @_;
1.265 albertel 4230: my @array;
4231:
4232: if($string !~ /^__ARRAY_REF__/) {
4233: if (! ($string eq '' || !defined($string))) {
4234: $array[0]='Array reference error';
4235: }
4236: return (\@array, $string);
4237: }
4238:
4239: $string =~ s/^__ARRAY_REF__//;
4240:
4241: while($string !~ /^__END_ARRAY_REF__/) {
4242: my $value='';
4243: if($string =~ /^__HASH_REF__/) {
4244: ($value, $string)=&str2hashref($string);
4245: if(defined($value->{'error'})) {
4246: $array[0] ='Array reference error';
4247: return (\@array, $string);
4248: }
4249: } elsif($string =~ /^__ARRAY_REF__/) {
4250: ($value, $string)=&str2arrayref($string);
4251: if($value->[0] eq 'Array reference error') {
4252: $array[0] ='Array reference error';
4253: return (\@array, $string);
4254: }
4255: } else {
4256: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4257: }
4258: $string =~ s/^&//;
4259:
4260: push(@array, $value);
1.191 harris41 4261: }
1.265 albertel 4262:
4263: $string =~ s/^__END_ARRAY_REF__//;
4264:
4265: return (\@array, $string);
1.168 albertel 4266: }
4267:
1.167 albertel 4268: # -------------------------------------------------------------------Temp Store
4269:
1.168 albertel 4270: sub tmpreset {
4271: my ($symb,$namespace,$domain,$stuname) = @_;
4272: if (!$symb) {
4273: $symb=&symbread();
1.620 albertel 4274: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4275: }
4276: $symb=escape($symb);
4277:
1.620 albertel 4278: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4279: $namespace=~s/\//\_/g;
4280: $namespace=~s/\W//g;
4281:
1.620 albertel 4282: if (!$domain) { $domain=$env{'user.domain'}; }
4283: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4284: if ($domain eq 'public' && $stuname eq 'public') {
4285: $stuname=$ENV{'REMOTE_ADDR'};
4286: }
1.1117 foxr 4287: my $path=LONCAPA::tempdir();
1.168 albertel 4288: my %hash;
4289: if (tie(%hash,'GDBM_File',
4290: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4291: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4292: foreach my $key (keys(%hash)) {
1.180 albertel 4293: if ($key=~ /:$symb/) {
1.168 albertel 4294: delete($hash{$key});
4295: }
4296: }
4297: }
4298: }
4299:
1.167 albertel 4300: sub tmpstore {
1.168 albertel 4301: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4302:
4303: if (!$symb) {
4304: $symb=&symbread();
1.620 albertel 4305: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4306: }
4307: $symb=escape($symb);
4308:
4309: if (!$namespace) {
4310: # I don't think we would ever want to store this for a course.
4311: # it seems this will only be used if we don't have a course.
1.620 albertel 4312: #$namespace=$env{'request.course.id'};
1.168 albertel 4313: #if (!$namespace) {
1.620 albertel 4314: $namespace=$env{'request.state'};
1.168 albertel 4315: #}
4316: }
4317: $namespace=~s/\//\_/g;
4318: $namespace=~s/\W//g;
1.620 albertel 4319: if (!$domain) { $domain=$env{'user.domain'}; }
4320: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4321: if ($domain eq 'public' && $stuname eq 'public') {
4322: $stuname=$ENV{'REMOTE_ADDR'};
4323: }
1.168 albertel 4324: my $now=time;
4325: my %hash;
1.1117 foxr 4326: my $path=LONCAPA::tempdir();
1.168 albertel 4327: if (tie(%hash,'GDBM_File',
4328: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4329: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4330: $hash{"version:$symb"}++;
4331: my $version=$hash{"version:$symb"};
4332: my $allkeys='';
4333: foreach my $key (keys(%$storehash)) {
4334: $allkeys.=$key.':';
1.591 albertel 4335: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4336: }
4337: $hash{"$version:$symb:timestamp"}=$now;
4338: $allkeys.='timestamp';
4339: $hash{"$version:keys:$symb"}=$allkeys;
4340: if (untie(%hash)) {
4341: return 'ok';
4342: } else {
4343: return "error:$!";
4344: }
4345: } else {
4346: return "error:$!";
4347: }
4348: }
1.167 albertel 4349:
1.168 albertel 4350: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4351:
1.168 albertel 4352: sub tmprestore {
4353: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4354:
1.168 albertel 4355: if (!$symb) {
4356: $symb=&symbread();
1.620 albertel 4357: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4358: }
4359: $symb=escape($symb);
4360:
1.620 albertel 4361: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4362:
1.620 albertel 4363: if (!$domain) { $domain=$env{'user.domain'}; }
4364: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4365: if ($domain eq 'public' && $stuname eq 'public') {
4366: $stuname=$ENV{'REMOTE_ADDR'};
4367: }
1.168 albertel 4368: my %returnhash;
4369: $namespace=~s/\//\_/g;
4370: $namespace=~s/\W//g;
4371: my %hash;
1.1117 foxr 4372: my $path=LONCAPA::tempdir();
1.168 albertel 4373: if (tie(%hash,'GDBM_File',
4374: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4375: &GDBM_READER(),0640)) {
1.168 albertel 4376: my $version=$hash{"version:$symb"};
4377: $returnhash{'version'}=$version;
4378: my $scope;
4379: for ($scope=1;$scope<=$version;$scope++) {
4380: my $vkeys=$hash{"$scope:keys:$symb"};
4381: my @keys=split(/:/,$vkeys);
4382: my $key;
4383: $returnhash{"$scope:keys"}=$vkeys;
4384: foreach $key (@keys) {
1.591 albertel 4385: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4386: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4387: }
4388: }
1.168 albertel 4389: if (!(untie(%hash))) {
4390: return "error:$!";
4391: }
4392: } else {
4393: return "error:$!";
4394: }
4395: return %returnhash;
1.167 albertel 4396: }
4397:
1.9 www 4398: # ----------------------------------------------------------------------- Store
4399:
4400: sub store {
1.124 www 4401: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4402: my $home='';
4403:
1.168 albertel 4404: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4405:
1.213 www 4406: $symb=&symbclean($symb);
1.122 albertel 4407: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4408:
1.620 albertel 4409: if (!$domain) { $domain=$env{'user.domain'}; }
4410: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4411:
4412: &devalidate($symb,$stuname,$domain);
1.109 www 4413:
4414: $symb=escape($symb);
1.187 www 4415: if (!$namespace) {
1.620 albertel 4416: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4417: return '';
4418: }
4419: }
1.620 albertel 4420: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4421:
4422: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4423: $$storehash{'host'}=$perlvar{'lonHostID'};
4424:
1.12 www 4425: my $namevalue='';
1.800 albertel 4426: foreach my $key (keys(%$storehash)) {
4427: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4428: }
1.12 www 4429: $namevalue=~s/\&$//;
1.187 www 4430: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4431: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4432: }
4433:
1.47 www 4434: # -------------------------------------------------------------- Critical Store
4435:
4436: sub cstore {
1.124 www 4437: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4438: my $home='';
4439:
1.168 albertel 4440: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4441:
1.213 www 4442: $symb=&symbclean($symb);
1.122 albertel 4443: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4444:
1.620 albertel 4445: if (!$domain) { $domain=$env{'user.domain'}; }
4446: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4447:
4448: &devalidate($symb,$stuname,$domain);
1.109 www 4449:
4450: $symb=escape($symb);
1.187 www 4451: if (!$namespace) {
1.620 albertel 4452: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4453: return '';
4454: }
4455: }
1.620 albertel 4456: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4457:
4458: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4459: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4460:
1.47 www 4461: my $namevalue='';
1.800 albertel 4462: foreach my $key (keys(%$storehash)) {
4463: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4464: }
1.47 www 4465: $namevalue=~s/\&$//;
1.187 www 4466: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4467: return critical
4468: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4469: }
4470:
1.9 www 4471: # --------------------------------------------------------------------- Restore
4472:
4473: sub restore {
1.124 www 4474: my ($symb,$namespace,$domain,$stuname) = @_;
4475: my $home='';
4476:
1.168 albertel 4477: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4478:
1.122 albertel 4479: if (!$symb) {
4480: unless ($symb=escape(&symbread())) { return ''; }
4481: } else {
1.213 www 4482: $symb=&escape(&symbclean($symb));
1.122 albertel 4483: }
1.188 www 4484: if (!$namespace) {
1.620 albertel 4485: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4486: return '';
4487: }
4488: }
1.620 albertel 4489: if (!$domain) { $domain=$env{'user.domain'}; }
4490: if (!$stuname) { $stuname=$env{'user.name'}; }
4491: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4492: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4493:
1.12 www 4494: my %returnhash=();
1.800 albertel 4495: foreach my $line (split(/\&/,$answer)) {
4496: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4497: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4498: }
1.75 www 4499: my $version;
4500: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4501: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4502: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4503: }
1.75 www 4504: }
1.13 www 4505: return %returnhash;
1.34 www 4506: }
4507:
4508: # ---------------------------------------------------------- Course Description
1.1118 foxr 4509: #
4510: #
1.34 www 4511:
4512: sub coursedescription {
1.731 albertel 4513: my ($courseid,$args)=@_;
1.34 www 4514: $courseid=~s/^\///;
1.49 www 4515: $courseid=~s/\_/\//g;
1.34 www 4516: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4517: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4518: my $normalid=$cdomain.'_'.$cnum;
4519: # need to always cache even if we get errors otherwise we keep
4520: # trying and trying and trying to get the course description.
4521: my %envhash=();
4522: my %returnhash=();
1.731 albertel 4523:
4524: my $expiretime=600;
4525: if ($env{'request.course.id'} eq $normalid) {
4526: $expiretime=120;
4527: }
4528:
4529: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4530: if (!$args->{'freshen_cache'}
4531: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4532: foreach my $key (keys(%env)) {
4533: next if ($key !~ /^\Q$prefix\E(.*)/);
4534: my ($setting) = $1;
4535: $returnhash{$setting} = $env{$key};
4536: }
4537: return %returnhash;
4538: }
4539:
1.1118 foxr 4540: # get the data again
4541:
1.731 albertel 4542: if (!$args->{'one_time'}) {
4543: $envhash{'course.'.$normalid.'.last_cache'}=time;
4544: }
1.811 albertel 4545:
1.34 www 4546: if ($chome ne 'no_host') {
1.302 albertel 4547: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4548: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4549: my $username = $env{'user.name'}; # Defult username
4550: if(defined $args->{'user'}) {
4551: $username = $args->{'user'};
4552: }
1.129 albertel 4553: $returnhash{'home'}= $chome;
4554: $returnhash{'domain'} = $cdomain;
4555: $returnhash{'num'} = $cnum;
1.741 raeburn 4556: if (!defined($returnhash{'type'})) {
4557: $returnhash{'type'} = 'Course';
4558: }
1.130 albertel 4559: while (my ($name,$value) = each %returnhash) {
1.53 www 4560: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4561: }
1.270 www 4562: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4563: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4564: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4565: $envhash{'course.'.$normalid.'.home'}=$chome;
4566: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4567: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4568: }
4569: }
1.731 albertel 4570: if (!$args->{'one_time'}) {
1.949 raeburn 4571: &appenv(\%envhash);
1.731 albertel 4572: }
1.302 albertel 4573: return %returnhash;
1.461 www 4574: }
4575:
1.1080 raeburn 4576: sub update_released_required {
4577: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4578: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4579: $cid = $env{'request.course.id'};
4580: $cdom = $env{'course.'.$cid.'.domain'};
4581: $cnum = $env{'course.'.$cid.'.num'};
4582: $chome = $env{'course.'.$cid.'.home'};
4583: }
4584: if ($needsrelease) {
4585: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4586: my $needsupdate;
4587: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4588: $needsupdate = 1;
4589: } else {
4590: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4591: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4592: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4593: $needsupdate = 1;
4594: }
4595: }
4596: if ($needsupdate) {
4597: my %needshash = (
4598: 'internal.releaserequired' => $needsrelease,
4599: );
4600: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4601: if ($putresult eq 'ok') {
4602: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4603: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4604: if (ref($crsinfo{$cid}) eq 'HASH') {
4605: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4606: &courseidput($cdom,\%crsinfo,$chome,'notime');
4607: }
4608: }
4609: }
4610: }
4611: return;
4612: }
4613:
1.461 www 4614: # -------------------------------------------------See if a user is privileged
4615:
4616: sub privileged {
4617: my ($username,$domain)=@_;
1.1170 droeschl 4618:
4619: my %rolesdump = &dump("roles", $domain, $username) or return 0;
4620: my $now = time;
4621:
4622: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
4623: my ($trole, $tend, $tstart) = split(/_/, $role);
4624: if (($trole eq 'dc') || ($trole eq 'su')) {
4625: return 1 unless ($tend && $tend < $now)
4626: or ($tstart && $tstart > $now);
4627: }
1.461 www 4628: }
1.1170 droeschl 4629:
1.461 www 4630: return 0;
1.9 www 4631: }
1.1 albertel 4632:
1.103 harris41 4633: # -------------------------------------------------------- Get user privileges
1.11 www 4634:
4635: sub rolesinit {
1.1169 droeschl 4636: my ($domain, $username) = @_;
4637: my %userroles = ('user.login.time' => time);
4638: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
4639:
4640: # firstaccess and timerinterval are related to timed maps/resources.
4641: # also, blocking can be triggered by an activating timer
4642: # it's saved in the user's %env.
4643: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
4644: my %timerinterval = &dump('timerinterval', $domain, $username);
4645: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
4646: %timerintchk, %timerintenv);
4647:
1.1162 raeburn 4648: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 4649: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 4650: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
4651: }
1.1169 droeschl 4652:
1.1162 raeburn 4653: foreach my $key (keys(%timerinterval)) {
4654: my ($cid,$rest) = split(/\0/,$key);
4655: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
4656: }
1.1169 droeschl 4657:
1.11 www 4658: my %allroles=();
1.1162 raeburn 4659: my %allgroups=();
1.11 www 4660:
1.1169 droeschl 4661: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
4662: my $role = $rolesdump{$area};
4663: $area =~ s/\_\w\w$//;
4664:
4665: my ($trole, $tend, $tstart, $group_privs);
4666:
4667: if ($role =~ /^cr/) {
4668: # Custom role, defined by a user
4669: # e.g., user.role.cr/msu/smith/mynewrole
4670: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4671: $trole = $1;
4672: ($tend, $tstart) = split('_', $2);
4673: } else {
4674: $trole = $role;
4675: }
4676: } elsif ($role =~ m|^gr/|) {
4677: # Role of member in a group, defined within a course/community
4678: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
4679: ($trole, $tend, $tstart) = split(/_/, $role);
4680: next if $tstart eq '-1';
4681: ($trole, $group_privs) = split(/\//, $trole);
4682: $group_privs = &unescape($group_privs);
4683: } else {
4684: # Just a normal role, defined in roles.tab
4685: ($trole, $tend, $tstart) = split(/_/,$role);
4686: }
4687:
4688: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4689: $username);
4690: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
4691:
4692: # role expired or not available yet?
4693: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
4694: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
4695:
4696: next if $area eq '' or $trole eq '';
4697:
4698: my $spec = "$trole.$area";
4699: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
4700:
4701: if ($trole =~ /^cr\//) {
4702: # Custom role, defined by a user
4703: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4704: } elsif ($trole eq 'gr') {
4705: # Role of a member in a group, defined within a course/community
4706: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
4707: next;
4708: } else {
4709: # Normal role, defined in roles.tab
4710: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4711: }
4712:
4713: my $cid = $tdomain.'_'.$trest;
4714: unless ($firstaccchk{$cid}) {
4715: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
4716: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
4717: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
4718: $coursetimerstarts{$cid}{$item};
4719: }
4720: }
4721: $firstaccchk{$cid} = 1;
4722: }
4723: unless ($timerintchk{$cid}) {
4724: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
4725: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
4726: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
4727: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 4728: }
1.12 www 4729: }
1.1169 droeschl 4730: $timerintchk{$cid} = 1;
1.191 harris41 4731: }
1.11 www 4732: }
1.1169 droeschl 4733:
4734: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
4735: \%allroles, \%allgroups);
4736: $env{'user.adv'} = $userroles{'user.adv'};
4737:
1.1162 raeburn 4738: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 4739: }
4740:
1.567 raeburn 4741: sub set_arearole {
4742: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4743: # log the associated role with the area
4744: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4745: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4746: }
4747:
4748: sub custom_roleprivs {
4749: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4750: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4751: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4752: if (&hostname($homsvr) ne '') {
1.567 raeburn 4753: my ($rdummy,$roledef)=
4754: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4755: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4756: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4757: if (defined($syspriv)) {
1.1043 raeburn 4758: if ($trest =~ /^$match_community$/) {
4759: $syspriv =~ s/bre\&S//;
4760: }
1.567 raeburn 4761: $$allroles{'cm./'}.=':'.$syspriv;
4762: $$allroles{$spec.'./'}.=':'.$syspriv;
4763: }
4764: if ($tdomain ne '') {
4765: if (defined($dompriv)) {
4766: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4767: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4768: }
4769: if (($trest ne '') && (defined($coursepriv))) {
4770: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4771: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4772: }
4773: }
4774: }
4775: }
4776: }
4777:
1.678 raeburn 4778: sub group_roleprivs {
4779: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4780: my $access = 1;
4781: my $now = time;
4782: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4783: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4784: if ($access) {
1.811 albertel 4785: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4786: $$allgroups{$course}{$group} .=':'.$group_privs;
4787: }
4788: }
1.567 raeburn 4789:
4790: sub standard_roleprivs {
4791: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4792: if (defined($pr{$trole.':s'})) {
4793: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4794: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4795: }
4796: if ($tdomain ne '') {
4797: if (defined($pr{$trole.':d'})) {
4798: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4799: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4800: }
4801: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4802: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4803: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4804: }
4805: }
4806: }
4807:
4808: sub set_userprivs {
1.1064 raeburn 4809: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4810: my $author=0;
4811: my $adv=0;
1.678 raeburn 4812: my %grouproles = ();
4813: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4814: my @groupkeys;
1.1000 raeburn 4815: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4816: push(@groupkeys,$role);
4817: }
4818: if (ref($groups_roles) eq 'HASH') {
4819: foreach my $key (keys(%{$groups_roles})) {
4820: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4821: push(@groupkeys,$key);
4822: }
4823: }
4824: }
4825: if (@groupkeys > 0) {
4826: foreach my $role (@groupkeys) {
4827: my ($trole,$area,$sec,$extendedarea);
4828: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4829: $trole = $1;
4830: $area = $2;
4831: $sec = $3;
4832: $extendedarea = $area.$sec;
4833: if (exists($$allgroups{$area})) {
4834: foreach my $group (keys(%{$$allgroups{$area}})) {
4835: my $spec = $trole.'.'.$extendedarea;
4836: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4837: $$allgroups{$area}{$group};
1.1064 raeburn 4838: }
1.678 raeburn 4839: }
4840: }
4841: }
4842: }
4843: }
1.800 albertel 4844: foreach my $group (keys(%grouproles)) {
4845: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4846: }
1.800 albertel 4847: foreach my $role (keys(%{$allroles})) {
4848: my %thesepriv;
1.941 raeburn 4849: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4850: foreach my $item (split(/:/,$$allroles{$role})) {
4851: if ($item ne '') {
4852: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4853: if ($restrictions eq '') {
4854: $thesepriv{$privilege}='F';
4855: } elsif ($thesepriv{$privilege} ne 'F') {
4856: $thesepriv{$privilege}.=$restrictions;
4857: }
4858: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4859: }
4860: }
4861: my $thesestr='';
1.1104 raeburn 4862: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 4863: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4864: }
4865: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4866: }
4867: return ($author,$adv);
4868: }
4869:
1.994 raeburn 4870: sub role_status {
1.1104 raeburn 4871: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4872: my @pwhere = ();
4873: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4874: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4875: unless (!defined($$role) || $$role eq '') {
4876: $$where=join('.',@pwhere);
4877: $$trolecode=$$role.'.'.$$where;
4878: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4879: $$tstatus='is';
1.1104 raeburn 4880: if ($$tstart && $$tstart>$update) {
1.994 raeburn 4881: $$tstatus='future';
1.1034 raeburn 4882: if ($$tstart<$now) {
4883: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4884: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4885: my (%allroles,%allgroups,$group_privs,
4886: %groups_roles,@rolecodes);
1.1002 raeburn 4887: my %userroles = (
4888: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4889: );
1.1064 raeburn 4890: @rolecodes = ('cm');
1.1002 raeburn 4891: my $spec=$$role.'.'.$$where;
4892: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4893: if ($$role =~ /^cr\//) {
4894: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4895: push(@rolecodes,'cr');
1.1002 raeburn 4896: } elsif ($$role eq 'gr') {
1.1064 raeburn 4897: push(@rolecodes,$$role);
1.1002 raeburn 4898: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4899: $env{'user.name'});
1.1064 raeburn 4900: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4901: (undef,my $group_privs) = split(/\//,$trole);
4902: $group_privs = &unescape($group_privs);
4903: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4904: 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 4905: &get_groups_roles($tdomain,$trest,
4906: \%course_roles,\@rolecodes,
4907: \%groups_roles);
1.1002 raeburn 4908: } else {
1.1064 raeburn 4909: push(@rolecodes,$$role);
1.1002 raeburn 4910: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4911: }
1.1064 raeburn 4912: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4913: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4914: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4915: }
4916: }
1.1034 raeburn 4917: $$tstatus = 'is';
1.1002 raeburn 4918: }
1.994 raeburn 4919: }
4920: if ($$tend) {
1.1104 raeburn 4921: if ($$tend<$update) {
1.994 raeburn 4922: $$tstatus='expired';
4923: } elsif ($$tend<$now) {
4924: $$tstatus='will_not';
4925: }
4926: }
4927: }
4928: }
4929: }
4930:
1.1104 raeburn 4931: sub get_groups_roles {
4932: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4933: return unless((ref($cdom_courseroles) eq 'HASH') &&
4934: (ref($rolecodes) eq 'ARRAY') &&
4935: (ref($groups_roles) eq 'HASH'));
4936: if (keys(%{$cdom_courseroles}) > 0) {
4937: my ($cnum) = ($rest =~ /^($match_courseid)/);
4938: if ($cdom ne '' && $cnum ne '') {
4939: foreach my $key (keys(%{$cdom_courseroles})) {
4940: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4941: my $crsrole = $1;
4942: my $crssec = $2;
4943: if ($crsrole =~ /^cr/) {
4944: unless (grep(/^cr$/,@{$rolecodes})) {
4945: push(@{$rolecodes},'cr');
4946: }
4947: } else {
4948: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4949: push(@{$rolecodes},$crsrole);
4950: }
4951: }
4952: my $rolekey = "$crsrole./$cdom/$cnum";
4953: if ($crssec ne '') {
4954: $rolekey .= "/$crssec";
4955: }
4956: $rolekey .= './';
4957: $groups_roles->{$rolekey} = $rolecodes;
4958: }
4959: }
4960: }
4961: }
4962: return;
4963: }
4964:
4965: sub delete_env_groupprivs {
4966: my ($where,$courseroles,$possroles) = @_;
4967: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4968: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4969: unless (ref($courseroles->{$udom}) eq 'HASH') {
4970: %{$courseroles->{$udom}} =
4971: &get_my_roles('','','userroles',['active'],
4972: $possroles,[$udom],1);
4973: }
4974: if (ref($courseroles->{$udom}) eq 'HASH') {
4975: foreach my $item (keys(%{$courseroles->{$udom}})) {
4976: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4977: my $area = '/'.$cdom.'/'.$cnum;
4978: my $privkey = "user.priv.$crsrole.$area";
4979: if ($crssec ne '') {
4980: $privkey .= '/'.$crssec;
4981: }
4982: $privkey .= ".$area/$group";
4983: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4984: }
4985: }
4986: return;
4987: }
4988:
1.994 raeburn 4989: sub check_adhoc_privs {
1.1104 raeburn 4990: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4991: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4992: if ($env{$cckey}) {
4993: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 4994: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4995: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 4996: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4997: }
4998: } else {
1.1088 raeburn 4999: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 5000: }
5001: }
5002:
5003: sub set_adhoc_privileges {
5004: # role can be cc or ca
1.1088 raeburn 5005: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5006: my $area = '/'.$dcdom.'/'.$pickedcourse;
5007: my $spec = $role.'.'.$area;
5008: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
5009: $env{'user.name'});
5010: my %ccrole = ();
5011: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5012: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5013: &appenv(\%userroles,[$role,'cm']);
5014: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5015: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5016: &appenv( {'request.role' => $spec,
5017: 'request.role.domain' => $dcdom,
5018: 'request.course.sec' => ''
5019: }
5020: );
5021: my $tadv=0;
5022: if (&allowed('adv') eq 'F') { $tadv=1; }
5023: &appenv({'request.role.adv' => $tadv});
5024: }
1.994 raeburn 5025: }
5026:
1.12 www 5027: # --------------------------------------------------------------- get interface
5028:
5029: sub get {
1.131 albertel 5030: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5031: my $items='';
1.800 albertel 5032: foreach my $item (@$storearr) {
5033: $items.=&escape($item).'&';
1.191 harris41 5034: }
1.12 www 5035: $items=~s/\&$//;
1.620 albertel 5036: if (!$udomain) { $udomain=$env{'user.domain'}; }
5037: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5038: my $uhome=&homeserver($uname,$udomain);
5039:
1.133 albertel 5040: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5041: my @pairs=split(/\&/,$rep);
1.273 albertel 5042: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5043: return @pairs;
5044: }
1.15 www 5045: my %returnhash=();
1.42 www 5046: my $i=0;
1.800 albertel 5047: foreach my $item (@$storearr) {
5048: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5049: $i++;
1.191 harris41 5050: }
1.15 www 5051: return %returnhash;
1.27 www 5052: }
5053:
5054: # --------------------------------------------------------------- del interface
5055:
5056: sub del {
1.133 albertel 5057: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5058: my $items='';
1.800 albertel 5059: foreach my $item (@$storearr) {
5060: $items.=&escape($item).'&';
1.191 harris41 5061: }
1.984 neumanie 5062:
1.27 www 5063: $items=~s/\&$//;
1.620 albertel 5064: if (!$udomain) { $udomain=$env{'user.domain'}; }
5065: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5066: my $uhome=&homeserver($uname,$udomain);
5067: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5068: }
5069:
5070: # -------------------------------------------------------------- dump interface
5071:
5072: sub dump {
1.1166 raeburn 5073: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.755 albertel 5074: if (!$udomain) { $udomain=$env{'user.domain'}; }
5075: if (!$uname) { $uname=$env{'user.name'}; }
5076: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5077:
1.755 albertel 5078: if ($regexp) {
5079: $regexp=&escape($regexp);
5080: } else {
5081: $regexp='.';
5082: }
1.1166 raeburn 5083: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5084: my @pairs=split(/\&/,$rep);
5085: my %returnhash=();
1.1098 foxr 5086: if (!($rep =~ /^error/ )) {
5087: foreach my $item (@pairs) {
5088: my ($key,$value)=split(/=/,$item,2);
5089: $key = &unescape($key);
5090: next if ($key =~ /^error: 2 /);
5091: $returnhash{$key}=&thaw_unescape($value);
5092: }
1.755 albertel 5093: }
5094: return %returnhash;
1.407 www 5095: }
5096:
1.1098 foxr 5097:
1.717 albertel 5098: # --------------------------------------------------------- dumpstore interface
5099:
5100: sub dumpstore {
5101: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 5102: if (!$udomain) { $udomain=$env{'user.domain'}; }
5103: if (!$uname) { $uname=$env{'user.name'}; }
5104: my $uhome=&homeserver($uname,$udomain);
5105: if ($regexp) {
5106: $regexp=&escape($regexp);
5107: } else {
5108: $regexp='.';
5109: }
5110: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
5111: my @pairs=split(/\&/,$rep);
5112: my %returnhash=();
5113: foreach my $item (@pairs) {
5114: my ($key,$value)=split(/=/,$item,2);
5115: next if ($key =~ /^error: 2 /);
5116: $returnhash{$key}=&thaw_unescape($value);
5117: }
5118: return %returnhash;
1.717 albertel 5119: }
5120:
1.407 www 5121: # -------------------------------------------------------------- keys interface
5122:
5123: sub getkeys {
5124: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5125: if (!$udomain) { $udomain=$env{'user.domain'}; }
5126: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5127: my $uhome=&homeserver($uname,$udomain);
5128: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5129: my @keyarray=();
1.800 albertel 5130: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5131: next if ($key =~ /^error: 2 /);
1.800 albertel 5132: push(@keyarray,&unescape($key));
1.407 www 5133: }
5134: return @keyarray;
1.318 matthew 5135: }
5136:
1.319 matthew 5137: # --------------------------------------------------------------- currentdump
5138: sub currentdump {
1.328 matthew 5139: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5140: $courseid = $env{'request.course.id'} if (! defined($courseid));
5141: $sdom = $env{'user.domain'} if (! defined($sdom));
5142: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5143: my $uhome = &homeserver($sname,$sdom);
5144: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 5145: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5146: #
1.318 matthew 5147: my %returnhash=();
1.319 matthew 5148: #
5149: if ($rep eq "unknown_cmd") {
5150: # an old lond will not know currentdump
5151: # Do a dump and make it look like a currentdump
1.822 albertel 5152: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5153: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5154: my %hash = @tmp;
5155: @tmp=();
1.424 matthew 5156: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5157: } else {
5158: my @pairs=split(/\&/,$rep);
1.800 albertel 5159: foreach my $pair (@pairs) {
5160: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5161: my ($symb,$param) = split(/:/,$key);
5162: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5163: &thaw_unescape($value);
1.319 matthew 5164: }
1.191 harris41 5165: }
1.12 www 5166: return %returnhash;
1.424 matthew 5167: }
5168:
5169: sub convert_dump_to_currentdump{
5170: my %hash = %{shift()};
5171: my %returnhash;
5172: # Code ripped from lond, essentially. The only difference
5173: # here is the unescaping done by lonnet::dump(). Conceivably
5174: # we might run in to problems with parameter names =~ /^v\./
5175: while (my ($key,$value) = each(%hash)) {
5176: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5177: $symb = &unescape($symb);
5178: $param = &unescape($param);
1.424 matthew 5179: next if ($v eq 'version' || $symb eq 'keys');
5180: next if (exists($returnhash{$symb}) &&
5181: exists($returnhash{$symb}->{$param}) &&
5182: $returnhash{$symb}->{'v.'.$param} > $v);
5183: $returnhash{$symb}->{$param}=$value;
5184: $returnhash{$symb}->{'v.'.$param}=$v;
5185: }
5186: #
5187: # Remove all of the keys in the hashes which keep track of
5188: # the version of the parameter.
5189: while (my ($symb,$param_hash) = each(%returnhash)) {
5190: # use a foreach because we are going to delete from the hash.
5191: foreach my $key (keys(%$param_hash)) {
5192: delete($param_hash->{$key}) if ($key =~ /^v\./);
5193: }
5194: }
5195: return \%returnhash;
1.12 www 5196: }
5197:
1.627 albertel 5198: # ------------------------------------------------------ critical inc interface
5199:
5200: sub cinc {
5201: return &inc(@_,'critical');
5202: }
5203:
1.449 matthew 5204: # --------------------------------------------------------------- inc interface
5205:
5206: sub inc {
1.627 albertel 5207: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5208: if (!$udomain) { $udomain=$env{'user.domain'}; }
5209: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5210: my $uhome=&homeserver($uname,$udomain);
5211: my $items='';
5212: if (! ref($store)) {
5213: # got a single value, so use that instead
5214: $items = &escape($store).'=&';
5215: } elsif (ref($store) eq 'SCALAR') {
5216: $items = &escape($$store).'=&';
5217: } elsif (ref($store) eq 'ARRAY') {
5218: $items = join('=&',map {&escape($_);} @{$store});
5219: } elsif (ref($store) eq 'HASH') {
5220: while (my($key,$value) = each(%{$store})) {
5221: $items.= &escape($key).'='.&escape($value).'&';
5222: }
5223: }
5224: $items=~s/\&$//;
1.627 albertel 5225: if ($critical) {
5226: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5227: } else {
5228: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5229: }
1.449 matthew 5230: }
5231:
1.12 www 5232: # --------------------------------------------------------------- put interface
5233:
5234: sub put {
1.134 albertel 5235: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5236: if (!$udomain) { $udomain=$env{'user.domain'}; }
5237: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5238: my $uhome=&homeserver($uname,$udomain);
1.12 www 5239: my $items='';
1.800 albertel 5240: foreach my $item (keys(%$storehash)) {
5241: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5242: }
1.12 www 5243: $items=~s/\&$//;
1.134 albertel 5244: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5245: }
5246:
1.631 albertel 5247: # ------------------------------------------------------------ newput interface
5248:
5249: sub newput {
5250: my ($namespace,$storehash,$udomain,$uname)=@_;
5251: if (!$udomain) { $udomain=$env{'user.domain'}; }
5252: if (!$uname) { $uname=$env{'user.name'}; }
5253: my $uhome=&homeserver($uname,$udomain);
5254: my $items='';
5255: foreach my $key (keys(%$storehash)) {
5256: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5257: }
5258: $items=~s/\&$//;
5259: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5260: }
5261:
5262: # --------------------------------------------------------- putstore interface
5263:
1.524 raeburn 5264: sub putstore {
1.715 albertel 5265: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5266: if (!$udomain) { $udomain=$env{'user.domain'}; }
5267: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5268: my $uhome=&homeserver($uname,$udomain);
5269: my $items='';
1.715 albertel 5270: foreach my $key (keys(%$storehash)) {
5271: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5272: }
1.715 albertel 5273: $items=~s/\&$//;
1.716 albertel 5274: my $esc_symb=&escape($symb);
5275: my $esc_v=&escape($version);
1.715 albertel 5276: my $reply =
1.716 albertel 5277: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5278: $uhome);
5279: if ($reply eq 'unknown_cmd') {
1.716 albertel 5280: # gfall back to way things use to be done
1.715 albertel 5281: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5282: $uname);
1.524 raeburn 5283: }
1.715 albertel 5284: return $reply;
5285: }
5286:
5287: sub old_putstore {
1.716 albertel 5288: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5289: if (!$udomain) { $udomain=$env{'user.domain'}; }
5290: if (!$uname) { $uname=$env{'user.name'}; }
5291: my $uhome=&homeserver($uname,$udomain);
5292: my %newstorehash;
1.800 albertel 5293: foreach my $item (keys(%$storehash)) {
5294: my $key = $version.':'.&escape($symb).':'.$item;
5295: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5296: }
5297: my $items='';
5298: my %allitems = ();
1.800 albertel 5299: foreach my $item (keys(%newstorehash)) {
5300: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5301: my $key = $1.':keys:'.$2;
5302: $allitems{$key} .= $3.':';
5303: }
1.800 albertel 5304: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5305: }
1.800 albertel 5306: foreach my $item (keys(%allitems)) {
5307: $allitems{$item} =~ s/\:$//;
5308: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5309: }
5310: $items=~s/\&$//;
5311: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5312: }
5313:
1.47 www 5314: # ------------------------------------------------------ critical put interface
5315:
5316: sub cput {
1.134 albertel 5317: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5318: if (!$udomain) { $udomain=$env{'user.domain'}; }
5319: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5320: my $uhome=&homeserver($uname,$udomain);
1.47 www 5321: my $items='';
1.800 albertel 5322: foreach my $item (keys(%$storehash)) {
5323: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5324: }
1.47 www 5325: $items=~s/\&$//;
1.134 albertel 5326: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5327: }
5328:
5329: # -------------------------------------------------------------- eget interface
5330:
5331: sub eget {
1.133 albertel 5332: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5333: my $items='';
1.800 albertel 5334: foreach my $item (@$storearr) {
5335: $items.=&escape($item).'&';
1.191 harris41 5336: }
1.12 www 5337: $items=~s/\&$//;
1.620 albertel 5338: if (!$udomain) { $udomain=$env{'user.domain'}; }
5339: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5340: my $uhome=&homeserver($uname,$udomain);
5341: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5342: my @pairs=split(/\&/,$rep);
5343: my %returnhash=();
1.42 www 5344: my $i=0;
1.800 albertel 5345: foreach my $item (@$storearr) {
5346: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5347: $i++;
1.191 harris41 5348: }
1.12 www 5349: return %returnhash;
5350: }
5351:
1.667 albertel 5352: # ------------------------------------------------------------ tmpput interface
5353: sub tmpput {
1.802 raeburn 5354: my ($storehash,$server,$context)=@_;
1.667 albertel 5355: my $items='';
1.800 albertel 5356: foreach my $item (keys(%$storehash)) {
5357: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5358: }
5359: $items=~s/\&$//;
1.802 raeburn 5360: if (defined($context)) {
5361: $items .= ':'.&escape($context);
5362: }
1.667 albertel 5363: return &reply("tmpput:$items",$server);
5364: }
5365:
5366: # ------------------------------------------------------------ tmpget interface
5367: sub tmpget {
1.688 albertel 5368: my ($token,$server)=@_;
5369: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5370: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5371: my %returnhash;
5372: foreach my $item (split(/\&/,$rep)) {
5373: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5374: next if ($key =~ /^error: 2 /);
1.667 albertel 5375: $returnhash{&unescape($key)}=&thaw_unescape($value);
5376: }
5377: return %returnhash;
5378: }
5379:
1.1113 raeburn 5380: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5381: sub tmpdel {
5382: my ($token,$server)=@_;
5383: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5384: return &reply("tmpdel:$token",$server);
5385: }
5386:
1.765 albertel 5387: # -------------------------------------------------- portfolio access checking
5388:
5389: sub portfolio_access {
1.766 albertel 5390: my ($requrl) = @_;
1.765 albertel 5391: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5392: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 5393: if ($result) {
5394: my %setters;
5395: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5396: my ($startblock,$endblock) =
5397: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5398: if ($startblock && $endblock) {
5399: return 'B';
5400: }
5401: } else {
5402: my ($startblock,$endblock) =
5403: &Apache::loncommon::blockcheck(\%setters,'port');
5404: if ($startblock && $endblock) {
5405: return 'B';
5406: }
5407: }
5408: }
1.765 albertel 5409: if ($result eq 'ok') {
1.766 albertel 5410: return 'F';
1.765 albertel 5411: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 5412: return 'A';
1.765 albertel 5413: }
1.766 albertel 5414: return '';
1.765 albertel 5415: }
5416:
5417: sub get_portfolio_access {
1.767 albertel 5418: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5419:
5420: if (!ref($access_hash)) {
5421: my $current_perms = &get_portfile_permissions($udom,$unum);
5422: my %access_controls = &get_access_controls($current_perms,$group,
5423: $file_name);
5424: $access_hash = $access_controls{$file_name};
5425: }
5426:
1.765 albertel 5427: my ($public,$guest,@domains,@users,@courses,@groups);
5428: my $now = time;
5429: if (ref($access_hash) eq 'HASH') {
5430: foreach my $key (keys(%{$access_hash})) {
5431: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5432: if ($start > $now) {
5433: next;
5434: }
5435: if ($end && $end<$now) {
5436: next;
5437: }
5438: if ($scope eq 'public') {
5439: $public = $key;
5440: last;
5441: } elsif ($scope eq 'guest') {
5442: $guest = $key;
5443: } elsif ($scope eq 'domains') {
5444: push(@domains,$key);
5445: } elsif ($scope eq 'users') {
5446: push(@users,$key);
5447: } elsif ($scope eq 'course') {
5448: push(@courses,$key);
5449: } elsif ($scope eq 'group') {
5450: push(@groups,$key);
5451: }
5452: }
5453: if ($public) {
5454: return 'ok';
5455: }
5456: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5457: if ($guest) {
5458: return $guest;
5459: }
5460: } else {
5461: if (@domains > 0) {
5462: foreach my $domkey (@domains) {
5463: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5464: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5465: return 'ok';
5466: }
5467: }
5468: }
5469: }
5470: if (@users > 0) {
5471: foreach my $userkey (@users) {
1.865 raeburn 5472: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5473: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5474: if (ref($item) eq 'HASH') {
5475: if (($item->{'uname'} eq $env{'user.name'}) &&
5476: ($item->{'udom'} eq $env{'user.domain'})) {
5477: return 'ok';
5478: }
5479: }
5480: }
5481: }
1.765 albertel 5482: }
5483: }
5484: my %roleshash;
5485: my @courses_and_groups = @courses;
5486: push(@courses_and_groups,@groups);
5487: if (@courses_and_groups > 0) {
5488: my (%allgroups,%allroles);
5489: my ($start,$end,$role,$sec,$group);
5490: foreach my $envkey (%env) {
1.1060 raeburn 5491: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5492: my $cid = $2.'_'.$3;
5493: if ($1 eq 'gr') {
5494: $group = $4;
5495: $allgroups{$cid}{$group} = $env{$envkey};
5496: } else {
5497: if ($4 eq '') {
5498: $sec = 'none';
5499: } else {
5500: $sec = $4;
5501: }
5502: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5503: }
1.811 albertel 5504: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5505: my $cid = $2.'_'.$3;
5506: if ($4 eq '') {
5507: $sec = 'none';
5508: } else {
5509: $sec = $4;
5510: }
5511: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5512: }
5513: }
5514: if (keys(%allroles) == 0) {
5515: return;
5516: }
5517: foreach my $key (@courses_and_groups) {
5518: my %content = %{$$access_hash{$key}};
5519: my $cnum = $content{'number'};
5520: my $cdom = $content{'domain'};
5521: my $cid = $cdom.'_'.$cnum;
5522: if (!exists($allroles{$cid})) {
5523: next;
5524: }
5525: foreach my $role_id (keys(%{$content{'roles'}})) {
5526: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5527: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5528: my @status = @{$content{'roles'}{$role_id}{'access'}};
5529: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5530: foreach my $role (keys(%{$allroles{$cid}})) {
5531: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5532: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5533: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5534: if (grep/^all$/,@sections) {
5535: return 'ok';
5536: } else {
5537: if (grep/^$sec$/,@sections) {
5538: return 'ok';
5539: }
5540: }
5541: }
5542: }
5543: if (keys(%{$allgroups{$cid}}) == 0) {
5544: if (grep/^none$/,@groups) {
5545: return 'ok';
5546: }
5547: } else {
5548: if (grep/^all$/,@groups) {
5549: return 'ok';
5550: }
5551: foreach my $group (keys(%{$allgroups{$cid}})) {
5552: if (grep/^$group$/,@groups) {
5553: return 'ok';
5554: }
5555: }
5556: }
5557: }
5558: }
5559: }
5560: }
5561: }
5562: if ($guest) {
5563: return $guest;
5564: }
5565: }
5566: }
5567: return;
5568: }
5569:
5570: sub course_group_datechecker {
5571: my ($dates,$now,$status) = @_;
5572: my ($start,$end) = split(/\./,$dates);
5573: if (!$start && !$end) {
5574: return 'ok';
5575: }
5576: if (grep/^active$/,@{$status}) {
5577: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5578: return 'ok';
5579: }
5580: }
5581: if (grep/^previous$/,@{$status}) {
5582: if ($end > $now ) {
5583: return 'ok';
5584: }
5585: }
5586: if (grep/^future$/,@{$status}) {
5587: if ($start > $now) {
5588: return 'ok';
5589: }
5590: }
5591: return;
5592: }
5593:
5594: sub parse_portfolio_url {
5595: my ($url) = @_;
5596:
5597: my ($type,$udom,$unum,$group,$file_name);
5598:
1.823 albertel 5599: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5600: $type = 1;
5601: $udom = $1;
5602: $unum = $2;
5603: $file_name = $3;
1.823 albertel 5604: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5605: $type = 2;
5606: $udom = $1;
5607: $unum = $2;
5608: $group = $3;
5609: $file_name = $3.'/'.$4;
5610: }
5611: if (wantarray) {
5612: return ($type,$udom,$unum,$file_name,$group);
5613: }
5614: return $type;
5615: }
5616:
5617: sub is_portfolio_url {
5618: my ($url) = @_;
5619: return scalar(&parse_portfolio_url($url));
5620: }
5621:
1.798 raeburn 5622: sub is_portfolio_file {
5623: my ($file) = @_;
1.820 raeburn 5624: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5625: return 1;
5626: }
5627: return;
5628: }
5629:
1.976 raeburn 5630: sub usertools_access {
1.1084 raeburn 5631: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 5632: my ($access,%tools);
5633: if ($context eq '') {
5634: $context = 'tools';
5635: }
5636: if ($context eq 'requestcourses') {
5637: %tools = (
5638: official => 1,
5639: unofficial => 1,
1.1006 raeburn 5640: community => 1,
1.985 raeburn 5641: );
5642: } else {
5643: %tools = (
5644: aboutme => 1,
5645: blog => 1,
1.1172.2.6 raeburn 5646: webdav => 1,
1.985 raeburn 5647: portfolio => 1,
5648: );
5649: }
1.976 raeburn 5650: return if (!defined($tools{$tool}));
5651:
5652: if ((!defined($udom)) || (!defined($uname))) {
5653: $udom = $env{'user.domain'};
5654: $uname = $env{'user.name'};
5655: }
5656:
1.978 raeburn 5657: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5658: if ($action ne 'reload') {
1.985 raeburn 5659: if ($context eq 'requestcourses') {
5660: return $env{'environment.canrequest.'.$tool};
5661: } else {
5662: return $env{'environment.availabletools.'.$tool};
5663: }
5664: }
1.976 raeburn 5665: }
5666:
5667: my ($toolstatus,$inststatus);
5668:
1.985 raeburn 5669: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5670: ($action ne 'reload')) {
5671: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5672: $inststatus = $env{'environment.inststatus'};
5673: } else {
1.1084 raeburn 5674: if (ref($userenvref) eq 'HASH') {
5675: $toolstatus = $userenvref->{$context.'.'.$tool};
5676: $inststatus = $userenvref->{'inststatus'};
5677: } else {
5678: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5679: $toolstatus = $userenv{$context.'.'.$tool};
5680: $inststatus = $userenv{'inststatus'};
5681: }
1.976 raeburn 5682: }
5683:
5684: if ($toolstatus ne '') {
5685: if ($toolstatus) {
5686: $access = 1;
5687: } else {
5688: $access = 0;
5689: }
5690: return $access;
5691: }
5692:
1.1084 raeburn 5693: my ($is_adv,%domdef);
5694: if (ref($is_advref) eq 'HASH') {
5695: $is_adv = $is_advref->{'is_adv'};
5696: } else {
5697: $is_adv = &is_advanced_user($udom,$uname);
5698: }
5699: if (ref($domdefref) eq 'HASH') {
5700: %domdef = %{$domdefref};
5701: } else {
5702: %domdef = &get_domain_defaults($udom);
5703: }
1.976 raeburn 5704: if (ref($domdef{$tool}) eq 'HASH') {
5705: if ($is_adv) {
5706: if ($domdef{$tool}{'_LC_adv'} ne '') {
5707: if ($domdef{$tool}{'_LC_adv'}) {
5708: $access = 1;
5709: } else {
5710: $access = 0;
5711: }
5712: return $access;
5713: }
5714: }
5715: if ($inststatus ne '') {
5716: my ($hasaccess,$hasnoaccess);
5717: foreach my $affiliation (split(/:/,$inststatus)) {
5718: if ($domdef{$tool}{$affiliation} ne '') {
5719: if ($domdef{$tool}{$affiliation}) {
5720: $hasaccess = 1;
5721: } else {
5722: $hasnoaccess = 1;
5723: }
5724: }
5725: }
5726: if ($hasaccess || $hasnoaccess) {
5727: if ($hasaccess) {
5728: $access = 1;
5729: } elsif ($hasnoaccess) {
5730: $access = 0;
5731: }
5732: return $access;
5733: }
5734: } else {
5735: if ($domdef{$tool}{'default'} ne '') {
5736: if ($domdef{$tool}{'default'}) {
5737: $access = 1;
5738: } elsif ($domdef{$tool}{'default'} == 0) {
5739: $access = 0;
5740: }
5741: return $access;
5742: }
5743: }
5744: } else {
1.1172.2.6 raeburn 5745: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 5746: $access = 1;
5747: } else {
5748: $access = 0;
5749: }
1.976 raeburn 5750: return $access;
5751: }
5752: }
5753:
1.1050 raeburn 5754: sub is_course_owner {
5755: my ($cdom,$cnum,$udom,$uname) = @_;
5756: if (($udom eq '') || ($uname eq '')) {
5757: $udom = $env{'user.domain'};
5758: $uname = $env{'user.name'};
5759: }
5760: unless (($udom eq '') || ($uname eq '')) {
5761: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5762: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5763: return 1;
5764: } else {
5765: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5766: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5767: return 1;
5768: }
5769: }
5770: }
5771: }
5772: return;
5773: }
5774:
1.976 raeburn 5775: sub is_advanced_user {
5776: my ($udom,$uname) = @_;
1.1085 raeburn 5777: if ($udom ne '' && $uname ne '') {
5778: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 5779: if (wantarray) {
5780: return ($env{'user.adv'},$env{'user.author'});
5781: } else {
5782: return $env{'user.adv'};
5783: }
1.1085 raeburn 5784: }
5785: }
1.976 raeburn 5786: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5787: my %allroles;
1.1128 raeburn 5788: my ($is_adv,$is_author);
1.976 raeburn 5789: foreach my $role (keys(%roleshash)) {
5790: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5791: my $area = '/'.$tdomain.'/'.$trest;
5792: if ($sec ne '') {
5793: $area .= '/'.$sec;
5794: }
5795: if (($area ne '') && ($trole ne '')) {
5796: my $spec=$trole.'.'.$area;
5797: if ($trole =~ /^cr\//) {
5798: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5799: } elsif ($trole ne 'gr') {
5800: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5801: }
1.1128 raeburn 5802: if ($trole eq 'au') {
5803: $is_author = 1;
5804: }
1.976 raeburn 5805: }
5806: }
5807: foreach my $role (keys(%allroles)) {
5808: last if ($is_adv);
5809: foreach my $item (split(/:/,$allroles{$role})) {
5810: if ($item ne '') {
5811: my ($privilege,$restrictions)=split(/&/,$item);
5812: if ($privilege eq 'adv') {
5813: $is_adv = 1;
5814: last;
5815: }
5816: }
5817: }
5818: }
1.1128 raeburn 5819: if (wantarray) {
5820: return ($is_adv,$is_author);
5821: }
1.976 raeburn 5822: return $is_adv;
5823: }
1.798 raeburn 5824:
1.1035 raeburn 5825: sub check_can_request {
1.1036 raeburn 5826: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5827: my $canreq = 0;
5828: my ($types,$typename) = &Apache::loncommon::course_types();
5829: my @options = ('approval','validate','autolimit');
5830: my $optregex = join('|',@options);
5831: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5832: foreach my $type (@{$types}) {
5833: if (&usertools_access($env{'user.name'},
5834: $env{'user.domain'},
5835: $type,undef,'requestcourses')) {
5836: $canreq ++;
1.1036 raeburn 5837: if (ref($request_domains) eq 'HASH') {
5838: push(@{$request_domains->{$type}},$env{'user.domain'});
5839: }
1.1035 raeburn 5840: if ($dom eq $env{'user.domain'}) {
5841: $can_request->{$type} = 1;
5842: }
5843: }
5844: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5845: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5846: if (@curr > 0) {
1.1036 raeburn 5847: foreach my $item (@curr) {
5848: if (ref($request_domains) eq 'HASH') {
5849: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5850: if ($otherdom ne '') {
5851: if (ref($request_domains->{$type}) eq 'ARRAY') {
5852: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5853: push(@{$request_domains->{$type}},$otherdom);
5854: }
5855: } else {
5856: push(@{$request_domains->{$type}},$otherdom);
5857: }
5858: }
5859: }
5860: }
5861: unless($dom eq $env{'user.domain'}) {
5862: $canreq ++;
1.1035 raeburn 5863: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5864: $can_request->{$type} = 1;
5865: }
5866: }
5867: }
5868: }
5869: }
5870: }
5871: return $canreq;
5872: }
5873:
1.341 www 5874: # ---------------------------------------------- Custom access rule evaluation
5875:
5876: sub customaccess {
5877: my ($priv,$uri)=@_;
1.807 albertel 5878: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5879: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5880: $udom = &LONCAPA::clean_domain($udom);
5881: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5882: my $access=0;
1.800 albertel 5883: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5884: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5885: if ($type eq 'user') {
5886: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5887: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5888: if ($tdom) {
5889: if ($tdom ne $env{'user.domain'}) { next; }
5890: }
1.896 albertel 5891: if ($tuname) {
5892: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5893: }
5894: $access=($effect eq 'allow');
5895: last;
5896: }
5897: } else {
5898: if ($role) {
5899: if ($role ne $urole) { next; }
5900: }
5901: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5902: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5903: if ($tdom) {
5904: if ($tdom ne $udom) { next; }
5905: }
5906: if ($tcrs) {
5907: if ($tcrs ne $ucrs) { next; }
5908: }
5909: if ($tsec) {
5910: if ($tsec ne $usec) { next; }
5911: }
5912: $access=($effect eq 'allow');
5913: last;
5914: }
5915: if ($realm eq '' && $role eq '') {
5916: $access=($effect eq 'allow');
5917: }
1.402 bowersj2 5918: }
1.341 www 5919: }
5920: return $access;
5921: }
5922:
1.103 harris41 5923: # ------------------------------------------------- Check for a user privilege
1.12 www 5924:
5925: sub allowed {
1.810 raeburn 5926: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5927: my $ver_orguri=$uri;
1.439 www 5928: $uri=&deversion($uri);
1.152 www 5929: my $orguri=$uri;
1.52 www 5930: $uri=&declutter($uri);
1.809 raeburn 5931:
1.810 raeburn 5932: if ($priv eq 'evb') {
5933: # Evade communication block restrictions for specified role in a course
5934: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5935: return $1;
5936: } else {
5937: return;
5938: }
5939: }
5940:
1.620 albertel 5941: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5942: # Free bre access to adm and meta resources
1.775 albertel 5943: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5944: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5945: && ($priv eq 'bre')) {
1.14 www 5946: return 'F';
1.159 www 5947: }
5948:
1.545 banghart 5949: # Free bre access to user's own portfolio contents
1.714 raeburn 5950: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5951: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5952: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5953: my %setters;
5954: my ($startblock,$endblock) =
5955: &Apache::loncommon::blockcheck(\%setters,'port');
5956: if ($startblock && $endblock) {
5957: return 'B';
5958: } else {
5959: return 'F';
5960: }
1.545 banghart 5961: }
5962:
1.762 raeburn 5963: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5964: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5965: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5966: if (exists($env{'request.course.id'})) {
5967: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5968: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5969: if (($domain eq $cdom) && ($name eq $cnum)) {
5970: my $courseprivid=$env{'request.course.id'};
5971: $courseprivid=~s/\_/\//;
5972: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5973: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5974: return $1;
1.762 raeburn 5975: } else {
5976: if ($env{'request.course.sec'}) {
5977: $courseprivid.='/'.$env{'request.course.sec'};
5978: }
5979: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5980: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5981: return $2;
5982: }
1.714 raeburn 5983: }
5984: }
5985: }
5986: }
5987:
1.159 www 5988: # Free bre to public access
5989:
5990: if ($priv eq 'bre') {
1.238 www 5991: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5992: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5993: return 'F';
5994: }
1.238 www 5995: if ($copyright eq 'priv') {
5996: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5997: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5998: return '';
5999: }
6000: }
6001: if ($copyright eq 'domain') {
6002: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6003: unless (($env{'user.domain'} eq $1) ||
6004: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6005: return '';
6006: }
1.262 matthew 6007: }
1.620 albertel 6008: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6009: # Library role, so allow browsing of resources in this domain.
6010: return 'F';
1.238 www 6011: }
1.341 www 6012: if ($copyright eq 'custom') {
6013: unless (&customaccess($priv,$uri)) { return ''; }
6014: }
1.14 www 6015: }
1.264 matthew 6016: # Domain coordinator is trying to create a course
1.620 albertel 6017: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6018: # uri is the requested domain in this case.
6019: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6020: # a role of dc for the domain in question.
1.620 albertel 6021: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6022: }
1.29 www 6023:
1.52 www 6024: my $thisallowed='';
6025: my $statecond=0;
6026: my $courseprivid='';
6027:
1.1039 raeburn 6028: my $ownaccess;
1.1043 raeburn 6029: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6030: if (($priv eq 'bro') && ($env{'user.author'})) {
6031: if ($uri eq '') {
6032: $ownaccess = 1;
6033: } else {
6034: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6035: my $udom = $env{'user.domain'};
6036: my $uname = $env{'user.name'};
6037: if ($uri =~ m{^\Q$udom\E/?$}) {
6038: $ownaccess = 1;
1.1040 raeburn 6039: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6040: unless ($uri =~ m{\.\./}) {
6041: $ownaccess = 1;
6042: }
6043: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6044: my $now = time;
6045: if ($uri =~ m{^([^/]+)/?$}) {
6046: my $adom = $1;
6047: foreach my $key (keys(%env)) {
1.1042 raeburn 6048: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6049: my ($start,$end) = split('.',$env{$key});
6050: if (($now >= $start) && (!$end || $end < $now)) {
6051: $ownaccess = 1;
6052: last;
6053: }
6054: }
6055: }
6056: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6057: my $adom = $1;
6058: my $aname = $2;
1.1042 raeburn 6059: foreach my $role ('ca','aa') {
6060: if ($env{"user.role.$role./$adom/$aname"}) {
6061: my ($start,$end) =
6062: split('.',$env{"user.role.$role./$adom/$aname"});
6063: if (($now >= $start) && (!$end || $end < $now)) {
6064: $ownaccess = 1;
6065: last;
6066: }
1.1039 raeburn 6067: }
6068: }
6069: }
6070: }
6071: }
6072: }
6073: }
6074:
1.52 www 6075: # Course
6076:
1.620 albertel 6077: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6078: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6079: $thisallowed.=$1;
6080: }
1.52 www 6081: }
1.29 www 6082:
1.52 www 6083: # Domain
6084:
1.620 albertel 6085: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6086: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6087: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6088: $thisallowed.=$1;
6089: }
1.12 www 6090: }
1.52 www 6091:
1.1141 raeburn 6092: # User who is not author or co-author might still be able to edit
6093: # resource of an author in the domain (e.g., if Domain Coordinator).
6094: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6095: (&allowed('mdc',$env{'request.course.id'}))) {
6096: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6097: $thisallowed.=$1;
6098: }
6099: }
6100:
1.52 www 6101: # Course: uri itself is a course
1.66 www 6102: my $courseuri=$uri;
6103: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6104: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6105:
1.620 albertel 6106: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6107: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6108: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6109: $thisallowed.=$1;
6110: }
1.12 www 6111: }
1.29 www 6112:
1.665 albertel 6113: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6114: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6115: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6116: $thisallowed='';
1.671 raeburn 6117: my ($match)=&is_on_map($uri);
6118: if ($match) {
6119: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6120: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6121: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6122: if (@blockers > 0) {
6123: $thisallowed = 'B';
6124: } else {
6125: $thisallowed.=$1;
6126: }
1.671 raeburn 6127: }
6128: } else {
1.705 albertel 6129: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6130: if ($refuri) {
6131: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6132: $thisallowed='F';
1.671 raeburn 6133: } else {
6134: $refuri=&declutter($refuri);
6135: my ($match) = &is_on_map($refuri);
6136: if ($match) {
1.1162 raeburn 6137: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6138: if (@blockers > 0) {
6139: $thisallowed = 'B';
6140: } else {
6141: $thisallowed='F';
6142: }
1.671 raeburn 6143: }
1.669 raeburn 6144: }
1.671 raeburn 6145: }
6146: }
1.314 www 6147: }
1.492 albertel 6148:
1.766 albertel 6149: if ($priv eq 'bre'
6150: && $thisallowed ne 'F'
6151: && $thisallowed ne '2'
6152: && &is_portfolio_url($uri)) {
6153: $thisallowed = &portfolio_access($uri);
6154: }
6155:
1.52 www 6156: # Full access at system, domain or course-wide level? Exit.
1.29 www 6157: if ($thisallowed=~/F/) {
6158: return 'F';
6159: }
6160:
1.52 www 6161: # If this is generating or modifying users, exit with special codes
1.29 www 6162:
1.643 www 6163: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6164: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6165: my ($audom,$auname)=split('/',$uri);
1.643 www 6166: # no author name given, so this just checks on the general right to make a co-author in this domain
6167: unless ($auname) { return $thisallowed; }
6168: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6169: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6170: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6171: ($audom ne $env{'request.role.domain'}))) { return ''; }
6172: }
1.52 www 6173: return $thisallowed;
6174: }
6175: #
1.103 harris41 6176: # Gathered so far: system, domain and course wide privileges
1.52 www 6177: #
6178: # Course: See if uri or referer is an individual resource that is part of
6179: # the course
6180:
1.620 albertel 6181: if ($env{'request.course.id'}) {
1.232 www 6182:
1.620 albertel 6183: $courseprivid=$env{'request.course.id'};
6184: if ($env{'request.course.sec'}) {
6185: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6186: }
6187: $courseprivid=~s/\_/\//;
6188: my $checkreferer=1;
1.232 www 6189: my ($match,$cond)=&is_on_map($uri);
6190: if ($match) {
6191: $statecond=$cond;
1.620 albertel 6192: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6193: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6194: my $value = $1;
6195: if ($priv eq 'bre') {
6196: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6197: if (@blockers > 0) {
6198: $thisallowed = 'B';
6199: } else {
6200: $thisallowed.=$value;
6201: }
6202: } else {
6203: $thisallowed.=$value;
6204: }
1.52 www 6205: $checkreferer=0;
6206: }
1.29 www 6207: }
1.83 www 6208:
1.148 www 6209: if ($checkreferer) {
1.620 albertel 6210: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6211: unless ($refuri) {
1.800 albertel 6212: foreach my $key (keys(%env)) {
6213: if ($key=~/^httpref\..*\*/) {
6214: my $pattern=$key;
1.156 www 6215: $pattern=~s/^httpref\.\/res\///;
1.148 www 6216: $pattern=~s/\*/\[\^\/\]\+/g;
6217: $pattern=~s/\//\\\//g;
1.152 www 6218: if ($orguri=~/$pattern/) {
1.800 albertel 6219: $refuri=$env{$key};
1.148 www 6220: }
6221: }
1.191 harris41 6222: }
1.148 www 6223: }
1.232 www 6224:
1.148 www 6225: if ($refuri) {
1.152 www 6226: $refuri=&declutter($refuri);
1.232 www 6227: my ($match,$cond)=&is_on_map($refuri);
6228: if ($match) {
6229: my $refstatecond=$cond;
1.620 albertel 6230: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6231: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6232: my $value = $1;
6233: if ($priv eq 'bre') {
6234: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6235: if (@blockers > 0) {
6236: $thisallowed = 'B';
6237: } else {
6238: $thisallowed.=$value;
6239: }
6240: } else {
6241: $thisallowed.=$value;
6242: }
1.53 www 6243: $uri=$refuri;
6244: $statecond=$refstatecond;
1.52 www 6245: }
6246: }
1.148 www 6247: }
1.29 www 6248: }
1.52 www 6249: }
1.29 www 6250:
1.52 www 6251: #
1.103 harris41 6252: # Gathered now: all privileges that could apply, and condition number
1.52 www 6253: #
6254: #
6255: # Full or no access?
6256: #
1.29 www 6257:
1.52 www 6258: if ($thisallowed=~/F/) {
6259: return 'F';
6260: }
1.29 www 6261:
1.52 www 6262: unless ($thisallowed) {
6263: return '';
6264: }
1.29 www 6265:
1.52 www 6266: # Restrictions exist, deal with them
6267: #
6268: # C:according to course preferences
6269: # R:according to resource settings
6270: # L:unless locked
6271: # X:according to user session state
6272: #
6273:
6274: # Possibly locked functionality, check all courses
1.54 www 6275: # Locks might take effect only after 10 minutes cache expiration for other
6276: # courses, and 2 minutes for current course
1.52 www 6277:
6278: my $envkey;
6279: if ($thisallowed=~/L/) {
1.1000 raeburn 6280: foreach $envkey (keys(%env)) {
1.54 www 6281: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6282: my $courseid=$2;
6283: my $roleid=$1.'.'.$2;
1.92 www 6284: $courseid=~s/^\///;
1.54 www 6285: my $expiretime=600;
1.620 albertel 6286: if ($env{'request.role'} eq $roleid) {
1.54 www 6287: $expiretime=120;
6288: }
6289: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6290: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6291: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6292: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6293: }
1.620 albertel 6294: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6295: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6296: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6297: &log($env{'user.domain'},$env{'user.name'},
6298: $env{'user.home'},
1.57 www 6299: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6300: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6301: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6302: return '';
6303: }
6304: }
1.620 albertel 6305: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6306: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6307: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6308: &log($env{'user.domain'},$env{'user.name'},
6309: $env{'user.home'},
1.57 www 6310: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6311: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6312: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6313: return '';
6314: }
6315: }
6316: }
1.29 www 6317: }
1.52 www 6318: }
6319:
6320: #
6321: # Rest of the restrictions depend on selected course
6322: #
6323:
1.620 albertel 6324: unless ($env{'request.course.id'}) {
1.766 albertel 6325: if ($thisallowed eq 'A') {
6326: return 'A';
1.814 raeburn 6327: } elsif ($thisallowed eq 'B') {
6328: return 'B';
1.766 albertel 6329: } else {
6330: return '1';
6331: }
1.52 www 6332: }
1.29 www 6333:
1.52 www 6334: #
6335: # Now user is definitely in a course
6336: #
1.53 www 6337:
6338:
6339: # Course preferences
6340:
6341: if ($thisallowed=~/C/) {
1.620 albertel 6342: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6343: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6344: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6345: =~/\Q$rolecode\E/) {
1.1103 raeburn 6346: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6347: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6348: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6349: $env{'request.course.id'});
6350: }
1.237 www 6351: return '';
6352: }
6353:
1.620 albertel 6354: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6355: =~/\Q$unamedom\E/) {
1.1103 raeburn 6356: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6357: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6358: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6359: $env{'request.course.id'});
6360: }
1.54 www 6361: return '';
6362: }
1.53 www 6363: }
6364:
6365: # Resource preferences
6366:
6367: if ($thisallowed=~/R/) {
1.620 albertel 6368: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6369: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6370: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6371: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6372: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6373: }
6374: return '';
1.54 www 6375: }
1.53 www 6376: }
1.30 www 6377:
1.246 www 6378: # Restricted by state or randomout?
1.30 www 6379:
1.52 www 6380: if ($thisallowed=~/X/) {
1.620 albertel 6381: if ($env{'acc.randomout'}) {
1.579 albertel 6382: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 6383: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 6384: return '';
6385: }
1.247 www 6386: }
6387: if (&condval($statecond)) {
1.52 www 6388: return '2';
6389: } else {
6390: return '';
6391: }
6392: }
1.30 www 6393:
1.766 albertel 6394: if ($thisallowed eq 'A') {
6395: return 'A';
1.814 raeburn 6396: } elsif ($thisallowed eq 'B') {
6397: return 'B';
1.766 albertel 6398: }
1.52 www 6399: return 'F';
1.232 www 6400: }
1.1162 raeburn 6401:
6402: sub get_comm_blocks {
6403: my ($cdom,$cnum) = @_;
6404: if ($cdom eq '' || $cnum eq '') {
6405: return unless ($env{'request.course.id'});
6406: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6407: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6408: }
6409: my %commblocks;
6410: my $hashid=$cdom.'_'.$cnum;
6411: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
6412: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
6413: %commblocks = %{$blocksref};
6414: } else {
6415: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
6416: my $cachetime = 600;
6417: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
6418: }
6419: return %commblocks;
6420: }
6421:
6422: sub has_comm_blocking {
6423: my ($priv,$symb,$uri,$blocks) = @_;
6424: return unless ($env{'request.course.id'});
6425: return unless ($priv eq 'bre');
6426: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
6427: my %commblocks;
6428: if (ref($blocks) eq 'HASH') {
6429: %commblocks = %{$blocks};
6430: } else {
6431: %commblocks = &get_comm_blocks();
6432: }
6433: return unless (keys(%commblocks) > 0);
6434: if (!$symb) { $symb=&symbread($uri,1); }
6435: my ($map,$resid,undef)=&decode_symb($symb);
6436: my %tocheck = (
6437: maps => $map,
6438: resources => $symb,
6439: );
6440: my @blockers;
6441: my $now = time;
1.1163 raeburn 6442: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 6443: foreach my $block (keys(%commblocks)) {
6444: if ($block =~ /^(\d+)____(\d+)$/) {
6445: my ($start,$end) = ($1,$2);
6446: if ($start <= $now && $end >= $now) {
6447: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6448: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6449: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
6450: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
6451: unless (grep(/^\Q$block\E$/,@blockers)) {
6452: push(@blockers,$block);
6453: }
6454: }
6455: }
6456: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
6457: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
6458: unless (grep(/^\Q$block\E$/,@blockers)) {
6459: push(@blockers,$block);
6460: }
6461: }
6462: }
6463: }
6464: }
6465: }
6466: } elsif ($block =~ /^firstaccess____(.+)$/) {
6467: my $item = $1;
1.1163 raeburn 6468: my @to_test;
1.1162 raeburn 6469: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6470: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6471: my $check_interval;
6472: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
6473: my @interval;
6474: my $type = 'map';
6475: if ($item eq 'course') {
6476: $type = 'course';
6477: @interval=&EXT("resource.0.interval");
6478: } else {
6479: if ($item =~ /___\d+___/) {
6480: $type = 'resource';
6481: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 6482: if (ref($navmap)) {
6483: my $res = $navmap->getBySymb($item);
6484: push(@to_test,$res);
6485: }
1.1162 raeburn 6486: } else {
6487: my $mapsymb = &symbread($item,1);
6488: if ($mapsymb) {
6489: if (ref($navmap)) {
6490: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 6491: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
6492: foreach my $res (@to_test) {
1.1162 raeburn 6493: my $symb = $res->symb();
6494: next if ($symb eq $mapsymb);
6495: if ($symb ne '') {
6496: @interval=&EXT("resource.0.interval",$symb);
6497: last;
6498: }
6499: }
6500: }
6501: }
6502: }
6503: }
6504: if ($interval[0] =~ /\d+/) {
6505: my $first_access;
6506: if ($type eq 'resource') {
6507: $first_access=&get_first_access($interval[1],$item);
6508: } elsif ($type eq 'map') {
6509: $first_access=&get_first_access($interval[1],undef,$item);
6510: } else {
6511: $first_access=&get_first_access($interval[1]);
6512: }
6513: if ($first_access) {
6514: my $timesup = $first_access+$interval[0];
6515: if ($timesup > $now) {
1.1163 raeburn 6516: foreach my $res (@to_test) {
6517: if ($res->is_problem()) {
6518: if ($res->completable()) {
6519: unless (grep(/^\Q$block\E$/,@blockers)) {
6520: push(@blockers,$block);
6521: }
6522: last;
6523: }
6524: }
1.1162 raeburn 6525: }
6526: }
6527: }
6528: }
6529: }
6530: }
6531: }
6532: }
6533: }
6534: return @blockers;
6535: }
6536:
6537: sub check_docs_block {
6538: my ($docsblock,$tocheck) =@_;
6539: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
6540: return;
6541: }
6542: if (ref($docsblock->{'maps'}) eq 'HASH') {
6543: if ($tocheck->{'maps'}) {
6544: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
6545: return 1;
6546: }
6547: }
6548: }
6549: if (ref($docsblock->{'resources'}) eq 'HASH') {
6550: if ($tocheck->{'resources'}) {
6551: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
6552: return 1;
6553: }
6554: }
6555: }
6556: return;
6557: }
6558:
1.1133 foxr 6559: #
6560: # Removes the versino from a URI and
6561: # splits it in to its filename and path to the filename.
6562: # Seems like File::Basename could have done this more clearly.
6563: # Parameters:
6564: # $uri - input URI
6565: # Returns:
6566: # Two element list consisting of
6567: # $pathname - the URI up to and excluding the trailing /
6568: # $filename - The part of the URI following the last /
6569: # NOTE:
6570: # Another realization of this is simply:
6571: # use File::Basename;
6572: # ...
6573: # $uri = shift;
6574: # $filename = basename($uri);
6575: # $path = dirname($uri);
6576: # return ($filename, $path);
6577: #
6578: # The implementation below is probably faster however.
6579: #
1.710 albertel 6580: sub split_uri_for_cond {
6581: my $uri=&deversion(&declutter(shift));
6582: my @uriparts=split(/\//,$uri);
6583: my $filename=pop(@uriparts);
6584: my $pathname=join('/',@uriparts);
6585: return ($pathname,$filename);
6586: }
1.232 www 6587: # --------------------------------------------------- Is a resource on the map?
6588:
6589: sub is_on_map {
1.710 albertel 6590: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 6591: #Trying to find the conditional for the file
1.620 albertel 6592: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 6593: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 6594: if ($match) {
1.289 bowersj2 6595: return (1,$1);
6596: } else {
1.434 www 6597: return (0,0);
1.289 bowersj2 6598: }
1.12 www 6599: }
6600:
1.427 www 6601: # --------------------------------------------------------- Get symb from alias
6602:
6603: sub get_symb_from_alias {
6604: my $symb=shift;
6605: my ($map,$resid,$url)=&decode_symb($symb);
6606: # Already is a symb
6607: if ($url) { return $symb; }
6608: # Must be an alias
6609: my $aliassymb='';
6610: my %bighash;
1.620 albertel 6611: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 6612: &GDBM_READER(),0640)) {
6613: my $rid=$bighash{'mapalias_'.$symb};
6614: if ($rid) {
6615: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 6616: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6617: $resid,$bighash{'src_'.$rid});
1.427 www 6618: }
6619: untie %bighash;
6620: }
6621: return $aliassymb;
6622: }
6623:
1.12 www 6624: # ----------------------------------------------------------------- Define Role
6625:
6626: sub definerole {
6627: if (allowed('mcr','/')) {
6628: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 6629: foreach my $role (split(':',$sysrole)) {
6630: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6631: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6632: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6633: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6634: return "refused:s:$crole&$cqual";
6635: }
6636: }
1.191 harris41 6637: }
1.800 albertel 6638: foreach my $role (split(':',$domrole)) {
6639: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6640: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6641: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6642: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 6643: return "refused:d:$crole&$cqual";
6644: }
6645: }
1.191 harris41 6646: }
1.800 albertel 6647: foreach my $role (split(':',$courole)) {
6648: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6649: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6650: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6651: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6652: return "refused:c:$crole&$cqual";
6653: }
6654: }
1.191 harris41 6655: }
1.620 albertel 6656: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6657: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6658: "rolesdef_$rolename=".
6659: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 6660: return reply($command,$env{'user.home'});
1.12 www 6661: } else {
6662: return 'refused';
6663: }
1.105 harris41 6664: }
6665:
6666: # ---------------- Make a metadata query against the network of library servers
6667:
6668: sub metadata_query {
1.244 matthew 6669: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 6670: my %rhash;
1.845 albertel 6671: my %libserv = &all_library();
1.244 matthew 6672: my @server_list = (defined($server_array) ? @$server_array
6673: : keys(%libserv) );
6674: for my $server (@server_list) {
1.118 harris41 6675: unless ($custom or $customshow) {
6676: my $reply=&reply("querysend:".&escape($query),$server);
6677: $rhash{$server}=$reply;
6678: }
6679: else {
6680: my $reply=&reply("querysend:".&escape($query).':'.
6681: &escape($custom).':'.&escape($customshow),
6682: $server);
6683: $rhash{$server}=$reply;
6684: }
1.112 harris41 6685: }
1.118 harris41 6686: return \%rhash;
1.240 www 6687: }
6688:
6689: # ----------------------------------------- Send log queries and wait for reply
6690:
6691: sub log_query {
6692: my ($uname,$udom,$query,%filters)=@_;
6693: my $uhome=&homeserver($uname,$udom);
6694: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 6695: my $uhost=&hostname($uhome);
1.800 albertel 6696: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 6697: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6698: $uhome);
1.479 albertel 6699: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 6700: return get_query_reply($queryid);
6701: }
6702:
1.818 raeburn 6703: # -------------------------- Update MySQL table for portfolio file
6704:
6705: sub update_portfolio_table {
1.821 raeburn 6706: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 6707: if ($group ne '') {
6708: $file_name =~s /^\Q$group\E//;
6709: }
1.818 raeburn 6710: my $homeserver = &homeserver($uname,$udom);
6711: my $queryid=
1.821 raeburn 6712: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6713: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 6714: my $reply = &get_query_reply($queryid);
6715: return $reply;
6716: }
6717:
1.899 raeburn 6718: # -------------------------- Update MySQL allusers table
6719:
6720: sub update_allusers_table {
6721: my ($uname,$udom,$names) = @_;
6722: my $homeserver = &homeserver($uname,$udom);
6723: my $queryid=
6724: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6725: 'lastname='.&escape($names->{'lastname'}).'%%'.
6726: 'firstname='.&escape($names->{'firstname'}).'%%'.
6727: 'middlename='.&escape($names->{'middlename'}).'%%'.
6728: 'generation='.&escape($names->{'generation'}).'%%'.
6729: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6730: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 6731: return;
1.899 raeburn 6732: }
6733:
1.508 raeburn 6734: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 6735:
6736: sub fetch_enrollment_query {
1.511 raeburn 6737: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 6738: my $homeserver;
1.547 raeburn 6739: my $maxtries = 1;
1.508 raeburn 6740: if ($context eq 'automated') {
6741: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 6742: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 6743: } else {
6744: $homeserver = &homeserver($cnum,$dom);
6745: }
1.838 albertel 6746: my $host=&hostname($homeserver);
1.506 raeburn 6747: my $cmd = '';
1.1000 raeburn 6748: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 6749: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 6750: }
6751: $cmd =~ s/%%$//;
6752: $cmd = &escape($cmd);
6753: my $query = 'fetchenrollment';
1.620 albertel 6754: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 6755: unless ($queryid=~/^\Q$host\E\_/) {
6756: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6757: return 'error: '.$queryid;
6758: }
1.506 raeburn 6759: my $reply = &get_query_reply($queryid);
1.547 raeburn 6760: my $tries = 1;
6761: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6762: $reply = &get_query_reply($queryid);
6763: $tries ++;
6764: }
1.526 raeburn 6765: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 6766: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 6767: } else {
1.901 albertel 6768: my @responses = split(/:/,$reply);
1.515 raeburn 6769: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 6770: foreach my $line (@responses) {
6771: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 6772: $$replyref{$key} = $value;
6773: }
6774: } else {
1.1117 foxr 6775: my $pathname = LONCAPA::tempdir();
1.800 albertel 6776: foreach my $line (@responses) {
6777: my ($key,$value) = split(/=/,$line);
1.506 raeburn 6778: $$replyref{$key} = $value;
6779: if ($value > 0) {
1.800 albertel 6780: foreach my $item (@{$$affiliatesref{$key}}) {
6781: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 6782: my $destname = $pathname.'/'.$filename;
6783: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 6784: if ($xml_classlist =~ /^error/) {
6785: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6786: } else {
1.506 raeburn 6787: if ( open(FILE,">$destname") ) {
6788: print FILE &unescape($xml_classlist);
6789: close(FILE);
1.526 raeburn 6790: } else {
6791: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6792: }
6793: }
6794: }
6795: }
6796: }
6797: }
6798: return 'ok';
6799: }
6800: return 'error';
6801: }
6802:
1.242 www 6803: sub get_query_reply {
6804: my $queryid=shift;
1.1117 foxr 6805: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 6806: my $reply='';
6807: for (1..100) {
6808: sleep 2;
6809: if (-e $replyfile.'.end') {
1.448 albertel 6810: if (open(my $fh,$replyfile)) {
1.904 albertel 6811: $reply = join('',<$fh>);
6812: close($fh);
1.240 www 6813: } else { return 'error: reply_file_error'; }
1.242 www 6814: return &unescape($reply);
6815: }
1.240 www 6816: }
1.242 www 6817: return 'timeout:'.$queryid;
1.240 www 6818: }
6819:
6820: sub courselog_query {
1.241 www 6821: #
6822: # possible filters:
6823: # url: url or symb
6824: # username
6825: # domain
6826: # action: view, submit, grade
6827: # start: timestamp
6828: # end: timestamp
6829: #
1.240 www 6830: my (%filters)=@_;
1.620 albertel 6831: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6832: if ($filters{'url'}) {
6833: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6834: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6835: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6836: }
1.620 albertel 6837: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6838: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6839: return &log_query($cname,$cdom,'courselog',%filters);
6840: }
6841:
6842: sub userlog_query {
1.858 raeburn 6843: #
6844: # possible filters:
6845: # action: log check role
6846: # start: timestamp
6847: # end: timestamp
6848: #
1.240 www 6849: my ($uname,$udom,%filters)=@_;
6850: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6851: }
6852:
1.506 raeburn 6853: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6854:
6855: sub auto_run {
1.508 raeburn 6856: my ($cnum,$cdom) = @_;
1.876 raeburn 6857: my $response = 0;
6858: my $settings;
6859: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6860: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6861: $settings = $domconfig{'autoenroll'};
6862: if ($settings->{'run'} eq '1') {
6863: $response = 1;
6864: }
6865: } else {
1.934 raeburn 6866: my $homeserver;
6867: if (&is_course($cdom,$cnum)) {
6868: $homeserver = &homeserver($cnum,$cdom);
6869: } else {
6870: $homeserver = &domain($cdom,'primary');
6871: }
6872: if ($homeserver ne 'no_host') {
6873: $response = &reply('autorun:'.$cdom,$homeserver);
6874: }
1.876 raeburn 6875: }
1.506 raeburn 6876: return $response;
6877: }
1.776 albertel 6878:
1.506 raeburn 6879: sub auto_get_sections {
1.508 raeburn 6880: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6881: my $homeserver;
6882: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6883: $homeserver = &homeserver($cnum,$cdom);
6884: }
6885: if (!defined($homeserver)) {
6886: if ($cdom =~ /^$match_domain$/) {
6887: $homeserver = &domain($cdom,'primary');
6888: }
6889: }
6890: my @secs;
6891: if (defined($homeserver)) {
6892: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6893: unless ($response eq 'refused') {
6894: @secs = split(/:/,$response);
6895: }
1.506 raeburn 6896: }
6897: return @secs;
6898: }
1.776 albertel 6899:
1.506 raeburn 6900: sub auto_new_course {
1.1099 raeburn 6901: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6902: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 6903: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6904: return $response;
6905: }
1.776 albertel 6906:
1.506 raeburn 6907: sub auto_validate_courseID {
1.508 raeburn 6908: my ($cnum,$cdom,$inst_course_id) = @_;
6909: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6910: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6911: return $response;
6912: }
1.776 albertel 6913:
1.1007 raeburn 6914: sub auto_validate_instcode {
1.1020 raeburn 6915: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6916: my ($homeserver,$response);
6917: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6918: $homeserver = &homeserver($cnum,$cdom);
6919: }
6920: if (!defined($homeserver)) {
6921: if ($cdom =~ /^$match_domain$/) {
6922: $homeserver = &domain($cdom,'primary');
6923: }
6924: }
1.1065 raeburn 6925: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6926: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6927: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6928: return ($outcome,$description);
1.1007 raeburn 6929: }
6930:
1.506 raeburn 6931: sub auto_create_password {
1.873 raeburn 6932: my ($cnum,$cdom,$authparam,$udom) = @_;
6933: my ($homeserver,$response);
1.506 raeburn 6934: my $create_passwd = 0;
6935: my $authchk = '';
1.873 raeburn 6936: if ($udom =~ /^$match_domain$/) {
6937: $homeserver = &domain($udom,'primary');
6938: }
6939: if ($homeserver eq '') {
6940: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6941: $homeserver = &homeserver($cnum,$cdom);
6942: }
6943: }
6944: if ($homeserver eq '') {
6945: $authchk = 'nodomain';
1.506 raeburn 6946: } else {
1.873 raeburn 6947: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6948: if ($response eq 'refused') {
6949: $authchk = 'refused';
6950: } else {
1.901 albertel 6951: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6952: }
1.506 raeburn 6953: }
6954: return ($authparam,$create_passwd,$authchk);
6955: }
6956:
1.706 raeburn 6957: sub auto_photo_permission {
6958: my ($cnum,$cdom,$students) = @_;
6959: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6960: my ($outcome,$perm_reqd,$conditions) =
6961: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6962: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6963: return (undef,undef);
6964: }
1.706 raeburn 6965: return ($outcome,$perm_reqd,$conditions);
6966: }
6967:
6968: sub auto_checkphotos {
6969: my ($uname,$udom,$pid) = @_;
6970: my $homeserver = &homeserver($uname,$udom);
6971: my ($result,$resulttype);
6972: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6973: &escape($uname).':'.&escape($pid),
6974: $homeserver));
1.709 albertel 6975: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6976: return (undef,undef);
6977: }
1.706 raeburn 6978: if ($outcome) {
6979: ($result,$resulttype) = split(/:/,$outcome);
6980: }
6981: return ($result,$resulttype);
6982: }
6983:
6984: sub auto_photochoice {
6985: my ($cnum,$cdom) = @_;
6986: my $homeserver = &homeserver($cnum,$cdom);
6987: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6988: &escape($cdom),
6989: $homeserver)));
1.709 albertel 6990: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6991: return (undef,undef);
6992: }
1.706 raeburn 6993: return ($update,$comment);
6994: }
6995:
6996: sub auto_photoupdate {
6997: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6998: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6999: my $host=&hostname($homeserver);
1.706 raeburn 7000: my $cmd = '';
7001: my $maxtries = 1;
1.800 albertel 7002: foreach my $affiliate (keys(%{$affiliatesref})) {
7003: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7004: }
7005: $cmd =~ s/%%$//;
7006: $cmd = &escape($cmd);
7007: my $query = 'institutionalphotos';
7008: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7009: unless ($queryid=~/^\Q$host\E\_/) {
7010: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7011: return 'error: '.$queryid;
7012: }
7013: my $reply = &get_query_reply($queryid);
7014: my $tries = 1;
7015: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7016: $reply = &get_query_reply($queryid);
7017: $tries ++;
7018: }
7019: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7020: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7021: } else {
7022: my @responses = split(/:/,$reply);
7023: my $outcome = shift(@responses);
7024: foreach my $item (@responses) {
7025: my ($key,$value) = split(/=/,$item);
7026: $$photo{$key} = $value;
7027: }
7028: return $outcome;
7029: }
7030: return 'error';
7031: }
7032:
1.521 raeburn 7033: sub auto_instcode_format {
1.793 albertel 7034: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7035: $cat_order) = @_;
1.521 raeburn 7036: my $courses = '';
1.772 raeburn 7037: my @homeservers;
1.521 raeburn 7038: if ($caller eq 'global') {
1.841 albertel 7039: my %servers = &get_servers($codedom,'library');
7040: foreach my $tryserver (keys(%servers)) {
7041: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7042: push(@homeservers,$tryserver);
7043: }
1.584 raeburn 7044: }
1.1022 raeburn 7045: } elsif ($caller eq 'requests') {
7046: if ($codedom =~ /^$match_domain$/) {
7047: my $chome = &domain($codedom,'primary');
7048: unless ($chome eq 'no_host') {
7049: push(@homeservers,$chome);
7050: }
7051: }
1.521 raeburn 7052: } else {
1.772 raeburn 7053: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7054: }
1.793 albertel 7055: foreach my $code (keys(%{$instcodes})) {
7056: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7057: }
7058: chop($courses);
1.772 raeburn 7059: my $ok_response = 0;
7060: my $response;
7061: while (@homeservers > 0 && $ok_response == 0) {
7062: my $server = shift(@homeservers);
7063: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7064: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7065: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7066: split(/:/,$response);
1.772 raeburn 7067: %{$codes} = (%{$codes},&str2hash($codes_str));
7068: push(@{$codetitles},&str2array($codetitles_str));
7069: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7070: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7071: $ok_response = 1;
7072: }
7073: }
7074: if ($ok_response) {
1.521 raeburn 7075: return 'ok';
1.772 raeburn 7076: } else {
7077: return $response;
1.521 raeburn 7078: }
7079: }
7080:
1.792 raeburn 7081: sub auto_instcode_defaults {
7082: my ($domain,$returnhash,$code_order) = @_;
7083: my @homeservers;
1.841 albertel 7084:
7085: my %servers = &get_servers($domain,'library');
7086: foreach my $tryserver (keys(%servers)) {
7087: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7088: push(@homeservers,$tryserver);
7089: }
1.792 raeburn 7090: }
1.841 albertel 7091:
1.792 raeburn 7092: my $response;
1.841 albertel 7093: foreach my $server (@homeservers) {
1.792 raeburn 7094: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7095: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7096:
7097: foreach my $pair (split(/\&/,$response)) {
7098: my ($name,$value)=split(/\=/,$pair);
7099: if ($name eq 'code_order') {
7100: @{$code_order} = split(/\&/,&unescape($value));
7101: } else {
7102: $returnhash->{&unescape($name)}=&unescape($value);
7103: }
7104: }
7105: return 'ok';
1.792 raeburn 7106: }
1.841 albertel 7107:
7108: return $response;
1.1003 raeburn 7109: }
7110:
7111: sub auto_possible_instcodes {
1.1007 raeburn 7112: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7113: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7114: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7115: return;
7116: }
1.1003 raeburn 7117: my (@homeservers,$uhome);
7118: if (defined(&domain($domain,'primary'))) {
7119: $uhome=&domain($domain,'primary');
7120: push(@homeservers,&domain($domain,'primary'));
7121: } else {
7122: my %servers = &get_servers($domain,'library');
7123: foreach my $tryserver (keys(%servers)) {
7124: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7125: push(@homeservers,$tryserver);
7126: }
7127: }
7128: }
7129: my $response;
7130: foreach my $server (@homeservers) {
7131: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7132: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7133: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7134: split(':',$response);
7135: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7136: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7137: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7138: my ($name,$value)=split('=',$item);
7139: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7140: }
7141: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7142: my ($name,$value)=split('=',$item);
7143: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7144: }
7145: return 'ok';
7146: }
7147: return $response;
7148: }
1.792 raeburn 7149:
1.1010 raeburn 7150: sub auto_courserequest_checks {
7151: my ($dom) = @_;
1.1020 raeburn 7152: my ($homeserver,%validations);
7153: if ($dom =~ /^$match_domain$/) {
7154: $homeserver = &domain($dom,'primary');
7155: }
7156: unless ($homeserver eq 'no_host') {
7157: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7158: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7159: my @items = split(/&/,$response);
7160: foreach my $item (@items) {
7161: my ($key,$value) = split('=',$item);
7162: $validations{&unescape($key)} = &thaw_unescape($value);
7163: }
7164: }
7165: }
1.1010 raeburn 7166: return %validations;
7167: }
7168:
1.1020 raeburn 7169: sub auto_courserequest_validation {
7170: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7171: my ($homeserver,$response);
7172: if ($dom =~ /^$match_domain$/) {
7173: $homeserver = &domain($dom,'primary');
7174: }
7175: unless ($homeserver eq 'no_host') {
1.1021 raeburn 7176:
1.1020 raeburn 7177: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7178: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 7179: ':'.&escape($instcode).':'.&escape($instseclist),
7180: $homeserver));
7181: }
7182: return $response;
7183: }
7184:
1.777 albertel 7185: sub auto_validate_class_sec {
1.918 raeburn 7186: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7187: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7188: my $ownerlist;
7189: if (ref($owners) eq 'ARRAY') {
7190: $ownerlist = join(',',@{$owners});
7191: } else {
7192: $ownerlist = $owners;
7193: }
1.773 raeburn 7194: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7195: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7196: return $response;
7197: }
7198:
1.679 raeburn 7199: # ------------------------------------------------------- Course Group routines
7200:
7201: sub get_coursegroups {
1.809 raeburn 7202: my ($cdom,$cnum,$group,$namespace) = @_;
7203: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7204: }
7205:
1.679 raeburn 7206: sub modify_coursegroup {
7207: my ($cdom,$cnum,$groupsettings) = @_;
7208: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7209: }
7210:
1.809 raeburn 7211: sub toggle_coursegroup_status {
7212: my ($cdom,$cnum,$group,$action) = @_;
7213: my ($from_namespace,$to_namespace);
7214: if ($action eq 'delete') {
7215: $from_namespace = 'coursegroups';
7216: $to_namespace = 'deleted_groups';
7217: } else {
7218: $from_namespace = 'deleted_groups';
7219: $to_namespace = 'coursegroups';
7220: }
7221: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7222: if (my $tmp = &error(%curr_group)) {
7223: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7224: return ('read error',$tmp);
7225: } else {
7226: my %savedsettings = %curr_group;
1.809 raeburn 7227: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7228: my $deloutcome;
7229: if ($result eq 'ok') {
1.809 raeburn 7230: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7231: } else {
7232: return ('write error',$result);
7233: }
7234: if ($deloutcome eq 'ok') {
7235: return 'ok';
7236: } else {
7237: return ('delete error',$deloutcome);
7238: }
7239: }
7240: }
7241:
1.679 raeburn 7242: sub modify_group_roles {
1.957 raeburn 7243: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7244: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7245: my $role = 'gr/'.&escape($userprivs);
7246: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7247: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7248: if ($result eq 'ok') {
7249: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7250: }
1.679 raeburn 7251: return $result;
7252: }
7253:
7254: sub modify_coursegroup_membership {
7255: my ($cdom,$cnum,$membership) = @_;
7256: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7257: return $result;
7258: }
7259:
1.682 raeburn 7260: sub get_active_groups {
7261: my ($udom,$uname,$cdom,$cnum) = @_;
7262: my $now = time;
7263: my %groups = ();
7264: foreach my $key (keys(%env)) {
1.811 albertel 7265: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7266: my ($start,$end) = split(/\./,$env{$key});
7267: if (($end!=0) && ($end<$now)) { next; }
7268: if (($start!=0) && ($start>$now)) { next; }
7269: if ($1 eq $cdom && $2 eq $cnum) {
7270: $groups{$3} = $env{$key} ;
7271: }
7272: }
7273: }
7274: return %groups;
7275: }
7276:
1.683 raeburn 7277: sub get_group_membership {
7278: my ($cdom,$cnum,$group) = @_;
7279: return(&dump('groupmembership',$cdom,$cnum,$group));
7280: }
7281:
7282: sub get_users_groups {
7283: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 7284: my @usersgroups;
1.683 raeburn 7285: my $cachetime=1800;
7286:
7287: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 7288: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7289: if (defined($cached)) {
1.734 albertel 7290: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 7291: } else {
7292: $grouplist = '';
1.816 raeburn 7293: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 7294: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 7295: my $access_end = $env{'course.'.$courseid.
7296: '.default_enrollment_end_date'};
7297: my $now = time;
7298: foreach my $key (keys(%roleshash)) {
7299: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7300: my $group = $1;
7301: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7302: my $start = $2;
7303: my $end = $1;
7304: if ($start == -1) { next; } # deleted from group
7305: if (($start!=0) && ($start>$now)) { next; }
7306: if (($end!=0) && ($end<$now)) {
7307: if ($access_end && $access_end < $now) {
7308: if ($access_end - $end < 86400) {
7309: push(@usersgroups,$group);
1.733 raeburn 7310: }
7311: }
1.817 raeburn 7312: next;
1.733 raeburn 7313: }
1.817 raeburn 7314: push(@usersgroups,$group);
1.683 raeburn 7315: }
7316: }
7317: }
1.817 raeburn 7318: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7319: $grouplist = join(':',@usersgroups);
7320: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 7321: }
1.733 raeburn 7322: return @usersgroups;
1.683 raeburn 7323: }
7324:
7325: sub devalidate_getgroups_cache {
7326: my ($udom,$uname,$cdom,$cnum)=@_;
7327: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 7328:
1.683 raeburn 7329: my $hashid="$udom:$uname:$courseid";
7330: &devalidate_cache_new('getgroups',$hashid);
7331: }
7332:
1.12 www 7333: # ------------------------------------------------------------------ Plain Text
7334:
7335: sub plaintext {
1.988 raeburn 7336: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 7337: if ($short =~ m{^cr/}) {
1.758 albertel 7338: return (split('/',$short))[-1];
7339: }
1.742 raeburn 7340: if (!defined($cid)) {
7341: $cid = $env{'request.course.id'};
7342: }
7343: my %rolenames = (
1.1008 raeburn 7344: Course => 'std',
7345: Community => 'alt1',
1.742 raeburn 7346: );
1.1037 raeburn 7347: if ($cid ne '') {
7348: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
7349: unless ($forcedefault) {
7350: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
7351: &Apache::lonlocal::mt_escape(\$roletext);
7352: return &Apache::lonlocal::mt($roletext);
7353: }
7354: }
7355: }
7356: if ((defined($type)) && (defined($rolenames{$type})) &&
7357: (defined($rolenames{$type})) &&
7358: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 7359: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 7360: } elsif ($cid ne '') {
7361: my $crstype = $env{'course.'.$cid.'.type'};
7362: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7363: (defined($prp{$short}{$rolenames{$crstype}}))) {
7364: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7365: }
1.742 raeburn 7366: }
1.1037 raeburn 7367: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 7368: }
7369:
7370: # ----------------------------------------------------------------- Assign Role
7371:
7372: sub assignrole {
1.957 raeburn 7373: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7374: $context)=@_;
1.21 www 7375: my $mrole;
7376: if ($role =~ /^cr\//) {
1.393 www 7377: my $cwosec=$url;
1.811 albertel 7378: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 7379: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 7380: my $refused = 1;
7381: if ($context eq 'requestcourses') {
7382: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7383: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7384: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7385: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7386: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7387: if ($crsenv{'internal.courseowner'} eq
7388: $env{'user.name'}.':'.$env{'user.domain'}) {
7389: $refused = '';
7390: }
7391: }
7392: }
7393: }
7394: }
7395: if ($refused) {
7396: &logthis('Refused custom assignrole: '.
7397: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7398: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7399: return 'refused';
7400: }
1.104 www 7401: }
1.21 www 7402: $mrole='cr';
1.678 raeburn 7403: } elsif ($role =~ /^gr\//) {
7404: my $cwogrp=$url;
1.811 albertel 7405: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 7406: unless (&allowed('mdg',$cwogrp)) {
7407: &logthis('Refused group assignrole: '.
7408: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7409: $env{'user.name'}.' at '.$env{'user.domain'});
7410: return 'refused';
7411: }
7412: $mrole='gr';
1.21 www 7413: } else {
1.82 www 7414: my $cwosec=$url;
1.811 albertel 7415: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 7416: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7417: my $refused;
7418: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7419: if (!(&allowed('c'.$role,$url))) {
7420: $refused = 1;
7421: }
7422: } else {
7423: $refused = 1;
7424: }
1.947 raeburn 7425: if ($refused) {
1.1045 raeburn 7426: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7427: if (!$selfenroll && $context eq 'course') {
7428: my %crsenv;
7429: if ($role eq 'cc' || $role eq 'co') {
7430: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7431: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7432: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7433: if ($crsenv{'internal.courseowner'} eq
7434: $env{'user.name'}.':'.$env{'user.domain'}) {
7435: $refused = '';
7436: }
7437: }
7438: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7439: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7440: if ($crsenv{'internal.courseowner'} eq
7441: $env{'user.name'}.':'.$env{'user.domain'}) {
7442: $refused = '';
7443: }
7444: }
7445: }
7446: }
7447: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 7448: $refused = '';
1.1017 raeburn 7449: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 7450: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 7451: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 7452: my $wrongcc;
7453: if ($cnum =~ /^$match_community$/) {
7454: $wrongcc = 1 if ($role eq 'cc');
7455: } else {
7456: $wrongcc = 1 if ($role eq 'co');
7457: }
7458: unless ($wrongcc) {
7459: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7460: if ($crsenv{'internal.courseowner'} eq
7461: $env{'user.name'}.':'.$env{'user.domain'}) {
7462: $refused = '';
7463: }
1.1017 raeburn 7464: }
7465: }
7466: }
7467: if ($refused) {
1.947 raeburn 7468: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7469: ' '.$role.' '.$end.' '.$start.' by '.
7470: $env{'user.name'}.' at '.$env{'user.domain'});
7471: return 'refused';
7472: }
1.932 raeburn 7473: }
1.1131 raeburn 7474: } elsif ($role eq 'au') {
7475: if ($url ne '/'.$udom.'/') {
7476: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
7477: ' to assign author role for '.$uname.':'.$udom.
7478: ' in domain: '.$url.' refused (wrong domain).');
7479: return 'refused';
7480: }
1.104 www 7481: }
1.21 www 7482: $mrole=$role;
7483: }
1.620 albertel 7484: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7485: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 7486: if ($end) { $command.='_'.$end; }
1.21 www 7487: if ($start) {
7488: if ($end) {
1.81 www 7489: $command.='_'.$start;
1.21 www 7490: } else {
1.81 www 7491: $command.='_0_'.$start;
1.21 www 7492: }
7493: }
1.739 raeburn 7494: my $origstart = $start;
7495: my $origend = $end;
1.957 raeburn 7496: my $delflag;
1.357 www 7497: # actually delete
7498: if ($deleteflag) {
1.373 www 7499: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 7500: # modify command to delete the role
1.620 albertel 7501: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 7502: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 7503: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 7504: # set start and finish to negative values for userrolelog
7505: $start=-1;
7506: $end=-1;
1.957 raeburn 7507: $delflag = 1;
1.357 www 7508: }
7509: }
7510: # send command
1.349 www 7511: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 7512: # log new user role if status is ok
1.349 www 7513: if ($answer eq 'ok') {
1.663 raeburn 7514: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 7515: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 7516: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 7517: unless ($role =~ /^gr/) {
7518: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 7519: $origstart,$selfenroll,$context);
1.739 raeburn 7520: }
1.1053 raeburn 7521: if ($role eq 'cc') {
7522: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7523: }
1.349 www 7524: }
7525: return $answer;
1.169 harris41 7526: }
7527:
1.1053 raeburn 7528: sub autoupdate_coowners {
7529: my ($url,$end,$start,$uname,$udom) = @_;
7530: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7531: if (($cdom ne '') && ($cnum ne '')) {
7532: my $now = time;
7533: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7534: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7535: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7536: my $instcode = $coursehash{'internal.coursecode'};
7537: if ($instcode ne '') {
1.1056 raeburn 7538: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7539: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 7540: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 7541: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7542: if ($result eq 'valid') {
7543: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 7544: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7545: push(@newcoowners,$coowner);
7546: }
7547: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7548: push(@newcoowners,$uname.':'.$udom);
7549: }
7550: @newcoowners = sort(@newcoowners);
7551: } else {
7552: push(@newcoowners,$uname.':'.$udom);
7553: }
7554: } else {
7555: if ($coursehash{'internal.co-owners'}) {
7556: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7557: unless ($coowner eq $uname.':'.$udom) {
7558: push(@newcoowners,$coowner);
7559: }
7560: }
7561: unless (@newcoowners > 0) {
7562: $delcoowners = 1;
7563: $coowners = '';
7564: }
7565: }
7566: }
7567: if (@newcoowners || $delcoowners) {
7568: &store_coowners($cdom,$cnum,$coursehash{'home'},
7569: $delcoowners,@newcoowners);
7570: }
7571: }
7572: }
7573: }
7574: }
7575: }
7576: }
7577:
7578: sub store_coowners {
7579: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7580: my $cid = $cdom.'_'.$cnum;
7581: my ($coowners,$delresult,$putresult);
7582: if (@newcoowners) {
7583: $coowners = join(',',@newcoowners);
7584: my %coownershash = (
7585: 'internal.co-owners' => $coowners,
7586: );
7587: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7588: if ($putresult eq 'ok') {
7589: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7590: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7591: }
7592: }
7593: }
7594: if ($delcoowners) {
7595: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7596: if ($delresult eq 'ok') {
7597: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7598: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7599: }
7600: }
7601: }
7602: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7603: my %crsinfo =
7604: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7605: if (ref($crsinfo{$cid}) eq 'HASH') {
7606: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7607: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7608: }
7609: }
7610: }
7611:
1.169 harris41 7612: # -------------------------------------------------- Modify user authentication
1.197 www 7613: # Overrides without validation
7614:
1.169 harris41 7615: sub modifyuserauth {
7616: my ($udom,$uname,$umode,$upass)=@_;
7617: my $uhome=&homeserver($uname,$udom);
1.197 www 7618: unless (&allowed('mau',$udom)) { return 'refused'; }
7619: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 7620: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7621: ' in domain '.$env{'request.role.domain'});
1.169 harris41 7622: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7623: &escape($upass),$uhome);
1.620 albertel 7624: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 7625: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7626: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7627: &log($udom,,$uname,$uhome,
1.620 albertel 7628: 'Authentication changed by '.$env{'user.domain'}.', '.
7629: $env{'user.name'}.', '.$umode.
1.197 www 7630: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 7631: unless ($reply eq 'ok') {
1.197 www 7632: &logthis('Authentication mode error: '.$reply);
1.169 harris41 7633: return 'error: '.$reply;
7634: }
1.170 harris41 7635: return 'ok';
1.80 www 7636: }
7637:
1.81 www 7638: # --------------------------------------------------------------- Modify a user
1.80 www 7639:
1.81 www 7640: sub modifyuser {
1.206 matthew 7641: my ($udom, $uname, $uid,
7642: $umode, $upass, $first,
7643: $middle, $last, $gene,
1.1058 raeburn 7644: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 7645: $udom= &LONCAPA::clean_domain($udom);
7646: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 7647: my $showcandelete = 'none';
7648: if (ref($candelete) eq 'ARRAY') {
7649: if (@{$candelete} > 0) {
7650: $showcandelete = join(', ',@{$candelete});
7651: }
7652: }
1.81 www 7653: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 7654: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 7655: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 7656: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7657: ' desiredhome not specified').
1.620 albertel 7658: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7659: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 7660: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 7661: my $newuser;
7662: if ($uhome eq 'no_host') {
7663: $newuser = 1;
7664: }
1.80 www 7665: # ----------------------------------------------------------------- Create User
1.406 albertel 7666: if (($uhome eq 'no_host') &&
7667: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 7668: my $unhome='';
1.844 albertel 7669: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 7670: $unhome = $desiredhome;
1.620 albertel 7671: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7672: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 7673: } else { # load balancing routine for determining $unhome
1.81 www 7674: my $loadm=10000000;
1.841 albertel 7675: my %servers = &get_servers($udom,'library');
7676: foreach my $tryserver (keys(%servers)) {
7677: my $answer=reply('load',$tryserver);
7678: if (($answer=~/\d+/) && ($answer<$loadm)) {
7679: $loadm=$answer;
7680: $unhome=$tryserver;
7681: }
1.80 www 7682: }
7683: }
7684: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 7685: return 'error: unable to find a home server for '.$uname.
7686: ' in domain '.$udom;
1.80 www 7687: }
7688: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7689: &escape($upass),$unhome);
7690: unless ($reply eq 'ok') {
7691: return 'error: '.$reply;
7692: }
1.230 stredwic 7693: $uhome=&homeserver($uname,$udom,'true');
1.80 www 7694: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 7695: return 'error: unable verify users home machine.';
1.80 www 7696: }
1.209 matthew 7697: } # End of creation of new user
1.80 www 7698: # ---------------------------------------------------------------------- Add ID
7699: if ($uid) {
7700: $uid=~tr/A-Z/a-z/;
7701: my %uidhash=&idrget($udom,$uname);
1.196 www 7702: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7703: && (!$forceid)) {
1.80 www 7704: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 7705: return 'error: user id "'.$uid.'" does not match '.
7706: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 7707: }
7708: } else {
7709: &idput($udom,($uname => $uid));
7710: }
7711: }
7712: # -------------------------------------------------------------- Add names, etc
1.313 matthew 7713: my @tmp=&get('environment',
1.899 raeburn 7714: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 7715: 'permanentemail','inststatus'],
1.134 albertel 7716: $udom,$uname);
1.1075 raeburn 7717: my (%names,%oldnames);
1.313 matthew 7718: if ($tmp[0] =~ m/^error:.*/) {
7719: %names=();
7720: } else {
7721: %names = @tmp;
1.1075 raeburn 7722: %oldnames = %names;
1.313 matthew 7723: }
1.388 www 7724: #
1.1058 raeburn 7725: # If name, email and/or uid are blank (e.g., because an uploaded file
7726: # of users did not contain them), do not overwrite existing values
7727: # unless field is in $candelete array ref.
7728: #
7729:
7730: my @fields = ('firstname','middlename','lastname','generation',
7731: 'permanentemail','id');
7732: my %newvalues;
7733: if (ref($candelete) eq 'ARRAY') {
7734: foreach my $field (@fields) {
7735: if (grep(/^\Q$field\E$/,@{$candelete})) {
7736: if ($field eq 'firstname') {
7737: $names{$field} = $first;
7738: } elsif ($field eq 'middlename') {
7739: $names{$field} = $middle;
7740: } elsif ($field eq 'lastname') {
7741: $names{$field} = $last;
7742: } elsif ($field eq 'generation') {
7743: $names{$field} = $gene;
7744: } elsif ($field eq 'permanentemail') {
7745: $names{$field} = $email;
7746: } elsif ($field eq 'id') {
7747: $names{$field} = $uid;
7748: }
7749: }
7750: }
7751: }
1.388 www 7752: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 7753: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 7754: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 7755: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 7756: if ($email) {
7757: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 7758: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 7759: }
1.899 raeburn 7760: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 7761: if (defined($inststatus)) {
7762: $names{'inststatus'} = '';
7763: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7764: if (ref($usertypes) eq 'HASH') {
7765: my @okstatuses;
7766: foreach my $item (split(/:/,$inststatus)) {
7767: if (defined($usertypes->{$item})) {
7768: push(@okstatuses,$item);
7769: }
7770: }
7771: if (@okstatuses) {
7772: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7773: }
7774: }
7775: }
1.1075 raeburn 7776: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 7777: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 7778: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 7779: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7780: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7781: } else {
7782: $logmsg .= ' during self creation';
7783: }
1.1075 raeburn 7784: my $changed;
7785: if ($newuser) {
7786: $changed = 1;
7787: } else {
7788: foreach my $field (@fields) {
7789: if ($names{$field} ne $oldnames{$field}) {
7790: $changed = 1;
7791: last;
7792: }
7793: }
7794: }
7795: unless ($changed) {
7796: $logmsg = 'No changes in user information needed for: '.$logmsg;
7797: &logthis($logmsg);
7798: return 'ok';
7799: }
7800: my $reply = &put('environment', \%names, $udom,$uname);
7801: if ($reply ne 'ok') {
7802: return 'error: '.$reply;
7803: }
1.1087 raeburn 7804: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7805: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7806: }
1.1075 raeburn 7807: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7808: &devalidate_cache_new('namescache',$uname.':'.$udom);
7809: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7810: &logthis($logmsg);
1.134 albertel 7811: return 'ok';
1.80 www 7812: }
7813:
1.81 www 7814: # -------------------------------------------------------------- Modify student
1.80 www 7815:
1.81 www 7816: sub modifystudent {
7817: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7818: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7819: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7820: if (!$cid) {
1.620 albertel 7821: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7822: return 'not_in_class';
7823: }
1.80 www 7824: }
7825: # --------------------------------------------------------------- Make the user
1.81 www 7826: my $reply=&modifyuser
1.209 matthew 7827: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7828: $desiredhome,$email,$inststatus);
1.80 www 7829: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7830: # This will cause &modify_student_enrollment to get the uid from the
7831: # students environment
7832: $uid = undef if (!$forceid);
1.455 albertel 7833: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7834: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7835: return $reply;
7836: }
7837:
7838: sub modify_student_enrollment {
1.957 raeburn 7839: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7840: my ($cdom,$cnum,$chome);
7841: if (!$cid) {
1.620 albertel 7842: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7843: return 'not_in_class';
7844: }
1.620 albertel 7845: $cdom=$env{'course.'.$cid.'.domain'};
7846: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7847: } else {
7848: ($cdom,$cnum)=split(/_/,$cid);
7849: }
1.620 albertel 7850: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7851: if (!$chome) {
1.457 raeburn 7852: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7853: }
1.455 albertel 7854: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7855: # Make sure the user exists
1.81 www 7856: my $uhome=&homeserver($uname,$udom);
7857: if (($uhome eq '') || ($uhome eq 'no_host')) {
7858: return 'error: no such user';
7859: }
1.297 matthew 7860: # Get student data if we were not given enough information
7861: if (!defined($first) || $first eq '' ||
7862: !defined($last) || $last eq '' ||
7863: !defined($uid) || $uid eq '' ||
7864: !defined($middle) || $middle eq '' ||
7865: !defined($gene) || $gene eq '') {
1.294 matthew 7866: # They did not supply us with enough data to enroll the student, so
7867: # we need to pick up more information.
1.297 matthew 7868: my %tmp = &get('environment',
1.294 matthew 7869: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7870: ,$udom,$uname);
7871:
1.800 albertel 7872: #foreach my $key (keys(%tmp)) {
7873: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7874: #}
1.294 matthew 7875: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7876: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7877: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7878: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7879: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7880: }
1.556 albertel 7881: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 7882: my $user = "$uname:$udom";
7883: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 7884: my $reply=cput('classlist',
1.1148 raeburn 7885: {$user =>
1.515 raeburn 7886: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7887: $cdom,$cnum);
1.1148 raeburn 7888: if (($reply eq 'ok') || ($reply eq 'delayed')) {
7889: &devalidate_getsection_cache($udom,$uname,$cid);
7890: } else {
1.81 www 7891: return 'error: '.$reply;
7892: }
1.297 matthew 7893: # Add student role to user
1.83 www 7894: my $uurl='/'.$cid;
1.81 www 7895: $uurl=~s/\_/\//g;
7896: if ($usec) {
7897: $uurl.='/'.$usec;
7898: }
1.1148 raeburn 7899: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
7900: $selfenroll,$context);
7901: if ($result ne 'ok') {
7902: if ($old_entry{$user} ne '') {
7903: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
7904: } else {
7905: $reply = &del('classlist',[$user],$cdom,$cnum);
7906: }
7907: }
7908: return $result;
1.21 www 7909: }
7910:
1.556 albertel 7911: sub format_name {
7912: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7913: my $name;
7914: if ($first ne 'lastname') {
7915: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7916: } else {
7917: if ($lastname=~/\S/) {
7918: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7919: $name=~s/\s+,/,/;
7920: } else {
7921: $name.= $firstname.' '.$middlename.' '.$generation;
7922: }
7923: }
7924: $name=~s/^\s+//;
7925: $name=~s/\s+$//;
7926: $name=~s/\s+/ /g;
7927: return $name;
7928: }
7929:
1.84 www 7930: # ------------------------------------------------- Write to course preferences
7931:
7932: sub writecoursepref {
7933: my ($courseid,%prefs)=@_;
7934: $courseid=~s/^\///;
7935: $courseid=~s/\_/\//g;
7936: my ($cdomain,$cnum)=split(/\//,$courseid);
7937: my $chome=homeserver($cnum,$cdomain);
7938: if (($chome eq '') || ($chome eq 'no_host')) {
7939: return 'error: no such course';
7940: }
7941: my $cstring='';
1.800 albertel 7942: foreach my $pref (keys(%prefs)) {
7943: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7944: }
1.84 www 7945: $cstring=~s/\&$//;
7946: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7947: }
7948:
7949: # ---------------------------------------------------------- Make/modify course
7950:
7951: sub createcourse {
1.741 raeburn 7952: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7953: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7954: $url=&declutter($url);
7955: my $cid='';
1.1028 raeburn 7956: if ($context eq 'requestcourses') {
7957: my $can_create = 0;
7958: my ($ownername,$ownerdom) = split(':',$course_owner);
7959: if ($udom eq $ownerdom) {
7960: if (&usertools_access($ownername,$ownerdom,$category,undef,
7961: $context)) {
7962: $can_create = 1;
7963: }
7964: } else {
7965: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7966: $category);
7967: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7968: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7969: if (@curr > 0) {
7970: my @options = qw(approval validate autolimit);
7971: my $optregex = join('|',@options);
7972: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7973: $can_create = 1;
7974: }
7975: }
7976: }
7977: }
7978: if ($can_create) {
7979: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7980: unless (&allowed('ccc',$udom)) {
7981: return 'refused';
7982: }
1.1017 raeburn 7983: }
7984: } else {
7985: return 'refused';
7986: }
1.1028 raeburn 7987: } elsif (!&allowed('ccc',$udom)) {
7988: return 'refused';
1.84 www 7989: }
1.1011 raeburn 7990: # --------------------------------------------------------------- Get Unique ID
7991: my $uname;
7992: if ($cnum =~ /^$match_courseid$/) {
7993: my $chome=&homeserver($cnum,$udom,'true');
7994: if (($chome eq '') || ($chome eq 'no_host')) {
7995: $uname = $cnum;
7996: } else {
1.1038 raeburn 7997: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7998: }
7999: } else {
1.1038 raeburn 8000: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8001: }
8002: return $uname if ($uname =~ /^error/);
8003: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8004: if (!defined($course_server)) {
8005: if (defined(&domain($udom,'primary'))) {
8006: $course_server = &domain($udom,'primary');
8007: } else {
8008: $course_server = $env{'user.home'};
8009: }
8010: }
8011: my %host_servers =
8012: &Apache::lonnet::get_servers($udom,'library');
8013: unless ($host_servers{$course_server}) {
8014: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8015: }
1.84 www 8016: # ------------------------------------------------------------- Make the course
8017: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8018: $course_server);
1.84 www 8019: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8020: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8021: if (($uhome eq '') || ($uhome eq 'no_host')) {
8022: return 'error: no such course';
8023: }
1.271 www 8024: # ----------------------------------------------------------------- Course made
1.516 raeburn 8025: # log existence
1.1029 raeburn 8026: my $now = time;
1.918 raeburn 8027: my $newcourse = {
8028: $udom.'_'.$uname => {
1.921 raeburn 8029: description => $description,
8030: inst_code => $inst_code,
8031: owner => $course_owner,
8032: type => $crstype,
1.1029 raeburn 8033: creator => $env{'user.name'}.':'.
8034: $env{'user.domain'},
8035: created => $now,
8036: context => $context,
1.918 raeburn 8037: },
8038: };
1.921 raeburn 8039: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8040: # set toplevel url
1.271 www 8041: my $topurl=$url;
8042: unless ($nonstandard) {
8043: # ------------------------------------------ For standard courses, make top url
8044: my $mapurl=&clutter($url);
1.278 www 8045: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8046: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8047: <map>
8048: <resource id="1" type="start"></resource>
8049: <resource id="2" src="$mapurl"></resource>
8050: <resource id="3" type="finish"></resource>
8051: <link index="1" from="1" to="2"></link>
8052: <link index="2" from="2" to="3"></link>
8053: </map>
8054: ENDINITMAP
8055: $topurl=&declutter(
1.638 albertel 8056: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8057: );
8058: }
8059: # ----------------------------------------------------------- Write preferences
1.84 www 8060: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8061: ('description' => $description,
8062: 'url' => $topurl,
8063: 'internal.creator' => $env{'user.name'}.':'.
8064: $env{'user.domain'},
8065: 'internal.created' => $now,
8066: 'internal.creationcontext' => $context)
8067: );
1.84 www 8068: return '/'.$udom.'/'.$uname;
8069: }
8070:
1.1011 raeburn 8071: # ------------------------------------------------------------------- Create ID
8072: sub generate_coursenum {
1.1038 raeburn 8073: my ($udom,$crstype) = @_;
1.1011 raeburn 8074: my $domdesc = &domain($udom);
8075: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8076: my $first;
8077: if ($crstype eq 'Community') {
8078: $first = '0';
8079: } else {
8080: $first = int(1+rand(9));
8081: }
8082: my $uname=$first.
1.1011 raeburn 8083: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8084: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8085: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8086: # ----------------------------------------------- Make sure that does not exist
8087: my $uhome=&homeserver($uname,$udom,'true');
8088: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8089: if ($crstype eq 'Community') {
8090: $first = '0';
8091: } else {
8092: $first = int(1+rand(9));
8093: }
8094: $uname=$first.
1.1011 raeburn 8095: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8096: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8097: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8098: $uhome=&homeserver($uname,$udom,'true');
8099: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8100: return 'error: unable to generate unique course-ID';
8101: }
8102: }
8103: return $uname;
8104: }
8105:
1.813 albertel 8106: sub is_course {
1.1167 droeschl 8107: my ($cdom, $cnum) = scalar(@_) == 1 ?
8108: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8109:
8110: return unless $cdom and $cnum;
8111:
8112: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8113: '.');
8114:
8115: return unless exists($courses{$cdom.'_'.$cnum});
8116: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8117: }
8118:
1.1015 raeburn 8119: sub store_userdata {
8120: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8121: my $result;
1.1016 raeburn 8122: if ($datakey ne '') {
1.1013 raeburn 8123: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8124: if ($udom eq '' || $uname eq '') {
8125: $udom = $env{'user.domain'};
8126: $uname = $env{'user.name'};
8127: }
8128: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8129: if (($uhome eq '') || ($uhome eq 'no_host')) {
8130: $result = 'error: no_host';
8131: } else {
8132: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8133: $storehash->{'host'} = $perlvar{'lonHostID'};
8134:
8135: my $namevalue='';
8136: foreach my $key (keys(%{$storehash})) {
8137: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8138: }
8139: $namevalue=~s/\&$//;
1.1105 raeburn 8140: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8141: $namevalue,$uhome);
1.1013 raeburn 8142: }
8143: } else {
8144: $result = 'error: data to store was not a hash reference';
8145: }
8146: } else {
8147: $result= 'error: invalid requestkey';
8148: }
8149: return $result;
8150: }
8151:
1.21 www 8152: # ---------------------------------------------------------- Assign Custom Role
8153:
8154: sub assigncustomrole {
1.957 raeburn 8155: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8156: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8157: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8158: }
8159:
8160: # ----------------------------------------------------------------- Revoke Role
8161:
8162: sub revokerole {
1.957 raeburn 8163: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8164: my $now=time;
1.965 raeburn 8165: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8166: }
8167:
8168: # ---------------------------------------------------------- Revoke Custom Role
8169:
8170: sub revokecustomrole {
1.957 raeburn 8171: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8172: my $now=time;
1.357 www 8173: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8174: $deleteflag,$selfenroll,$context);
1.17 www 8175: }
8176:
1.533 banghart 8177: # ------------------------------------------------------------ Disk usage
1.535 albertel 8178: sub diskusage {
1.955 raeburn 8179: my ($udom,$uname,$directorypath,$getpropath)=@_;
8180: $directorypath =~ s/\/$//;
8181: my $listing=&reply('du2:'.&escape($directorypath).':'
8182: .&escape($getpropath).':'.&escape($uname).':'
8183: .&escape($udom),homeserver($uname,$udom));
8184: if ($listing eq 'unknown_cmd') {
8185: if ($getpropath) {
8186: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8187: }
8188: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8189: }
1.514 albertel 8190: return $listing;
1.512 banghart 8191: }
8192:
1.566 banghart 8193: sub is_locked {
1.1096 raeburn 8194: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8195: my @check;
8196: my $is_locked;
1.1093 raeburn 8197: push (@check,$file_name);
1.613 albertel 8198: my %locked = &get('file_permissions',\@check,
1.620 albertel 8199: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8200: my ($tmp)=keys(%locked);
8201: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8202:
1.566 banghart 8203: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8204: $is_locked = 'false';
8205: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8206: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8207: $is_locked = 'true';
1.1096 raeburn 8208: if (ref($which) eq 'ARRAY') {
8209: push(@{$which},$entry);
8210: } else {
8211: last;
8212: }
1.745 raeburn 8213: }
8214: }
1.566 banghart 8215: } else {
8216: $is_locked = 'false';
8217: }
1.1093 raeburn 8218: return $is_locked;
1.566 banghart 8219: }
8220:
1.759 albertel 8221: sub declutter_portfile {
8222: my ($file) = @_;
1.833 albertel 8223: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 8224: return $file;
8225: }
8226:
1.559 banghart 8227: # ------------------------------------------------------------- Mark as Read Only
8228:
8229: sub mark_as_readonly {
8230: my ($domain,$user,$files,$what) = @_;
1.613 albertel 8231: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8232: my ($tmp)=keys(%current_permissions);
8233: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 8234: foreach my $file (@{$files}) {
1.759 albertel 8235: $file = &declutter_portfile($file);
1.561 banghart 8236: push(@{$current_permissions{$file}},$what);
1.559 banghart 8237: }
1.613 albertel 8238: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8239: return;
8240: }
8241:
1.572 banghart 8242: # ------------------------------------------------------------Save Selected Files
8243:
8244: sub save_selected_files {
8245: my ($user, $path, @files) = @_;
8246: my $filename = $user."savedfiles";
1.573 banghart 8247: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 8248: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 8249: foreach my $file (@files) {
1.620 albertel 8250: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 8251: }
8252: foreach my $file (@other_files) {
1.574 banghart 8253: print (OUT $file."\n");
1.572 banghart 8254: }
1.574 banghart 8255: close (OUT);
1.572 banghart 8256: return 'ok';
8257: }
8258:
1.574 banghart 8259: sub clear_selected_files {
8260: my ($user) = @_;
8261: my $filename = $user."savedfiles";
1.1117 foxr 8262: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 8263: print (OUT undef);
8264: close (OUT);
8265: return ("ok");
8266: }
8267:
1.572 banghart 8268: sub files_in_path {
8269: my ($user, $path) = @_;
8270: my $filename = $user."savedfiles";
8271: my %return_files;
1.1117 foxr 8272: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 8273: while (my $line_in = <IN>) {
1.574 banghart 8274: chomp ($line_in);
8275: my @paths_and_file = split (m!/!, $line_in);
8276: my $file_part = pop (@paths_and_file);
8277: my $path_part = join ('/', @paths_and_file);
1.573 banghart 8278: $path_part.='/';
8279: my $path_and_file = $path_part.$file_part;
8280: if ($path_part eq $path) {
8281: $return_files{$file_part}= 'selected';
8282: }
8283: }
1.574 banghart 8284: close (IN);
8285: return (\%return_files);
1.572 banghart 8286: }
8287:
8288: # called in portfolio select mode, to show files selected NOT in current directory
8289: sub files_not_in_path {
8290: my ($user, $path) = @_;
8291: my $filename = $user."savedfiles";
8292: my @return_files;
8293: my $path_part;
1.1117 foxr 8294: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 8295: while (my $line = <IN>) {
1.572 banghart 8296: #ok, I know it's clunky, but I want it to work
1.800 albertel 8297: my @paths_and_file = split(m|/|, $line);
8298: my $file_part = pop(@paths_and_file);
8299: chomp($file_part);
8300: my $path_part = join('/', @paths_and_file);
1.572 banghart 8301: $path_part .= '/';
8302: my $path_and_file = $path_part.$file_part;
8303: if ($path_part ne $path) {
1.800 albertel 8304: push(@return_files, ($path_and_file));
1.572 banghart 8305: }
8306: }
1.800 albertel 8307: close(OUT);
1.574 banghart 8308: return (@return_files);
1.572 banghart 8309: }
8310:
1.745 raeburn 8311: #----------------------------------------------Get portfolio file permissions
1.629 banghart 8312:
1.745 raeburn 8313: sub get_portfile_permissions {
8314: my ($domain,$user) = @_;
1.613 albertel 8315: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8316: my ($tmp)=keys(%current_permissions);
8317: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8318: return \%current_permissions;
8319: }
8320:
8321: #---------------------------------------------Get portfolio file access controls
8322:
1.749 raeburn 8323: sub get_access_controls {
1.745 raeburn 8324: my ($current_permissions,$group,$file) = @_;
1.769 albertel 8325: my %access;
8326: my $real_file = $file;
8327: $file =~ s/\.meta$//;
1.745 raeburn 8328: if (defined($file)) {
1.749 raeburn 8329: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
8330: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 8331: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 8332: }
8333: }
1.745 raeburn 8334: } else {
1.749 raeburn 8335: foreach my $key (keys(%{$current_permissions})) {
8336: if ($key =~ /\0accesscontrol$/) {
8337: if (defined($group)) {
8338: if ($key !~ m-^\Q$group\E/-) {
8339: next;
8340: }
8341: }
8342: my ($fullpath) = split(/\0/,$key);
8343: if (ref($$current_permissions{$key}) eq 'HASH') {
8344: foreach my $control (keys(%{$$current_permissions{$key}})) {
8345: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
8346: }
8347: }
8348: }
8349: }
8350: }
8351: return %access;
8352: }
8353:
8354: sub modify_access_controls {
8355: my ($file_name,$changes,$domain,$user)=@_;
8356: my ($outcome,$deloutcome);
8357: my %store_permissions;
8358: my %new_values;
8359: my %new_control;
8360: my %translation;
8361: my @deletions = ();
8362: my $now = time;
8363: if (exists($$changes{'activate'})) {
8364: if (ref($$changes{'activate'}) eq 'HASH') {
8365: my @newitems = sort(keys(%{$$changes{'activate'}}));
8366: my $numnew = scalar(@newitems);
8367: for (my $i=0; $i<$numnew; $i++) {
8368: my $newkey = $newitems[$i];
8369: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 8370: if ($newkey =~ /^\d+:/) {
8371: $newkey =~ s/^(\d+)/$newid/;
8372: $translation{$1} = $newid;
8373: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
8374: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
8375: $translation{$1} = $newid;
8376: }
1.749 raeburn 8377: $new_values{$file_name."\0".$newkey} =
8378: $$changes{'activate'}{$newitems[$i]};
8379: $new_control{$newkey} = $now;
8380: }
8381: }
8382: }
8383: my %todelete;
8384: my %changed_items;
8385: foreach my $action ('delete','update') {
8386: if (exists($$changes{$action})) {
8387: if (ref($$changes{$action}) eq 'HASH') {
8388: foreach my $key (keys(%{$$changes{$action}})) {
8389: my ($itemnum) = ($key =~ /^([^:]+):/);
8390: if ($action eq 'delete') {
8391: $todelete{$itemnum} = 1;
8392: } else {
8393: $changed_items{$itemnum} = $key;
8394: }
8395: }
1.745 raeburn 8396: }
8397: }
1.749 raeburn 8398: }
8399: # get lock on access controls for file.
8400: my $lockhash = {
8401: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8402: ':'.$env{'user.domain'},
8403: };
8404: my $tries = 0;
8405: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8406:
8407: while (($gotlock ne 'ok') && $tries <3) {
8408: $tries ++;
8409: sleep 1;
8410: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8411: }
8412: if ($gotlock eq 'ok') {
8413: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8414: my ($tmp)=keys(%curr_permissions);
8415: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8416: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8417: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8418: if (ref($curr_controls) eq 'HASH') {
8419: foreach my $control_item (keys(%{$curr_controls})) {
8420: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8421: if (defined($todelete{$itemnum})) {
8422: push(@deletions,$file_name."\0".$control_item);
8423: } else {
8424: if (defined($changed_items{$itemnum})) {
8425: $new_control{$changed_items{$itemnum}} = $now;
8426: push(@deletions,$file_name."\0".$control_item);
8427: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8428: } else {
8429: $new_control{$control_item} = $$curr_controls{$control_item};
8430: }
8431: }
1.745 raeburn 8432: }
8433: }
8434: }
1.970 raeburn 8435: my ($group);
8436: if (&is_course($domain,$user)) {
8437: ($group,my $file) = split(/\//,$file_name,2);
8438: }
1.749 raeburn 8439: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8440: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8441: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8442: # remove lock
8443: my @del_lock = ($file_name."\0".'locked_access_records');
8444: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 8445: my $sqlresult =
1.970 raeburn 8446: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 8447: $group);
1.749 raeburn 8448: } else {
8449: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 8450: }
1.749 raeburn 8451: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 8452: }
8453:
1.827 raeburn 8454: sub make_public_indefinitely {
8455: my ($requrl) = @_;
8456: my $now = time;
8457: my $action = 'activate';
8458: my $aclnum = 0;
8459: if (&is_portfolio_url($requrl)) {
8460: my (undef,$udom,$unum,$file_name,$group) =
8461: &parse_portfolio_url($requrl);
8462: my $current_perms = &get_portfile_permissions($udom,$unum);
8463: my %access_controls = &get_access_controls($current_perms,
8464: $group,$file_name);
8465: foreach my $key (keys(%{$access_controls{$file_name}})) {
8466: my ($num,$scope,$end,$start) =
8467: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8468: if ($scope eq 'public') {
8469: if ($start <= $now && $end == 0) {
8470: $action = 'none';
8471: } else {
8472: $action = 'update';
8473: $aclnum = $num;
8474: }
8475: last;
8476: }
8477: }
8478: if ($action eq 'none') {
8479: return 'ok';
8480: } else {
8481: my %changes;
8482: my $newend = 0;
8483: my $newstart = $now;
8484: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8485: $changes{$action}{$newkey} = {
8486: type => 'public',
8487: time => {
8488: start => $newstart,
8489: end => $newend,
8490: },
8491: };
8492: my ($outcome,$deloutcome,$new_values,$translation) =
8493: &modify_access_controls($file_name,\%changes,$udom,$unum);
8494: return $outcome;
8495: }
8496: } else {
8497: return 'invalid';
8498: }
8499: }
8500:
1.745 raeburn 8501: #------------------------------------------------------Get Marked as Read Only
8502:
8503: sub get_marked_as_readonly {
8504: my ($domain,$user,$what,$group) = @_;
8505: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 8506: my @readonly_files;
1.629 banghart 8507: my $cmp1=$what;
8508: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 8509: while (my ($file_name,$value) = each(%{$current_permissions})) {
8510: if (defined($group)) {
8511: if ($file_name !~ m-^\Q$group\E/-) {
8512: next;
8513: }
8514: }
1.561 banghart 8515: if (ref($value) eq "ARRAY"){
8516: foreach my $stored_what (@{$value}) {
1.629 banghart 8517: my $cmp2=$stored_what;
1.759 albertel 8518: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 8519: $cmp2=join('',@{$stored_what});
1.745 raeburn 8520: }
1.629 banghart 8521: if ($cmp1 eq $cmp2) {
1.561 banghart 8522: push(@readonly_files, $file_name);
1.745 raeburn 8523: last;
1.563 banghart 8524: } elsif (!defined($what)) {
8525: push(@readonly_files, $file_name);
1.745 raeburn 8526: last;
1.561 banghart 8527: }
8528: }
1.745 raeburn 8529: }
1.561 banghart 8530: }
8531: return @readonly_files;
8532: }
1.577 banghart 8533: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 8534:
1.577 banghart 8535: sub get_marked_as_readonly_hash {
1.745 raeburn 8536: my ($current_permissions,$group,$what) = @_;
1.577 banghart 8537: my %readonly_files;
1.745 raeburn 8538: while (my ($file_name,$value) = each(%{$current_permissions})) {
8539: if (defined($group)) {
8540: if ($file_name !~ m-^\Q$group\E/-) {
8541: next;
8542: }
8543: }
1.577 banghart 8544: if (ref($value) eq "ARRAY"){
8545: foreach my $stored_what (@{$value}) {
1.745 raeburn 8546: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 8547: foreach my $lock_descriptor(@{$stored_what}) {
8548: if ($lock_descriptor eq 'graded') {
8549: $readonly_files{$file_name} = 'graded';
8550: } elsif ($lock_descriptor eq 'handback') {
8551: $readonly_files{$file_name} = 'handback';
8552: } else {
8553: if (!exists($readonly_files{$file_name})) {
8554: $readonly_files{$file_name} = 'locked';
8555: }
8556: }
1.745 raeburn 8557: }
1.750 banghart 8558: }
1.577 banghart 8559: }
8560: }
8561: }
8562: return %readonly_files;
8563: }
1.559 banghart 8564: # ------------------------------------------------------------ Unmark as Read Only
8565:
8566: sub unmark_as_readonly {
1.629 banghart 8567: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8568: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 8569: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 8570: $file_name = &declutter_portfile($file_name);
1.634 albertel 8571: my $symb_crs = $what;
8572: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 8573: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 8574: my ($tmp)=keys(%current_permissions);
8575: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8576: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 8577: foreach my $file (@readonly_files) {
1.759 albertel 8578: my $clean_file = &declutter_portfile($file);
8579: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 8580: my $current_locks = $current_permissions{$file};
1.563 banghart 8581: my @new_locks;
8582: my @del_keys;
8583: if (ref($current_locks) eq "ARRAY"){
8584: foreach my $locker (@{$current_locks}) {
1.632 albertel 8585: my $compare=$locker;
1.749 raeburn 8586: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 8587: $compare=join('',@{$locker});
1.746 raeburn 8588: if ($compare ne $symb_crs) {
8589: push(@new_locks, $locker);
8590: }
1.563 banghart 8591: }
8592: }
1.650 albertel 8593: if (scalar(@new_locks) > 0) {
1.563 banghart 8594: $current_permissions{$file} = \@new_locks;
8595: } else {
8596: push(@del_keys, $file);
1.613 albertel 8597: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 8598: delete($current_permissions{$file});
1.563 banghart 8599: }
8600: }
1.561 banghart 8601: }
1.613 albertel 8602: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8603: return;
8604: }
1.512 banghart 8605:
1.17 www 8606: # ------------------------------------------------------------ Directory lister
8607:
8608: sub dirlist {
1.955 raeburn 8609: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 8610: $uri=~s/^\///;
8611: $uri=~s/\/$//;
1.253 stredwic 8612: my ($udom, $uname);
1.955 raeburn 8613: if ($getuserdir) {
1.253 stredwic 8614: $udom = $userdomain;
8615: $uname = $username;
1.955 raeburn 8616: } else {
8617: (undef,$udom,$uname)=split(/\//,$uri);
8618: if(defined($userdomain)) {
8619: $udom = $userdomain;
8620: }
8621: if(defined($username)) {
8622: $uname = $username;
8623: }
1.253 stredwic 8624: }
1.955 raeburn 8625: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 8626:
1.955 raeburn 8627: $dirRoot = $perlvar{'lonDocRoot'};
8628: if (defined($getpropath)) {
8629: $dirRoot = &propath($udom,$uname);
1.253 stredwic 8630: $dirRoot =~ s/\/$//;
1.955 raeburn 8631: } elsif (defined($getuserdir)) {
8632: my $subdir=$uname.'__';
8633: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8634: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8635: ."/$udom/$subdir/$uname";
8636: } elsif (defined($alternateRoot)) {
8637: $dirRoot = $alternateRoot;
1.751 banghart 8638: }
1.253 stredwic 8639:
8640: if($udom) {
8641: if($uname) {
1.1135 raeburn 8642: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 8643: if ($uhome eq 'no_host') {
8644: return ([],'no_host');
8645: }
1.955 raeburn 8646: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 8647: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 8648: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 8649: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8650: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 8651: } else {
8652: @listing_results = map { &unescape($_); } split(/:/,$listing);
8653: }
1.605 matthew 8654: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8655: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 8656: @listing_results = split(/:/,$listing);
8657: } else {
8658: @listing_results = map { &unescape($_); } split(/:/,$listing);
8659: }
1.1135 raeburn 8660: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 8661: ($listing eq 'rejected') || ($listing eq 'refused') ||
8662: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8663: return ([],$listing);
8664: } else {
8665: return (\@listing_results);
1.1135 raeburn 8666: }
1.955 raeburn 8667: } elsif(!$alternateRoot) {
1.1136 raeburn 8668: my (%allusers,%listerror);
1.841 albertel 8669: my %servers = &get_servers($udom,'library');
1.955 raeburn 8670: foreach my $tryserver (keys(%servers)) {
8671: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8672: &escape($udom),$tryserver);
8673: if ($listing eq 'unknown_cmd') {
8674: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8675: $udom, $tryserver);
8676: } else {
8677: @listing_results = map { &unescape($_); } split(/:/,$listing);
8678: }
1.841 albertel 8679: if ($listing eq 'unknown_cmd') {
8680: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8681: $udom, $tryserver);
8682: @listing_results = split(/:/,$listing);
8683: } else {
8684: @listing_results =
8685: map { &unescape($_); } split(/:/,$listing);
8686: }
1.1136 raeburn 8687: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8688: ($listing eq 'rejected') || ($listing eq 'refused') ||
8689: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8690: $listerror{$tryserver} = $listing;
8691: } else {
1.841 albertel 8692: foreach my $line (@listing_results) {
8693: my ($entry) = split(/&/,$line,2);
8694: $allusers{$entry} = 1;
8695: }
8696: }
1.253 stredwic 8697: }
1.1136 raeburn 8698: my @alluserslist=();
1.800 albertel 8699: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 8700: push(@alluserslist,$user.'&user');
1.253 stredwic 8701: }
1.1136 raeburn 8702: return (\@alluserslist);
1.253 stredwic 8703: } else {
1.1136 raeburn 8704: return ([],'missing username');
1.253 stredwic 8705: }
1.955 raeburn 8706: } elsif(!defined($getpropath)) {
1.1136 raeburn 8707: my $path = $perlvar{'lonDocRoot'}.'/res/';
8708: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
8709: return (\@all_domains);
1.955 raeburn 8710: } else {
1.1136 raeburn 8711: return ([],'missing domain');
1.275 stredwic 8712: }
8713: }
8714:
8715: # --------------------------------------------- GetFileTimestamp
8716: # This function utilizes dirlist and returns the date stamp for
8717: # when it was last modified. It will also return an error of -1
8718: # if an error occurs
8719:
8720: sub GetFileTimestamp {
1.955 raeburn 8721: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 8722: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8723: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 8724: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
8725: undef,$getuserdir);
8726: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8727: return -1;
8728: }
8729: if (ref($fileref) eq 'ARRAY') {
8730: my @stats = split('&',$fileref->[0]);
1.375 matthew 8731: # @stats contains first the filename, then the stat output
8732: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 8733: } else {
8734: return -1;
1.253 stredwic 8735: }
1.26 www 8736: }
8737:
1.712 albertel 8738: sub stat_file {
8739: my ($uri) = @_;
1.787 albertel 8740: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 8741:
1.955 raeburn 8742: my ($udom,$uname,$file);
1.712 albertel 8743: if ($uri =~ m-^/(uploaded|editupload)/-) {
8744: ($udom,$uname,$file) =
1.811 albertel 8745: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 8746: $file = 'userfiles/'.$file;
8747: }
8748: if ($uri =~ m-^/res/-) {
8749: ($udom,$uname) =
1.807 albertel 8750: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 8751: $file = $uri;
8752: }
8753:
8754: if (!$udom || !$uname || !$file) {
8755: # unable to handle the uri
8756: return ();
8757: }
1.956 raeburn 8758: my $getpropath;
8759: if ($file =~ /^userfiles\//) {
8760: $getpropath = 1;
8761: }
1.1136 raeburn 8762: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
8763: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8764: return ();
8765: } else {
8766: if (ref($listref) eq 'ARRAY') {
8767: my @stats = split('&',$listref->[0]);
8768: shift(@stats); #filename is first
8769: return @stats;
8770: }
1.712 albertel 8771: }
8772: return ();
8773: }
8774:
1.26 www 8775: # -------------------------------------------------------- Value of a Condition
8776:
1.713 albertel 8777: # gets the value of a specific preevaluated condition
8778: # stored in the string $env{user.state.<cid>}
8779: # or looks up a condition reference in the bighash and if if hasn't
8780: # already been evaluated recurses into docondval to get the value of
8781: # the condition, then memoizing it to
8782: # $env{user.state.<cid>.<condition>}
1.40 www 8783: sub directcondval {
8784: my $number=shift;
1.620 albertel 8785: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 8786: &Apache::lonuserstate::evalstate();
8787: }
1.713 albertel 8788: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8789: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8790: } elsif ($number =~ /^_/) {
8791: my $sub_condition;
8792: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8793: &GDBM_READER(),0640)) {
8794: $sub_condition=$bighash{'conditions'.$number};
8795: untie(%bighash);
8796: }
8797: my $value = &docondval($sub_condition);
1.949 raeburn 8798: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 8799: return $value;
8800: }
1.620 albertel 8801: if ($env{'user.state.'.$env{'request.course.id'}}) {
8802: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 8803: } else {
8804: return 2;
8805: }
8806: }
8807:
1.713 albertel 8808: # get the collection of conditions for this resource
1.26 www 8809: sub condval {
8810: my $condidx=shift;
1.54 www 8811: my $allpathcond='';
1.713 albertel 8812: foreach my $cond (split(/\|/,$condidx)) {
8813: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8814: $allpathcond.=
8815: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8816: }
1.191 harris41 8817: }
1.54 www 8818: $allpathcond=~s/\|$//;
1.713 albertel 8819: return &docondval($allpathcond);
8820: }
8821:
8822: #evaluates an expression of conditions
8823: sub docondval {
8824: my ($allpathcond) = @_;
8825: my $result=0;
8826: if ($env{'request.course.id'}
8827: && defined($allpathcond)) {
8828: my $operand='|';
8829: my @stack;
8830: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8831: if ($chunk eq '(') {
8832: push @stack,($operand,$result);
8833: } elsif ($chunk eq ')') {
8834: my $before=pop @stack;
8835: if (pop @stack eq '&') {
8836: $result=$result>$before?$before:$result;
8837: } else {
8838: $result=$result>$before?$result:$before;
8839: }
8840: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8841: $operand=$chunk;
8842: } else {
8843: my $new=directcondval($chunk);
8844: if ($operand eq '&') {
8845: $result=$result>$new?$new:$result;
8846: } else {
8847: $result=$result>$new?$result:$new;
8848: }
8849: }
8850: }
1.26 www 8851: }
8852: return $result;
1.421 albertel 8853: }
8854:
8855: # ---------------------------------------------------- Devalidate courseresdata
8856:
8857: sub devalidatecourseresdata {
8858: my ($coursenum,$coursedomain)=@_;
8859: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8860: &devalidate_cache_new('courseres',$hashid);
1.28 www 8861: }
8862:
1.763 www 8863:
1.200 www 8864: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8865: #
8866: # Parameters:
8867: # $coursenum - Number of the course.
8868: # $coursedomain - Domain at which the course was created.
8869: # Returns:
8870: # A hash of the course parameters along (I think) with timestamps
8871: # and version info.
1.877 foxr 8872:
1.624 albertel 8873: sub get_courseresdata {
8874: my ($coursenum,$coursedomain)=@_;
1.200 www 8875: my $coursehom=&homeserver($coursenum,$coursedomain);
8876: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8877: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8878: my %dumpreply;
1.417 albertel 8879: unless (defined($cached)) {
1.624 albertel 8880: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 8881: $result=\%dumpreply;
1.251 albertel 8882: my ($tmp) = keys(%dumpreply);
8883: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 8884: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 8885: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8886: return $tmp;
1.416 albertel 8887: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8888: $result=undef;
1.599 albertel 8889: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8890: }
8891: }
1.624 albertel 8892: return $result;
8893: }
8894:
1.633 albertel 8895: sub devalidateuserresdata {
8896: my ($uname,$udom)=@_;
8897: my $hashid="$udom:$uname";
8898: &devalidate_cache_new('userres',$hashid);
8899: }
8900:
1.624 albertel 8901: sub get_userresdata {
8902: my ($uname,$udom)=@_;
8903: #most student don\'t have any data set, check if there is some data
8904: if (&EXT_cache_status($udom,$uname)) { return undef; }
8905:
8906: my $hashid="$udom:$uname";
8907: my ($result,$cached)=&is_cached_new('userres',$hashid);
8908: if (!defined($cached)) {
8909: my %resourcedata=&dump('resourcedata',$udom,$uname);
8910: $result=\%resourcedata;
8911: &do_cache_new('userres',$hashid,$result,600);
8912: }
8913: my ($tmp)=keys(%$result);
8914: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8915: return $result;
8916: }
8917: #error 2 occurs when the .db doesn't exist
8918: if ($tmp!~/error: 2 /) {
1.672 albertel 8919: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8920: " Trying to get resource data for ".
8921: $uname." at ".$udom.": ".
8922: $tmp."</font>");
8923: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8924: #&EXT_cache_set($udom,$uname);
8925: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8926: undef($tmp); # not really an error so don't send it back
1.624 albertel 8927: }
8928: return $tmp;
8929: }
1.879 foxr 8930: #----------------------------------------------- resdata - return resource data
8931: # Purpose:
8932: # Return resource data for either users or for a course.
8933: # Parameters:
8934: # $name - Course/user name.
8935: # $domain - Name of the domain the user/course is registered on.
8936: # $type - Type of thing $name is (must be 'course' or 'user'
8937: # @which - Array of names of resources desired.
8938: # Returns:
8939: # The value of the first reasource in @which that is found in the
8940: # resource hash.
8941: # Exceptional Conditions:
8942: # If the $type passed in is not valid (not the string 'course' or
8943: # 'user', an undefined reference is returned.
8944: # If none of the resources are found, an undef is returned
1.624 albertel 8945: sub resdata {
8946: my ($name,$domain,$type,@which)=@_;
8947: my $result;
8948: if ($type eq 'course') {
8949: $result=&get_courseresdata($name,$domain);
8950: } elsif ($type eq 'user') {
8951: $result=&get_userresdata($name,$domain);
8952: }
8953: if (!ref($result)) { return $result; }
1.251 albertel 8954: foreach my $item (@which) {
1.927 albertel 8955: if (defined($result->{$item->[0]})) {
8956: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8957: }
1.250 albertel 8958: }
1.291 albertel 8959: return undef;
1.200 www 8960: }
8961:
1.379 matthew 8962: #
8963: # EXT resource caching routines
8964: #
8965:
8966: sub clear_EXT_cache_status {
1.383 albertel 8967: &delenv('cache.EXT.');
1.379 matthew 8968: }
8969:
8970: sub EXT_cache_status {
8971: my ($target_domain,$target_user) = @_;
1.383 albertel 8972: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8973: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8974: # We know already the user has no data
8975: return 1;
8976: } else {
8977: return 0;
8978: }
8979: }
8980:
8981: sub EXT_cache_set {
8982: my ($target_domain,$target_user) = @_;
1.383 albertel 8983: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8984: #&appenv({$cachename => time});
1.379 matthew 8985: }
8986:
1.28 www 8987: # --------------------------------------------------------- Value of a Variable
1.58 www 8988: sub EXT {
1.715 albertel 8989:
1.395 albertel 8990: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8991: unless ($varname) { return ''; }
1.218 albertel 8992: #get real user name/domain, courseid and symb
8993: my $courseid;
1.359 albertel 8994: my $publicuser;
1.427 www 8995: if ($symbparm) {
8996: $symbparm=&get_symb_from_alias($symbparm);
8997: }
1.218 albertel 8998: if (!($uname && $udom)) {
1.790 albertel 8999: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9000: if (!$symbparm) { $symbparm=$cursymb; }
9001: } else {
1.620 albertel 9002: $courseid=$env{'request.course.id'};
1.218 albertel 9003: }
1.48 www 9004: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9005: my $rest;
1.320 albertel 9006: if (defined($therest[0])) {
1.48 www 9007: $rest=join('.',@therest);
9008: } else {
9009: $rest='';
9010: }
1.320 albertel 9011:
1.57 www 9012: my $qualifierrest=$qualifier;
9013: if ($rest) { $qualifierrest.='.'.$rest; }
9014: my $spacequalifierrest=$space;
9015: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9016: if ($realm eq 'user') {
1.48 www 9017: # --------------------------------------------------------------- user.resource
9018: if ($space eq 'resource') {
1.651 albertel 9019: if ( (defined($Apache::lonhomework::parsing_a_problem)
9020: || defined($Apache::lonhomework::parsing_a_task))
9021: &&
1.744 albertel 9022: ($symbparm eq &symbread()) ) {
9023: # if we are in the middle of processing the resource the
9024: # get the value we are planning on committing
9025: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9026: return $Apache::lonhomework::results{$qualifierrest};
9027: } else {
9028: return $Apache::lonhomework::history{$qualifierrest};
9029: }
1.335 albertel 9030: } else {
1.359 albertel 9031: my %restored;
1.620 albertel 9032: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9033: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9034: } else {
9035: %restored=&restore($symbparm,$courseid,$udom,$uname);
9036: }
1.335 albertel 9037: return $restored{$qualifierrest};
9038: }
1.48 www 9039: # ----------------------------------------------------------------- user.access
9040: } elsif ($space eq 'access') {
1.218 albertel 9041: # FIXME - not supporting calls for a specific user
1.48 www 9042: return &allowed($qualifier,$rest);
9043: # ------------------------------------------ user.preferences, user.environment
9044: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9045: if (($uname eq $env{'user.name'}) &&
9046: ($udom eq $env{'user.domain'})) {
9047: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9048: } else {
1.359 albertel 9049: my %returnhash;
9050: if (!$publicuser) {
9051: %returnhash=&userenvironment($udom,$uname,
9052: $qualifierrest);
9053: }
1.218 albertel 9054: return $returnhash{$qualifierrest};
9055: }
1.48 www 9056: # ----------------------------------------------------------------- user.course
9057: } elsif ($space eq 'course') {
1.218 albertel 9058: # FIXME - not supporting calls for a specific user
1.620 albertel 9059: return $env{join('.',('request.course',$qualifier))};
1.48 www 9060: # ------------------------------------------------------------------- user.role
9061: } elsif ($space eq 'role') {
1.218 albertel 9062: # FIXME - not supporting calls for a specific user
1.620 albertel 9063: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9064: if ($qualifier eq 'value') {
9065: return $role;
9066: } elsif ($qualifier eq 'extent') {
9067: return $where;
9068: }
9069: # ----------------------------------------------------------------- user.domain
9070: } elsif ($space eq 'domain') {
1.218 albertel 9071: return $udom;
1.48 www 9072: # ------------------------------------------------------------------- user.name
9073: } elsif ($space eq 'name') {
1.218 albertel 9074: return $uname;
1.48 www 9075: # ---------------------------------------------------- Any other user namespace
1.29 www 9076: } else {
1.359 albertel 9077: my %reply;
9078: if (!$publicuser) {
9079: %reply=&get($space,[$qualifierrest],$udom,$uname);
9080: }
9081: return $reply{$qualifierrest};
1.48 www 9082: }
1.236 www 9083: } elsif ($realm eq 'query') {
9084: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9085: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9086: [$spacequalifierrest]);
1.620 albertel 9087: return $env{'form.'.$spacequalifierrest};
1.236 www 9088: } elsif ($realm eq 'request') {
1.48 www 9089: # ------------------------------------------------------------- request.browser
9090: if ($space eq 'browser') {
1.1145 bisitz 9091: return $env{'browser.'.$qualifier};
1.57 www 9092: # ------------------------------------------------------------ request.filename
9093: } else {
1.620 albertel 9094: return $env{'request.'.$spacequalifierrest};
1.29 www 9095: }
1.28 www 9096: } elsif ($realm eq 'course') {
1.48 www 9097: # ---------------------------------------------------------- course.description
1.620 albertel 9098: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9099: } elsif ($realm eq 'resource') {
1.165 www 9100:
1.620 albertel 9101: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9102: if (!$symbparm) { $symbparm=&symbread(); }
9103: }
1.693 albertel 9104:
9105: if ($space eq 'title') {
9106: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9107: return &gettitle($symbparm);
9108: }
9109:
9110: if ($space eq 'map') {
9111: my ($map) = &decode_symb($symbparm);
9112: return &symbread($map);
9113: }
1.905 albertel 9114: if ($space eq 'filename') {
9115: if ($symbparm) {
9116: return &clutter((&decode_symb($symbparm))[2]);
9117: }
9118: return &hreflocation('',$env{'request.filename'});
9119: }
1.693 albertel 9120:
9121: my ($section, $group, @groups);
1.593 albertel 9122: my ($courselevelm,$courselevel);
1.539 albertel 9123: if ($symbparm && defined($courseid) &&
1.620 albertel 9124: $courseid eq $env{'request.course.id'}) {
1.165 www 9125:
1.218 albertel 9126: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9127:
1.60 www 9128: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9129: my $symbp=$symbparm;
1.735 albertel 9130: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9131:
9132: my $symbparm=$symbp.'.'.$spacequalifierrest;
9133: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9134:
1.620 albertel 9135: if (($env{'user.name'} eq $uname) &&
9136: ($env{'user.domain'} eq $udom)) {
9137: $section=$env{'request.course.sec'};
1.733 raeburn 9138: @groups = split(/:/,$env{'request.course.groups'});
9139: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9140: } else {
1.539 albertel 9141: if (! defined($usection)) {
1.551 albertel 9142: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9143: } else {
9144: $section = $usection;
9145: }
1.733 raeburn 9146: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9147: }
9148:
9149: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9150: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9151: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9152:
1.593 albertel 9153: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9154: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9155: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9156:
1.60 www 9157: # ----------------------------------------------------------- first, check user
1.624 albertel 9158:
9159: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9160: ([$courselevelr,'resource'],
9161: [$courselevelm,'map' ],
9162: [$courselevel, 'course' ]));
1.931 albertel 9163: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9164:
1.594 albertel 9165: # ------------------------------------------------ second, check some of course
1.684 raeburn 9166: my $coursereply;
1.691 raeburn 9167: if (@groups > 0) {
9168: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9169: $mapparm,$spacequalifierrest);
1.927 albertel 9170: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9171: }
1.96 www 9172:
1.684 raeburn 9173: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9174: $env{'course.'.$courseid.'.domain'},
9175: 'course',
9176: ([$seclevelr, 'resource'],
9177: [$seclevelm, 'map' ],
9178: [$seclevel, 'course' ],
9179: [$courselevelr,'resource']));
9180: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 9181:
1.60 www 9182: # ------------------------------------------------------ third, check map parms
1.218 albertel 9183: my %parmhash=();
9184: my $thisparm='';
9185: if (tie(%parmhash,'GDBM_File',
1.620 albertel 9186: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 9187: &GDBM_READER(),0640)) {
1.218 albertel 9188: $thisparm=$parmhash{$symbparm};
9189: untie(%parmhash);
9190: }
1.927 albertel 9191: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 9192: }
1.594 albertel 9193: # ------------------------------------------ fourth, look in resource metadata
1.71 www 9194:
1.218 albertel 9195: $spacequalifierrest=~s/\./\_/;
1.282 albertel 9196: my $filename;
9197: if (!$symbparm) { $symbparm=&symbread(); }
9198: if ($symbparm) {
1.409 www 9199: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 9200: } else {
1.620 albertel 9201: $filename=$env{'request.filename'};
1.282 albertel 9202: }
9203: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 9204: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 9205: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 9206: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 9207:
1.927 albertel 9208: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 9209: if ($symbparm && defined($courseid) &&
1.620 albertel 9210: $courseid eq $env{'request.course.id'}) {
1.624 albertel 9211: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9212: $env{'course.'.$courseid.'.domain'},
9213: 'course',
1.927 albertel 9214: ([$courselevelm,'map' ],
9215: [$courselevel, 'course']));
9216: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 9217: }
1.145 www 9218: # ------------------------------------------------------------------ Cascade up
1.218 albertel 9219: unless ($space eq '0') {
1.336 albertel 9220: my @parts=split(/_/,$space);
9221: my $id=pop(@parts);
9222: my $part=join('_',@parts);
9223: if ($part eq '') { $part='0'; }
1.927 albertel 9224: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 9225: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 9226: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 9227: }
1.395 albertel 9228: if ($recurse) { return undef; }
9229: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 9230: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 9231: # ---------------------------------------------------- Any other user namespace
9232: } elsif ($realm eq 'environment') {
9233: # ----------------------------------------------------------------- environment
1.620 albertel 9234: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9235: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 9236: } else {
1.770 albertel 9237: if ($uname eq 'anonymous' && $udom eq '') {
9238: return '';
9239: }
1.219 albertel 9240: my %returnhash=&userenvironment($udom,$uname,
9241: $spacequalifierrest);
9242: return $returnhash{$spacequalifierrest};
9243: }
1.28 www 9244: } elsif ($realm eq 'system') {
1.48 www 9245: # ----------------------------------------------------------------- system.time
9246: if ($space eq 'time') {
9247: return time;
9248: }
1.696 albertel 9249: } elsif ($realm eq 'server') {
9250: # ----------------------------------------------------------------- system.time
9251: if ($space eq 'name') {
9252: return $ENV{'SERVER_NAME'};
9253: }
1.28 www 9254: }
1.48 www 9255: return '';
1.61 www 9256: }
9257:
1.927 albertel 9258: sub get_reply {
9259: my ($reply_value) = @_;
1.940 raeburn 9260: if (ref($reply_value) eq 'ARRAY') {
9261: if (wantarray) {
9262: return @$reply_value;
9263: }
9264: return $reply_value->[0];
9265: } else {
9266: return $reply_value;
1.927 albertel 9267: }
9268: }
9269:
1.691 raeburn 9270: sub check_group_parms {
9271: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
9272: my @groupitems = ();
9273: my $resultitem;
1.927 albertel 9274: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 9275: foreach my $group (@{$groups}) {
9276: foreach my $level (@levels) {
1.927 albertel 9277: my $item = $courseid.'.['.$group.'].'.$level->[0];
9278: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 9279: }
9280: }
9281: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
9282: $env{'course.'.$courseid.'.domain'},
9283: 'course',@groupitems);
9284: return $coursereply;
9285: }
9286:
9287: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 9288: my ($courseid,@groups) = @_;
9289: @groups = sort(@groups);
1.691 raeburn 9290: return @groups;
9291: }
9292:
1.395 albertel 9293: sub packages_tab_default {
9294: my ($uri,$varname)=@_;
9295: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 9296:
9297: my (@extension,@specifics,$do_default);
9298: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 9299: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 9300: if ($pack_type eq 'default') {
9301: $do_default=1;
9302: } elsif ($pack_type eq 'extension') {
9303: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 9304: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 9305: # only look at packages defaults for packages that this id is
1.738 albertel 9306: push(@specifics,[$package,$pack_type,$pack_part]);
9307: }
9308: }
9309: # first look for a package that matches the requested part id
9310: foreach my $package (@specifics) {
9311: my (undef,$pack_type,$pack_part)=@{$package};
9312: next if ($pack_part ne $part);
9313: if (defined($packagetab{"$pack_type&$name&default"})) {
9314: return $packagetab{"$pack_type&$name&default"};
9315: }
9316: }
9317: # look for any possible matching non extension_ package
9318: foreach my $package (@specifics) {
9319: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 9320: if (defined($packagetab{"$pack_type&$name&default"})) {
9321: return $packagetab{"$pack_type&$name&default"};
9322: }
1.585 albertel 9323: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 9324: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
9325: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 9326: }
9327: }
1.738 albertel 9328: # look for any posible extension_ match
9329: foreach my $package (@extension) {
9330: my ($package,$pack_type)=@{$package};
9331: if (defined($packagetab{"$pack_type&$name&default"})) {
9332: return $packagetab{"$pack_type&$name&default"};
9333: }
9334: if (defined($packagetab{$package."&$name&default"})) {
9335: return $packagetab{$package."&$name&default"};
9336: }
9337: }
9338: # look for a global default setting
9339: if ($do_default && defined($packagetab{"default&$name&default"})) {
9340: return $packagetab{"default&$name&default"};
9341: }
1.395 albertel 9342: return undef;
9343: }
9344:
1.334 albertel 9345: sub add_prefix_and_part {
9346: my ($prefix,$part)=@_;
9347: my $keyroot;
9348: if (defined($prefix) && $prefix !~ /^__/) {
9349: # prefix that has a part already
9350: $keyroot=$prefix;
9351: } elsif (defined($prefix)) {
9352: # prefix that is missing a part
9353: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
9354: } else {
9355: # no prefix at all
9356: if (defined($part)) { $keyroot='_'.$part; }
9357: }
9358: return $keyroot;
9359: }
9360:
1.71 www 9361: # ---------------------------------------------------------------- Get metadata
9362:
1.599 albertel 9363: my %metaentry;
1.1070 www 9364: my %importedpartids;
1.71 www 9365: sub metadata {
1.176 www 9366: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 9367: $uri=&declutter($uri);
1.288 albertel 9368: # if it is a non metadata possible uri return quickly
1.529 albertel 9369: if (($uri eq '') ||
9370: (($uri =~ m|^/*adm/|) &&
1.698 albertel 9371: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108 raeburn 9372: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 9373: return undef;
9374: }
1.1140 www 9375: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 9376: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 9377: return undef;
1.288 albertel 9378: }
1.73 www 9379: my $filename=$uri;
9380: $uri=~s/\.meta$//;
1.172 www 9381: #
9382: # Is the metadata already cached?
1.177 www 9383: # Look at timestamp of caching
1.172 www 9384: # Everything is cached by the main uri, libraries are never directly cached
9385: #
1.428 albertel 9386: if (!defined($liburi)) {
1.599 albertel 9387: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 9388: if (defined($cached)) { return $result->{':'.$what}; }
9389: }
9390: {
1.1069 www 9391: # Imported parts would go here
1.1070 www 9392: my %importedids=();
9393: my @origfileimportpartids=();
1.1069 www 9394: my $importedparts=0;
1.172 www 9395: #
9396: # Is this a recursive call for a library?
9397: #
1.599 albertel 9398: # if (! exists($metacache{$uri})) {
9399: # $metacache{$uri}={};
9400: # }
1.924 albertel 9401: my $cachetime = 60*60;
1.171 www 9402: if ($liburi) {
9403: $liburi=&declutter($liburi);
9404: $filename=$liburi;
1.401 bowersj2 9405: } else {
1.599 albertel 9406: &devalidate_cache_new('meta',$uri);
9407: undef(%metaentry);
1.401 bowersj2 9408: }
1.140 www 9409: my %metathesekeys=();
1.73 www 9410: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 9411: my $metastring;
1.1140 www 9412: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 9413: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 9414: $metastring =
1.929 albertel 9415: &Apache::lonnet::ssi_body($which,
1.924 albertel 9416: ('grade_target' => 'meta'));
9417: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 9418: } elsif (($uri !~ m -^(editupload)/-) &&
9419: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 9420: my $file=&filelocation('',&clutter($filename));
1.599 albertel 9421: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 9422: $metastring=&getfile($file);
1.489 albertel 9423: }
1.208 albertel 9424: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 9425: my $token;
1.140 www 9426: undef %metathesekeys;
1.71 www 9427: while ($token=$parser->get_token) {
1.339 albertel 9428: if ($token->[0] eq 'S') {
9429: if (defined($token->[2]->{'package'})) {
1.172 www 9430: #
9431: # This is a package - get package info
9432: #
1.339 albertel 9433: my $package=$token->[2]->{'package'};
9434: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9435: if (defined($token->[2]->{'id'})) {
9436: $keyroot.='_'.$token->[2]->{'id'};
9437: }
1.599 albertel 9438: if ($metaentry{':packages'}) {
9439: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 9440: } else {
1.599 albertel 9441: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 9442: }
1.736 albertel 9443: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 9444: my $part=$keyroot;
9445: $part=~s/^\_//;
1.736 albertel 9446: if ($pack_entry=~/^\Q$package\E\&/ ||
9447: $pack_entry=~/^\Q$package\E_0\&/) {
9448: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 9449: # ignore package.tab specified default values
9450: # here &package_tab_default() will fetch those
9451: if ($subp eq 'default') { next; }
1.736 albertel 9452: my $value=$packagetab{$pack_entry};
1.432 albertel 9453: my $unikey;
9454: if ($pack =~ /_0$/) {
9455: $unikey='parameter_0_'.$name;
9456: $part=0;
9457: } else {
9458: $unikey='parameter'.$keyroot.'_'.$name;
9459: }
1.339 albertel 9460: if ($subp eq 'display') {
9461: $value.=' [Part: '.$part.']';
9462: }
1.599 albertel 9463: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 9464: $metathesekeys{$unikey}=1;
1.599 albertel 9465: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9466: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 9467: }
1.599 albertel 9468: if (defined($metaentry{':'.$unikey.'.default'})) {
9469: $metaentry{':'.$unikey}=
9470: $metaentry{':'.$unikey.'.default'};
1.356 albertel 9471: }
1.339 albertel 9472: }
9473: }
9474: } else {
1.172 www 9475: #
9476: # This is not a package - some other kind of start tag
1.339 albertel 9477: #
9478: my $entry=$token->[1];
1.1068 www 9479: my $unikey='';
1.175 www 9480:
1.339 albertel 9481: if ($entry eq 'import') {
1.175 www 9482: #
9483: # Importing a library here
1.339 albertel 9484: #
1.1067 www 9485: my $location=$parser->get_text('/import');
9486: my $dir=$filename;
9487: $dir=~s|[^/]*$||;
9488: $location=&filelocation($dir,$location);
1.1069 www 9489:
1.1068 www 9490: my $importmode=$token->[2]->{'importmode'};
9491: if ($importmode eq 'problem') {
1.1069 www 9492: # Import as problem/response
1.1068 www 9493: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9494: } elsif ($importmode eq 'part') {
9495: # Import as part(s)
1.1069 www 9496: $importedparts=1;
9497: # We need to get the original file and the imported file to get the part order correct
9498: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9499: # Load and inspect original file
1.1070 www 9500: if ($#origfileimportpartids<0) {
9501: undef(%importedpartids);
9502: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9503: my $origfile=&getfile($origfilelocation);
9504: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9505: }
9506:
1.1069 www 9507: # Load and inspect imported file
9508: my $impfile=&getfile($location);
9509: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9510: if ($#impfilepartids>=0) {
9511: # This problem had parts
1.1070 www 9512: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 9513: } else {
9514: # Importing by turning a single problem into a problem part
9515: # It gets the import-tags ID as part-ID
9516: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 9517: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 9518: }
1.1068 www 9519: } else {
9520: # Normal import
9521: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9522: if (defined($token->[2]->{'id'})) {
9523: $unikey.='_'.$token->[2]->{'id'};
9524: }
1.1067 www 9525: }
9526:
1.339 albertel 9527: if ($depthcount<20) {
1.736 albertel 9528: my $metadata =
9529: &metadata($uri,'keys', $location,$unikey,
9530: $depthcount+1);
9531: foreach my $meta (split(',',$metadata)) {
9532: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9533: $metathesekeys{$meta}=1;
1.339 albertel 9534: }
1.1068 www 9535:
9536: }
1.1067 www 9537: } else {
9538: #
9539: # Not importing, some other kind of non-package, non-library start tag
9540: #
9541: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9542: if (defined($token->[2]->{'id'})) {
9543: $unikey.='_'.$token->[2]->{'id'};
9544: }
1.339 albertel 9545: if (defined($token->[2]->{'name'})) {
9546: $unikey.='_'.$token->[2]->{'name'};
9547: }
9548: $metathesekeys{$unikey}=1;
1.736 albertel 9549: foreach my $param (@{$token->[3]}) {
9550: $metaentry{':'.$unikey.'.'.$param} =
9551: $token->[2]->{$param};
1.339 albertel 9552: }
9553: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 9554: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 9555: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9556: # only ws inside the tag, and not in default, so use default
9557: # as value
1.599 albertel 9558: $metaentry{':'.$unikey}=$default;
1.908 albertel 9559: } elsif ( $internaltext =~ /\S/ ) {
9560: # something interesting inside the tag
9561: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 9562: } else {
1.908 albertel 9563: # no interesting values, don't set a default
1.339 albertel 9564: }
1.172 www 9565: # end of not-a-package not-a-library import
1.339 albertel 9566: }
1.172 www 9567: # end of not-a-package start tag
1.339 albertel 9568: }
1.172 www 9569: # the next is the end of "start tag"
1.339 albertel 9570: }
9571: }
1.483 albertel 9572: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 9573: $extension = lc($extension);
9574: if ($extension eq 'htm') { $extension='html'; }
9575:
1.737 albertel 9576: foreach my $key (keys(%packagetab)) {
1.483 albertel 9577: #no specific packages #how's our extension
9578: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 9579: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 9580: \%metathesekeys);
9581: }
1.883 albertel 9582:
9583: if (!exists($metaentry{':packages'})
9584: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 9585: foreach my $key (keys(%packagetab)) {
1.483 albertel 9586: #no specific packages well let's get default then
9587: if ($key!~/^default&/) { next; }
1.488 albertel 9588: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 9589: \%metathesekeys);
9590: }
9591: }
1.338 www 9592: # are there custom rights to evaluate
1.599 albertel 9593: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 9594:
1.338 www 9595: #
9596: # Importing a rights file here
1.339 albertel 9597: #
9598: unless ($depthcount) {
1.599 albertel 9599: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 9600: my $dir=$filename;
9601: $dir=~s|[^/]*$||;
9602: $location=&filelocation($dir,$location);
1.736 albertel 9603: my $rights_metadata =
9604: &metadata($uri,'keys',$location,'_rights',
9605: $depthcount+1);
9606: foreach my $rights (split(',',$rights_metadata)) {
9607: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9608: $metathesekeys{$rights}=1;
1.339 albertel 9609: }
9610: }
9611: }
1.737 albertel 9612: # uniqifiy package listing
9613: my %seen;
9614: my @uniq_packages =
9615: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9616: $metaentry{':packages'} = join(',',@uniq_packages);
9617:
1.1070 www 9618: if ($importedparts) {
9619: # We had imported parts and need to rebuild partorder
9620: $metaentry{':partorder'}='';
9621: $metathesekeys{'partorder'}=1;
9622: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9623: if ($origfileimportpartids[$index] eq 'part') {
9624: # original part, part of the problem
9625: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9626: } else {
9627: # we have imported parts at this position
9628: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9629: }
9630: }
9631: $metaentry{':partorder'}=~s/^\,//;
9632: }
9633:
1.737 albertel 9634: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 9635: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9636: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 9637: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 9638: # this is the end of "was not already recently cached
1.71 www 9639: }
1.599 albertel 9640: return $metaentry{':'.$what};
1.261 albertel 9641: }
9642:
1.488 albertel 9643: sub metadata_create_package_def {
1.483 albertel 9644: my ($uri,$key,$package,$metathesekeys)=@_;
9645: my ($pack,$name,$subp)=split(/\&/,$key);
9646: if ($subp eq 'default') { next; }
9647:
1.599 albertel 9648: if (defined($metaentry{':packages'})) {
9649: $metaentry{':packages'}.=','.$package;
1.483 albertel 9650: } else {
1.599 albertel 9651: $metaentry{':packages'}=$package;
1.483 albertel 9652: }
9653: my $value=$packagetab{$key};
9654: my $unikey;
9655: $unikey='parameter_0_'.$name;
1.599 albertel 9656: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 9657: $$metathesekeys{$unikey}=1;
1.599 albertel 9658: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9659: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 9660: }
1.599 albertel 9661: if (defined($metaentry{':'.$unikey.'.default'})) {
9662: $metaentry{':'.$unikey}=
9663: $metaentry{':'.$unikey.'.default'};
1.483 albertel 9664: }
9665: }
9666:
1.261 albertel 9667: sub metadata_generate_part0 {
9668: my ($metadata,$metacache,$uri) = @_;
9669: my %allnames;
1.737 albertel 9670: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 9671: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 9672: my $part=$$metacache{':'.$metakey.'.part'};
9673: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 9674: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 9675: $allnames{$name}=$part;
9676: }
9677: }
9678: }
9679: foreach my $name (keys(%allnames)) {
9680: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 9681: my $key=":parameter_0_$name";
1.261 albertel 9682: $$metacache{"$key.part"}='0';
9683: $$metacache{"$key.name"}=$name;
1.428 albertel 9684: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 9685: $allnames{$name}.'_'.$name.
9686: '.type'};
1.428 albertel 9687: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 9688: '.display'};
1.644 www 9689: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 9690: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 9691: $$metacache{"$key.display"}=$olddis;
9692: }
1.71 www 9693: }
9694:
1.764 albertel 9695: # ------------------------------------------------------ Devalidate title cache
9696:
9697: sub devalidate_title_cache {
9698: my ($url)=@_;
9699: if (!$env{'request.course.id'}) { return; }
9700: my $symb=&symbread($url);
9701: if (!$symb) { return; }
9702: my $key=$env{'request.course.id'}."\0".$symb;
9703: &devalidate_cache_new('title',$key);
9704: }
9705:
1.1014 droeschl 9706: # ------------------------------------------------- Get the title of a course
9707:
9708: sub current_course_title {
9709: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9710: }
1.301 www 9711: # ------------------------------------------------- Get the title of a resource
9712:
9713: sub gettitle {
9714: my $urlsymb=shift;
9715: my $symb=&symbread($urlsymb);
1.534 albertel 9716: if ($symb) {
1.620 albertel 9717: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 9718: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 9719: if (defined($cached)) {
9720: return $result;
9721: }
1.534 albertel 9722: my ($map,$resid,$url)=&decode_symb($symb);
9723: my $title='';
1.907 albertel 9724: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9725: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9726: } else {
9727: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9728: &GDBM_READER(),0640)) {
9729: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9730: $title=$bighash{'title_'.$mapid.'.'.$resid};
9731: untie(%bighash);
9732: }
1.534 albertel 9733: }
9734: $title=~s/\&colon\;/\:/gs;
9735: if ($title) {
1.1159 www 9736: # Remember both $symb and $title for dynamic metadata
9737: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 9738: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 9739: # Cache this title and then return it
1.599 albertel 9740: return &do_cache_new('title',$key,$title,600);
1.534 albertel 9741: }
9742: $urlsymb=$url;
9743: }
9744: my $title=&metadata($urlsymb,'title');
9745: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9746: return $title;
1.301 www 9747: }
1.613 albertel 9748:
1.614 albertel 9749: sub get_slot {
9750: my ($which,$cnum,$cdom)=@_;
9751: if (!$cnum || !$cdom) {
1.790 albertel 9752: (undef,my $courseid)=&whichuser();
1.620 albertel 9753: $cdom=$env{'course.'.$courseid.'.domain'};
9754: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 9755: }
1.703 albertel 9756: my $key=join("\0",'slots',$cdom,$cnum,$which);
9757: my %slotinfo;
9758: if (exists($remembered{$key})) {
9759: $slotinfo{$which} = $remembered{$key};
9760: } else {
9761: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9762: &Apache::lonhomework::showhash(%slotinfo);
9763: my ($tmp)=keys(%slotinfo);
9764: if ($tmp=~/^error:/) { return (); }
9765: $remembered{$key} = $slotinfo{$which};
9766: }
1.616 albertel 9767: if (ref($slotinfo{$which}) eq 'HASH') {
9768: return %{$slotinfo{$which}};
9769: }
9770: return $slotinfo{$which};
1.614 albertel 9771: }
1.1150 raeburn 9772:
9773: sub get_reservable_slots {
9774: my ($cnum,$cdom,$uname,$udom) = @_;
9775: my $now = time;
9776: my $reservable_info;
9777: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
9778: if (exists($remembered{$key})) {
9779: $reservable_info = $remembered{$key};
9780: } else {
9781: my %resv;
9782: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
9783: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
9784: $reservable_info = \%resv;
9785: $remembered{$key} = $reservable_info;
9786: }
9787: return $reservable_info;
9788: }
9789:
9790: sub get_course_slots {
9791: my ($cnum,$cdom) = @_;
9792: my $hashid=$cnum.':'.$cdom;
9793: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
9794: if (defined($cached)) {
9795: if (ref($result) eq 'HASH') {
9796: return %{$result};
9797: }
9798: } else {
9799: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
9800: my ($tmp) = keys(%slots);
9801: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9802: &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
9803: return %slots;
9804: }
9805: }
9806: return;
9807: }
9808:
9809: sub devalidate_slots_cache {
9810: my ($cnum,$cdom)=@_;
9811: my $hashid=$cnum.':'.$cdom;
9812: &devalidate_cache_new('allslots',$hashid);
9813: }
9814:
1.1172.2.8! raeburn 9815: sub get_coursechange {
! 9816: my ($cdom,$cnum) = @_;
! 9817: if ($cdom eq '' || $cnum eq '') {
! 9818: return unless ($env{'request.course.id'});
! 9819: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
! 9820: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
! 9821: }
! 9822: my $hashid=$cdom.'_'.$cnum;
! 9823: my ($change,$cached)=&is_cached_new('crschange',$hashid);
! 9824: if ((defined($cached)) && ($change ne '')) {
! 9825: return $change;
! 9826: } else {
! 9827: my %crshash;
! 9828: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
! 9829: if ($crshash{'internal.contentchange'} eq '') {
! 9830: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
! 9831: if ($change eq '') {
! 9832: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
! 9833: $change = $crshash{'internal.created'};
! 9834: }
! 9835: } else {
! 9836: $change = $crshash{'internal.contentchange'};
! 9837: }
! 9838: my $cachetime = 600;
! 9839: &do_cache_new('crschange',$hashid,$change,$cachetime);
! 9840: }
! 9841: return $change;
! 9842: }
! 9843:
! 9844: sub devalidate_coursechange_cache {
! 9845: my ($cnum,$cdom)=@_;
! 9846: my $hashid=$cnum.':'.$cdom;
! 9847: &devalidate_cache_new('crschange',$hashid);
! 9848: }
! 9849:
1.31 www 9850: # ------------------------------------------------- Update symbolic store links
9851:
9852: sub symblist {
9853: my ($mapname,%newhash)=@_;
1.438 www 9854: $mapname=&deversion(&declutter($mapname));
1.31 www 9855: my %hash;
1.620 albertel 9856: if (($env{'request.course.fn'}) && (%newhash)) {
9857: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9858: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 9859: foreach my $url (keys(%newhash)) {
1.711 albertel 9860: next if ($url eq 'last_known'
9861: && $env{'form.no_update_last_known'});
9862: $hash{declutter($url)}=&encode_symb($mapname,
9863: $newhash{$url}->[1],
9864: $newhash{$url}->[0]);
1.191 harris41 9865: }
1.31 www 9866: if (untie(%hash)) {
9867: return 'ok';
9868: }
9869: }
9870: }
9871: return 'error';
1.212 www 9872: }
9873:
9874: # --------------------------------------------------------------- Verify a symb
9875:
9876: sub symbverify {
1.510 www 9877: my ($symb,$thisurl)=@_;
9878: my $thisfn=$thisurl;
1.439 www 9879: $thisfn=&declutter($thisfn);
1.215 www 9880: # direct jump to resource in page or to a sequence - will construct own symbs
9881: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9882: # check URL part
1.409 www 9883: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 9884:
1.431 www 9885: unless ($url eq $thisfn) { return 0; }
1.213 www 9886:
1.216 www 9887: $symb=&symbclean($symb);
1.510 www 9888: $thisurl=&deversion($thisurl);
1.439 www 9889: $thisfn=&deversion($thisfn);
1.213 www 9890:
9891: my %bighash;
9892: my $okay=0;
1.431 www 9893:
1.620 albertel 9894: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9895: &GDBM_READER(),0640)) {
1.1032 raeburn 9896: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9897: $thisurl =~ s/\?.+$//;
9898: }
1.510 www 9899: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102 raeburn 9900: unless ($ids) {
9901: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9902: $ids=$bighash{$idkey};
1.216 www 9903: }
9904: if ($ids) {
9905: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 9906: foreach my $id (split(/\,/,$ids)) {
9907: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 9908: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9909: $symb =~ s/\?.+$//;
9910: }
1.216 www 9911: if (
9912: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9913: eq $symb) {
1.620 albertel 9914: if (($env{'request.role.adv'}) ||
1.1101 raeburn 9915: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9916: ($thisurl eq '/adm/navmaps')) {
1.582 albertel 9917: $okay=1;
9918: }
9919: }
1.216 www 9920: }
9921: }
1.213 www 9922: untie(%bighash);
9923: }
9924: return $okay;
1.31 www 9925: }
9926:
1.210 www 9927: # --------------------------------------------------------------- Clean-up symb
9928:
9929: sub symbclean {
9930: my $symb=shift;
1.568 albertel 9931: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 9932: # remove version from map
9933: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 9934:
1.210 www 9935: # remove version from URL
9936: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 9937:
1.507 www 9938: # remove wrapper
9939:
1.510 www 9940: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 9941: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 9942: return $symb;
1.409 www 9943: }
9944:
9945: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 9946:
9947: sub encode_symb {
9948: my ($map,$resid,$url)=@_;
9949: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9950: }
1.409 www 9951:
9952: sub decode_symb {
1.568 albertel 9953: my $symb=shift;
9954: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9955: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 9956: return (&fixversion($map),$resid,&fixversion($url));
9957: }
9958:
9959: sub fixversion {
9960: my $fn=shift;
1.609 banghart 9961: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 9962: my %bighash;
9963: my $uri=&clutter($fn);
1.620 albertel 9964: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 9965: # is this cached?
1.599 albertel 9966: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 9967: if (defined($cached)) { return $result; }
9968: # unfortunately not cached, or expired
1.620 albertel 9969: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 9970: &GDBM_READER(),0640)) {
9971: if ($bighash{'version_'.$uri}) {
9972: my $version=$bighash{'version_'.$uri};
1.444 www 9973: unless (($version eq 'mostrecent') ||
9974: ($version==&getversion($uri))) {
1.440 www 9975: $uri=~s/\.(\w+)$/\.$version\.$1/;
9976: }
9977: }
9978: untie %bighash;
1.413 www 9979: }
1.599 albertel 9980: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 9981: }
9982:
9983: sub deversion {
9984: my $url=shift;
9985: $url=~s/\.\d+\.(\w+)$/\.$1/;
9986: return $url;
1.210 www 9987: }
9988:
1.31 www 9989: # ------------------------------------------------------ Return symb list entry
9990:
9991: sub symbread {
1.249 www 9992: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 9993: my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.8! raeburn 9994: if (defined($env{$cache_str})) {
! 9995: if (($thisfn) || ($env{$cache_str} ne '')) {
! 9996: return $env{$cache_str};
! 9997: }
! 9998: }
1.242 www 9999: # no filename provided? try from environment
1.44 www 10000: unless ($thisfn) {
1.620 albertel 10001: if ($env{'request.symb'}) {
10002: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 10003: }
1.620 albertel 10004: $thisfn=$env{'request.filename'};
1.44 www 10005: }
1.569 albertel 10006: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10007: # is that filename actually a symb? Verify, clean, and return
10008: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10009: if (&symbverify($thisfn,$1)) {
1.620 albertel 10010: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10011: }
1.242 www 10012: }
1.44 www 10013: $thisfn=declutter($thisfn);
1.31 www 10014: my %hash;
1.37 www 10015: my %bighash;
10016: my $syval='';
1.620 albertel 10017: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10018: my $targetfn = $thisfn;
1.609 banghart 10019: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10020: $targetfn = 'adm/wrapper/'.$thisfn;
10021: }
1.687 albertel 10022: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10023: $targetfn=$1;
10024: }
1.620 albertel 10025: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10026: &GDBM_READER(),0640)) {
1.481 raeburn 10027: $syval=$hash{$targetfn};
1.37 www 10028: untie(%hash);
10029: }
10030: # ---------------------------------------------------------- There was an entry
10031: if ($syval) {
1.601 albertel 10032: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10033: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10034: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10035: #return $env{$cache_str}='';
1.601 albertel 10036: #}
10037: #$syval.=$1;
10038: #}
1.37 www 10039: } else {
10040: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10041: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10042: &GDBM_READER(),0640)) {
1.37 www 10043: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10044: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10045: unless ($ids) {
10046: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10047: }
10048: unless ($ids) {
10049: # alias?
10050: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10051: }
1.37 www 10052: if ($ids) {
10053: # ------------------------------------------------------------------- Has ID(s)
10054: my @possibilities=split(/\,/,$ids);
1.39 www 10055: if ($#possibilities==0) {
10056: # ----------------------------------------------- There is only one possibility
1.37 www 10057: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10058: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10059: $resid,$thisfn);
1.249 www 10060: } elsif (!$donotrecurse) {
1.39 www 10061: # ------------------------------------------ There is more than one possibility
10062: my $realpossible=0;
1.800 albertel 10063: foreach my $id (@possibilities) {
10064: my $file=$bighash{'src_'.$id};
1.39 www 10065: if (&allowed('bre',$file)) {
1.800 albertel 10066: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10067: if ($bighash{'map_type_'.$mapid} ne 'page') {
10068: $realpossible++;
1.626 albertel 10069: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10070: $resid,$thisfn);
1.39 www 10071: }
10072: }
1.191 harris41 10073: }
1.39 www 10074: if ($realpossible!=1) { $syval=''; }
1.249 www 10075: } else {
10076: $syval='';
1.37 www 10077: }
10078: }
10079: untie(%bighash)
1.481 raeburn 10080: }
1.31 www 10081: }
1.62 www 10082: if ($syval) {
1.620 albertel 10083: return $env{$cache_str}=$syval;
1.62 www 10084: }
1.31 www 10085: }
1.949 raeburn 10086: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10087: return $env{$cache_str}='';
1.31 www 10088: }
10089:
10090: # ---------------------------------------------------------- Return random seed
10091:
1.32 www 10092: sub numval {
10093: my $txt=shift;
10094: $txt=~tr/A-J/0-9/;
10095: $txt=~tr/a-j/0-9/;
10096: $txt=~tr/K-T/0-9/;
10097: $txt=~tr/k-t/0-9/;
10098: $txt=~tr/U-Z/0-5/;
10099: $txt=~tr/u-z/0-5/;
10100: $txt=~s/\D//g;
1.564 albertel 10101: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10102: return int($txt);
1.368 albertel 10103: }
10104:
1.484 albertel 10105: sub numval2 {
10106: my $txt=shift;
10107: $txt=~tr/A-J/0-9/;
10108: $txt=~tr/a-j/0-9/;
10109: $txt=~tr/K-T/0-9/;
10110: $txt=~tr/k-t/0-9/;
10111: $txt=~tr/U-Z/0-5/;
10112: $txt=~tr/u-z/0-5/;
10113: $txt=~s/\D//g;
10114: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10115: my $total;
10116: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10117: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10118: return int($total);
10119: }
10120:
1.575 albertel 10121: sub numval3 {
10122: use integer;
10123: my $txt=shift;
10124: $txt=~tr/A-J/0-9/;
10125: $txt=~tr/a-j/0-9/;
10126: $txt=~tr/K-T/0-9/;
10127: $txt=~tr/k-t/0-9/;
10128: $txt=~tr/U-Z/0-5/;
10129: $txt=~tr/u-z/0-5/;
10130: $txt=~s/\D//g;
10131: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10132: my $total;
10133: foreach my $val (@txts) { $total+=$val; }
10134: if ($_64bit) { $total=(($total<<32)>>32); }
10135: return $total;
10136: }
10137:
1.675 albertel 10138: sub digest {
10139: my ($data)=@_;
10140: my $digest=&Digest::MD5::md5($data);
10141: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10142: my ($e,$f);
10143: {
10144: use integer;
10145: $e=($a+$b);
10146: $f=($c+$d);
10147: if ($_64bit) {
10148: $e=(($e<<32)>>32);
10149: $f=(($f<<32)>>32);
10150: }
10151: }
10152: if (wantarray) {
10153: return ($e,$f);
10154: } else {
10155: my $g;
10156: {
10157: use integer;
10158: $g=($e+$f);
10159: if ($_64bit) {
10160: $g=(($g<<32)>>32);
10161: }
10162: }
10163: return $g;
10164: }
10165: }
10166:
1.368 albertel 10167: sub latest_rnd_algorithm_id {
1.675 albertel 10168: return '64bit5';
1.366 albertel 10169: }
1.32 www 10170:
1.503 albertel 10171: sub get_rand_alg {
10172: my ($courseid)=@_;
1.790 albertel 10173: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 10174: if ($courseid) {
1.620 albertel 10175: return $env{"course.$courseid.rndseed"};
1.503 albertel 10176: }
10177: return &latest_rnd_algorithm_id();
10178: }
10179:
1.562 albertel 10180: sub validCODE {
10181: my ($CODE)=@_;
10182: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10183: return 0;
10184: }
10185:
1.491 albertel 10186: sub getCODE {
1.620 albertel 10187: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 10188: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10189: defined($Apache::lonhomework::parsing_a_task) ) &&
10190: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 10191: return $Apache::lonhomework::history{'resource.CODE'};
10192: }
10193: return undef;
10194: }
1.1133 foxr 10195: #
10196: # Determines the random seed for a specific context:
10197: #
10198: # parameters:
10199: # symb - in course context the symb for the seed.
10200: # course_id - The course id of the form domain_coursenum.
10201: # domain - Domain for the user.
10202: # course - Course for the user.
10203: # cenv - environment of the course.
10204: #
10205: # NOTE:
10206: # All parameters are picked out of the environment if missing
10207: # or not defined.
10208: # If a symb cannot be determined the current time is used instead.
10209: #
10210: # For a given well defined symb, courside, domain, username,
10211: # and course environment, the seed is reproducible.
10212: #
1.31 www 10213: sub rndseed {
1.1133 foxr 10214: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 10215: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 10216: if (!defined($symb)) {
1.366 albertel 10217: unless ($symb=$wsymb) { return time; }
10218: }
1.1146 foxr 10219: if (!defined $courseid) {
10220: $courseid=$wcourseid;
10221: }
10222: if (!defined $domain) { $domain=$wdomain; }
10223: if (!defined $username) { $username=$wusername }
1.1133 foxr 10224:
10225: my $which;
10226: if (defined($cenv->{'rndseed'})) {
10227: $which = $cenv->{'rndseed'};
10228: } else {
10229: $which =&get_rand_alg($courseid);
10230: }
1.491 albertel 10231: if (defined(&getCODE())) {
1.1133 foxr 10232:
1.675 albertel 10233: if ($which eq '64bit5') {
10234: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10235: } elsif ($which eq '64bit4') {
1.575 albertel 10236: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10237: } else {
10238: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10239: }
1.675 albertel 10240: } elsif ($which eq '64bit5') {
10241: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 10242: } elsif ($which eq '64bit4') {
10243: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 10244: } elsif ($which eq '64bit3') {
10245: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 10246: } elsif ($which eq '64bit2') {
10247: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 10248: } elsif ($which eq '64bit') {
10249: return &rndseed_64bit($symb,$courseid,$domain,$username);
10250: }
10251: return &rndseed_32bit($symb,$courseid,$domain,$username);
10252: }
10253:
10254: sub rndseed_32bit {
10255: my ($symb,$courseid,$domain,$username)=@_;
10256: {
10257: use integer;
10258: my $symbchck=unpack("%32C*",$symb) << 27;
10259: my $symbseed=numval($symb) << 22;
10260: my $namechck=unpack("%32C*",$username) << 17;
10261: my $nameseed=numval($username) << 12;
10262: my $domainseed=unpack("%32C*",$domain) << 7;
10263: my $courseseed=unpack("%32C*",$courseid);
10264: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 10265: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10266: #&logthis("rndseed :$num:$symb");
1.564 albertel 10267: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 10268: return $num;
10269: }
10270: }
10271:
10272: sub rndseed_64bit {
10273: my ($symb,$courseid,$domain,$username)=@_;
10274: {
10275: use integer;
10276: my $symbchck=unpack("%32S*",$symb) << 21;
10277: my $symbseed=numval($symb) << 10;
10278: my $namechck=unpack("%32S*",$username);
10279:
10280: my $nameseed=numval($username) << 21;
10281: my $domainseed=unpack("%32S*",$domain) << 10;
10282: my $courseseed=unpack("%32S*",$courseid);
10283:
10284: my $num1=$symbchck+$symbseed+$namechck;
10285: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10286: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10287: #&logthis("rndseed :$num:$symb");
1.564 albertel 10288: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 10289: return "$num1,$num2";
1.155 albertel 10290: }
1.366 albertel 10291: }
10292:
1.443 albertel 10293: sub rndseed_64bit2 {
10294: my ($symb,$courseid,$domain,$username)=@_;
10295: {
10296: use integer;
10297: # strings need to be an even # of cahracters long, it it is odd the
10298: # last characters gets thrown away
10299: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10300: my $symbseed=numval($symb) << 10;
10301: my $namechck=unpack("%32S*",$username.' ');
10302:
10303: my $nameseed=numval($username) << 21;
1.501 albertel 10304: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10305: my $courseseed=unpack("%32S*",$courseid.' ');
10306:
10307: my $num1=$symbchck+$symbseed+$namechck;
10308: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10309: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10310: #&logthis("rndseed :$num:$symb");
1.803 albertel 10311: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 10312: return "$num1,$num2";
10313: }
10314: }
10315:
10316: sub rndseed_64bit3 {
10317: my ($symb,$courseid,$domain,$username)=@_;
10318: {
10319: use integer;
10320: # strings need to be an even # of cahracters long, it it is odd the
10321: # last characters gets thrown away
10322: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10323: my $symbseed=numval2($symb) << 10;
10324: my $namechck=unpack("%32S*",$username.' ');
10325:
10326: my $nameseed=numval2($username) << 21;
1.443 albertel 10327: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10328: my $courseseed=unpack("%32S*",$courseid.' ');
10329:
10330: my $num1=$symbchck+$symbseed+$namechck;
10331: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10332: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10333: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 10334: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 10335:
1.503 albertel 10336: return "$num1:$num2";
1.443 albertel 10337: }
10338: }
10339:
1.575 albertel 10340: sub rndseed_64bit4 {
10341: my ($symb,$courseid,$domain,$username)=@_;
10342: {
10343: use integer;
10344: # strings need to be an even # of cahracters long, it it is odd the
10345: # last characters gets thrown away
10346: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10347: my $symbseed=numval3($symb) << 10;
10348: my $namechck=unpack("%32S*",$username.' ');
10349:
10350: my $nameseed=numval3($username) << 21;
10351: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10352: my $courseseed=unpack("%32S*",$courseid.' ');
10353:
10354: my $num1=$symbchck+$symbseed+$namechck;
10355: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10356: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10357: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 10358: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 10359:
1.575 albertel 10360: return "$num1:$num2";
10361: }
10362: }
10363:
1.675 albertel 10364: sub rndseed_64bit5 {
10365: my ($symb,$courseid,$domain,$username)=@_;
10366: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10367: return "$num1:$num2";
10368: }
10369:
1.366 albertel 10370: sub rndseed_CODE_64bit {
10371: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 10372: {
1.366 albertel 10373: use integer;
1.443 albertel 10374: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 10375: my $symbseed=numval2($symb);
1.491 albertel 10376: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10377: my $CODEseed=numval(&getCODE());
1.443 albertel 10378: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 10379: my $num1=$symbseed+$CODEchck;
10380: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 10381: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10382: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 10383: if ($_64bit) { $num1=(($num1<<32)>>32); }
10384: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 10385: return "$num1:$num2";
1.366 albertel 10386: }
10387: }
10388:
1.575 albertel 10389: sub rndseed_CODE_64bit4 {
10390: my ($symb,$courseid,$domain,$username)=@_;
10391: {
10392: use integer;
10393: my $symbchck=unpack("%32S*",$symb.' ') << 16;
10394: my $symbseed=numval3($symb);
10395: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10396: my $CODEseed=numval3(&getCODE());
10397: my $courseseed=unpack("%32S*",$courseid.' ');
10398: my $num1=$symbseed+$CODEchck;
10399: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 10400: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10401: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 10402: if ($_64bit) { $num1=(($num1<<32)>>32); }
10403: if ($_64bit) { $num2=(($num2<<32)>>32); }
10404: return "$num1:$num2";
10405: }
10406: }
10407:
1.675 albertel 10408: sub rndseed_CODE_64bit5 {
10409: my ($symb,$courseid,$domain,$username)=@_;
10410: my $code = &getCODE();
10411: my ($num1,$num2)=&digest("$symb,$courseid,$code");
10412: return "$num1:$num2";
10413: }
10414:
1.366 albertel 10415: sub setup_random_from_rndseed {
10416: my ($rndseed)=@_;
1.503 albertel 10417: if ($rndseed =~/([,:])/) {
10418: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 10419: &Math::Random::random_set_seed(abs($num1),abs($num2));
10420: } else {
10421: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 10422: }
1.36 albertel 10423: }
10424:
1.474 albertel 10425: sub latest_receipt_algorithm_id {
1.835 albertel 10426: return 'receipt3';
1.474 albertel 10427: }
10428:
1.480 www 10429: sub recunique {
10430: my $fucourseid=shift;
10431: my $unique;
1.835 albertel 10432: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10433: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 10434: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 10435: } else {
10436: $unique=$perlvar{'lonReceipt'};
10437: }
10438: return unpack("%32C*",$unique);
10439: }
10440:
10441: sub recprefix {
10442: my $fucourseid=shift;
10443: my $prefix;
1.835 albertel 10444: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10445: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 10446: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 10447: } else {
10448: $prefix=$perlvar{'lonHostID'};
10449: }
10450: return unpack("%32C*",$prefix);
10451: }
10452:
1.76 www 10453: sub ireceipt {
1.474 albertel 10454: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 10455:
10456: my $return =&recprefix($fucourseid).'-';
10457:
10458: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10459: $env{'request.state'} eq 'construct') {
10460: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10461: return $return;
10462: }
10463:
1.76 www 10464: my $cuname=unpack("%32C*",$funame);
10465: my $cudom=unpack("%32C*",$fudom);
10466: my $cucourseid=unpack("%32C*",$fucourseid);
10467: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 10468: my $cunique=&recunique($fucourseid);
1.474 albertel 10469: my $cpart=unpack("%32S*",$part);
1.835 albertel 10470: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10471:
1.790 albertel 10472: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 10473:
10474: $return.= ($cunique%$cuname+
10475: $cunique%$cudom+
10476: $cusymb%$cuname+
10477: $cusymb%$cudom+
10478: $cucourseid%$cuname+
10479: $cucourseid%$cudom+
10480: $cpart%$cuname+
10481: $cpart%$cudom);
10482: } else {
10483: $return.= ($cunique%$cuname+
10484: $cunique%$cudom+
10485: $cusymb%$cuname+
10486: $cusymb%$cudom+
10487: $cucourseid%$cuname+
10488: $cucourseid%$cudom);
10489: }
10490: return $return;
1.76 www 10491: }
10492:
10493: sub receipt {
1.474 albertel 10494: my ($part)=@_;
1.790 albertel 10495: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 10496: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 10497: }
1.260 ng 10498:
1.790 albertel 10499: sub whichuser {
10500: my ($passedsymb)=@_;
10501: my ($symb,$courseid,$domain,$name,$publicuser);
10502: if (defined($env{'form.grade_symb'})) {
10503: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10504: my $allowed=&allowed('vgr',$tmp_courseid);
10505: if (!$allowed &&
10506: exists($env{'request.course.sec'}) &&
10507: $env{'request.course.sec'} !~ /^\s*$/) {
10508: $allowed=&allowed('vgr',$tmp_courseid.
10509: '/'.$env{'request.course.sec'});
10510: }
10511: if ($allowed) {
10512: ($symb)=&get_env_multiple('form.grade_symb');
10513: $courseid=$tmp_courseid;
10514: ($domain)=&get_env_multiple('form.grade_domain');
10515: ($name)=&get_env_multiple('form.grade_username');
10516: return ($symb,$courseid,$domain,$name,$publicuser);
10517: }
10518: }
10519: if (!$passedsymb) {
10520: $symb=&symbread();
10521: } else {
10522: $symb=$passedsymb;
10523: }
10524: $courseid=$env{'request.course.id'};
10525: $domain=$env{'user.domain'};
10526: $name=$env{'user.name'};
10527: if ($name eq 'public' && $domain eq 'public') {
10528: if (!defined($env{'form.username'})) {
10529: $env{'form.username'}.=time.rand(10000000);
10530: }
10531: $name.=$env{'form.username'};
10532: }
10533: return ($symb,$courseid,$domain,$name,$publicuser);
10534:
10535: }
10536:
1.36 albertel 10537: # ------------------------------------------------------------ Serves up a file
1.472 albertel 10538: # returns either the contents of the file or
10539: # -1 if the file doesn't exist
1.481 raeburn 10540: #
10541: # if the target is a file that was uploaded via DOCS,
10542: # a check will be made to see if a current copy exists on the local server,
10543: # if it does this will be served, otherwise a copy will be retrieved from
10544: # the home server for the course and stored in /home/httpd/html/userfiles on
10545: # the local server.
1.472 albertel 10546:
1.36 albertel 10547: sub getfile {
1.538 albertel 10548: my ($file) = @_;
1.609 banghart 10549: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 10550: &repcopy($file);
10551: return &readfile($file);
10552: }
10553:
10554: sub repcopy_userfile {
10555: my ($file)=@_;
1.1142 raeburn 10556: my $londocroot = $perlvar{'lonDocRoot'};
10557: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 10558: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 10559: my ($cdom,$cnum,$filename) =
1.811 albertel 10560: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 10561: my $uri="/uploaded/$cdom/$cnum/$filename";
10562: if (-e "$file") {
1.828 www 10563: # we already have a local copy, check it out
1.538 albertel 10564: my @fileinfo = stat($file);
1.828 www 10565: my $rtncode;
10566: my $info;
1.538 albertel 10567: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 10568: if ($lwpresp ne 'ok') {
1.828 www 10569: # there is no such file anymore, even though we had a local copy
1.482 albertel 10570: if ($rtncode eq '404') {
1.538 albertel 10571: unlink($file);
1.482 albertel 10572: }
10573: return -1;
10574: }
10575: if ($info < $fileinfo[9]) {
1.828 www 10576: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 10577: return 'ok';
1.828 www 10578: } else {
10579: # the file is outdated, get rid of it
10580: unlink($file);
1.482 albertel 10581: }
1.828 www 10582: }
10583: # one way or the other, at this point, we don't have the file
10584: # construct the correct path for the file
10585: my @parts = ($cdom,$cnum);
10586: if ($filename =~ m|^(.+)/[^/]+$|) {
10587: push @parts, split(/\//,$1);
10588: }
10589: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10590: foreach my $part (@parts) {
10591: $path .= '/'.$part;
10592: if (!-e $path) {
10593: mkdir($path,0770);
1.482 albertel 10594: }
10595: }
1.828 www 10596: # now the path exists for sure
10597: # get a user agent
10598: my $ua=new LWP::UserAgent;
10599: my $transferfile=$file.'.in.transfer';
10600: # FIXME: this should flock
10601: if (-e $transferfile) { return 'ok'; }
10602: my $request;
10603: $uri=~s/^\///;
1.980 raeburn 10604: my $homeserver = &homeserver($cnum,$cdom);
10605: my $protocol = $protocol{$homeserver};
10606: $protocol = 'http' if ($protocol ne 'https');
10607: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 10608: my $response=$ua->request($request,$transferfile);
10609: # did it work?
10610: if ($response->is_error()) {
10611: unlink($transferfile);
10612: &logthis("Userfile repcopy failed for $uri");
10613: return -1;
10614: }
10615: # worked, rename the transfer file
10616: rename($transferfile,$file);
1.607 raeburn 10617: return 'ok';
1.481 raeburn 10618: }
10619:
1.517 albertel 10620: sub tokenwrapper {
10621: my $uri=shift;
1.980 raeburn 10622: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 10623: $uri=~s|^/||;
1.620 albertel 10624: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 10625: my $token=$1;
1.552 albertel 10626: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10627: if ($udom && $uname && $file) {
10628: $file=~s|(\?\.*)*$||;
1.949 raeburn 10629: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 10630: my $homeserver = &homeserver($uname,$udom);
10631: my $protocol = $protocol{$homeserver};
10632: $protocol = 'http' if ($protocol ne 'https');
10633: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 10634: (($uri=~/\?/)?'&':'?').'token='.$token.
10635: '&tokenissued='.$perlvar{'lonHostID'};
10636: } else {
10637: return '/adm/notfound.html';
10638: }
10639: }
10640:
1.828 www 10641: # call with reqtype HEAD: get last modification time
10642: # call with reqtype GET: get the file contents
10643: # Do not call this with reqtype GET for large files! It loads everything into memory
10644: #
1.481 raeburn 10645: sub getuploaded {
10646: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10647: $uri=~s/^\///;
1.980 raeburn 10648: my $homeserver = &homeserver($cnum,$cdom);
10649: my $protocol = $protocol{$homeserver};
10650: $protocol = 'http' if ($protocol ne 'https');
10651: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 10652: my $ua=new LWP::UserAgent;
10653: my $request=new HTTP::Request($reqtype,$uri);
10654: my $response=$ua->request($request);
10655: $$rtncode = $response->code;
1.482 albertel 10656: if (! $response->is_success()) {
10657: return 'failed';
10658: }
10659: if ($reqtype eq 'HEAD') {
1.486 www 10660: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 10661: } elsif ($reqtype eq 'GET') {
10662: $$info = $response->content;
1.472 albertel 10663: }
1.482 albertel 10664: return 'ok';
1.36 albertel 10665: }
10666:
1.481 raeburn 10667: sub readfile {
10668: my $file = shift;
10669: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10670: my $fh;
10671: open($fh,"<$file");
10672: my $a='';
1.800 albertel 10673: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 10674: return $a;
10675: }
10676:
1.36 albertel 10677: sub filelocation {
1.590 banghart 10678: my ($dir,$file) = @_;
10679: my $location;
10680: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 10681:
10682: if ($file =~ m-^/adm/-) {
10683: $file=~s-^/adm/wrapper/-/-;
10684: $file=~s-^/adm/coursedocs/showdoc/-/-;
10685: }
1.882 albertel 10686:
1.1139 www 10687: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 10688: $location = $file;
1.609 banghart 10689: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 10690: my ($udom,$uname,$filename)=
1.811 albertel 10691: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 10692: my $home=&homeserver($uname,$udom);
10693: my $is_me=0;
10694: my @ids=¤t_machine_ids();
10695: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10696: if ($is_me) {
1.1117 foxr 10697: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 10698: } else {
10699: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10700: $udom.'/'.$uname.'/'.$filename;
10701: }
1.882 albertel 10702: } elsif ($file =~ m-^/adm/-) {
10703: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 10704: } else {
10705: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 10706: $file=~s:^/(res|priv)/:/:;
10707: my $space=$1;
1.590 banghart 10708: if ( !( $file =~ m:^/:) ) {
10709: $location = $dir. '/'.$file;
10710: } else {
1.1142 raeburn 10711: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 10712: }
1.59 albertel 10713: }
1.590 banghart 10714: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 10715: while ($location=~m{/\.\./}) {
10716: if ($location =~ m{/[^/]+/\.\./}) {
10717: $location=~ s{/[^/]+/\.\./}{/}g;
10718: } else {
10719: $location=~ s{/\.\./}{/}g;
10720: }
10721: } #remove dir/..
1.590 banghart 10722: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10723: return $location;
1.46 www 10724: }
1.36 albertel 10725:
1.46 www 10726: sub hreflocation {
10727: my ($dir,$file)=@_;
1.980 raeburn 10728: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 10729: $file=filelocation($dir,$file);
1.700 albertel 10730: } elsif ($file=~m-^/adm/-) {
10731: $file=~s-^/adm/wrapper/-/-;
10732: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 10733: }
10734: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10735: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10736: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 10737: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10738: {/uploaded/$1/$2/}x;
1.46 www 10739: }
1.913 albertel 10740: if ($file=~ m{^/userfiles/}) {
10741: $file =~ s{^/userfiles/}{/uploaded/};
10742: }
1.462 albertel 10743: return $file;
1.465 albertel 10744: }
10745:
1.1139 www 10746:
10747:
10748:
10749:
1.465 albertel 10750: sub current_machine_domains {
1.853 albertel 10751: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10752: }
10753:
10754: sub machine_domains {
10755: my ($hostname) = @_;
1.465 albertel 10756: my @domains;
1.838 albertel 10757: my %hostname = &all_hostnames();
1.465 albertel 10758: while( my($id, $name) = each(%hostname)) {
1.467 matthew 10759: # &logthis("-$id-$name-$hostname-");
1.465 albertel 10760: if ($hostname eq $name) {
1.844 albertel 10761: push(@domains,&host_domain($id));
1.465 albertel 10762: }
10763: }
10764: return @domains;
10765: }
10766:
10767: sub current_machine_ids {
1.853 albertel 10768: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10769: }
10770:
10771: sub machine_ids {
10772: my ($hostname) = @_;
10773: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 10774: my @ids;
1.888 albertel 10775: my %name_to_host = &all_names();
1.889 albertel 10776: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10777: return @{ $name_to_host{$hostname} };
10778: }
10779: return;
1.31 www 10780: }
10781:
1.824 raeburn 10782: sub additional_machine_domains {
10783: my @domains;
10784: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10785: while( my $line = <$fh>) {
10786: $line =~ s/\s//g;
10787: push(@domains,$line);
10788: }
10789: return @domains;
10790: }
10791:
10792: sub default_login_domain {
10793: my $domain = $perlvar{'lonDefDomain'};
10794: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10795: foreach my $posdom (¤t_machine_domains(),
10796: &additional_machine_domains()) {
10797: if (lc($posdom) eq lc($testdomain)) {
10798: $domain=$posdom;
10799: last;
10800: }
10801: }
10802: return $domain;
10803: }
10804:
1.31 www 10805: # ------------------------------------------------------------- Declutters URLs
10806:
10807: sub declutter {
10808: my $thisfn=shift;
1.569 albertel 10809: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 10810: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 10811: $thisfn=~s/^\///;
1.697 albertel 10812: $thisfn=~s|^adm/wrapper/||;
10813: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 10814: $thisfn=~s/^res\///;
1.1172 bisitz 10815: $thisfn=~s/^priv\///;
1.1032 raeburn 10816: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10817: $thisfn=~s/\?.+$//;
10818: }
1.268 www 10819: return $thisfn;
10820: }
10821:
10822: # ------------------------------------------------------------- Clutter up URLs
10823:
10824: sub clutter {
10825: my $thisfn='/'.&declutter(shift);
1.887 albertel 10826: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 10827: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 10828: $thisfn='/res'.$thisfn;
10829: }
1.1031 raeburn 10830: if ($thisfn !~m|^/adm|) {
10831: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 10832: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 10833: } else {
10834: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10835: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 10836: if ($embstyle eq 'ssi'
10837: || ($embstyle eq 'hdn')
10838: || ($embstyle eq 'rat')
10839: || ($embstyle eq 'prv')
10840: || ($embstyle eq 'ign')) {
10841: #do nothing with these
10842: } elsif (($embstyle eq 'img')
1.695 albertel 10843: || ($embstyle eq 'emb')
10844: || ($embstyle eq 'wrp')) {
10845: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 10846: } elsif ($embstyle eq 'unk'
10847: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 10848: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 10849: } else {
1.718 www 10850: # &logthis("Got a blank emb style");
1.695 albertel 10851: }
1.694 albertel 10852: }
10853: }
1.31 www 10854: return $thisfn;
1.12 www 10855: }
10856:
1.787 albertel 10857: sub clutter_with_no_wrapper {
10858: my $uri = &clutter(shift);
10859: if ($uri =~ m-^/adm/-) {
10860: $uri =~ s-^/adm/wrapper/-/-;
10861: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
10862: }
10863: return $uri;
10864: }
10865:
1.557 albertel 10866: sub freeze_escape {
10867: my ($value)=@_;
10868: if (ref($value)) {
10869: $value=&nfreeze($value);
10870: return '__FROZEN__'.&escape($value);
10871: }
10872: return &escape($value);
10873: }
10874:
1.11 www 10875:
1.557 albertel 10876: sub thaw_unescape {
10877: my ($value)=@_;
10878: if ($value =~ /^__FROZEN__/) {
10879: substr($value,0,10,undef);
10880: $value=&unescape($value);
10881: return &thaw($value);
10882: }
10883: return &unescape($value);
10884: }
10885:
1.436 albertel 10886: sub correct_line_ends {
10887: my ($result)=@_;
10888: $$result =~s/\r\n/\n/mg;
10889: $$result =~s/\r/\n/mg;
1.415 albertel 10890: }
1.1 albertel 10891: # ================================================================ Main Program
10892:
1.184 www 10893: sub goodbye {
1.204 albertel 10894: &logthis("Starting Shut down");
1.443 albertel 10895: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 10896: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 10897: #converted
1.599 albertel 10898: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 10899: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10900: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10901: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 10902: #1.1 only
1.870 albertel 10903: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10904: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10905: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10906: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10907: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 10908: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10909: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 10910: &flushcourselogs();
10911: &logthis("Shutting down");
10912: }
10913:
1.852 albertel 10914: sub get_dns {
1.869 albertel 10915: my ($url,$func,$ignore_cache) = @_;
10916: if (!$ignore_cache) {
10917: my ($content,$cached)=
10918: &Apache::lonnet::is_cached_new('dns',$url);
10919: if ($cached) {
10920: &$func($content);
10921: return;
10922: }
10923: }
10924:
10925: my %alldns;
1.852 albertel 10926: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10927: foreach my $dns (<$config>) {
10928: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 10929: my $line = $1;
10930: my ($host,$protocol) = split(/:/,$line);
10931: if ($protocol ne 'https') {
10932: $protocol = 'http';
10933: }
10934: $alldns{$host} = $protocol;
1.869 albertel 10935: }
10936: while (%alldns) {
10937: my ($dns) = keys(%alldns);
1.852 albertel 10938: my $ua=new LWP::UserAgent;
1.1134 raeburn 10939: $ua->timeout(30);
1.979 raeburn 10940: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 10941: my $response=$ua->request($request);
1.979 raeburn 10942: delete($alldns{$dns});
1.852 albertel 10943: next if ($response->is_error());
10944: my @content = split("\n",$response->content);
1.869 albertel 10945: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 10946: &$func(\@content);
1.869 albertel 10947: return;
1.852 albertel 10948: }
10949: close($config);
1.871 albertel 10950: my $which = (split('/',$url))[3];
10951: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10952: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 10953: my @content = <$config>;
10954: &$func(\@content);
10955: return;
1.852 albertel 10956: }
1.327 albertel 10957: # ------------------------------------------------------------ Read domain file
10958: {
1.852 albertel 10959: my $loaded;
1.846 albertel 10960: my %domain;
10961:
1.852 albertel 10962: sub parse_domain_tab {
10963: my ($lines) = @_;
10964: foreach my $line (@$lines) {
10965: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 10966:
1.846 albertel 10967: chomp($line);
1.852 albertel 10968: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 10969: my %this_domain;
10970: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10971: 'lang_def', 'city', 'longi', 'lati',
10972: 'primary') {
10973: $this_domain{$field} = shift(@elements);
10974: }
10975: $domain{$name} = \%this_domain;
1.852 albertel 10976: }
10977: }
1.864 albertel 10978:
10979: sub reset_domain_info {
10980: undef($loaded);
10981: undef(%domain);
10982: }
10983:
1.852 albertel 10984: sub load_domain_tab {
1.869 albertel 10985: my ($ignore_cache) = @_;
10986: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 10987: my $fh;
10988: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10989: my @lines = <$fh>;
10990: &parse_domain_tab(\@lines);
1.448 albertel 10991: }
1.852 albertel 10992: close($fh);
10993: $loaded = 1;
1.327 albertel 10994: }
1.846 albertel 10995:
10996: sub domain {
1.852 albertel 10997: &load_domain_tab() if (!$loaded);
10998:
1.846 albertel 10999: my ($name,$what) = @_;
11000: return if ( !exists($domain{$name}) );
11001:
11002: if (!$what) {
11003: return $domain{$name}{'description'};
11004: }
11005: return $domain{$name}{$what};
11006: }
1.974 raeburn 11007:
11008: sub domain_info {
11009: &load_domain_tab() if (!$loaded);
11010: return %domain;
11011: }
11012:
1.327 albertel 11013: }
11014:
11015:
1.1 albertel 11016: # ------------------------------------------------------------- Read hosts file
11017: {
1.838 albertel 11018: my %hostname;
1.844 albertel 11019: my %hostdom;
1.845 albertel 11020: my %libserv;
1.852 albertel 11021: my $loaded;
1.888 albertel 11022: my %name_to_host;
1.1074 raeburn 11023: my %internetdom;
1.1107 raeburn 11024: my %LC_dns_serv;
1.852 albertel 11025:
11026: sub parse_hosts_tab {
11027: my ($file) = @_;
11028: foreach my $configline (@$file) {
11029: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11030: chomp($configline);
11031: if ($configline =~ /^\^/) {
11032: if ($configline =~ /^\^([\w.\-]+)/) {
11033: $LC_dns_serv{$1} = 1;
11034: }
11035: next;
11036: }
1.1074 raeburn 11037: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11038: $name=~s/\s//g;
11039: if ($id && $domain && $role && $name) {
11040: $hostname{$id}=$name;
1.888 albertel 11041: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11042: $hostdom{$id}=$domain;
11043: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11044: if (defined($protocol)) {
11045: if ($protocol eq 'https') {
11046: $protocol{$id} = $protocol;
11047: } else {
11048: $protocol{$id} = 'http';
11049: }
1.968 raeburn 11050: } else {
1.969 raeburn 11051: $protocol{$id} = 'http';
1.968 raeburn 11052: }
1.1074 raeburn 11053: if (defined($intdom)) {
11054: $internetdom{$id} = $intdom;
11055: }
1.852 albertel 11056: }
11057: }
11058: }
1.864 albertel 11059:
11060: sub reset_hosts_info {
1.897 albertel 11061: &purge_remembered();
1.864 albertel 11062: &reset_domain_info();
11063: &reset_hosts_ip_info();
1.892 albertel 11064: undef(%name_to_host);
1.864 albertel 11065: undef(%hostname);
11066: undef(%hostdom);
11067: undef(%libserv);
11068: undef($loaded);
11069: }
1.1 albertel 11070:
1.852 albertel 11071: sub load_hosts_tab {
1.869 albertel 11072: my ($ignore_cache) = @_;
11073: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11074: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11075: my @config = <$config>;
11076: &parse_hosts_tab(\@config);
11077: close($config);
11078: $loaded=1;
1.1 albertel 11079: }
1.852 albertel 11080:
1.838 albertel 11081: sub hostname {
1.852 albertel 11082: &load_hosts_tab() if (!$loaded);
11083:
1.838 albertel 11084: my ($lonid) = @_;
11085: return $hostname{$lonid};
11086: }
1.845 albertel 11087:
1.838 albertel 11088: sub all_hostnames {
1.852 albertel 11089: &load_hosts_tab() if (!$loaded);
11090:
1.838 albertel 11091: return %hostname;
11092: }
1.845 albertel 11093:
1.888 albertel 11094: sub all_names {
11095: &load_hosts_tab() if (!$loaded);
11096:
11097: return %name_to_host;
11098: }
11099:
1.974 raeburn 11100: sub all_host_domain {
11101: &load_hosts_tab() if (!$loaded);
11102: return %hostdom;
11103: }
11104:
1.845 albertel 11105: sub is_library {
1.852 albertel 11106: &load_hosts_tab() if (!$loaded);
11107:
1.845 albertel 11108: return exists($libserv{$_[0]});
11109: }
11110:
11111: sub all_library {
1.852 albertel 11112: &load_hosts_tab() if (!$loaded);
11113:
1.845 albertel 11114: return %libserv;
11115: }
11116:
1.1062 droeschl 11117: sub unique_library {
11118: #2x reverse removes all hostnames that appear more than once
11119: my %unique = reverse &all_library();
11120: return reverse %unique;
11121: }
11122:
1.841 albertel 11123: sub get_servers {
1.852 albertel 11124: &load_hosts_tab() if (!$loaded);
11125:
1.841 albertel 11126: my ($domain,$type) = @_;
11127: my %possible_hosts = ($type eq 'library') ? %libserv
11128: : %hostname;
11129: my %result;
1.842 albertel 11130: if (ref($domain) eq 'ARRAY') {
11131: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 11132: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 11133: $result{$host} = $hostname;
11134: }
11135: }
11136: } else {
11137: while ( my ($host,$hostname) = each(%possible_hosts)) {
11138: if ($hostdom{$host} eq $domain) {
11139: $result{$host} = $hostname;
11140: }
1.841 albertel 11141: }
11142: }
11143: return %result;
11144: }
1.845 albertel 11145:
1.1062 droeschl 11146: sub get_unique_servers {
11147: my %unique = reverse &get_servers(@_);
11148: return reverse %unique;
11149: }
11150:
1.844 albertel 11151: sub host_domain {
1.852 albertel 11152: &load_hosts_tab() if (!$loaded);
11153:
1.844 albertel 11154: my ($lonid) = @_;
11155: return $hostdom{$lonid};
11156: }
11157:
1.841 albertel 11158: sub all_domains {
1.852 albertel 11159: &load_hosts_tab() if (!$loaded);
11160:
1.841 albertel 11161: my %seen;
11162: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11163: return @uniq;
11164: }
1.1074 raeburn 11165:
11166: sub internet_dom {
11167: &load_hosts_tab() if (!$loaded);
11168:
11169: my ($lonid) = @_;
11170: return $internetdom{$lonid};
11171: }
1.1107 raeburn 11172:
11173: sub is_LC_dns {
11174: &load_hosts_tab() if (!$loaded);
11175:
11176: my ($hostname) = @_;
11177: return exists($LC_dns_serv{$hostname});
11178: }
11179:
1.1 albertel 11180: }
11181:
1.847 albertel 11182: {
11183: my %iphost;
1.856 albertel 11184: my %name_to_ip;
11185: my %lonid_to_ip;
1.869 albertel 11186:
1.847 albertel 11187: sub get_hosts_from_ip {
11188: my ($ip) = @_;
11189: my %iphosts = &get_iphost();
11190: if (ref($iphosts{$ip})) {
11191: return @{$iphosts{$ip}};
11192: }
11193: return;
1.839 albertel 11194: }
1.864 albertel 11195:
11196: sub reset_hosts_ip_info {
11197: undef(%iphost);
11198: undef(%name_to_ip);
11199: undef(%lonid_to_ip);
11200: }
1.856 albertel 11201:
11202: sub get_host_ip {
11203: my ($lonid) = @_;
11204: if (exists($lonid_to_ip{$lonid})) {
11205: return $lonid_to_ip{$lonid};
11206: }
11207: my $name=&hostname($lonid);
11208: my $ip = gethostbyname($name);
11209: return if (!$ip || length($ip) ne 4);
11210: $ip=inet_ntoa($ip);
11211: $name_to_ip{$name} = $ip;
11212: $lonid_to_ip{$lonid} = $ip;
11213: return $ip;
11214: }
1.847 albertel 11215:
11216: sub get_iphost {
1.869 albertel 11217: my ($ignore_cache) = @_;
1.894 albertel 11218:
1.869 albertel 11219: if (!$ignore_cache) {
11220: if (%iphost) {
11221: return %iphost;
11222: }
11223: my ($ip_info,$cached)=
11224: &Apache::lonnet::is_cached_new('iphost','iphost');
11225: if ($cached) {
11226: %iphost = %{$ip_info->[0]};
11227: %name_to_ip = %{$ip_info->[1]};
11228: %lonid_to_ip = %{$ip_info->[2]};
11229: return %iphost;
11230: }
11231: }
1.894 albertel 11232:
11233: # get yesterday's info for fallback
11234: my %old_name_to_ip;
11235: my ($ip_info,$cached)=
11236: &Apache::lonnet::is_cached_new('iphost','iphost');
11237: if ($cached) {
11238: %old_name_to_ip = %{$ip_info->[1]};
11239: }
11240:
1.888 albertel 11241: my %name_to_host = &all_names();
11242: foreach my $name (keys(%name_to_host)) {
1.847 albertel 11243: my $ip;
11244: if (!exists($name_to_ip{$name})) {
11245: $ip = gethostbyname($name);
11246: if (!$ip || length($ip) ne 4) {
1.894 albertel 11247: if (defined($old_name_to_ip{$name})) {
11248: $ip = $old_name_to_ip{$name};
11249: &logthis("Can't find $name defaulting to old $ip");
11250: } else {
11251: &logthis("Name $name no IP found");
11252: next;
11253: }
11254: } else {
11255: $ip=inet_ntoa($ip);
1.847 albertel 11256: }
11257: $name_to_ip{$name} = $ip;
11258: } else {
11259: $ip = $name_to_ip{$name};
1.653 albertel 11260: }
1.888 albertel 11261: foreach my $id (@{ $name_to_host{$name} }) {
11262: $lonid_to_ip{$id} = $ip;
11263: }
11264: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 11265: }
1.869 albertel 11266: &Apache::lonnet::do_cache_new('iphost','iphost',
11267: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 11268: 48*60*60);
1.869 albertel 11269:
1.847 albertel 11270: return %iphost;
1.598 albertel 11271: }
11272:
1.992 raeburn 11273: #
11274: # Given a DNS returns the loncapa host name for that DNS
11275: #
11276: sub host_from_dns {
11277: my ($dns) = @_;
11278: my @hosts;
11279: my $ip;
11280:
1.993 raeburn 11281: if (exists($name_to_ip{$dns})) {
1.992 raeburn 11282: $ip = $name_to_ip{$dns};
11283: }
11284: if (!$ip) {
11285: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11286: if (length($ip) == 4) {
11287: $ip = &IO::Socket::inet_ntoa($ip);
11288: }
11289: }
11290: if ($ip) {
11291: @hosts = get_hosts_from_ip($ip);
11292: return $hosts[0];
11293: }
11294: return undef;
1.986 foxr 11295: }
1.992 raeburn 11296:
1.1074 raeburn 11297: sub get_internet_names {
11298: my ($lonid) = @_;
11299: return if ($lonid eq '');
11300: my ($idnref,$cached)=
11301: &Apache::lonnet::is_cached_new('internetnames',$lonid);
11302: if ($cached) {
11303: return $idnref;
11304: }
11305: my $ip = &get_host_ip($lonid);
11306: my @hosts = &get_hosts_from_ip($ip);
11307: my %iphost = &get_iphost();
11308: my (@idns,%seen);
11309: foreach my $id (@hosts) {
11310: my $dom = &host_domain($id);
11311: my $prim_id = &domain($dom,'primary');
11312: my $prim_ip = &get_host_ip($prim_id);
11313: next if ($seen{$prim_ip});
11314: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11315: foreach my $id (@{$iphost{$prim_ip}}) {
11316: my $intdom = &internet_dom($id);
11317: unless (grep(/^\Q$intdom\E$/,@idns)) {
11318: push(@idns,$intdom);
11319: }
11320: }
11321: }
11322: $seen{$prim_ip} = 1;
11323: }
11324: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11325: }
11326:
1.986 foxr 11327: }
11328:
1.1079 raeburn 11329: sub all_loncaparevs {
11330: 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);
11331: }
11332:
1.862 albertel 11333: BEGIN {
11334:
11335: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11336: unless ($readit) {
11337: {
11338: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11339: %perlvar = (%perlvar,%{$configvars});
11340: }
11341:
11342:
1.1 albertel 11343: # ------------------------------------------------------ Read spare server file
11344: {
1.448 albertel 11345: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 11346:
11347: while (my $configline=<$config>) {
11348: chomp($configline);
1.284 matthew 11349: if ($configline) {
1.784 albertel 11350: my ($host,$type) = split(':',$configline,2);
1.785 albertel 11351: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 11352: push(@{ $spareid{$type} }, $host);
1.1 albertel 11353: }
11354: }
1.448 albertel 11355: close($config);
1.1 albertel 11356: }
1.11 www 11357: # ------------------------------------------------------------ Read permissions
11358: {
1.448 albertel 11359: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 11360:
11361: while (my $configline=<$config>) {
1.448 albertel 11362: chomp($configline);
11363: if ($configline) {
11364: my ($role,$perm)=split(/ /,$configline);
11365: if ($perm ne '') { $pr{$role}=$perm; }
11366: }
1.11 www 11367: }
1.448 albertel 11368: close($config);
1.11 www 11369: }
11370:
11371: # -------------------------------------------- Read plain texts for permissions
11372: {
1.448 albertel 11373: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 11374:
11375: while (my $configline=<$config>) {
1.448 albertel 11376: chomp($configline);
11377: if ($configline) {
1.742 raeburn 11378: my ($short,@plain)=split(/:/,$configline);
11379: %{$prp{$short}} = ();
11380: if (@plain > 0) {
11381: $prp{$short}{'std'} = $plain[0];
11382: for (my $i=1; $i<@plain; $i++) {
11383: $prp{$short}{'alt'.$i} = $plain[$i];
11384: }
11385: }
1.448 albertel 11386: }
1.135 www 11387: }
1.448 albertel 11388: close($config);
1.135 www 11389: }
11390:
11391: # ---------------------------------------------------------- Read package table
11392: {
1.448 albertel 11393: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 11394:
11395: while (my $configline=<$config>) {
1.483 albertel 11396: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 11397: chomp($configline);
11398: my ($short,$plain)=split(/:/,$configline);
11399: my ($pack,$name)=split(/\&/,$short);
11400: if ($plain ne '') {
11401: $packagetab{$pack.'&'.$name.'&name'}=$name;
11402: $packagetab{$short}=$plain;
11403: }
1.11 www 11404: }
1.448 albertel 11405: close($config);
1.329 matthew 11406: }
11407:
1.1073 raeburn 11408: # ---------------------------------------------------------- Read loncaparev table
11409: {
11410: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11411: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11412: while (my $configline=<$config>) {
11413: chomp($configline);
11414: my ($hostid,$loncaparev)=split(/:/,$configline);
11415: $loncaparevs{$hostid}=$loncaparev;
11416: }
11417: close($config);
11418: }
11419: }
11420: }
11421:
1.1074 raeburn 11422: # ---------------------------------------------------------- Read serverhostID table
11423: {
11424: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11425: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11426: while (my $configline=<$config>) {
11427: chomp($configline);
11428: my ($name,$id)=split(/:/,$configline);
11429: $serverhomeIDs{$name}=$id;
11430: }
11431: close($config);
11432: }
11433: }
11434: }
11435:
1.1079 raeburn 11436: {
11437: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11438: if (-e $file) {
11439: my $parser = HTML::LCParser->new($file);
11440: while (my $token = $parser->get_token()) {
11441: if ($token->[0] eq 'S') {
11442: my $item = $token->[1];
11443: my $name = $token->[2]{'name'};
11444: my $value = $token->[2]{'value'};
11445: if ($item ne '' && $name ne '' && $value ne '') {
11446: my $release = $parser->get_text();
11447: $release =~ s/(^\s*|\s*$ )//gx;
11448: $needsrelease{$item.':'.$name.':'.$value} = $release;
11449: }
11450: }
11451: }
11452: }
1.1073 raeburn 11453: }
11454:
1.1138 raeburn 11455: # ---------------------------------------------------------- Read managers table
11456: {
11457: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11458: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11459: while (my $configline=<$config>) {
11460: chomp($configline);
11461: next if ($configline =~ /^\#/);
11462: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11463: $managerstab{$configline} = 1;
11464: }
11465: }
11466: close($config);
11467: }
11468: }
11469: }
11470:
1.329 matthew 11471: # ------------- set up temporary directory
11472: {
1.1117 foxr 11473: $tmpdir = LONCAPA::tempdir();
1.329 matthew 11474:
1.11 www 11475: }
11476:
1.794 albertel 11477: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
11478: 'compress_threshold'=> 20_000,
11479: });
1.185 www 11480:
1.281 www 11481: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 11482: $dumpcount=0;
1.958 www 11483: $locknum=0;
1.22 www 11484:
1.163 harris41 11485: &logtouch();
1.672 albertel 11486: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 11487: $readit=1;
1.564 albertel 11488: {
11489: use integer;
11490: my $test=(2**32)+1;
1.568 albertel 11491: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 11492: &logthis(" Detected 64bit platform ($_64bit)");
11493: }
1.195 www 11494: }
1.1 albertel 11495: }
1.179 www 11496:
1.1 albertel 11497: 1;
1.191 harris41 11498: __END__
11499:
1.243 albertel 11500: =pod
11501:
1.191 harris41 11502: =head1 NAME
11503:
1.243 albertel 11504: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 11505:
11506: =head1 SYNOPSIS
11507:
1.243 albertel 11508: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 11509:
11510: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11511:
1.243 albertel 11512: Common parameters:
11513:
11514: =over 4
11515:
11516: =item *
11517:
11518: $uname : an internal username (if $cname expecting a course Id specifically)
11519:
11520: =item *
11521:
11522: $udom : a domain (if $cdom expecting a course's domain specifically)
11523:
11524: =item *
11525:
11526: $symb : a resource instance identifier
11527:
11528: =item *
11529:
11530: $namespace : the name of a .db file that contains the data needed or
11531: being set.
11532:
11533: =back
11534:
1.394 bowersj2 11535: =head1 OVERVIEW
1.191 harris41 11536:
1.394 bowersj2 11537: lonnet provides subroutines which interact with the
11538: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11539: about classes, users, and resources.
1.243 albertel 11540:
11541: For many of these objects you can also use this to store data about
11542: them or modify them in various ways.
1.191 harris41 11543:
1.394 bowersj2 11544: =head2 Symbs
1.191 harris41 11545:
1.394 bowersj2 11546: To identify a specific instance of a resource, LON-CAPA uses symbols
11547: or "symbs"X<symb>. These identifiers are built from the URL of the
11548: map, the resource number of the resource in the map, and the URL of
11549: the resource itself. The latter is somewhat redundant, but might help
11550: if maps change.
11551:
11552: An example is
11553:
11554: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11555:
11556: The respective map entry is
11557:
11558: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11559: title="Problem 2">
11560: </resource>
11561:
11562: Symbs are used by the random number generator, as well as to store and
11563: restore data specific to a certain instance of for example a problem.
11564:
11565: =head2 Storing And Retrieving Data
11566:
11567: X<store()>X<cstore()>X<restore()>Three of the most important functions
11568: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11569: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11570: is is the non-critical message twin of cstore. These functions are for
11571: handlers to store a perl hash to a user's permanent data space in an
11572: easy manner, and to retrieve it again on another call. It is expected
11573: that a handler would use this once at the beginning to retrieve data,
11574: and then again once at the end to send only the new data back.
11575:
11576: The data is stored in the user's data directory on the user's
11577: homeserver under the ID of the course.
11578:
11579: The hash that is returned by restore will have all of the previous
11580: value for all of the elements of the hash.
11581:
11582: Example:
11583:
11584: #creating a hash
11585: my %hash;
11586: $hash{'foo'}='bar';
11587:
11588: #storing it
11589: &Apache::lonnet::cstore(\%hash);
11590:
11591: #changing a value
11592: $hash{'foo'}='notbar';
11593:
11594: #adding a new value
11595: $hash{'bar'}='foo';
11596: &Apache::lonnet::cstore(\%hash);
11597:
11598: #retrieving the hash
11599: my %history=&Apache::lonnet::restore();
11600:
11601: #print the hash
11602: foreach my $key (sort(keys(%history))) {
11603: print("\%history{$key} = $history{$key}");
11604: }
11605:
11606: Will print out:
1.191 harris41 11607:
1.394 bowersj2 11608: %history{1:foo} = bar
11609: %history{1:keys} = foo:timestamp
11610: %history{1:timestamp} = 990455579
11611: %history{2:bar} = foo
11612: %history{2:foo} = notbar
11613: %history{2:keys} = foo:bar:timestamp
11614: %history{2:timestamp} = 990455580
11615: %history{bar} = foo
11616: %history{foo} = notbar
11617: %history{timestamp} = 990455580
11618: %history{version} = 2
11619:
11620: Note that the special hash entries C<keys>, C<version> and
11621: C<timestamp> were added to the hash. C<version> will be equal to the
11622: total number of versions of the data that have been stored. The
11623: C<timestamp> attribute will be the UNIX time the hash was
11624: stored. C<keys> is available in every historical section to list which
11625: keys were added or changed at a specific historical revision of a
11626: hash.
11627:
11628: B<Warning>: do not store the hash that restore returns directly. This
11629: will cause a mess since it will restore the historical keys as if the
11630: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 11631:
1.394 bowersj2 11632: Calling convention:
1.191 harris41 11633:
1.394 bowersj2 11634: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11635: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 11636:
1.394 bowersj2 11637: For more detailed information, see lonnet specific documentation.
1.191 harris41 11638:
1.394 bowersj2 11639: =head1 RETURN MESSAGES
1.191 harris41 11640:
1.394 bowersj2 11641: =over 4
1.191 harris41 11642:
1.394 bowersj2 11643: =item * B<con_lost>: unable to contact remote host
1.191 harris41 11644:
1.394 bowersj2 11645: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11646: when the connection is brought back up
1.191 harris41 11647:
1.394 bowersj2 11648: =item * B<con_failed>: unable to contact remote host and unable to save message
11649: for later delivery
1.191 harris41 11650:
1.967 bisitz 11651: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 11652:
1.394 bowersj2 11653: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 11654: that was requested
1.191 harris41 11655:
1.243 albertel 11656: =back
1.191 harris41 11657:
1.243 albertel 11658: =head1 PUBLIC SUBROUTINES
1.191 harris41 11659:
1.243 albertel 11660: =head2 Session Environment Functions
1.191 harris41 11661:
1.243 albertel 11662: =over 4
1.191 harris41 11663:
1.394 bowersj2 11664: =item *
11665: X<appenv()>
1.949 raeburn 11666: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 11667: the user envirnoment file, and will be restored for each access this
1.620 albertel 11668: user makes during this session, also modifies the %env for the current
1.949 raeburn 11669: process. Optional rolesarrayref - if defined contains a reference to an array
11670: of roles which are exempt from the restriction on modifying user.role entries
11671: in the user's environment.db and in %env.
1.191 harris41 11672:
11673: =item *
1.394 bowersj2 11674: X<delenv()>
1.987 raeburn 11675: B<delenv($delthis,$regexp)>: removes all items from the session
11676: environment file that begin with $delthis. If the
11677: optional second arg - $regexp - is true, $delthis is treated as a
11678: regular expression, otherwise \Q$delthis\E is used.
11679: The values are also deleted from the current processes %env.
1.191 harris41 11680:
1.795 albertel 11681: =item * get_env_multiple($name)
11682:
11683: gets $name from the %env hash, it seemlessly handles the cases where multiple
11684: values may be defined and end up as an array ref.
11685:
11686: returns an array of values
11687:
1.243 albertel 11688: =back
11689:
11690: =head2 User Information
1.191 harris41 11691:
1.243 albertel 11692: =over 4
1.191 harris41 11693:
11694: =item *
1.394 bowersj2 11695: X<queryauthenticate()>
11696: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 11697: authentication scheme
11698:
11699: =item *
1.394 bowersj2 11700: X<authenticate()>
1.1073 raeburn 11701: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 11702: authenticate user from domain's lib servers (first use the current
11703: one). C<$upass> should be the users password.
1.1073 raeburn 11704: $checkdefauth is optional (value is 1 if a check should be made to
11705: authenticate user using default authentication method, and allow
11706: account creation if username does not have account in the domain).
11707: $clientcancheckhost is optional (value is 1 if checking whether the
11708: server can host will occur on the client side in lonauth.pm).
1.191 harris41 11709:
11710: =item *
1.394 bowersj2 11711: X<homeserver()>
11712: B<homeserver($uname,$udom)>: find the server which has
11713: the user's directory and files (there must be only one), this caches
11714: the answer, and also caches if there is a borken connection.
1.191 harris41 11715:
11716: =item *
1.394 bowersj2 11717: X<idget()>
11718: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11719: (IDs are a unique resource in a domain, there must be only 1 ID per
11720: username, and only 1 username per ID in a specific domain) (returns
11721: hash: id=>name,id=>name)
1.191 harris41 11722:
11723: =item *
1.394 bowersj2 11724: X<idrget()>
11725: B<idrget($udom,@unames)>: find the IDs behind a list of
11726: usernames (returns hash: name=>id,name=>id)
1.191 harris41 11727:
11728: =item *
1.394 bowersj2 11729: X<idput()>
11730: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 11731:
11732: =item *
1.394 bowersj2 11733: X<rolesinit()>
1.1169 droeschl 11734: B<rolesinit($udom,$username)>: get user privileges.
11735: returns user role, first access and timer interval hashes
1.243 albertel 11736:
11737: =item *
1.1171 droeschl 11738: X<privileged()>
11739: B<privileged($username,$domain)>: returns a true if user has a
11740: privileged and active role (i.e. su or dc), false otherwise.
11741:
11742: =item *
1.551 albertel 11743: X<getsection()>
11744: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 11745: course $cname, return section name/number or '' for "not in course"
11746: and '-1' for "no section"
11747:
11748: =item *
1.394 bowersj2 11749: X<userenvironment()>
11750: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 11751: passed in @what from the requested user's environment, returns a hash
11752:
1.858 raeburn 11753: =item *
11754: X<userlog_query()>
1.859 albertel 11755: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11756: activity.log file. %filters defines filters applied when parsing the
11757: log file. These can be start or end timestamps, or the type of action
11758: - log to look for Login or Logout events, check for Checkin or
11759: Checkout, role for role selection. The response is in the form
11760: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11761: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 11762:
1.243 albertel 11763: =back
11764:
11765: =head2 User Roles
11766:
11767: =over 4
11768:
11769: =item *
11770:
1.810 raeburn 11771: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 11772: F: full access
11773: U,I,K: authentication modes (cxx only)
11774: '': forbidden
11775: 1: user needs to choose course
11776: 2: browse allowed
1.766 albertel 11777: A: passphrase authentication needed
1.243 albertel 11778:
11779: =item *
11780:
11781: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11782: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11783: and course level
11784:
11785: =item *
11786:
1.988 raeburn 11787: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11788: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 11789: $type is Course (default) or Community.
1.988 raeburn 11790: If $forcedefault evaluates to true, text returned will be default
11791: text for $type. Otherwise, if this is a course, the text returned
11792: will be a custom name for the role (if defined in the course's
11793: environment). If no custom name is defined the default is returned.
11794:
1.832 raeburn 11795: =item *
11796:
1.935 raeburn 11797: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 11798: All arguments are optional. Returns a hash of a roles, either for
11799: co-author/assistant author roles for a user's Construction Space
1.906 albertel 11800: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 11801: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11802: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11803: For each key, value is set to colon-separated start and end times for
11804: the role. If no username and domain are specified, will default to
1.934 raeburn 11805: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 11806: of role statuses (active, future or previous), roles
11807: (e.g., cc,in, st etc.) and domains of the roles which can be used
11808: to restrict the list of roles reported. If no array ref is
11809: provided for types, will default to return only active roles.
1.834 albertel 11810:
1.243 albertel 11811: =back
11812:
11813: =head2 User Modification
11814:
11815: =over 4
11816:
11817: =item *
11818:
1.957 raeburn 11819: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 11820: user for the level given by URL. Optional start and end dates (leave empty
11821: string or zero for "no date")
1.191 harris41 11822:
11823: =item *
11824:
1.243 albertel 11825: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11826: change a users, password, possible return values are: ok,
11827: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11828: refused
1.191 harris41 11829:
11830: =item *
11831:
1.243 albertel 11832: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 11833:
11834: =item *
11835:
1.1058 raeburn 11836: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11837: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11838:
11839: will update user information (firstname,middlename,lastname,generation,
11840: permanentemail), and if forceid is true, student/employee ID also.
11841: A user's institutional affiliation(s) can also be updated.
11842: User information fields will not be overwritten with empty entries
11843: unless the field is included in the $candelete array reference.
11844: This array is included when a single user is modified via "Manage Users",
11845: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 11846:
11847: =item *
11848:
1.286 matthew 11849: modifystudent
11850:
1.957 raeburn 11851: modify a student's enrollment and identification information.
1.286 matthew 11852: The course id is resolved based on the current users environment.
11853: This means the envoking user must be a course coordinator or otherwise
11854: associated with a course.
11855:
1.297 matthew 11856: This call is essentially a wrapper for lonnet::modifyuser and
11857: lonnet::modify_student_enrollment
1.286 matthew 11858:
11859: Inputs:
11860:
11861: =over 4
11862:
1.957 raeburn 11863: =item B<$udom> Student's loncapa domain
1.286 matthew 11864:
1.957 raeburn 11865: =item B<$uname> Student's loncapa login name
1.286 matthew 11866:
1.964 bisitz 11867: =item B<$uid> Student/Employee ID
1.286 matthew 11868:
1.957 raeburn 11869: =item B<$umode> Student's authentication mode
1.286 matthew 11870:
1.957 raeburn 11871: =item B<$upass> Student's password
1.286 matthew 11872:
1.957 raeburn 11873: =item B<$first> Student's first name
1.286 matthew 11874:
1.957 raeburn 11875: =item B<$middle> Student's middle name
1.286 matthew 11876:
1.957 raeburn 11877: =item B<$last> Student's last name
1.286 matthew 11878:
1.957 raeburn 11879: =item B<$gene> Student's generation
1.286 matthew 11880:
1.957 raeburn 11881: =item B<$usec> Student's section in course
1.286 matthew 11882:
11883: =item B<$end> Unix time of the roles expiration
11884:
11885: =item B<$start> Unix time of the roles start date
11886:
11887: =item B<$forceid> If defined, allow $uid to be changed
11888:
11889: =item B<$desiredhome> server to use as home server for student
11890:
1.957 raeburn 11891: =item B<$email> Student's permanent e-mail address
11892:
11893: =item B<$type> Type of enrollment (auto or manual)
11894:
1.963 raeburn 11895: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
11896:
11897: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 11898:
1.963 raeburn 11899: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 11900:
1.963 raeburn 11901: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 11902:
1.963 raeburn 11903: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 11904:
1.286 matthew 11905: =back
1.297 matthew 11906:
11907: =item *
11908:
11909: modify_student_enrollment
11910:
11911: Change a students enrollment status in a class. The environment variable
11912: 'role.request.course' must be defined for this function to proceed.
11913:
11914: Inputs:
11915:
11916: =over 4
11917:
11918: =item $udom, students domain
11919:
11920: =item $uname, students name
11921:
11922: =item $uid, students user id
11923:
11924: =item $first, students first name
11925:
11926: =item $middle
11927:
11928: =item $last
11929:
11930: =item $gene
11931:
11932: =item $usec
11933:
11934: =item $end
11935:
11936: =item $start
11937:
1.957 raeburn 11938: =item $type
11939:
11940: =item $locktype
11941:
11942: =item $cid
11943:
11944: =item $selfenroll
11945:
11946: =item $context
11947:
1.297 matthew 11948: =back
11949:
1.191 harris41 11950:
11951: =item *
11952:
1.243 albertel 11953: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11954: custom role; give a custom role to a user for the level given by URL. Specify
11955: name and domain of role author, and role name
1.191 harris41 11956:
11957: =item *
11958:
1.243 albertel 11959: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 11960:
11961: =item *
11962:
1.243 albertel 11963: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11964:
11965: =back
11966:
11967: =head2 Course Infomation
11968:
11969: =over 4
1.191 harris41 11970:
11971: =item *
11972:
1.1118 foxr 11973: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 11974: specified course id, including all environment settings for the
11975: course, the description of the course will be in the hash under the
11976: key 'description'
1.191 harris41 11977:
1.1118 foxr 11978: $options is an optional parameter that if supplied is a hash reference that controls
11979: what how this function works. It has the following key/values:
11980:
11981: =over 4
11982:
11983: =item freshen_cache
11984:
11985: If defined, and the environment cache for the course is valid, it is
11986: returned in the returned hash.
11987:
11988: =item one_time
11989:
11990: If defined, the last cache time is set to _now_
11991:
11992: =item user
11993:
11994: If defined, the supplied username is used instead of the current user.
11995:
11996:
11997: =back
11998:
1.191 harris41 11999: =item *
12000:
1.624 albertel 12001: resdata($name,$domain,$type,@which) : request for current parameter
12002: setting for a specific $type, where $type is either 'course' or 'user',
12003: @what should be a list of parameters to ask about. This routine caches
12004: answers for 5 minutes.
1.243 albertel 12005:
1.877 foxr 12006: =item *
12007:
12008: get_courseresdata($courseid, $domain) : dump the entire course resource
12009: data base, returning a hash that is keyed by the resource name and has
12010: values that are the resource value. I believe that the timestamps and
12011: versions are also returned.
12012:
12013:
1.243 albertel 12014: =back
12015:
12016: =head2 Course Modification
12017:
12018: =over 4
1.191 harris41 12019:
12020: =item *
12021:
1.243 albertel 12022: writecoursepref($courseid,%prefs) : write preferences (environment
12023: database) for a course
1.191 harris41 12024:
12025: =item *
12026:
1.1011 raeburn 12027: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12028:
12029: =item *
12030:
1.1038 raeburn 12031: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 12032:
1.1167 droeschl 12033: =item *
12034:
12035: is_course($courseid), is_course($cdom, $cnum)
12036:
12037: Accepts either a combined $courseid (in the form of domain_courseid) or the
12038: two component version $cdom, $cnum. It checks if the specified course exists.
12039:
12040: Returns:
12041: undef if the course doesn't exist, otherwise
12042: in scalar context the combined courseid.
12043: in list context the two components of the course identifier, domain and
12044: courseid.
12045:
1.243 albertel 12046: =back
12047:
12048: =head2 Resource Subroutines
12049:
12050: =over 4
1.191 harris41 12051:
12052: =item *
12053:
1.243 albertel 12054: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 12055:
12056: =item *
12057:
1.243 albertel 12058: repcopy($filename) : subscribes to the requested file, and attempts to
12059: replicate from the owning library server, Might return
1.607 raeburn 12060: 'unavailable', 'not_found', 'forbidden', 'ok', or
12061: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 12062: resource. Expects the local filesystem pathname
12063: (/home/httpd/html/res/....)
12064:
12065: =back
12066:
12067: =head2 Resource Information
12068:
12069: =over 4
1.191 harris41 12070:
12071: =item *
12072:
1.243 albertel 12073: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12074: a vairety of different possible values, $varname should be a request
12075: string, and the other parameters can be used to specify who and what
12076: one is asking about.
12077:
12078: Possible values for $varname are environment.lastname (or other item
12079: from the envirnment hash), user.name (or someother aspect about the
12080: user), resource.0.maxtries (or some other part and parameter of a
12081: resource)
1.204 albertel 12082:
12083: =item *
12084:
1.243 albertel 12085: directcondval($number) : get current value of a condition; reads from a state
12086: string
1.204 albertel 12087:
12088: =item *
12089:
1.243 albertel 12090: condval($condidx) : value of condition index based on state
1.204 albertel 12091:
12092: =item *
12093:
1.243 albertel 12094: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12095: resource's metadata, $what should be either a specific key, or either
12096: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12097: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12098:
12099: this function automatically caches all requests
1.191 harris41 12100:
12101: =item *
12102:
1.243 albertel 12103: metadata_query($query,$custom,$customshow) : make a metadata query against the
12104: network of library servers; returns file handle of where SQL and regex results
12105: will be stored for query
1.191 harris41 12106:
12107: =item *
12108:
1.243 albertel 12109: symbread($filename) : return symbolic list entry (filename argument optional);
12110: returns the data handle
1.191 harris41 12111:
12112: =item *
12113:
1.243 albertel 12114: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 12115: a possible symb for the URL in $thisfn, and if is an encryypted
12116: resource that the user accessed using /enc/ returns a 1 on success, 0
12117: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 12118: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 12119:
1.191 harris41 12120:
12121: =item *
12122:
1.243 albertel 12123: symbclean($symb) : removes versions numbers from a symb, returns the
12124: cleaned symb
1.191 harris41 12125:
12126: =item *
12127:
1.243 albertel 12128: is_on_map($uri) : checks if the $uri is somewhere on the current
12129: course map, user must be in a course for it to work.
1.191 harris41 12130:
12131: =item *
12132:
1.243 albertel 12133: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 12134:
12135: =item *
12136:
1.243 albertel 12137: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12138: a random seed, all arguments are optional, if they aren't sent it uses the
12139: environment to derive them. Note: if symb isn't sent and it can't get one
12140: from &symbread it will use the current time as its return value
1.191 harris41 12141:
12142: =item *
12143:
1.243 albertel 12144: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12145: unfakeable, receipt
1.191 harris41 12146:
12147: =item *
12148:
1.620 albertel 12149: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 12150:
12151: =item *
12152:
1.243 albertel 12153: countacc($url) : count the number of accesses to a given URL
1.191 harris41 12154:
12155: =item *
12156:
1.243 albertel 12157: 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 12158:
12159: =item *
12160:
1.243 albertel 12161: 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 12162:
12163: =item *
12164:
1.243 albertel 12165: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 12166:
12167: =item *
12168:
1.243 albertel 12169: devalidate($symb) : devalidate temporary spreadsheet calculations,
12170: forcing spreadsheet to reevaluate the resource scores next time.
12171:
12172: =back
12173:
12174: =head2 Storing/Retreiving Data
12175:
12176: =over 4
1.191 harris41 12177:
12178: =item *
12179:
1.243 albertel 12180: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12181: for this url; hashref needs to be given and should be a \%hashname; the
12182: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 12183: be derived from the env
1.191 harris41 12184:
12185: =item *
12186:
1.243 albertel 12187: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12188: uses critical subroutine
1.191 harris41 12189:
12190: =item *
12191:
1.243 albertel 12192: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12193: all args are optional
1.191 harris41 12194:
12195: =item *
12196:
1.717 albertel 12197: dumpstore($namespace,$udom,$uname,$regexp,$range) :
12198: dumps the complete (or key matching regexp) namespace into a hash
12199: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12200: normally &store()ed into
12201:
12202: $range should be either an integer '100' (give me the first 100
12203: matching records)
12204: or be two integers sperated by a - with no spaces
12205: '30-50' (give me the 30th through the 50th matching
12206: records)
12207:
12208:
12209: =item *
12210:
12211: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12212: replaces a &store() version of data with a replacement set of data
12213: for a particular resource in a namespace passed in the $storehash hash
12214: reference
12215:
12216: =item *
12217:
1.243 albertel 12218: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12219: works very similar to store/cstore, but all data is stored in a
12220: temporary location and can be reset using tmpreset, $storehash should
12221: be a hash reference, returns nothing on success
1.191 harris41 12222:
12223: =item *
12224:
1.243 albertel 12225: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12226: similar to restore, but all data is stored in a temporary location and
12227: can be reset using tmpreset. Returns a hash of values on success,
12228: error string otherwise.
1.191 harris41 12229:
12230: =item *
12231:
1.243 albertel 12232: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12233: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 12234:
12235: =item *
12236:
1.243 albertel 12237: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12238: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 12239:
12240: =item *
12241:
1.243 albertel 12242: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12243: namesp ($udom and $uname are optional)
1.191 harris41 12244:
12245: =item *
12246:
1.702 albertel 12247: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 12248: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 12249: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 12250:
1.702 albertel 12251: $range should be either an integer '100' (give me the first 100
12252: matching records)
12253: or be two integers sperated by a - with no spaces
12254: '30-50' (give me the 30th through the 50th matching
12255: records)
1.449 matthew 12256: =item *
12257:
12258: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12259: $store can be a scalar, an array reference, or if the amount to be
12260: incremented is > 1, a hash reference.
12261:
12262: ($udom and $uname are optional)
1.191 harris41 12263:
12264: =item *
12265:
1.243 albertel 12266: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12267: ($udom and $uname are optional)
1.191 harris41 12268:
12269: =item *
12270:
1.243 albertel 12271: cput($namespace,$storehash,$udom,$uname) : critical put
12272: ($udom and $uname are optional)
1.191 harris41 12273:
12274: =item *
12275:
1.748 albertel 12276: newput($namespace,$storehash,$udom,$uname) :
12277:
12278: Attempts to store the items in the $storehash, but only if they don't
12279: currently exist, if this succeeds you can be certain that you have
12280: successfully created a new key value pair in the $namespace db.
12281:
12282:
12283: Args:
12284: $namespace: name of database to store values to
12285: $storehash: hashref to store to the db
12286: $udom: (optional) domain of user containing the db
12287: $uname: (optional) name of user caontaining the db
12288:
12289: Returns:
12290: 'ok' -> succeeded in storing all keys of $storehash
12291: 'key_exists: <key>' -> failed to anything out of $storehash, as at
12292: least <key> already existed in the db (other
12293: requested keys may also already exist)
1.967 bisitz 12294: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 12295: 'con_lost' -> unable to contact request server
12296: 'refused' -> action was not allowed by remote machine
12297:
12298:
12299: =item *
12300:
1.243 albertel 12301: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12302: reference filled in from namesp (encrypts the return communication)
12303: ($udom and $uname are optional)
1.191 harris41 12304:
12305: =item *
12306:
1.243 albertel 12307: log($udom,$name,$home,$message) : write to permanent log for user; use
12308: critical subroutine
12309:
1.806 raeburn 12310: =item *
12311:
1.860 raeburn 12312: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12313: array reference filled in from namespace found in domain level on either
12314: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 12315:
12316: =item *
12317:
1.860 raeburn 12318: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
12319: domain level either on specified domain server ($uhome) or primary domain
12320: server ($udom and $uhome are optional)
1.806 raeburn 12321:
1.943 raeburn 12322: =item *
12323:
12324: get_domain_defaults($target_domain) : returns hash with defaults for
12325: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12326: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12327: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12328: Values are retrieved from cache (if current), or from domain's configuration.db
12329: (if available), or lastly from values in lonTabs/dns_domain,tab,
12330: or lonTabs/domain.tab.
12331:
12332: %domdefaults = &get_auth_defaults($target_domain);
12333:
1.243 albertel 12334: =back
12335:
12336: =head2 Network Status Functions
12337:
12338: =over 4
1.191 harris41 12339:
12340: =item *
12341:
1.1137 raeburn 12342: dirlist() : return directory list based on URI (first arg).
12343:
12344: Inputs: 1 required, 5 optional.
12345:
12346: =over
12347:
12348: =item
12349: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12350:
12351: =item
12352: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
12353:
12354: =item
12355: $username - username of user/course to be listed. Extracted from $uri if absent.
12356:
12357: =item
12358: $getpropath - boolean: 1 if prepend path using &propath().
12359:
12360: =item
12361: $getuserdir - boolean: 1 if prepend path for "userfiles".
12362:
12363: =item
12364: $alternateRoot - path to prepend in place of path from $uri.
12365:
12366: =back
12367:
12368: Returns: Array of up to two items.
12369:
12370: =over
12371:
12372: a reference to an array of files/subdirectories
12373:
12374: =over
12375:
12376: Each element in the array of files/subdirectories is a & separated list of
12377: item name and the result of running stat on the item. If dirlist was requested
12378: for a file instead of a directory, the item name will be ''. For a directory
12379: listing, if the item is a metadata file, the element will end &N&M
12380: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12381: default copyright set (1).
12382:
12383: =back
12384:
12385: a scalar containing error condition (if encountered).
12386:
12387: =over
12388:
12389: =item
12390: no_host (no homeserver identified for $username:$domain).
12391:
12392: =item
12393: no_such_host (server contacted for listing not identified as valid host).
12394:
12395: =item
12396: con_lost (connection to remote server failed).
12397:
12398: =item
12399: refused (invalid $username:$domain received on lond side).
12400:
12401: =item
12402: no_such_dir (directory at specified path on lond side does not exist).
12403:
12404: =item
12405: empty (directory at specified path on lond side is empty).
12406:
12407: =over
12408:
12409: This is currently not encountered because the &ls3, &ls2,
12410: &ls (_handler) routines on the lond side do not filter out
12411: . and .. from a directory listing.
12412:
12413: =back
12414:
12415: =back
12416:
12417: =back
1.191 harris41 12418:
12419: =item *
12420:
1.243 albertel 12421: spareserver() : find server with least workload from spare.tab
12422:
1.986 foxr 12423:
12424: =item *
12425:
12426: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12427: if there is no corresponding loncapa host.
12428:
1.243 albertel 12429: =back
12430:
1.986 foxr 12431:
1.243 albertel 12432: =head2 Apache Request
12433:
12434: =over 4
1.191 harris41 12435:
12436: =item *
12437:
1.243 albertel 12438: ssi($url,%hash) : server side include, does a complete request cycle on url to
12439: localhost, posts hash
12440:
12441: =back
12442:
12443: =head2 Data to String to Data
12444:
12445: =over 4
1.191 harris41 12446:
12447: =item *
12448:
1.243 albertel 12449: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12450: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 12451:
12452: =item *
12453:
1.243 albertel 12454: hashref2str($hashref) : convert a hashref into a string complete with
12455: escaping and '=' and '&' separators, supports elements that are
12456: arrayrefs and hashrefs
1.191 harris41 12457:
12458: =item *
12459:
1.243 albertel 12460: arrayref2str($arrayref) : convert an arrayref into a string complete
12461: with escaping and '&' separators, supports elements that are arrayrefs
12462: and hashrefs
1.191 harris41 12463:
12464: =item *
12465:
1.243 albertel 12466: str2hash($string) : convert string to hash using unescaping and
12467: splitting on '=' and '&', supports elements that are arrayrefs and
12468: hashrefs
1.191 harris41 12469:
12470: =item *
12471:
1.243 albertel 12472: str2array($string) : convert string to hash using unescaping and
12473: splitting on '&', supports elements that are arrayrefs and hashrefs
12474:
12475: =back
12476:
12477: =head2 Logging Routines
12478:
12479:
12480: These routines allow one to make log messages in the lonnet.log and
12481: lonnet.perm logfiles.
1.191 harris41 12482:
1.1119 foxr 12483: =over 4
12484:
1.191 harris41 12485: =item *
12486:
1.243 albertel 12487: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 12488:
12489: =item *
12490:
1.243 albertel 12491: logthis() : append message to the normal lonnet.log file, it gets
12492: preiodically rolled over and deleted.
1.191 harris41 12493:
12494: =item *
12495:
1.243 albertel 12496: logperm() : append a permanent message to lonnet.perm.log, this log
12497: file never gets deleted by any automated portion of the system, only
12498: messages of critical importance should go in here.
12499:
1.1119 foxr 12500:
1.243 albertel 12501: =back
12502:
12503: =head2 General File Helper Routines
12504:
12505: =over 4
1.191 harris41 12506:
12507: =item *
12508:
1.481 raeburn 12509: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12510: (a) files in /uploaded
12511: (i) If a local copy of the file exists -
12512: compares modification date of local copy with last-modified date for
12513: definitive version stored on home server for course. If local copy is
12514: stale, requests a new version from the home server and stores it.
12515: If the original has been removed from the home server, then local copy
12516: is unlinked.
12517: (ii) If local copy does not exist -
12518: requests the file from the home server and stores it.
12519:
12520: If $caller is 'uploadrep':
12521: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12522: for request for files originally uploaded via DOCS.
12523: - returns 'ok' if fresh local copy now available, -1 otherwise.
12524:
12525: Otherwise:
12526: This indicates a call from the content generation phase of the request.
12527: - returns the entire contents of the file or -1.
12528:
12529: (b) files in /res
12530: - returns the entire contents of a file or -1;
12531: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 12532:
1.712 albertel 12533:
12534: =item *
12535:
12536: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12537: reference
12538:
12539: returns either a stat() list of data about the file or an empty list
12540: if the file doesn't exist or couldn't find out about it (connection
12541: problems or user unknown)
12542:
1.191 harris41 12543: =item *
12544:
1.243 albertel 12545: filelocation($dir,$file) : returns file system location of a file
12546: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12547: directory that relative $file lookups are to looked in ($dir of /a/dir
12548: and a file of ../bob will become /a/bob)
1.191 harris41 12549:
12550: =item *
12551:
12552: hreflocation($dir,$file) : returns file system location or a URL; same as
12553: filelocation except for hrefs
12554:
12555: =item *
12556:
12557: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12558:
1.243 albertel 12559: =back
12560:
1.608 albertel 12561: =head2 Usererfile file routines (/uploaded*)
12562:
12563: =over 4
12564:
12565: =item *
12566:
12567: userfileupload(): main rotine for putting a file in a user or course's
12568: filespace, arguments are,
12569:
1.620 albertel 12570: formname - required - this is the name of the element in $env where the
1.608 albertel 12571: filename, and the contents of the file to create/modifed exist
1.620 albertel 12572: the filename is in $env{'form.'.$formname.'.filename'} and the
12573: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 12574: context - if coursedoc, store the file in the course of the active role
12575: of the current user;
12576: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12577: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 12578: subdir - required - subdirectory to put the file in under ../userfiles/
12579: if undefined, it will be placed in "unknown"
12580:
12581: (This routine calls clean_filename() to remove any dangerous
12582: characters from the filename, and then calls finuserfileupload() to
12583: complete the transaction)
12584:
12585: returns either the url of the uploaded file (/uploaded/....) if successful
12586: and /adm/notfound.html if unsuccessful
12587:
12588: =item *
12589:
12590: clean_filename(): routine for cleaing a filename up for storage in
12591: userfile space, argument is:
12592:
12593: filename - proposed filename
12594:
12595: returns: the new clean filename
12596:
12597: =item *
12598:
1.1090 raeburn 12599: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 12600: userspace, probably shouldn't be called directly
12601:
12602: docuname: username or courseid of destination for the file
12603: docudom: domain of user/course of destination for the file
12604: formname: same as for userfileupload()
1.1090 raeburn 12605: fname: filename (including subdirectories) for the file
12606: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12607: allfiles: reference to hash used to store objects found by parser
12608: codebase: reference to hash used for codebases of java objects found by parser
12609: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12610: thumbheight: height (pixels) of thumbnail to be created for uploaded image
12611: resizewidth: width to be used to resize image using resizeImage from ImageMagick
12612: resizeheight: height to be used to resize image using resizeImage from ImageMagick
12613: context: if 'overwrite', will move the uploaded file from its temporary location to
12614: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 12615: mimetype: reference to scalar to accommodate mime type determined
12616: from File::MMagic if $parser = parse.
1.608 albertel 12617:
12618: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 12619: and /adm/notfound.html if unsuccessful (or an error message if context
12620: was 'overwrite').
12621:
1.608 albertel 12622:
12623: =item *
12624:
12625: renameuserfile(): renames an existing userfile to a new name
12626:
12627: Args:
12628: docuname: username or courseid of destination for the file
12629: docudom: domain of user/course of destination for the file
12630: old: current file name (including any subdirs under userfiles)
12631: new: desired file name (including any subdirs under userfiles)
12632:
12633: =item *
12634:
12635: mkdiruserfile(): creates a directory is a userfiles dir
12636:
12637: Args:
12638: docuname: username or courseid of destination for the file
12639: docudom: domain of user/course of destination for the file
12640: dir: dir to create (including any subdirs under userfiles)
12641:
12642: =item *
12643:
12644: removeuserfile(): removes a file that exists in userfiles
12645:
12646: Args:
12647: docuname: username or courseid of destination for the file
12648: docudom: domain of user/course of destination for the file
12649: fname: filname to delete (including any subdirs under userfiles)
12650:
12651: =item *
12652:
12653: removeuploadedurl(): convience function for removeuserfile()
12654:
12655: Args:
12656: url: a full /uploaded/... url to delete
12657:
1.747 albertel 12658: =item *
12659:
12660: get_portfile_permissions():
12661: Args:
12662: domain: domain of user or course contain the portfolio files
12663: user: name of user or num of course contain the portfolio files
12664: Returns:
12665: hashref of a dump of the proper file_permissions.db
12666:
12667:
12668: =item *
12669:
12670: get_access_controls():
12671:
12672: Args:
12673: current_permissions: the hash ref returned from get_portfile_permissions()
12674: group: (optional) the group you want the files associated with
12675: file: (optional) the file you want access info on
12676:
12677: Returns:
1.749 raeburn 12678: a hash (keys are file names) of hashes containing
12679: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12680: values are XML containing access control settings (see below)
1.747 albertel 12681:
12682: Internal notes:
12683:
1.749 raeburn 12684: access controls are stored in file_permissions.db as key=value pairs.
12685: key -> path to file/file_name\0uniqueID:scope_end_start
12686: where scope -> public,guest,course,group,domains or users.
12687: end -> UNIX time for end of access (0 -> no end date)
12688: start -> UNIX time for start of access
12689:
12690: value -> XML description of access control
12691: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12692: <start></start>
12693: <end></end>
12694:
12695: <password></password> for scope type = guest
12696:
12697: <domain></domain> for scope type = course or group
12698: <number></number>
12699: <roles id="">
12700: <role></role>
12701: <access></access>
12702: <section></section>
12703: <group></group>
12704: </roles>
12705:
12706: <dom></dom> for scope type = domains
12707:
12708: <users> for scope type = users
12709: <user>
12710: <uname></uname>
12711: <udom></udom>
12712: </user>
12713: </users>
12714: </scope>
12715:
12716: Access data is also aggregated for each file in an additional key=value pair:
12717: key -> path to file/file_name\0accesscontrol
12718: value -> reference to hash
12719: hash contains key = value pairs
12720: where key = uniqueID:scope_end_start
12721: value = UNIX time record was last updated
12722:
12723: Used to improve speed of look-ups of access controls for each file.
12724:
12725: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12726:
12727: modify_access_controls():
12728:
12729: Modifies access controls for a portfolio file
12730: Args
12731: 1. file name
12732: 2. reference to hash of required changes,
12733: 3. domain
12734: 4. username
12735: where domain,username are the domain of the portfolio owner
12736: (either a user or a course)
12737:
12738: Returns:
12739: 1. result of additions or updates ('ok' or 'error', with error message).
12740: 2. result of deletions ('ok' or 'error', with error message).
12741: 3. reference to hash of any new or updated access controls.
12742: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12743: key = integer (inbound ID)
12744: value = uniqueID
1.747 albertel 12745:
1.608 albertel 12746: =back
12747:
1.243 albertel 12748: =head2 HTTP Helper Routines
12749:
12750: =over 4
12751:
1.191 harris41 12752: =item *
12753:
12754: escape() : unpack non-word characters into CGI-compatible hex codes
12755:
12756: =item *
12757:
12758: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12759:
1.243 albertel 12760: =back
12761:
12762: =head1 PRIVATE SUBROUTINES
12763:
12764: =head2 Underlying communication routines (Shouldn't call)
12765:
12766: =over 4
12767:
12768: =item *
12769:
12770: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12771:
12772: =item *
12773:
12774: reply() : uses subreply to send a message to remote machine, logs all failures
12775:
12776: =item *
12777:
12778: critical() : passes a critical message to another server; if cannot
12779: get through then place message in connection buffer directory and
12780: returns con_delayed, if incapable of saving message, returns
12781: con_failed
12782:
12783: =item *
12784:
12785: reconlonc() : tries to reconnect lonc client processes.
12786:
12787: =back
12788:
12789: =head2 Resource Access Logging
12790:
12791: =over 4
12792:
12793: =item *
12794:
12795: flushcourselogs() : flush (save) buffer logs and access logs
12796:
12797: =item *
12798:
12799: courselog($what) : save message for course in hash
12800:
12801: =item *
12802:
12803: courseacclog($what) : save message for course using &courselog(). Perform
12804: special processing for specific resource types (problems, exams, quizzes, etc).
12805:
1.191 harris41 12806: =item *
12807:
12808: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12809: as a PerlChildExitHandler
1.243 albertel 12810:
12811: =back
12812:
12813: =head2 Other
12814:
12815: =over 4
12816:
12817: =item *
12818:
12819: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 12820:
12821: =back
12822:
12823: =cut
1.877 foxr 12824:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>