Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1149
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1149 ! raeburn 4: # $Id: lonnet.pm,v 1.1148 2011/12/14 16:16:50 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.1117 foxr 99:
1.1090 raeburn 100: use File::Copy;
1.676 albertel 101:
1.195 www 102: my $readit;
1.550 foxr 103: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 104:
1.619 albertel 105: require Exporter;
106:
107: our @ISA = qw (Exporter);
108: our @EXPORT = qw(%env);
109:
1.449 matthew 110:
1.1 albertel 111: # --------------------------------------------------------------------- Logging
1.729 www 112: {
113: my $logid;
114: sub instructor_log {
1.957 raeburn 115: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
116: if (($cnum eq '') || ($cdom eq '')) {
117: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
118: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
119: }
1.729 www 120: $logid++;
1.957 raeburn 121: my $now = time();
122: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 123: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 124: { $id => {
125: 'exe_uname' => $env{'user.name'},
126: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 127: 'exe_time' => $now,
1.730 www 128: 'exe_ip' => $ENV{'REMOTE_ADDR'},
129: 'delflag' => $delflag,
130: 'logentry' => $storehash,
131: 'uname' => $uname,
132: 'udom' => $udom,
133: }
1.957 raeburn 134: },$cdom,$cnum);
1.729 www 135: }
136: }
1.1 albertel 137:
1.163 harris41 138: sub logtouch {
139: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 140: unless (-e "$execdir/logs/lonnet.log") {
141: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 142: close $fh;
143: }
144: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
145: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
146: }
147:
1.1 albertel 148: sub logthis {
149: my $message=shift;
150: my $execdir=$perlvar{'lonDaemons'};
151: my $now=time;
152: my $local=localtime($now);
1.448 albertel 153: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 154: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
155: print $fh $logstring;
1.448 albertel 156: close($fh);
157: }
1.1 albertel 158: return 1;
159: }
160:
161: sub logperm {
162: my $message=shift;
163: my $execdir=$perlvar{'lonDaemons'};
164: my $now=time;
165: my $local=localtime($now);
1.448 albertel 166: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
167: print $fh "$now:$message:$local\n";
168: close($fh);
169: }
1.1 albertel 170: return 1;
171: }
172:
1.850 albertel 173: sub create_connection {
1.853 albertel 174: my ($hostname,$lonid) = @_;
1.851 albertel 175: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 176: Type => SOCK_STREAM,
177: Timeout => 10);
178: return 0 if (!$client);
1.890 albertel 179: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 180: my $result = <$client>;
181: chomp($result);
182: return 1 if ($result eq 'done');
183: return 0;
184: }
185:
1.983 raeburn 186: sub get_server_timezone {
187: my ($cnum,$cdom) = @_;
188: my $home=&homeserver($cnum,$cdom);
189: if ($home ne 'no_host') {
190: my $cachetime = 24*3600;
191: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
192: if (defined($cached)) {
193: return $timezone;
194: } else {
195: my $timezone = &reply('servertimezone',$home);
196: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
197: }
198: }
199: }
1.850 albertel 200:
1.1106 raeburn 201: sub get_server_distarch {
202: my ($lonhost,$ignore_cache) = @_;
203: if (defined($lonhost)) {
204: if (!defined(&hostname($lonhost))) {
205: return;
206: }
207: my $cachetime = 12*3600;
208: if (!$ignore_cache) {
209: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
210: if (defined($cached)) {
211: return $distarch;
212: }
213: }
214: my $rep = &reply('serverdistarch',$lonhost);
215: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
216: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
217: $rep eq '') {
218: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
219: }
220: }
221: return;
222: }
223:
1.993 raeburn 224: sub get_server_loncaparev {
1.1073 raeburn 225: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 226: if (defined($lonhost)) {
227: if (!defined(&hostname($lonhost))) {
228: undef($lonhost);
229: }
230: }
231: if (!defined($lonhost)) {
232: if (defined(&domain($dom,'primary'))) {
233: $lonhost=&domain($dom,'primary');
234: if ($lonhost eq 'no_host') {
235: undef($lonhost);
236: }
237: }
238: }
239: if (defined($lonhost)) {
1.1073 raeburn 240: my $cachetime = 12*3600;
241: if (!$ignore_cache) {
242: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
243: if (defined($cached)) {
244: return $loncaparev;
245: }
246: }
247: my ($answer,$loncaparev);
248: my @ids=¤t_machine_ids();
249: if (grep(/^\Q$lonhost\E$/,@ids)) {
250: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 251: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 252: $loncaparev = $1;
253: }
254: } else {
255: $answer = &reply('serverloncaparev',$lonhost);
256: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
257: if ($caller eq 'loncron') {
258: my $ua=new LWP::UserAgent;
1.1082 raeburn 259: $ua->timeout(4);
1.1073 raeburn 260: my $protocol = $protocol{$lonhost};
261: $protocol = 'http' if ($protocol ne 'https');
262: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
263: my $request=new HTTP::Request('GET',$url);
264: my $response=$ua->request($request);
265: unless ($response->is_error()) {
266: my $content = $response->content;
1.1081 raeburn 267: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 268: $loncaparev = $1;
269: }
270: }
271: } else {
272: $loncaparev = $loncaparevs{$lonhost};
273: }
1.1081 raeburn 274: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 275: $loncaparev = $1;
276: }
1.993 raeburn 277: }
1.1073 raeburn 278: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 279: }
280: }
281:
1.1074 raeburn 282: sub get_server_homeID {
283: my ($hostname,$ignore_cache,$caller) = @_;
284: unless ($ignore_cache) {
285: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
286: if (defined($cached)) {
287: return $serverhomeID;
288: }
289: }
290: my $cachetime = 12*3600;
291: my $serverhomeID;
292: if ($caller eq 'loncron') {
293: my @machine_ids = &machine_ids($hostname);
294: foreach my $id (@machine_ids) {
295: my $response = &reply('serverhomeID',$id);
296: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
297: $serverhomeID = $response;
298: last;
299: }
300: }
301: if ($serverhomeID eq '') {
302: $serverhomeID = $machine_ids[-1];
303: }
304: } else {
305: $serverhomeID = $serverhomeIDs{$hostname};
306: }
307: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
308: }
309:
1.1121 raeburn 310: sub get_remote_globals {
311: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 312: my ($result,%returnhash,%whatneeded);
313: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 314: foreach my $what (sort(keys(%{$whathash}))) {
315: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 316: my ($response,$cached);
1.1121 raeburn 317: unless ($ignore_cache) {
1.1125 raeburn 318: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 319: }
320: if (defined($cached)) {
1.1125 raeburn 321: $returnhash{$what} = $response;
1.1121 raeburn 322: } else {
1.1125 raeburn 323: $whatneeded{$what} = 1;
1.1121 raeburn 324: }
325: }
1.1125 raeburn 326: if (keys(%whatneeded) == 0) {
327: $result = 'ok';
328: } else {
1.1121 raeburn 329: my $requested = &freeze_escape(\%whatneeded);
330: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 331: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
332: ($rep eq 'unknown_cmd')) {
333: $result = $rep;
334: } else {
335: $result = 'ok';
1.1121 raeburn 336: my @pairs=split(/\&/,$rep);
1.1125 raeburn 337: foreach my $item (@pairs) {
338: my ($key,$value)=split(/=/,$item,2);
339: my $what = &unescape($key);
340: my $hashid = $lonhost.'-'.$what;
341: $returnhash{$what}=&thaw_unescape($value);
342: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 343: }
344: }
345: }
346: }
1.1125 raeburn 347: return ($result,\%returnhash);
1.1121 raeburn 348: }
349:
1.1124 raeburn 350: sub remote_devalidate_cache {
351: my ($lonhost,$name,$id) = @_;
1.1130 raeburn 352: my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124 raeburn 353: return $response;
354: }
355:
1.1 albertel 356: # -------------------------------------------------- Non-critical communication
357: sub subreply {
358: my ($cmd,$server)=@_;
1.838 albertel 359: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 360: #
361: # With loncnew process trimming, there's a timing hole between lonc server
362: # process exit and the master server picking up the listen on the AF_UNIX
363: # socket. In that time interval, a lock file will exist:
364:
365: my $lockfile=$peerfile.".lock";
366: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
367: sleep(1);
368: }
369: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 370: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 371: #
1.550 foxr 372: # We'll give the connection a few tries before abandoning it. If
373: # connection is not possible, we'll con_lost back to the client.
374: #
375: my $client;
376: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
377: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
378: Type => SOCK_STREAM,
379: Timeout => 10);
1.869 albertel 380: if ($client) {
1.550 foxr 381: last; # Connected!
1.850 albertel 382: } else {
1.853 albertel 383: &create_connection(&hostname($server),$server);
1.550 foxr 384: }
1.850 albertel 385: sleep(1); # Try again later if failed connection.
1.550 foxr 386: }
387: my $answer;
388: if ($client) {
1.704 albertel 389: print $client "sethost:$server:$cmd\n";
1.550 foxr 390: $answer=<$client>;
391: if (!$answer) { $answer="con_lost"; }
392: chomp($answer);
393: } else {
394: $answer = 'con_lost'; # Failed connection.
395: }
1.1 albertel 396: return $answer;
397: }
398:
399: sub reply {
400: my ($cmd,$server)=@_;
1.838 albertel 401: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 402: my $answer=subreply($cmd,$server);
1.65 www 403: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 404: &logthis("<font color=\"blue\">WARNING:".
1.12 www 405: " $cmd to $server returned $answer</font>");
406: }
1.1 albertel 407: return $answer;
408: }
409:
410: # ----------------------------------------------------------- Send USR1 to lonc
411:
412: sub reconlonc {
1.891 albertel 413: my ($lonid) = @_;
414: my $hostname = &hostname($lonid);
415: if ($lonid) {
416: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
417: if ($hostname && -e $peerfile) {
418: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
419: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
420: Type => SOCK_STREAM,
421: Timeout => 10);
422: if ($client) {
423: print $client ("reset_retries\n");
424: my $answer=<$client>;
425: #reset just this one.
426: }
427: }
428: return;
429: }
430:
1.836 www 431: &logthis("Trying to reconnect lonc");
1.1 albertel 432: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 433: if (open(my $fh,"<$loncfile")) {
1.1 albertel 434: my $loncpid=<$fh>;
435: chomp($loncpid);
436: if (kill 0 => $loncpid) {
437: &logthis("lonc at pid $loncpid responding, sending USR1");
438: kill USR1 => $loncpid;
439: sleep 1;
1.836 www 440: } else {
1.12 www 441: &logthis(
1.672 albertel 442: "<font color=\"blue\">WARNING:".
1.12 www 443: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 444: }
445: } else {
1.836 www 446: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 447: }
448: }
449:
450: # ------------------------------------------------------ Critical communication
1.12 www 451:
1.1 albertel 452: sub critical {
453: my ($cmd,$server)=@_;
1.838 albertel 454: unless (&hostname($server)) {
1.672 albertel 455: &logthis("<font color=\"blue\">WARNING:".
1.89 www 456: " Critical message to unknown server ($server)</font>");
457: return 'no_such_host';
458: }
1.1 albertel 459: my $answer=reply($cmd,$server);
460: if ($answer eq 'con_lost') {
461: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 462: my $answer=reply($cmd,$server);
1.1 albertel 463: if ($answer eq 'con_lost') {
464: my $now=time;
465: my $middlename=$cmd;
1.5 www 466: $middlename=substr($middlename,0,16);
1.1 albertel 467: $middlename=~s/\W//g;
468: my $dfilename=
1.305 www 469: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
470: $dumpcount++;
1.1 albertel 471: {
1.448 albertel 472: my $dfh;
473: if (open($dfh,">$dfilename")) {
474: print $dfh "$cmd\n";
475: close($dfh);
476: }
1.1 albertel 477: }
478: sleep 2;
479: my $wcmd='';
480: {
1.448 albertel 481: my $dfh;
482: if (open($dfh,"<$dfilename")) {
483: $wcmd=<$dfh>;
484: close($dfh);
485: }
1.1 albertel 486: }
487: chomp($wcmd);
1.7 www 488: if ($wcmd eq $cmd) {
1.672 albertel 489: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 490: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 491: &logperm("D:$server:$cmd");
492: return 'con_delayed';
493: } else {
1.672 albertel 494: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 495: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 496: &logperm("F:$server:$cmd");
497: return 'con_failed';
498: }
499: }
500: }
501: return $answer;
1.405 albertel 502: }
503:
1.755 albertel 504: # ------------------------------------------- check if return value is an error
505:
506: sub error {
507: my ($result) = @_;
1.756 albertel 508: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 509: if ($2 == 2) { return undef; }
510: return $1;
511: }
512: return undef;
513: }
514:
1.783 albertel 515: sub convert_and_load_session_env {
516: my ($lonidsdir,$handle)=@_;
517: my @profile;
518: {
1.917 albertel 519: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
520: if (!$opened) {
1.915 albertel 521: return 0;
522: }
1.783 albertel 523: flock($idf,LOCK_SH);
524: @profile=<$idf>;
525: close($idf);
526: }
527: my %temp_env;
528: foreach my $line (@profile) {
1.786 albertel 529: if ($line !~ m/=/) {
530: return 0;
531: }
1.783 albertel 532: chomp($line);
533: my ($envname,$envvalue)=split(/=/,$line,2);
534: $temp_env{&unescape($envname)} = &unescape($envvalue);
535: }
536: unlink("$lonidsdir/$handle.id");
537: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
538: 0640)) {
539: %disk_env = %temp_env;
540: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
541: untie(%disk_env);
542: }
1.786 albertel 543: return 1;
1.783 albertel 544: }
545:
1.374 www 546: # ------------------------------------------- Transfer profile into environment
1.780 albertel 547: my $env_loaded;
548: sub transfer_profile_to_env {
1.788 albertel 549: my ($lonidsdir,$handle,$force_transfer) = @_;
550: if (!$force_transfer && $env_loaded) { return; }
1.374 www 551:
1.720 albertel 552: if (!defined($lonidsdir)) {
553: $lonidsdir = $perlvar{'lonIDsDir'};
554: }
555: if (!defined($handle)) {
556: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
557: }
558:
1.786 albertel 559: my $convert;
560: {
1.917 albertel 561: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
562: if (!$opened) {
1.915 albertel 563: return;
564: }
1.786 albertel 565: flock($idf,LOCK_SH);
566: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
567: &GDBM_READER(),0640)) {
568: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
569: untie(%disk_env);
570: } else {
571: $convert = 1;
572: }
573: }
574: if ($convert) {
575: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
576: &logthis("Failed to load session, or convert session.");
577: }
1.374 www 578: }
1.783 albertel 579:
1.786 albertel 580: my %remove;
1.783 albertel 581: while ( my $envname = each(%env) ) {
1.433 matthew 582: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
583: if ($time < time-300) {
1.783 albertel 584: $remove{$key}++;
1.433 matthew 585: }
586: }
587: }
1.783 albertel 588:
1.619 albertel 589: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 590: $env_loaded=1;
1.783 albertel 591: foreach my $expired_key (keys(%remove)) {
1.433 matthew 592: &delenv($expired_key);
1.374 www 593: }
1.1 albertel 594: }
595:
1.916 albertel 596: # ---------------------------------------------------- Check for valid session
597: sub check_for_valid_session {
598: my ($r) = @_;
599: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
600: my $lonid=$cookies{'lonID'};
601: return undef if (!$lonid);
602:
603: my $handle=&LONCAPA::clean_handle($lonid->value);
604: my $lonidsdir=$r->dir_config('lonIDsDir');
605: return undef if (!-e "$lonidsdir/$handle.id");
606:
1.917 albertel 607: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
608: return undef if (!$opened);
1.916 albertel 609:
610: flock($idf,LOCK_SH);
611: my %disk_env;
612: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
613: &GDBM_READER(),0640)) {
614: return undef;
615: }
616:
617: if (!defined($disk_env{'user.name'})
618: || !defined($disk_env{'user.domain'})) {
619: return undef;
620: }
621: return $handle;
622: }
623:
1.830 albertel 624: sub timed_flock {
625: my ($file,$lock_type) = @_;
626: my $failed=0;
627: eval {
628: local $SIG{__DIE__}='DEFAULT';
629: local $SIG{ALRM}=sub {
630: $failed=1;
631: die("failed lock");
632: };
633: alarm(13);
634: flock($file,$lock_type);
635: alarm(0);
636: };
637: if ($failed) {
638: return undef;
639: } else {
640: return 1;
641: }
642: }
643:
1.5 www 644: # ---------------------------------------------------------- Append Environment
645:
646: sub appenv {
1.949 raeburn 647: my ($newenv,$roles) = @_;
648: if (ref($newenv) eq 'HASH') {
649: foreach my $key (keys(%{$newenv})) {
650: my $refused = 0;
651: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
652: $refused = 1;
653: if (ref($roles) eq 'ARRAY') {
654: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
655: if (grep(/^\Q$role\E$/,@{$roles})) {
656: $refused = 0;
657: }
658: }
659: }
660: if ($refused) {
661: &logthis("<font color=\"blue\">WARNING: ".
662: "Attempt to modify environment ".$key." to ".$newenv->{$key}
663: .'</font>');
664: delete($newenv->{$key});
665: } else {
666: $env{$key}=$newenv->{$key};
667: }
668: }
669: my $opened = open(my $env_file,'+<',$env{'user.environment'});
670: if ($opened
671: && &timed_flock($env_file,LOCK_EX)
672: &&
673: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
674: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
675: while (my ($key,$value) = each(%{$newenv})) {
676: $disk_env{$key} = $value;
677: }
678: untie(%disk_env);
1.35 www 679: }
1.191 harris41 680: }
1.56 www 681: return 'ok';
682: }
683: # ----------------------------------------------------- Delete from Environment
684:
685: sub delenv {
1.1104 raeburn 686: my ($delthis,$regexp,$roles) = @_;
687: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
688: my $refused = 1;
689: if (ref($roles) eq 'ARRAY') {
690: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
691: if (grep(/^\Q$role\E$/,@{$roles})) {
692: $refused = 0;
693: }
694: }
695: if ($refused) {
696: &logthis("<font color=\"blue\">WARNING: ".
697: "Attempt to delete from environment ".$delthis);
698: return 'error';
699: }
1.56 www 700: }
1.917 albertel 701: my $opened = open(my $env_file,'+<',$env{'user.environment'});
702: if ($opened
1.915 albertel 703: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 704: &&
705: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
706: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 707: foreach my $key (keys(%disk_env)) {
1.987 raeburn 708: if ($regexp) {
709: if ($key=~/^$delthis/) {
710: delete($env{$key});
711: delete($disk_env{$key});
712: }
713: } else {
714: if ($key=~/^\Q$delthis\E/) {
715: delete($env{$key});
716: delete($disk_env{$key});
717: }
718: }
1.448 albertel 719: }
1.783 albertel 720: untie(%disk_env);
1.5 www 721: }
722: return 'ok';
1.369 albertel 723: }
724:
1.790 albertel 725: sub get_env_multiple {
726: my ($name) = @_;
727: my @values;
728: if (defined($env{$name})) {
729: # exists is it an array
730: if (ref($env{$name})) {
731: @values=@{ $env{$name} };
732: } else {
733: $values[0]=$env{$name};
734: }
735: }
736: return(@values);
737: }
738:
1.958 www 739: # ------------------------------------------------------------------- Locking
740:
741: sub set_lock {
742: my ($text)=@_;
743: $locknum++;
744: my $id=$$.'-'.$locknum;
745: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
746: 'session.lock.'.$id => $text});
747: return $id;
748: }
749:
750: sub get_locks {
751: my $num=0;
752: my %texts=();
753: foreach my $lock (split(/\,/,$env{'session.locks'})) {
754: if ($lock=~/\w/) {
755: $num++;
756: $texts{$lock}=$env{'session.lock.'.$lock};
757: }
758: }
759: return ($num,%texts);
760: }
761:
762: sub remove_lock {
763: my ($id)=@_;
764: my $newlocks='';
765: foreach my $lock (split(/\,/,$env{'session.locks'})) {
766: if (($lock=~/\w/) && ($lock ne $id)) {
767: $newlocks.=','.$lock;
768: }
769: }
770: &appenv({'session.locks' => $newlocks});
771: &delenv('session.lock.'.$id);
772: }
773:
774: sub remove_all_locks {
775: my $activelocks=$env{'session.locks'};
776: foreach my $lock (split(/\,/,$env{'session.locks'})) {
777: if ($lock=~/\w/) {
778: &remove_lock($lock);
779: }
780: }
781: }
782:
783:
1.369 albertel 784: # ------------------------------------------ Find out current server userload
785: sub userload {
786: my $numusers=0;
787: {
788: opendir(LONIDS,$perlvar{'lonIDsDir'});
789: my $filename;
790: my $curtime=time;
791: while ($filename=readdir(LONIDS)) {
1.925 albertel 792: next if ($filename eq '.' || $filename eq '..');
793: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 794: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 795: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 796: }
797: closedir(LONIDS);
798: }
799: my $userloadpercent=0;
800: my $maxuserload=$perlvar{'lonUserLoadLim'};
801: if ($maxuserload) {
1.371 albertel 802: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 803: }
1.372 albertel 804: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 805: return $userloadpercent;
1.283 www 806: }
807:
1.1 albertel 808: # ------------------------------ Find server with least workload from spare.tab
1.11 www 809:
1.1 albertel 810: sub spareserver {
1.1083 raeburn 811: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 812: my $spare_server;
1.370 albertel 813: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 814: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
815: : $userloadpercent;
1.1083 raeburn 816: my ($uint_dom,$remotesessions);
817: if (($udom ne '') && (&domain($udom) ne '')) {
818: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
819: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
820: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
821: $remotesessions = $udomdefaults{'remotesessions'};
822: }
1.1123 raeburn 823: my $spareshash = &this_host_spares($udom);
824: if (ref($spareshash) eq 'HASH') {
825: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
826: foreach my $try_server (@{ $spareshash->{'primary'} }) {
827: if ($uint_dom) {
828: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
829: $try_server));
830: }
831: ($spare_server, $lowest_load) =
832: &compare_server_load($try_server, $spare_server, $lowest_load);
833: }
1.1083 raeburn 834: }
1.784 albertel 835:
1.1123 raeburn 836: my $found_server = ($spare_server ne '' && $lowest_load < 100);
837:
838: if (!$found_server) {
839: if (ref($spareshash->{'default'}) eq 'ARRAY') {
840: foreach my $try_server (@{ $spareshash->{'default'} }) {
841: if ($uint_dom) {
842: next unless (&spare_can_host($udom,$uint_dom,
843: $remotesessions,$try_server));
844: }
845: ($spare_server, $lowest_load) =
846: &compare_server_load($try_server, $spare_server, $lowest_load);
847: }
848: }
849: }
1.784 albertel 850: }
851:
852: if (!$want_server_name) {
1.968 raeburn 853: my $protocol = 'http';
854: if ($protocol{$spare_server} eq 'https') {
855: $protocol = $protocol{$spare_server};
856: }
1.1001 raeburn 857: if (defined($spare_server)) {
858: my $hostname = &hostname($spare_server);
1.1083 raeburn 859: if (defined($hostname)) {
1.1001 raeburn 860: $spare_server = $protocol.'://'.$hostname;
861: }
862: }
1.784 albertel 863: }
864: return $spare_server;
865: }
866:
867: sub compare_server_load {
868: my ($try_server, $spare_server, $lowest_load) = @_;
869:
870: my $loadans = &reply('load', $try_server);
871: my $userloadans = &reply('userload',$try_server);
872:
873: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 874: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 875: }
876:
877: my $load;
878: if ($loadans =~ /\d/) {
879: if ($userloadans =~ /\d/) {
880: #both are numbers, pick the bigger one
881: $load = ($loadans > $userloadans) ? $loadans
882: : $userloadans;
1.411 albertel 883: } else {
1.784 albertel 884: $load = $loadans;
1.411 albertel 885: }
1.784 albertel 886: } else {
887: $load = $userloadans;
888: }
889:
890: if (($load =~ /\d/) && ($load < $lowest_load)) {
891: $spare_server = $try_server;
892: $lowest_load = $load;
1.370 albertel 893: }
1.784 albertel 894: return ($spare_server,$lowest_load);
1.202 matthew 895: }
1.914 albertel 896:
897: # --------------------------- ask offload servers if user already has a session
898: sub find_existing_session {
899: my ($udom,$uname) = @_;
1.1123 raeburn 900: my $spareshash = &this_host_spares($udom);
901: if (ref($spareshash) eq 'HASH') {
902: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
903: foreach my $try_server (@{ $spareshash->{'primary'} }) {
904: return $try_server if (&has_user_session($try_server, $udom, $uname));
905: }
906: }
907: if (ref($spareshash->{'default'}) eq 'ARRAY') {
908: foreach my $try_server (@{ $spareshash->{'default'} }) {
909: return $try_server if (&has_user_session($try_server, $udom, $uname));
910: }
911: }
1.914 albertel 912: }
913: return;
914: }
915:
916: # -------------------------------- ask if server already has a session for user
917: sub has_user_session {
918: my ($lonid,$udom,$uname) = @_;
919: my $result = &reply(join(':','userhassession',
920: map {&escape($_)} ($udom,$uname)),$lonid);
921: return 1 if ($result eq 'ok');
922:
923: return 0;
924: }
925:
1.1076 raeburn 926: # --------- determine least loaded server in a user's domain which allows login
927:
928: sub choose_server {
1.1115 raeburn 929: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 930: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 931: my %servers = &get_servers($udom);
1.1076 raeburn 932: my $lowest_load = 30000;
1.1116 raeburn 933: my ($login_host,$hostname,$portal_path);
1.1076 raeburn 934: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 935: my $loginvia;
936: if ($checkloginvia) {
937: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 938: if ($loginvia) {
939: my ($server,$path) = split(/:/,$loginvia);
940: ($login_host, $lowest_load) =
941: &compare_server_load($server, $login_host, $lowest_load);
942: if ($login_host eq $server) {
943: $portal_path = $path;
944: }
945: } else {
946: ($login_host, $lowest_load) =
947: &compare_server_load($lonhost, $login_host, $lowest_load);
948: if ($login_host eq $lonhost) {
949: $portal_path = '';
950: }
951: }
952: } else {
1.1076 raeburn 953: ($login_host, $lowest_load) =
1.1116 raeburn 954: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 955: }
956: }
957: if ($login_host ne '') {
1.1116 raeburn 958: $hostname = &hostname($login_host);
1.1076 raeburn 959: }
1.1116 raeburn 960: return ($login_host,$hostname,$portal_path);
1.1076 raeburn 961: }
962:
1.202 matthew 963: # --------------------------------------------- Try to change a user's password
964:
965: sub changepass {
1.799 raeburn 966: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 967: $currentpass = &escape($currentpass);
968: $newpass = &escape($newpass);
1.1030 raeburn 969: my $lonhost = $perlvar{'lonHostID'};
970: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 971: $server);
972: if (! $answer) {
973: &logthis("No reply on password change request to $server ".
974: "by $uname in domain $udom.");
975: } elsif ($answer =~ "^ok") {
976: &logthis("$uname in $udom successfully changed their password ".
977: "on $server.");
978: } elsif ($answer =~ "^pwchange_failure") {
979: &logthis("$uname in $udom was unable to change their password ".
980: "on $server. The action was blocked by either lcpasswd ".
981: "or pwchange");
982: } elsif ($answer =~ "^non_authorized") {
983: &logthis("$uname in $udom did not get their password correct when ".
984: "attempting to change it on $server.");
985: } elsif ($answer =~ "^auth_mode_error") {
986: &logthis("$uname in $udom attempted to change their password despite ".
987: "not being locally or internally authenticated on $server.");
988: } elsif ($answer =~ "^unknown_user") {
989: &logthis("$uname in $udom attempted to change their password ".
990: "on $server but were unable to because $server is not ".
991: "their home server.");
992: } elsif ($answer =~ "^refused") {
993: &logthis("$server refused to change $uname in $udom password because ".
994: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 995: } elsif ($answer =~ "invalid_client") {
996: &logthis("$server refused to change $uname in $udom password because ".
997: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 998: }
999: return $answer;
1.1 albertel 1000: }
1001:
1.169 harris41 1002: # ----------------------- Try to determine user's current authentication scheme
1003:
1004: sub queryauthenticate {
1005: my ($uname,$udom)=@_;
1.456 albertel 1006: my $uhome=&homeserver($uname,$udom);
1007: if (!$uhome) {
1008: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1009: return 'no_host';
1010: }
1011: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1012: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1013: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1014: }
1.456 albertel 1015: return $answer;
1.169 harris41 1016: }
1017:
1.1 albertel 1018: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1019:
1.1 albertel 1020: sub authenticate {
1.1073 raeburn 1021: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1022: $upass=&escape($upass);
1023: $uname= &LONCAPA::clean_username($uname);
1.836 www 1024: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1025: my $newhome;
1.836 www 1026: if ((!$uhome) || ($uhome eq 'no_host')) {
1027: # Maybe the machine was offline and only re-appeared again recently?
1028: &reconlonc();
1029: # One more
1.952 raeburn 1030: $uhome=&homeserver($uname,$udom,1);
1031: if (($uhome eq 'no_host') && $checkdefauth) {
1032: if (defined(&domain($udom,'primary'))) {
1033: $newhome=&domain($udom,'primary');
1034: }
1035: if ($newhome ne '') {
1036: $uhome = $newhome;
1037: }
1038: }
1.836 www 1039: if ((!$uhome) || ($uhome eq 'no_host')) {
1040: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1041: return 'no_host';
1042: }
1.1 albertel 1043: }
1.1073 raeburn 1044: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1045: if ($answer eq 'authorized') {
1.952 raeburn 1046: if ($newhome) {
1047: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1048: return 'no_account_on_host';
1049: } else {
1050: &logthis("User $uname at $udom authorized by $uhome");
1051: return $uhome;
1052: }
1.471 albertel 1053: }
1054: if ($answer eq 'non_authorized') {
1055: &logthis("User $uname at $udom rejected by $uhome");
1056: return 'no_host';
1.9 www 1057: }
1.471 albertel 1058: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1059: return 'no_host';
1060: }
1061:
1.1073 raeburn 1062: sub can_host_session {
1.1074 raeburn 1063: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1064: my $canhost = 1;
1.1074 raeburn 1065: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1066: if (ref($remotesessions) eq 'HASH') {
1067: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1068: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1069: $canhost = 0;
1070: } else {
1071: $canhost = 1;
1072: }
1073: }
1074: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1075: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1076: $canhost = 1;
1077: } else {
1078: $canhost = 0;
1079: }
1080: }
1081: if ($canhost) {
1082: if ($remotesessions->{'version'} ne '') {
1083: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1084: if ($reqmajor ne '' && $reqminor ne '') {
1085: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1086: my $major = $1;
1087: my $minor = $2;
1088: if (($major < $reqmajor ) ||
1089: (($major == $reqmajor) && ($minor < $reqminor))) {
1090: $canhost = 0;
1091: }
1092: } else {
1093: $canhost = 0;
1094: }
1095: }
1096: }
1097: }
1098: }
1099: if ($canhost) {
1100: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1101: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1102: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1103: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1104: if (($uint_dom ne '') &&
1105: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1106: $canhost = 0;
1107: } else {
1108: $canhost = 1;
1109: }
1110: }
1111: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1112: if (($uint_dom ne '') &&
1113: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1114: $canhost = 1;
1115: } else {
1116: $canhost = 0;
1117: }
1118: }
1119: }
1120: }
1121: return $canhost;
1122: }
1123:
1.1083 raeburn 1124: sub spare_can_host {
1125: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1126: my $canhost=1;
1127: my @intdoms;
1128: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1129: if (ref($internet_names) eq 'ARRAY') {
1130: @intdoms = @{$internet_names};
1131: }
1132: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1133: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1134: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1135: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1136: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1137: $canhost = &can_host_session($udom,$try_server,$remoterev,
1138: $remotesessions,
1139: $defdomdefaults{'hostedsessions'});
1140: }
1141: return $canhost;
1142: }
1143:
1.1123 raeburn 1144: sub this_host_spares {
1145: my ($dom) = @_;
1.1126 raeburn 1146: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1147: my @hosts = ¤t_machine_ids();
1148: foreach my $lonhost (@hosts) {
1149: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1150: $dom_in_use = $dom;
1151: $lonhost_in_use = $lonhost;
1.1123 raeburn 1152: last;
1153: }
1154: }
1.1126 raeburn 1155: if ($dom_in_use ne '') {
1156: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1157: }
1158: if (ref($result) ne 'HASH') {
1159: $lonhost_in_use = $perlvar{'lonHostID'};
1160: $dom_in_use = &host_domain($lonhost_in_use);
1161: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1162: if (ref($result) ne 'HASH') {
1163: $result = \%spareid;
1164: }
1165: }
1166: return $result;
1167: }
1168:
1169: sub spares_for_offload {
1170: my ($dom_in_use,$lonhost_in_use) = @_;
1171: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1172: if (defined($cached)) {
1173: return $result;
1174: } else {
1.1126 raeburn 1175: my $cachetime = 60*60*24;
1176: my %domconfig =
1177: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1178: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1179: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1180: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1181: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1182: }
1183: }
1184: }
1185: }
1.1126 raeburn 1186: return;
1.1123 raeburn 1187: }
1188:
1.1129 raeburn 1189: sub get_lonbalancer_config {
1190: my ($servers) = @_;
1191: my ($currbalancer,$currtargets);
1192: if (ref($servers) eq 'HASH') {
1193: foreach my $server (keys(%{$servers})) {
1194: my %what = (
1195: spareid => 1,
1196: perlvar => 1,
1197: );
1198: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1199: if ($result eq 'ok') {
1200: if (ref($returnhash) eq 'HASH') {
1201: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1202: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1203: $currbalancer = $server;
1204: $currtargets = {};
1205: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1206: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1207: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1208: }
1209: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1210: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1211: }
1212: }
1213: last;
1214: }
1215: }
1216: }
1217: }
1218: }
1219: }
1220: return ($currbalancer,$currtargets);
1221: }
1222:
1223: sub check_loadbalancing {
1224: my ($uname,$udom) = @_;
1225: my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
1226: $offloadto,$otherserver);
1227: my $lonhost = $perlvar{'lonHostID'};
1228: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1229: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1230: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1231: my $serverhomedom = &host_domain($lonhost);
1232:
1233: my $cachetime = 60*60*24;
1234:
1235: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1236: $dom_in_use = $udom;
1237: $homeintdom = 1;
1238: } else {
1239: $dom_in_use = $serverhomedom;
1240: }
1241: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1242: unless (defined($cached)) {
1243: my %domconfig =
1244: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1245: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1246: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1247: }
1248: }
1249: if (ref($result) eq 'HASH') {
1250: my $currbalancer = $result->{'lonhost'};
1251: my $currtargets = $result->{'targets'};
1252: my $currrules = $result->{'rules'};
1253: if ($currbalancer ne '') {
1254: my @hosts = ¤t_machine_ids();
1255: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1256: $is_balancer = 1;
1257: }
1258: }
1259: if ($is_balancer) {
1260: if (ref($currrules) eq 'HASH') {
1261: if ($homeintdom) {
1262: if ($uname ne '') {
1263: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1264: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1265: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1266: $rule_in_effect = $currrules->{'_LC_author'};
1267: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1268: $rule_in_effect = $currrules->{'_LC_adv'}
1269: }
1270: }
1271: if ($rule_in_effect eq '') {
1272: my %userenv = &userenvironment($udom,$uname,'inststatus');
1273: if ($userenv{'inststatus'} ne '') {
1274: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1275: my ($othertitle,$usertypes,$types) =
1276: &Apache::loncommon::sorted_inst_types($udom);
1277: if (ref($types) eq 'ARRAY') {
1278: foreach my $type (@{$types}) {
1279: if (grep(/^\Q$type\E$/,@statuses)) {
1280: if (exists($currrules->{$type})) {
1281: $rule_in_effect = $currrules->{$type};
1282: }
1283: }
1284: }
1285: }
1286: } else {
1287: if (exists($currrules->{'default'})) {
1288: $rule_in_effect = $currrules->{'default'};
1289: }
1290: }
1291: }
1292: } else {
1293: if (exists($currrules->{'default'})) {
1294: $rule_in_effect = $currrules->{'default'};
1295: }
1296: }
1297: } else {
1298: if ($currrules->{'_LC_external'} ne '') {
1299: $rule_in_effect = $currrules->{'_LC_external'};
1300: }
1301: }
1302: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1303: $uname,$udom);
1304: }
1305: }
1306: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1307: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1308: unless (defined($cached)) {
1309: my %domconfig =
1310: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1311: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1312: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1313: }
1314: }
1315: if (ref($result) eq 'HASH') {
1316: my $currbalancer = $result->{'lonhost'};
1317: my $currtargets = $result->{'targets'};
1318: my $currrules = $result->{'rules'};
1319:
1320: if ($currbalancer eq $lonhost) {
1321: $is_balancer = 1;
1322: if (ref($currrules) eq 'HASH') {
1323: if ($currrules->{'_LC_internetdom'} ne '') {
1324: $rule_in_effect = $currrules->{'_LC_internetdom'};
1325: }
1326: }
1327: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1328: $uname,$udom);
1329: }
1330: } else {
1331: if ($perlvar{'lonBalancer'} eq 'yes') {
1332: $is_balancer = 1;
1333: $offloadto = &this_host_spares($dom_in_use);
1334: }
1335: }
1336: } else {
1337: if ($perlvar{'lonBalancer'} eq 'yes') {
1338: $is_balancer = 1;
1339: $offloadto = &this_host_spares($dom_in_use);
1340: }
1341: }
1342: my $lowest_load = 30000;
1343: if (ref($offloadto) eq 'HASH') {
1344: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1345: foreach my $try_server (@{$offloadto->{'primary'}}) {
1346: ($otherserver,$lowest_load) =
1347: &compare_server_load($try_server,$otherserver,$lowest_load);
1348: }
1349: }
1350: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1351:
1352: if (!$found_server) {
1353: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1354: foreach my $try_server (@{$offloadto->{'default'}}) {
1355: ($otherserver,$lowest_load) =
1356: &compare_server_load($try_server,$otherserver,$lowest_load);
1357: }
1358: }
1359: }
1360: } elsif (ref($offloadto) eq 'ARRAY') {
1361: if (@{$offloadto} == 1) {
1362: $otherserver = $offloadto->[0];
1363: } elsif (@{$offloadto} > 1) {
1364: foreach my $try_server (@{$offloadto}) {
1365: ($otherserver,$lowest_load) =
1366: &compare_server_load($try_server,$otherserver,$lowest_load);
1367: }
1368: }
1369: }
1370: return ($is_balancer,$otherserver);
1371: }
1372:
1373: sub get_loadbalancer_targets {
1374: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1375: my $offloadto;
1376: if ($rule_in_effect eq '') {
1377: $offloadto = $currtargets;
1378: } else {
1379: if ($rule_in_effect eq 'homeserver') {
1380: my $homeserver = &homeserver($uname,$udom);
1381: if ($homeserver ne 'no_host') {
1382: $offloadto = [$homeserver];
1383: }
1384: } elsif ($rule_in_effect eq 'externalbalancer') {
1385: my %domconfig =
1386: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1387: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1388: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1389: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1390: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1391: }
1392: }
1393: } else {
1394: my %servers = &dom_servers($udom);
1395: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1396: if (&hostname($remotebalancer) ne '') {
1397: $offloadto = [$remotebalancer];
1398: }
1399: }
1400: } elsif (&hostname($rule_in_effect) ne '') {
1401: $offloadto = [$rule_in_effect];
1402: }
1403: }
1404: return $offloadto;
1405: }
1406:
1.1127 raeburn 1407: sub internet_dom_servers {
1408: my ($dom) = @_;
1409: my (%uniqservers,%servers);
1410: my $primaryserver = &hostname(&domain($dom,'primary'));
1411: my @machinedoms = &machine_domains($primaryserver);
1412: foreach my $mdom (@machinedoms) {
1413: my %currservers = %servers;
1414: my %server = &get_servers($mdom);
1415: %servers = (%currservers,%server);
1416: }
1417: my %by_hostname;
1418: foreach my $id (keys(%servers)) {
1419: push(@{$by_hostname{$servers{$id}}},$id);
1420: }
1421: foreach my $hostname (sort(keys(%by_hostname))) {
1422: if (@{$by_hostname{$hostname}} > 1) {
1423: my $match = 0;
1424: foreach my $id (@{$by_hostname{$hostname}}) {
1425: if (&host_domain($id) eq $dom) {
1426: $uniqservers{$id} = $hostname;
1427: $match = 1;
1428: }
1429: }
1430: unless ($match) {
1431: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1432: }
1433: } else {
1434: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1435: }
1436: }
1437: return %uniqservers;
1438: }
1439:
1.1 albertel 1440: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1441:
1.599 albertel 1442: my %homecache;
1.1 albertel 1443: sub homeserver {
1.230 stredwic 1444: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1445: my $index="$uname:$udom";
1.426 albertel 1446:
1.599 albertel 1447: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1448:
1449: my %servers = &get_servers($udom,'library');
1450: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1451: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1452: exists($badServerCache{$tryserver}));
1.841 albertel 1453:
1454: my $answer=reply("home:$udom:$uname",$tryserver);
1455: if ($answer eq 'found') {
1456: delete($badServerCache{$tryserver});
1457: return $homecache{$index}=$tryserver;
1458: } elsif ($answer eq 'no_host') {
1459: $badServerCache{$tryserver}=1;
1460: }
1.1 albertel 1461: }
1462: return 'no_host';
1.70 www 1463: }
1464:
1465: # ------------------------------------- Find the usernames behind a list of IDs
1466:
1467: sub idget {
1468: my ($udom,@ids)=@_;
1469: my %returnhash=();
1470:
1.841 albertel 1471: my %servers = &get_servers($udom,'library');
1472: foreach my $tryserver (keys(%servers)) {
1473: my $idlist=join('&',@ids);
1474: $idlist=~tr/A-Z/a-z/;
1475: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1476: my @answer=();
1477: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1478: @answer=split(/\&/,$reply);
1479: } ;
1480: my $i;
1481: for ($i=0;$i<=$#ids;$i++) {
1482: if ($answer[$i]) {
1483: $returnhash{$ids[$i]}=$answer[$i];
1484: }
1485: }
1486: }
1.70 www 1487: return %returnhash;
1488: }
1489:
1490: # ------------------------------------- Find the IDs behind a list of usernames
1491:
1492: sub idrget {
1493: my ($udom,@unames)=@_;
1494: my %returnhash=();
1.800 albertel 1495: foreach my $uname (@unames) {
1496: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1497: }
1.70 www 1498: return %returnhash;
1499: }
1500:
1501: # ------------------------------- Store away a list of names and associated IDs
1502:
1503: sub idput {
1504: my ($udom,%ids)=@_;
1505: my %servers=();
1.800 albertel 1506: foreach my $uname (keys(%ids)) {
1507: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1508: my $uhom=&homeserver($uname,$udom);
1.70 www 1509: if ($uhom ne 'no_host') {
1.800 albertel 1510: my $id=&escape($ids{$uname});
1.70 www 1511: $id=~tr/A-Z/a-z/;
1.800 albertel 1512: my $esc_unam=&escape($uname);
1.70 www 1513: if ($servers{$uhom}) {
1.800 albertel 1514: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1515: } else {
1.800 albertel 1516: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1517: }
1518: }
1.191 harris41 1519: }
1.800 albertel 1520: foreach my $server (keys(%servers)) {
1521: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1522: }
1.344 www 1523: }
1524:
1.1023 raeburn 1525: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1526: sub dump_dom {
1.1023 raeburn 1527: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1528: if (!$udom) {
1529: $udom=$env{'user.domain'};
1530: }
1531: my %returnhash;
1.1023 raeburn 1532: if ($udom) {
1533: my $uname = &get_domainconfiguser($udom);
1534: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1535: }
1536: return %returnhash;
1537: }
1538:
1.1023 raeburn 1539: # ------------------------------------------ get items from domain db files
1.806 raeburn 1540:
1541: sub get_dom {
1.860 raeburn 1542: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1543: my $items='';
1544: foreach my $item (@$storearr) {
1545: $items.=&escape($item).'&';
1546: }
1547: $items=~s/\&$//;
1.860 raeburn 1548: if (!$udom) {
1549: $udom=$env{'user.domain'};
1550: if (defined(&domain($udom,'primary'))) {
1551: $uhome=&domain($udom,'primary');
1552: } else {
1.874 albertel 1553: undef($uhome);
1.860 raeburn 1554: }
1555: } else {
1556: if (!$uhome) {
1557: if (defined(&domain($udom,'primary'))) {
1558: $uhome=&domain($udom,'primary');
1559: }
1560: }
1561: }
1562: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1563: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1564: my %returnhash;
1.875 albertel 1565: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1566: return %returnhash;
1567: }
1.806 raeburn 1568: my @pairs=split(/\&/,$rep);
1569: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1570: return @pairs;
1571: }
1572: my $i=0;
1573: foreach my $item (@$storearr) {
1574: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1575: $i++;
1576: }
1577: return %returnhash;
1578: } else {
1.880 banghart 1579: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1580: }
1581: }
1582:
1583: # -------------------------------------------- put items in domain db files
1584:
1585: sub put_dom {
1.860 raeburn 1586: my ($namespace,$storehash,$udom,$uhome)=@_;
1587: if (!$udom) {
1588: $udom=$env{'user.domain'};
1589: if (defined(&domain($udom,'primary'))) {
1590: $uhome=&domain($udom,'primary');
1591: } else {
1.874 albertel 1592: undef($uhome);
1.860 raeburn 1593: }
1594: } else {
1595: if (!$uhome) {
1596: if (defined(&domain($udom,'primary'))) {
1597: $uhome=&domain($udom,'primary');
1598: }
1599: }
1600: }
1601: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1602: my $items='';
1603: foreach my $item (keys(%$storehash)) {
1604: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1605: }
1606: $items=~s/\&$//;
1607: return &reply("putdom:$udom:$namespace:$items",$uhome);
1608: } else {
1.860 raeburn 1609: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1610: }
1611: }
1612:
1.1023 raeburn 1613: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1614: sub newput_dom {
1.1023 raeburn 1615: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1616: my $result;
1617: if (!$udom) {
1618: $udom=$env{'user.domain'};
1619: }
1.1023 raeburn 1620: if ($udom) {
1621: my $uname = &get_domainconfiguser($udom);
1622: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1623: }
1624: return $result;
1625: }
1626:
1.1023 raeburn 1627: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1628: sub del_dom {
1.1023 raeburn 1629: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1630: if (ref($storearr) eq 'ARRAY') {
1631: if (!$udom) {
1632: $udom=$env{'user.domain'};
1633: }
1.1023 raeburn 1634: if ($udom) {
1635: my $uname = &get_domainconfiguser($udom);
1636: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1637: }
1638: }
1639: }
1640:
1.1023 raeburn 1641: # ----------------------------------construct domainconfig user for a domain
1642: sub get_domainconfiguser {
1643: my ($udom) = @_;
1644: return $udom.'-domainconfig';
1645: }
1646:
1.837 raeburn 1647: sub retrieve_inst_usertypes {
1648: my ($udom) = @_;
1649: my (%returnhash,@order);
1.989 raeburn 1650: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1651: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1652: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1653: %returnhash = %{$domdefs{'inststatustypes'}};
1654: @order = @{$domdefs{'inststatusorder'}};
1655: } else {
1656: if (defined(&domain($udom,'primary'))) {
1657: my $uhome=&domain($udom,'primary');
1658: my $rep=&reply("inst_usertypes:$udom",$uhome);
1659: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1660: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1661: return (\%returnhash,\@order);
1662: }
1663: my ($hashitems,$orderitems) = split(/:/,$rep);
1664: my @pairs=split(/\&/,$hashitems);
1665: foreach my $item (@pairs) {
1666: my ($key,$value)=split(/=/,$item,2);
1667: $key = &unescape($key);
1668: next if ($key =~ /^error: 2 /);
1669: $returnhash{$key}=&thaw_unescape($value);
1670: }
1671: my @esc_order = split(/\&/,$orderitems);
1672: foreach my $item (@esc_order) {
1673: push(@order,&unescape($item));
1674: }
1675: } else {
1676: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1677: }
1678: }
1679: return (\%returnhash,\@order);
1680: }
1681:
1.868 raeburn 1682: sub is_domainimage {
1683: my ($url) = @_;
1684: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1685: if (&domain($1) ne '') {
1686: return '1';
1687: }
1688: }
1689: return;
1690: }
1691:
1.899 raeburn 1692: sub inst_directory_query {
1693: my ($srch) = @_;
1694: my $udom = $srch->{'srchdomain'};
1695: my %results;
1696: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1697: my $outcome;
1.899 raeburn 1698: if ($homeserver ne '') {
1.904 albertel 1699: my $queryid=&reply("querysend:instdirsearch:".
1700: &escape($srch->{'srchby'}).':'.
1701: &escape($srch->{'srchterm'}).':'.
1702: &escape($srch->{'srchtype'}),$homeserver);
1703: my $host=&hostname($homeserver);
1704: if ($queryid !~/^\Q$host\E\_/) {
1705: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1706: return;
1707: }
1708: my $response = &get_query_reply($queryid);
1709: my $maxtries = 5;
1710: my $tries = 1;
1711: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1712: $response = &get_query_reply($queryid);
1713: $tries ++;
1714: }
1715:
1716: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1717: if ($response eq 'unavailable') {
1718: $outcome = $response;
1719: } else {
1720: $outcome = 'ok';
1721: my @matches = split(/\n/,$response);
1722: foreach my $match (@matches) {
1723: my ($key,$value) = split(/=/,$match);
1724: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1725: }
1.899 raeburn 1726: }
1727: }
1728: }
1.909 raeburn 1729: return ($outcome,%results);
1.899 raeburn 1730: }
1731:
1732: sub usersearch {
1733: my ($srch) = @_;
1734: my $dom = $srch->{'srchdomain'};
1735: my %results;
1736: my %libserv = &all_library();
1737: my $query = 'usersearch';
1738: foreach my $tryserver (keys(%libserv)) {
1739: if (&host_domain($tryserver) eq $dom) {
1740: my $host=&hostname($tryserver);
1741: my $queryid=
1.911 raeburn 1742: &reply("querysend:".&escape($query).':'.
1743: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1744: &escape($srch->{'srchtype'}).':'.
1745: &escape($srch->{'srchterm'}),$tryserver);
1746: if ($queryid !~/^\Q$host\E\_/) {
1747: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1748: next;
1.899 raeburn 1749: }
1750: my $reply = &get_query_reply($queryid);
1751: my $maxtries = 1;
1752: my $tries = 1;
1753: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1754: $reply = &get_query_reply($queryid);
1755: $tries ++;
1756: }
1757: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1758: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1759: } else {
1.911 raeburn 1760: my @matches;
1761: if ($reply =~ /\n/) {
1762: @matches = split(/\n/,$reply);
1763: } else {
1764: @matches = split(/\&/,$reply);
1765: }
1.899 raeburn 1766: foreach my $match (@matches) {
1767: my ($uname,$udom,%userhash);
1.911 raeburn 1768: foreach my $entry (split(/:/,$match)) {
1769: my ($key,$value) =
1770: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1771: $userhash{$key} = $value;
1772: if ($key eq 'username') {
1773: $uname = $value;
1774: } elsif ($key eq 'domain') {
1775: $udom = $value;
1.911 raeburn 1776: }
1.899 raeburn 1777: }
1778: $results{$uname.':'.$udom} = \%userhash;
1779: }
1780: }
1781: }
1782: }
1783: return %results;
1784: }
1785:
1.912 raeburn 1786: sub get_instuser {
1787: my ($udom,$uname,$id) = @_;
1788: my $homeserver = &domain($udom,'primary');
1789: my ($outcome,%results);
1790: if ($homeserver ne '') {
1791: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1792: &escape($id).':'.&escape($udom),$homeserver);
1793: my $host=&hostname($homeserver);
1794: if ($queryid !~/^\Q$host\E\_/) {
1795: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1796: return;
1797: }
1798: my $response = &get_query_reply($queryid);
1799: my $maxtries = 5;
1800: my $tries = 1;
1801: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1802: $response = &get_query_reply($queryid);
1803: $tries ++;
1804: }
1805: if (!&error($response) && $response ne 'refused') {
1806: if ($response eq 'unavailable') {
1807: $outcome = $response;
1808: } else {
1809: $outcome = 'ok';
1810: my @matches = split(/\n/,$response);
1811: foreach my $match (@matches) {
1812: my ($key,$value) = split(/=/,$match);
1813: $results{&unescape($key)} = &thaw_unescape($value);
1814: }
1815: }
1816: }
1817: }
1818: my %userinfo;
1819: if (ref($results{$uname}) eq 'HASH') {
1820: %userinfo = %{$results{$uname}};
1821: }
1822: return ($outcome,%userinfo);
1823: }
1824:
1825: sub inst_rulecheck {
1.923 raeburn 1826: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1827: my %returnhash;
1828: if ($udom ne '') {
1829: if (ref($rules) eq 'ARRAY') {
1830: @{$rules} = map {&escape($_);} (@{$rules});
1831: my $rulestr = join(':',@{$rules});
1832: my $homeserver=&domain($udom,'primary');
1833: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1834: my $response;
1835: if ($item eq 'username') {
1836: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1837: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1838: $homeserver));
1.923 raeburn 1839: } elsif ($item eq 'id') {
1840: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1841: ':'.&escape($id).':'.$rulestr,
1842: $homeserver));
1.945 raeburn 1843: } elsif ($item eq 'selfcreate') {
1844: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1845: &escape($udom).':'.&escape($uname).
1846: ':'.$rulestr,$homeserver));
1.923 raeburn 1847: }
1.912 raeburn 1848: if ($response ne 'refused') {
1849: my @pairs=split(/\&/,$response);
1850: foreach my $item (@pairs) {
1851: my ($key,$value)=split(/=/,$item,2);
1852: $key = &unescape($key);
1853: next if ($key =~ /^error: 2 /);
1854: $returnhash{$key}=&thaw_unescape($value);
1855: }
1856: }
1857: }
1858: }
1859: }
1860: return %returnhash;
1861: }
1862:
1863: sub inst_userrules {
1.923 raeburn 1864: my ($udom,$check) = @_;
1.912 raeburn 1865: my (%ruleshash,@ruleorder);
1866: if ($udom ne '') {
1867: my $homeserver=&domain($udom,'primary');
1868: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1869: my $response;
1870: if ($check eq 'id') {
1871: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1872: $homeserver);
1.943 raeburn 1873: } elsif ($check eq 'email') {
1874: $response=&reply('instemailrules:'.&escape($udom),
1875: $homeserver);
1.923 raeburn 1876: } else {
1877: $response=&reply('instuserrules:'.&escape($udom),
1878: $homeserver);
1879: }
1.912 raeburn 1880: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1881: ($response ne 'unknown_cmd') &&
1.912 raeburn 1882: ($response ne 'no_such_host')) {
1883: my ($hashitems,$orderitems) = split(/:/,$response);
1884: my @pairs=split(/\&/,$hashitems);
1885: foreach my $item (@pairs) {
1886: my ($key,$value)=split(/=/,$item,2);
1887: $key = &unescape($key);
1888: next if ($key =~ /^error: 2 /);
1889: $ruleshash{$key}=&thaw_unescape($value);
1890: }
1891: my @esc_order = split(/\&/,$orderitems);
1892: foreach my $item (@esc_order) {
1893: push(@ruleorder,&unescape($item));
1894: }
1895: }
1896: }
1897: }
1898: return (\%ruleshash,\@ruleorder);
1899: }
1900:
1.976 raeburn 1901: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1902:
1903: sub get_domain_defaults {
1904: my ($domain) = @_;
1905: my $cachetime = 60*60*24;
1906: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1907: if (defined($cached)) {
1908: if (ref($result) eq 'HASH') {
1909: return %{$result};
1910: }
1911: }
1912: my %domdefaults;
1913: my %domconfig =
1.989 raeburn 1914: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1915: 'requestcourses','inststatus',
1.1073 raeburn 1916: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1917: if (ref($domconfig{'defaults'}) eq 'HASH') {
1918: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1919: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1920: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1921: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1922: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 1923: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 1924: } else {
1925: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1926: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1927: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1928: }
1.976 raeburn 1929: if (ref($domconfig{'quotas'}) eq 'HASH') {
1930: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1931: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1932: } else {
1933: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1934: }
1935: my @usertools = ('aboutme','blog','portfolio');
1936: foreach my $item (@usertools) {
1937: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1938: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1939: }
1940: }
1941: }
1.985 raeburn 1942: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1943: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1944: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1945: }
1946: }
1.989 raeburn 1947: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1948: foreach my $item ('inststatustypes','inststatusorder') {
1949: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1950: }
1951: }
1.1047 raeburn 1952: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1953: foreach my $item ('canuse_pdfforms') {
1954: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1955: }
1956: }
1.1073 raeburn 1957: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1958: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1959: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1960: }
1961: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1962: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1963: }
1964: }
1.943 raeburn 1965: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1966: $cachetime);
1967: return %domdefaults;
1968: }
1969:
1.344 www 1970: # --------------------------------------------------- Assign a key to a student
1971:
1972: sub assign_access_key {
1.364 www 1973: #
1974: # a valid key looks like uname:udom#comments
1975: # comments are being appended
1976: #
1.498 www 1977: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1978: $kdom=
1.620 albertel 1979: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1980: $knum=
1.620 albertel 1981: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1982: $cdom=
1.620 albertel 1983: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1984: $cnum=
1.620 albertel 1985: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1986: $udom=$env{'user.name'} unless (defined($udom));
1987: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1988: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1989: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1990: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1991: # assigned to this person
1992: # - this should not happen,
1.345 www 1993: # unless something went wrong
1994: # the first time around
1995: # ready to assign
1.364 www 1996: $logentry=$1.'; '.$logentry;
1.496 www 1997: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1998: $kdom,$knum) eq 'ok') {
1.345 www 1999: # key now belongs to user
1.346 www 2000: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2001: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2002: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2003: return 'ok';
2004: } else {
2005: return
2006: 'error: Count not permanently assign key, will need to be re-entered later.';
2007: }
2008: } else {
2009: return 'error: Could not assign key, try again later.';
2010: }
1.364 www 2011: } elsif (!$existing{$ckey}) {
1.345 www 2012: # the key does not exist
2013: return 'error: The key does not exist';
2014: } else {
2015: # the key is somebody else's
2016: return 'error: The key is already in use';
2017: }
1.344 www 2018: }
2019:
1.364 www 2020: # ------------------------------------------ put an additional comment on a key
2021:
2022: sub comment_access_key {
2023: #
2024: # a valid key looks like uname:udom#comments
2025: # comments are being appended
2026: #
2027: my ($ckey,$cdom,$cnum,$logentry)=@_;
2028: $cdom=
1.620 albertel 2029: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2030: $cnum=
1.620 albertel 2031: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2032: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2033: if ($existing{$ckey}) {
2034: $existing{$ckey}.='; '.$logentry;
2035: # ready to assign
1.367 www 2036: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2037: $cdom,$cnum) eq 'ok') {
2038: return 'ok';
2039: } else {
2040: return 'error: Count not store comment.';
2041: }
2042: } else {
2043: # the key does not exist
2044: return 'error: The key does not exist';
2045: }
2046: }
2047:
1.344 www 2048: # ------------------------------------------------------ Generate a set of keys
2049:
2050: sub generate_access_keys {
1.364 www 2051: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2052: $cdom=
1.620 albertel 2053: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2054: $cnum=
1.620 albertel 2055: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2056: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2057: unless (($cdom) && ($cnum)) { return 0; }
2058: if ($number>10000) { return 0; }
2059: sleep(2); # make sure don't get same seed twice
2060: srand(time()^($$+($$<<15))); # from "Programming Perl"
2061: my $total=0;
2062: for (my $i=1;$i<=$number;$i++) {
2063: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2064: sprintf("%lx",int(100000*rand)).'-'.
2065: sprintf("%lx",int(100000*rand));
2066: $newkey=~s/1/g/g; # folks mix up 1 and l
2067: $newkey=~s/0/h/g; # and also 0 and O
2068: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2069: if ($existing{$newkey}) {
2070: $i--;
2071: } else {
1.364 www 2072: if (&put('accesskeys',
2073: { $newkey => '# generated '.localtime().
1.620 albertel 2074: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2075: '; '.$logentry },
2076: $cdom,$cnum) eq 'ok') {
1.344 www 2077: $total++;
2078: }
2079: }
2080: }
1.620 albertel 2081: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2082: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2083: return $total;
2084: }
2085:
2086: # ------------------------------------------------------- Validate an accesskey
2087:
2088: sub validate_access_key {
2089: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2090: $cdom=
1.620 albertel 2091: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2092: $cnum=
1.620 albertel 2093: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2094: $udom=$env{'user.domain'} unless (defined($udom));
2095: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2096: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2097: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2098: }
2099:
2100: # ------------------------------------- Find the section of student in a course
1.652 albertel 2101: sub devalidate_getsection_cache {
2102: my ($udom,$unam,$courseid)=@_;
2103: my $hashid="$udom:$unam:$courseid";
2104: &devalidate_cache_new('getsection',$hashid);
2105: }
1.298 matthew 2106:
1.815 albertel 2107: sub courseid_to_courseurl {
2108: my ($courseid) = @_;
2109: #already url style courseid
2110: return $courseid if ($courseid =~ m{^/});
2111:
2112: if (exists($env{'course.'.$courseid.'.num'})) {
2113: my $cnum = $env{'course.'.$courseid.'.num'};
2114: my $cdom = $env{'course.'.$courseid.'.domain'};
2115: return "/$cdom/$cnum";
2116: }
2117:
2118: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2119: if (exists($courseinfo{'num'})) {
2120: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2121: }
2122:
2123: return undef;
2124: }
2125:
1.298 matthew 2126: sub getsection {
2127: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2128: my $cachetime=1800;
1.551 albertel 2129:
2130: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2131: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2132: if (defined($cached)) { return $result; }
2133:
1.298 matthew 2134: my %Pending;
2135: my %Expired;
2136: #
2137: # Each role can either have not started yet (pending), be active,
2138: # or have expired.
2139: #
2140: # If there is an active role, we are done.
2141: #
2142: # If there is more than one role which has not started yet,
2143: # choose the one which will start sooner
2144: # If there is one role which has not started yet, return it.
2145: #
2146: # If there is more than one expired role, choose the one which ended last.
2147: # If there is a role which has expired, return it.
2148: #
1.815 albertel 2149: $courseid = &courseid_to_courseurl($courseid);
1.1086 raeburn 2150: my $extra = &freeze_escape({'skipcheck' => 1});
2151: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817 raeburn 2152: foreach my $key (keys(%roleshash)) {
1.479 albertel 2153: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2154: my $section=$1;
2155: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2156: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2157: my $now=time;
1.548 albertel 2158: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2159: $Expired{$end}=$section;
2160: next;
2161: }
1.548 albertel 2162: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2163: $Pending{$start}=$section;
2164: next;
2165: }
1.599 albertel 2166: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2167: }
2168: #
2169: # Presumedly there will be few matching roles from the above
2170: # loop and the sorting time will be negligible.
2171: if (scalar(keys(%Pending))) {
2172: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2173: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2174: }
2175: if (scalar(keys(%Expired))) {
2176: my @sorted = sort {$a <=> $b} keys(%Expired);
2177: my $time = pop(@sorted);
1.599 albertel 2178: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2179: }
1.599 albertel 2180: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2181: }
1.70 www 2182:
1.599 albertel 2183: sub save_cache {
2184: &purge_remembered();
1.722 albertel 2185: #&Apache::loncommon::validate_page();
1.620 albertel 2186: undef(%env);
1.780 albertel 2187: undef($env_loaded);
1.599 albertel 2188: }
1.452 albertel 2189:
1.599 albertel 2190: my $to_remember=-1;
2191: my %remembered;
2192: my %accessed;
2193: my $kicks=0;
2194: my $hits=0;
1.849 albertel 2195: sub make_key {
2196: my ($name,$id) = @_;
1.872 albertel 2197: if (length($id) > 65
2198: && length(&escape($id)) > 200) {
2199: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2200: }
1.849 albertel 2201: return &escape($name.':'.$id);
2202: }
2203:
1.599 albertel 2204: sub devalidate_cache_new {
2205: my ($name,$id,$debug) = @_;
2206: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2207: $id=&make_key($name,$id);
1.599 albertel 2208: $memcache->delete($id);
2209: delete($remembered{$id});
2210: delete($accessed{$id});
2211: }
2212:
2213: sub is_cached_new {
2214: my ($name,$id,$debug) = @_;
1.849 albertel 2215: $id=&make_key($name,$id);
1.599 albertel 2216: if (exists($remembered{$id})) {
1.1133 foxr 2217: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2218: $accessed{$id}=[&gettimeofday()];
2219: $hits++;
2220: return ($remembered{$id},1);
2221: }
2222: my $value = $memcache->get($id);
2223: if (!(defined($value))) {
2224: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2225: return (undef,undef);
1.416 albertel 2226: }
1.599 albertel 2227: if ($value eq '__undef__') {
2228: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2229: $value=undef;
2230: }
2231: &make_room($id,$value,$debug);
2232: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2233: return ($value,1);
2234: }
2235:
2236: sub do_cache_new {
2237: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2238: $id=&make_key($name,$id);
1.599 albertel 2239: my $setvalue=$value;
2240: if (!defined($setvalue)) {
2241: $setvalue='__undef__';
2242: }
1.623 albertel 2243: if (!defined($time) ) {
2244: $time=600;
2245: }
1.599 albertel 2246: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2247: my $result = $memcache->set($id,$setvalue,$time);
2248: if (! $result) {
1.872 albertel 2249: &logthis("caching of id -> $id failed");
1.910 albertel 2250: $memcache->disconnect_all();
1.872 albertel 2251: }
1.600 albertel 2252: # need to make a copy of $value
1.919 albertel 2253: &make_room($id,$value,$debug);
1.599 albertel 2254: return $value;
2255: }
2256:
2257: sub make_room {
2258: my ($id,$value,$debug)=@_;
1.919 albertel 2259:
2260: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2261: : $value;
1.599 albertel 2262: if ($to_remember<0) { return; }
2263: $accessed{$id}=[&gettimeofday()];
2264: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2265: my $to_kick;
2266: my $max_time=0;
2267: foreach my $other (keys(%accessed)) {
2268: if (&tv_interval($accessed{$other}) > $max_time) {
2269: $to_kick=$other;
2270: $max_time=&tv_interval($accessed{$other});
2271: }
2272: }
2273: delete($remembered{$to_kick});
2274: delete($accessed{$to_kick});
2275: $kicks++;
2276: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2277: return;
2278: }
2279:
1.599 albertel 2280: sub purge_remembered {
1.604 albertel 2281: #&logthis("Tossing ".scalar(keys(%remembered)));
2282: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2283: undef(%remembered);
2284: undef(%accessed);
1.428 albertel 2285: }
1.70 www 2286: # ------------------------------------- Read an entry from a user's environment
2287:
2288: sub userenvironment {
2289: my ($udom,$unam,@what)=@_;
1.976 raeburn 2290: my $items;
2291: foreach my $item (@what) {
2292: $items.=&escape($item).'&';
2293: }
2294: $items=~s/\&$//;
1.70 www 2295: my %returnhash=();
1.1009 raeburn 2296: my $uhome = &homeserver($unam,$udom);
2297: unless ($uhome eq 'no_host') {
2298: my @answer=split(/\&/,
2299: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2300: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2301: return %returnhash;
2302: }
1.1009 raeburn 2303: my $i;
2304: for ($i=0;$i<=$#what;$i++) {
2305: $returnhash{$what[$i]}=&unescape($answer[$i]);
2306: }
1.70 www 2307: }
2308: return %returnhash;
1.1 albertel 2309: }
2310:
1.617 albertel 2311: # ---------------------------------------------------------- Get a studentphoto
2312: sub studentphoto {
2313: my ($udom,$unam,$ext) = @_;
2314: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2315: if (defined($env{'request.course.id'})) {
1.708 raeburn 2316: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2317: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2318: return(&retrievestudentphoto($udom,$unam,$ext));
2319: } else {
2320: my ($result,$perm_reqd)=
1.707 albertel 2321: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2322: if ($result eq 'ok') {
2323: if (!($perm_reqd eq 'yes')) {
2324: return(&retrievestudentphoto($udom,$unam,$ext));
2325: }
2326: }
2327: }
2328: }
2329: } else {
2330: my ($result,$perm_reqd) =
1.707 albertel 2331: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2332: if ($result eq 'ok') {
2333: if (!($perm_reqd eq 'yes')) {
2334: return(&retrievestudentphoto($udom,$unam,$ext));
2335: }
2336: }
2337: }
2338: return '/adm/lonKaputt/lonlogo_broken.gif';
2339: }
2340:
2341: sub retrievestudentphoto {
2342: my ($udom,$unam,$ext,$type) = @_;
2343: my $home=&Apache::lonnet::homeserver($unam,$udom);
2344: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2345: if ($ret eq 'ok') {
2346: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2347: if ($type eq 'thumbnail') {
2348: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2349: }
2350: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2351: return $tokenurl;
2352: } else {
2353: if ($type eq 'thumbnail') {
2354: return '/adm/lonKaputt/genericstudent_tn.gif';
2355: } else {
2356: return '/adm/lonKaputt/lonlogo_broken.gif';
2357: }
1.617 albertel 2358: }
2359: }
2360:
1.263 www 2361: # -------------------------------------------------------------------- New chat
2362:
2363: sub chatsend {
1.724 raeburn 2364: my ($newentry,$anon,$group)=@_;
1.620 albertel 2365: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2366: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2367: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2368: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2369: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2370: &escape($newentry)).':'.$group,$chome);
1.292 www 2371: }
2372:
2373: # ------------------------------------------ Find current version of a resource
2374:
2375: sub getversion {
2376: my $fname=&clutter(shift);
2377: unless ($fname=~/^\/res\//) { return -1; }
2378: return ¤tversion(&filelocation('',$fname));
2379: }
2380:
2381: sub currentversion {
2382: my $fname=shift;
2383: my $author=$fname;
2384: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2385: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2386: my $home=&homeserver($uname,$udom);
1.292 www 2387: if ($home eq 'no_host') {
2388: return -1;
2389: }
1.1112 www 2390: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2391: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2392: return -1;
2393: }
1.1112 www 2394: return $answer;
1.263 www 2395: }
2396:
1.1111 www 2397: #
2398: # Return special version number of resource if set by override, empty otherwise
2399: #
2400: sub usedversion {
2401: my $fname=shift;
2402: unless ($fname) { $fname=$env{'request.uri'}; }
2403: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2404: if ($urlversion) { return $urlversion; }
2405: return '';
2406: }
2407:
1.1 albertel 2408: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2409:
1.1 albertel 2410: sub subscribe {
2411: my $fname=shift;
1.761 raeburn 2412: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2413: $fname=~s/[\n\r]//g;
1.1 albertel 2414: my $author=$fname;
2415: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2416: my ($udom,$uname)=split(/\//,$author);
2417: my $home=homeserver($uname,$udom);
1.335 albertel 2418: if ($home eq 'no_host') {
2419: return 'not_found';
1.1 albertel 2420: }
2421: my $answer=reply("sub:$fname",$home);
1.64 www 2422: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2423: $answer.=' by '.$home;
2424: }
1.1 albertel 2425: return $answer;
2426: }
2427:
1.8 www 2428: # -------------------------------------------------------------- Replicate file
2429:
2430: sub repcopy {
2431: my $filename=shift;
1.23 www 2432: $filename=~s/\/+/\//g;
1.1142 raeburn 2433: my $londocroot = $perlvar{'lonDocRoot'};
2434: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
2435: if ($filename=~m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
2436: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2437: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2438: return &repcopy_userfile($filename);
2439: }
1.532 albertel 2440: $filename=~s/[\n\r]//g;
1.8 www 2441: my $transname="$filename.in.transfer";
1.828 www 2442: # FIXME: this should flock
1.607 raeburn 2443: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2444: my $remoteurl=subscribe($filename);
1.64 www 2445: if ($remoteurl =~ /^con_lost by/) {
2446: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2447: return 'unavailable';
1.8 www 2448: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2449: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2450: return 'not_found';
1.64 www 2451: } elsif ($remoteurl =~ /^rejected by/) {
2452: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2453: return 'forbidden';
1.20 www 2454: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2455: return 'ok';
1.8 www 2456: } else {
1.290 www 2457: my $author=$filename;
2458: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2459: my ($udom,$uname)=split(/\//,$author);
2460: my $home=homeserver($uname,$udom);
2461: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2462: my @parts=split(/\//,$filename);
2463: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2464: if ($path ne "$londocroot/res") {
1.8 www 2465: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2466: return 'bad_request';
1.8 www 2467: }
2468: my $count;
2469: for ($count=5;$count<$#parts;$count++) {
2470: $path.="/$parts[$count]";
2471: if ((-e $path)!=1) {
2472: mkdir($path,0777);
2473: }
2474: }
2475: my $ua=new LWP::UserAgent;
2476: my $request=new HTTP::Request('GET',"$remoteurl");
2477: my $response=$ua->request($request,$transname);
2478: if ($response->is_error()) {
2479: unlink($transname);
2480: my $message=$response->status_line;
1.672 albertel 2481: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2482: ." LWP get: $message: $filename</font>");
1.607 raeburn 2483: return 'unavailable';
1.8 www 2484: } else {
1.16 www 2485: if ($remoteurl!~/\.meta$/) {
2486: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2487: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2488: if ($mresponse->is_error()) {
2489: unlink($filename.'.meta');
2490: &logthis(
1.672 albertel 2491: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2492: }
2493: }
1.8 www 2494: rename($transname,$filename);
1.607 raeburn 2495: return 'ok';
1.8 www 2496: }
1.290 www 2497: }
1.8 www 2498: }
1.330 www 2499: }
2500:
2501: # ------------------------------------------------ Get server side include body
2502: sub ssi_body {
1.381 albertel 2503: my ($filelink,%form)=@_;
1.606 matthew 2504: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2505: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2506: }
1.953 www 2507: my $output='';
2508: my $response;
1.980 raeburn 2509: if ($filelink=~/^https?\:/) {
1.954 raeburn 2510: ($output,$response)=&externalssi($filelink);
1.953 www 2511: } else {
1.1004 droeschl 2512: $filelink .= $filelink=~/\?/ ? '&' : '?';
2513: $filelink .= 'inhibitmenu=yes';
1.953 www 2514: ($output,$response)=&ssi($filelink,%form);
2515: }
1.778 albertel 2516: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2517: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2518: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2519: if (wantarray) {
2520: return ($output, $response);
2521: } else {
2522: return $output;
2523: }
1.8 www 2524: }
2525:
1.15 www 2526: # --------------------------------------------------------- Server Side Include
2527:
1.782 albertel 2528: sub absolute_url {
2529: my ($host_name) = @_;
2530: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2531: if ($host_name eq '') {
2532: $host_name = $ENV{'SERVER_NAME'};
2533: }
2534: return $protocol.$host_name;
2535: }
2536:
1.942 foxr 2537: #
2538: # Server side include.
2539: # Parameters:
2540: # fn Possibly encrypted resource name/id.
2541: # form Hash that describes how the rendering should be done
2542: # and other things.
1.944 foxr 2543: # Returns:
1.950 raeburn 2544: # Scalar context: The content of the response.
2545: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2546: #
1.15 www 2547: sub ssi {
2548:
1.944 foxr 2549: my ($fn,%form)=@_;
1.15 www 2550: my $ua=new LWP::UserAgent;
1.23 www 2551: my $request;
1.711 albertel 2552:
2553: $form{'no_update_last_known'}=1;
1.895 albertel 2554: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2555: if (%form) {
1.782 albertel 2556: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2557: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2558: } else {
1.782 albertel 2559: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2560: }
2561:
1.15 www 2562: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2563: my $response=$ua->request($request);
2564:
1.944 foxr 2565: if (wantarray) {
2566: return ($response->content, $response);
2567: } else {
2568: return $response->content;
1.942 foxr 2569: }
1.324 www 2570: }
2571:
2572: sub externalssi {
2573: my ($url)=@_;
2574: my $ua=new LWP::UserAgent;
2575: my $request=new HTTP::Request('GET',$url);
2576: my $response=$ua->request($request);
1.954 raeburn 2577: if (wantarray) {
2578: return ($response->content, $response);
2579: } else {
2580: return $response->content;
2581: }
1.15 www 2582: }
1.254 www 2583:
1.492 albertel 2584: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2585:
2586: sub allowuploaded {
2587: my ($srcurl,$url)=@_;
2588: $url=&clutter(&declutter($url));
2589: my $dir=$url;
2590: $dir=~s/\/[^\/]+$//;
2591: my %httpref=();
2592: my $httpurl=&hreflocation('',$url);
2593: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2594: &Apache::lonnet::appenv(\%httpref);
1.254 www 2595: }
1.477 raeburn 2596:
1.478 albertel 2597: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2598: # input: action, courseID, current domain, intended
1.637 raeburn 2599: # path to file, source of file, instruction to parse file for objects,
2600: # ref to hash for embedded objects,
2601: # ref to hash for codebase of java objects.
1.1095 raeburn 2602: # reference to scalar to accommodate mime type determined
2603: # from File::MMagic if $parser = parse.
1.637 raeburn 2604: #
1.485 raeburn 2605: # output: url to file (if action was uploaddoc),
2606: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2607: #
1.478 albertel 2608: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2609: # course.
1.477 raeburn 2610: #
1.478 albertel 2611: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2612: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2613: # course's home server.
1.477 raeburn 2614: #
1.478 albertel 2615: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2616: # be copied from $source (current location) to
2617: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2618: # and will then be copied to
2619: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2620: # course's home server.
1.485 raeburn 2621: #
1.481 raeburn 2622: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2623: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2624: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2625: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2626: # in course's home server.
1.637 raeburn 2627: #
1.477 raeburn 2628:
2629: sub process_coursefile {
1.1095 raeburn 2630: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2631: $mimetype)=@_;
1.477 raeburn 2632: my $fetchresult;
1.638 albertel 2633: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2634: if ($action eq 'propagate') {
1.638 albertel 2635: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2636: $home);
1.481 raeburn 2637: } else {
1.477 raeburn 2638: my $fpath = '';
2639: my $fname = $file;
1.478 albertel 2640: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2641: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2642: my $filepath = &build_filepath($fpath);
1.481 raeburn 2643: if ($action eq 'copy') {
2644: if ($source eq '') {
2645: $fetchresult = 'no source file';
2646: return $fetchresult;
2647: } else {
2648: my $destination = $filepath.'/'.$fname;
2649: rename($source,$destination);
2650: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2651: $home);
1.481 raeburn 2652: }
2653: } elsif ($action eq 'uploaddoc') {
2654: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2655: print $fh $env{'form.'.$source};
1.481 raeburn 2656: close($fh);
1.637 raeburn 2657: if ($parser eq 'parse') {
1.1024 raeburn 2658: my $mm = new File::MMagic;
1.1095 raeburn 2659: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2660: if ($type eq 'text/html') {
1.1024 raeburn 2661: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2662: unless ($parse_result eq 'ok') {
2663: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2664: }
1.637 raeburn 2665: }
1.1095 raeburn 2666: if (ref($mimetype)) {
2667: $$mimetype = $type;
2668: }
1.637 raeburn 2669: }
1.477 raeburn 2670: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2671: $home);
1.481 raeburn 2672: if ($fetchresult eq 'ok') {
2673: return '/uploaded/'.$fpath.'/'.$fname;
2674: } else {
2675: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2676: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2677: return '/adm/notfound.html';
2678: }
1.477 raeburn 2679: }
2680: }
1.485 raeburn 2681: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2682: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2683: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2684: }
2685: return $fetchresult;
2686: }
2687:
1.637 raeburn 2688: sub build_filepath {
2689: my ($fpath) = @_;
2690: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2691: unless ($fpath eq '') {
2692: my @parts=split('/',$fpath);
2693: foreach my $part (@parts) {
2694: $filepath.= '/'.$part;
2695: if ((-e $filepath)!=1) {
2696: mkdir($filepath,0777);
2697: }
2698: }
2699: }
2700: return $filepath;
2701: }
2702:
2703: sub store_edited_file {
1.638 albertel 2704: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2705: my $file = $primary_url;
2706: $file =~ s#^/uploaded/$docudom/$docuname/##;
2707: my $fpath = '';
2708: my $fname = $file;
2709: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2710: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2711: my $filepath = &build_filepath($fpath);
2712: open(my $fh,'>'.$filepath.'/'.$fname);
2713: print $fh $content;
2714: close($fh);
1.638 albertel 2715: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2716: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2717: $home);
1.637 raeburn 2718: if ($$fetchresult eq 'ok') {
2719: return '/uploaded/'.$fpath.'/'.$fname;
2720: } else {
1.638 albertel 2721: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2722: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2723: return '/adm/notfound.html';
2724: }
2725: }
2726:
1.531 albertel 2727: sub clean_filename {
1.831 albertel 2728: my ($fname,$args)=@_;
1.315 www 2729: # Replace Windows backslashes by forward slashes
1.257 www 2730: $fname=~s/\\/\//g;
1.831 albertel 2731: if (!$args->{'keep_path'}) {
2732: # Get rid of everything but the actual filename
2733: $fname=~s/^.*\/([^\/]+)$/$1/;
2734: }
1.315 www 2735: # Replace spaces by underscores
2736: $fname=~s/\s+/\_/g;
2737: # Replace all other weird characters by nothing
1.831 albertel 2738: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2739: # Replace all .\d. sequences with _\d. so they no longer look like version
2740: # numbers
2741: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2742: return $fname;
2743: }
1.1051 raeburn 2744: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2745: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2746: # image with the same aspect ratio as the original, but with dimensions which do
2747: # not exceed $resizewidth and $resizeheight.
2748:
1.984 neumanie 2749: sub resizeImage {
1.1051 raeburn 2750: my ($img_path,$resizewidth,$resizeheight) = @_;
2751: my $ima = Image::Magick->new;
2752: my $resized;
2753: if (-e $img_path) {
2754: $ima->Read($img_path);
2755: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2756: my $width = $ima->Get('width');
2757: my $height = $ima->Get('height');
2758: if ($width > $resizewidth) {
2759: my $factor = $width/$resizewidth;
2760: my $newheight = $height/$factor;
2761: $ima->Scale(width=>$resizewidth,height=>$newheight);
2762: $resized = 1;
2763: }
2764: }
2765: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2766: my $width = $ima->Get('width');
2767: my $height = $ima->Get('height');
2768: if ($height > $resizeheight) {
2769: my $factor = $height/$resizeheight;
2770: my $newwidth = $width/$factor;
2771: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2772: $resized = 1;
2773: }
2774: }
2775: if ($resized) {
2776: $ima->Write($img_path);
2777: }
2778: }
2779: return;
1.977 amueller 2780: }
2781:
1.608 albertel 2782: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2783: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 2784: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 2785: # $context - possible values: coursedoc, existingfile, overwrite,
2786: # canceloverwrite, or ''.
2787: # if 'coursedoc': upload to the current course
2788: # if 'existingfile': write file to tmp/overwrites directory
2789: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2790: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2791: # $subdir - directory in userfile to store the file into
1.858 raeburn 2792: # $parser - instruction to parse file for objects ($parser = parse)
2793: # $allfiles - reference to hash for embedded objects
2794: # $codebase - reference to hash for codebase of java objects
2795: # $desuname - username for permanent storage of uploaded file
2796: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2797: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2798: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2799: # $resizewidth - width (pixels) to which to resize uploaded image
2800: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 2801: # $mimetype - reference to scalar to accommodate mime type determined
2802: # from File::MMagic if $parser = parse.
1.858 raeburn 2803: #
1.686 albertel 2804: # output: url of file in userspace, or error: <message>
2805: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2806:
1.531 albertel 2807: sub userfileupload {
1.1090 raeburn 2808: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 2809: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2810: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2811: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2812: $fname=&clean_filename($fname);
1.1090 raeburn 2813: # See if there is anything left
1.257 www 2814: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 2815: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2816: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2817: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2818: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2819: my $now = time;
1.1090 raeburn 2820: my $filepath;
1.1095 raeburn 2821: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 2822: $filepath = 'tmp/helprequests/'.$now;
2823: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2824: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2825: '_'.$env{'user.domain'}.'/pending';
2826: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2827: my ($docuname,$docudom);
2828: if ($destudom) {
2829: $docudom = $destudom;
2830: } else {
2831: $docudom = $env{'user.domain'};
2832: }
2833: if ($destuname) {
2834: $docuname = $destuname;
2835: } else {
2836: $docuname = $env{'user.name'};
2837: }
2838: if (exists($env{'form.group'})) {
2839: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2840: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2841: }
2842: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2843: if ($context eq 'canceloverwrite') {
2844: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2845: if (-e $tempfile) {
2846: my @info = stat($tempfile);
2847: if ($info[9] eq $env{'form.timestamp'}) {
2848: unlink($tempfile);
2849: }
2850: }
2851: return;
1.523 raeburn 2852: }
2853: }
1.1090 raeburn 2854: # Create the directory if not present
1.741 raeburn 2855: my @parts=split(/\//,$filepath);
2856: my $fullpath = $perlvar{'lonDaemons'};
2857: for (my $i=0;$i<@parts;$i++) {
2858: $fullpath .= '/'.$parts[$i];
2859: if ((-e $fullpath)!=1) {
2860: mkdir($fullpath,0777);
2861: }
2862: }
2863: open(my $fh,'>'.$fullpath.'/'.$fname);
2864: print $fh $env{'form.'.$formname};
2865: close($fh);
1.1090 raeburn 2866: if ($context eq 'existingfile') {
2867: my @info = stat($fullpath.'/'.$fname);
2868: return ($fullpath.'/'.$fname,$info[9]);
2869: } else {
2870: return $fullpath.'/'.$fname;
2871: }
1.523 raeburn 2872: }
1.995 raeburn 2873: if ($subdir eq 'scantron') {
2874: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 2875: } else {
1.995 raeburn 2876: $fname="$subdir/$fname";
2877: }
1.1090 raeburn 2878: if ($context eq 'coursedoc') {
1.638 albertel 2879: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2880: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2881: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2882: return &finishuserfileupload($docuname,$docudom,
2883: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2884: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 2885: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2886: } else {
1.620 albertel 2887: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2888: return &process_coursefile('uploaddoc',$docuname,$docudom,
2889: $fname,$formname,$parser,
1.1095 raeburn 2890: $allfiles,$codebase,$mimetype);
1.481 raeburn 2891: }
1.719 banghart 2892: } elsif (defined($destuname)) {
2893: my $docuname=$destuname;
2894: my $docudom=$destudom;
1.860 raeburn 2895: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2896: $parser,$allfiles,$codebase,
1.1051 raeburn 2897: $thumbwidth,$thumbheight,
1.1095 raeburn 2898: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2899: } else {
1.638 albertel 2900: my $docuname=$env{'user.name'};
2901: my $docudom=$env{'user.domain'};
1.714 raeburn 2902: if (exists($env{'form.group'})) {
2903: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2904: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2905: }
1.860 raeburn 2906: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2907: $parser,$allfiles,$codebase,
1.1051 raeburn 2908: $thumbwidth,$thumbheight,
1.1095 raeburn 2909: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2910: }
1.271 www 2911: }
2912:
2913: sub finishuserfileupload {
1.860 raeburn 2914: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 2915: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2916: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2917: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2918:
1.860 raeburn 2919: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2920: $file=$fname;
2921: if ($fname=~m|/|) {
2922: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2923: $path.=$fnamepath.'/';
2924: }
1.259 www 2925: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2926: my $count;
2927: for ($count=4;$count<=$#parts;$count++) {
2928: $filepath.="/$parts[$count]";
2929: if ((-e $filepath)!=1) {
2930: mkdir($filepath,0777);
2931: }
2932: }
1.984 neumanie 2933:
1.258 www 2934: # Save the file
2935: {
1.701 albertel 2936: if (!open(FH,'>'.$filepath.'/'.$file)) {
2937: &logthis('Failed to create '.$filepath.'/'.$file);
2938: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2939: return '/adm/notfound.html';
2940: }
1.1090 raeburn 2941: if ($context eq 'overwrite') {
1.1117 foxr 2942: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 2943: my $target = $filepath.'/'.$file;
2944: if (-e $source) {
2945: my @info = stat($source);
2946: if ($info[9] eq $env{'form.timestamp'}) {
2947: unless (&File::Copy::move($source,$target)) {
2948: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2949: return "Moving from $source failed";
2950: }
2951: } else {
2952: return "Temporary file: $source had unexpected date/time for last modification";
2953: }
2954: } else {
2955: return "Temporary file: $source missing";
2956: }
2957: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2958: &logthis('Failed to write to '.$filepath.'/'.$file);
2959: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2960: return '/adm/notfound.html';
2961: }
1.570 albertel 2962: close(FH);
1.1051 raeburn 2963: if ($resizewidth && $resizeheight) {
2964: my $mm = new File::MMagic;
2965: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2966: if ($mime_type =~ m{^image/}) {
2967: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2968: }
1.977 amueller 2969: }
1.258 www 2970: }
1.637 raeburn 2971: if ($parser eq 'parse') {
1.1024 raeburn 2972: my $mm = new File::MMagic;
1.1095 raeburn 2973: my $type = $mm->checktype_filename($filepath.'/'.$file);
2974: if ($type eq 'text/html') {
1.1024 raeburn 2975: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2976: $allfiles,$codebase);
2977: unless ($parse_result eq 'ok') {
2978: &logthis('Failed to parse '.$filepath.$file.
2979: ' for embedded media: '.$parse_result);
2980: }
1.637 raeburn 2981: }
1.1095 raeburn 2982: if (ref($mimetype)) {
2983: $$mimetype = $type;
2984: }
1.637 raeburn 2985: }
1.860 raeburn 2986: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2987: my $input = $filepath.'/'.$file;
2988: my $output = $filepath.'/'.'tn-'.$file;
2989: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2990: system("convert -sample $thumbsize $input $output");
2991: if (-e $filepath.'/'.'tn-'.$file) {
2992: $fetchthumb = 1;
2993: }
2994: }
1.858 raeburn 2995:
1.259 www 2996: # Notify homeserver to grep it
2997: #
1.984 neumanie 2998: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2999: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3000: if ($fetchresult eq 'ok') {
1.860 raeburn 3001: if ($fetchthumb) {
3002: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3003: if ($thumbresult ne 'ok') {
3004: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3005: $docuhome.': '.$thumbresult);
3006: }
3007: }
1.259 www 3008: #
1.258 www 3009: # Return the URL to it
1.494 albertel 3010: return '/uploaded/'.$path.$file;
1.263 www 3011: } else {
1.494 albertel 3012: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3013: ': '.$fetchresult);
1.263 www 3014: return '/adm/notfound.html';
1.858 raeburn 3015: }
1.493 albertel 3016: }
3017:
1.637 raeburn 3018: sub extract_embedded_items {
1.961 raeburn 3019: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3020: my @state = ();
3021: my %javafiles = (
3022: codebase => '',
3023: code => '',
3024: archive => ''
3025: );
3026: my %mediafiles = (
3027: src => '',
3028: movie => '',
3029: );
1.648 raeburn 3030: my $p;
3031: if ($content) {
3032: $p = HTML::LCParser->new($content);
3033: } else {
1.961 raeburn 3034: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3035: }
1.641 albertel 3036: while (my $t=$p->get_token()) {
1.640 albertel 3037: if ($t->[0] eq 'S') {
3038: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3039: push(@state, $tagname);
1.648 raeburn 3040: if (lc($tagname) eq 'allow') {
3041: &add_filetype($allfiles,$attr->{'src'},'src');
3042: }
1.640 albertel 3043: if (lc($tagname) eq 'img') {
3044: &add_filetype($allfiles,$attr->{'src'},'src');
3045: }
1.886 albertel 3046: if (lc($tagname) eq 'a') {
3047: &add_filetype($allfiles,$attr->{'href'},'href');
3048: }
1.645 raeburn 3049: if (lc($tagname) eq 'script') {
3050: if ($attr->{'archive'} =~ /\.jar$/i) {
3051: &add_filetype($allfiles,$attr->{'archive'},'archive');
3052: } else {
3053: &add_filetype($allfiles,$attr->{'src'},'src');
3054: }
3055: }
3056: if (lc($tagname) eq 'link') {
3057: if (lc($attr->{'rel'}) eq 'stylesheet') {
3058: &add_filetype($allfiles,$attr->{'href'},'href');
3059: }
3060: }
1.640 albertel 3061: if (lc($tagname) eq 'object' ||
3062: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3063: foreach my $item (keys(%javafiles)) {
3064: $javafiles{$item} = '';
3065: }
3066: }
3067: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3068: my $name = lc($attr->{'name'});
3069: foreach my $item (keys(%javafiles)) {
3070: if ($name eq $item) {
3071: $javafiles{$item} = $attr->{'value'};
3072: last;
3073: }
3074: }
3075: foreach my $item (keys(%mediafiles)) {
3076: if ($name eq $item) {
3077: &add_filetype($allfiles, $attr->{'value'}, 'value');
3078: last;
3079: }
3080: }
3081: }
3082: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3083: foreach my $item (keys(%javafiles)) {
3084: if ($attr->{$item}) {
3085: $javafiles{$item} = $attr->{$item};
3086: last;
3087: }
3088: }
3089: foreach my $item (keys(%mediafiles)) {
3090: if ($attr->{$item}) {
3091: &add_filetype($allfiles,$attr->{$item},$item);
3092: last;
3093: }
3094: }
3095: }
3096: } elsif ($t->[0] eq 'E') {
3097: my ($tagname) = ($t->[1]);
3098: if ($javafiles{'codebase'} ne '') {
3099: $javafiles{'codebase'} .= '/';
3100: }
3101: if (lc($tagname) eq 'applet' ||
3102: lc($tagname) eq 'object' ||
3103: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3104: ) {
3105: foreach my $item (keys(%javafiles)) {
3106: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3107: my $file=$javafiles{'codebase'}.$javafiles{$item};
3108: &add_filetype($allfiles,$file,$item);
3109: }
3110: }
3111: }
3112: pop @state;
3113: }
3114: }
1.637 raeburn 3115: return 'ok';
3116: }
3117:
1.639 albertel 3118: sub add_filetype {
3119: my ($allfiles,$file,$type)=@_;
3120: if (exists($allfiles->{$file})) {
3121: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3122: push(@{$allfiles->{$file}}, &escape($type));
3123: }
3124: } else {
3125: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3126: }
3127: }
3128:
1.493 albertel 3129: sub removeuploadedurl {
1.984 neumanie 3130: my ($url)=@_;
3131: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3132: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3133: }
3134:
3135: sub removeuserfile {
3136: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3137: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3138: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3139: if ($result eq 'ok') {
1.798 raeburn 3140: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3141: my $metafile = $fname.'.meta';
3142: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3143: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3144: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3145: my $sqlresult =
1.823 albertel 3146: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3147: 'portfolio_metadata',$group,
3148: 'delete');
1.798 raeburn 3149: }
3150: }
3151: return $result;
1.257 www 3152: }
1.15 www 3153:
1.530 albertel 3154: sub mkdiruserfile {
3155: my ($docuname,$docudom,$dir)=@_;
3156: my $home=&homeserver($docuname,$docudom);
3157: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3158: }
3159:
1.531 albertel 3160: sub renameuserfile {
3161: my ($docuname,$docudom,$old,$new)=@_;
3162: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3163: my $result = &reply("renameuserfile:$docudom:$docuname:".
3164: &escape("$old").':'.&escape("$new"),$home);
3165: if ($result eq 'ok') {
3166: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3167: my $oldmeta = $old.'.meta';
3168: my $newmeta = $new.'.meta';
3169: my $metaresult =
3170: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3171: my $url = "/uploaded/$docudom/$docuname/$old";
3172: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3173: my $sqlresult =
1.823 albertel 3174: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3175: 'portfolio_metadata',$group,
3176: 'delete');
1.798 raeburn 3177: }
3178: }
3179: return $result;
1.531 albertel 3180: }
3181:
1.14 www 3182: # ------------------------------------------------------------------------- Log
3183:
3184: sub log {
3185: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3186: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3187: }
3188:
3189: # ------------------------------------------------------------------ Course Log
1.352 www 3190: #
3191: # This routine flushes several buffers of non-mission-critical nature
3192: #
1.157 www 3193:
3194: sub flushcourselogs {
1.352 www 3195: &logthis('Flushing log buffers');
3196: #
3197: # course logs
3198: # This is a log of all transactions in a course, which can be used
3199: # for data mining purposes
3200: #
3201: # It also collects the courseid database, which lists last transaction
3202: # times and course titles for all courseids
3203: #
3204: my %courseidbuffer=();
1.921 raeburn 3205: foreach my $crsid (keys(%courselogs)) {
1.352 www 3206: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3207: &escape($courselogs{$crsid}),
3208: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3209: delete $courselogs{$crsid};
3210: } else {
3211: &logthis('Failed to flush log buffer for '.$crsid);
3212: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3213: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3214: " exceeded maximum size, deleting.</font>");
3215: delete $courselogs{$crsid};
3216: }
1.352 www 3217: }
1.920 raeburn 3218: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3219: 'description' => $coursedescrbuf{$crsid},
3220: 'inst_code' => $courseinstcodebuf{$crsid},
3221: 'type' => $coursetypebuf{$crsid},
3222: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3223: };
1.191 harris41 3224: }
1.352 www 3225: #
3226: # Write course id database (reverse lookup) to homeserver of courses
3227: # Is used in pickcourse
3228: #
1.840 albertel 3229: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3230: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3231: $courseidbuffer{$crs_home},
3232: $crs_home,'timeonly');
1.352 www 3233: }
3234: #
3235: # File accesses
3236: # Writes to the dynamic metadata of resources to get hit counts, etc.
3237: #
1.449 matthew 3238: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3239: if ($entry =~ /___count$/) {
3240: my ($dom,$name);
1.807 albertel 3241: ($dom,$name,undef)=
1.811 albertel 3242: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3243: if (! defined($dom) || $dom eq '' ||
3244: ! defined($name) || $name eq '') {
1.620 albertel 3245: my $cid = $env{'request.course.id'};
3246: $dom = $env{'request.'.$cid.'.domain'};
3247: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3248: }
1.450 matthew 3249: my $value = $accesshash{$entry};
3250: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3251: my %temphash=($url => $value);
1.449 matthew 3252: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3253: if ($result eq 'ok') {
3254: delete $accesshash{$entry};
3255: } elsif ($result eq 'unknown_cmd') {
3256: # Target server has old code running on it.
1.450 matthew 3257: my %temphash=($entry => $value);
1.449 matthew 3258: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3259: delete $accesshash{$entry};
3260: }
3261: }
3262: } else {
1.811 albertel 3263: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 3264: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3265: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3266: delete $accesshash{$entry};
3267: }
1.185 www 3268: }
1.191 harris41 3269: }
1.352 www 3270: #
3271: # Roles
3272: # Reverse lookup of user roles for course faculty/staff and co-authorship
3273: #
1.800 albertel 3274: foreach my $entry (keys(%userrolehash)) {
1.351 www 3275: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3276: split(/\:/,$entry);
3277: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3278: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3279: $rudom,$runame) eq 'ok') {
3280: delete $userrolehash{$entry};
3281: }
3282: }
1.662 raeburn 3283: #
3284: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3285: #
3286: my %domrolebuffer = ();
1.1000 raeburn 3287: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3288: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3289: if ($domrolebuffer{$rudom}) {
3290: $domrolebuffer{$rudom}.='&'.&escape($entry).
3291: '='.&escape($domainrolehash{$entry});
3292: } else {
3293: $domrolebuffer{$rudom}.=&escape($entry).
3294: '='.&escape($domainrolehash{$entry});
3295: }
3296: delete $domainrolehash{$entry};
3297: }
3298: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3299: my %servers = &get_servers($dom,'library');
3300: foreach my $tryserver (keys(%servers)) {
3301: unless (&reply('domroleput:'.$dom.':'.
3302: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3303: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3304: }
1.662 raeburn 3305: }
3306: }
1.186 www 3307: $dumpcount++;
1.157 www 3308: }
3309:
3310: sub courselog {
3311: my $what=shift;
1.158 www 3312: $what=time.':'.$what;
1.620 albertel 3313: unless ($env{'request.course.id'}) { return ''; }
3314: $coursedombuf{$env{'request.course.id'}}=
3315: $env{'course.'.$env{'request.course.id'}.'.domain'};
3316: $coursenumbuf{$env{'request.course.id'}}=
3317: $env{'course.'.$env{'request.course.id'}.'.num'};
3318: $coursehombuf{$env{'request.course.id'}}=
3319: $env{'course.'.$env{'request.course.id'}.'.home'};
3320: $coursedescrbuf{$env{'request.course.id'}}=
3321: $env{'course.'.$env{'request.course.id'}.'.description'};
3322: $courseinstcodebuf{$env{'request.course.id'}}=
3323: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3324: $courseownerbuf{$env{'request.course.id'}}=
3325: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3326: $coursetypebuf{$env{'request.course.id'}}=
3327: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3328: if (defined $courselogs{$env{'request.course.id'}}) {
3329: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3330: } else {
1.620 albertel 3331: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3332: }
1.620 albertel 3333: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3334: &flushcourselogs();
3335: }
1.158 www 3336: }
3337:
3338: sub courseacclog {
3339: my $fnsymb=shift;
1.620 albertel 3340: unless ($env{'request.course.id'}) { return ''; }
3341: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3342: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3343: $what.=':POST';
1.583 matthew 3344: # FIXME: Probably ought to escape things....
1.800 albertel 3345: foreach my $key (keys(%env)) {
3346: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3347: my $formitem = $1;
3348: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3349: $what.=':'.$formitem.'='.$env{$key};
3350: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3351: $what.=':'.$formitem.'='.$env{$key};
3352: }
1.158 www 3353: }
1.191 harris41 3354: }
1.583 matthew 3355: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3356: # FIXME: We should not be depending on a form parameter that someone
3357: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3358: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3359: $what.= ':POST';
3360: # FIXME: Probably ought to escape things....
3361: foreach my $element ('courseexp','crsfulltext','crsrelated',
3362: 'crsdiscuss') {
1.620 albertel 3363: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3364: }
3365: }
1.158 www 3366: }
3367: &courselog($what);
1.149 www 3368: }
3369:
1.185 www 3370: sub countacc {
3371: my $url=&declutter(shift);
1.458 matthew 3372: return if (! defined($url) || $url eq '');
1.620 albertel 3373: unless ($env{'request.course.id'}) { return ''; }
3374: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 3375: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3376: $accesshash{$key}++;
1.185 www 3377: }
1.349 www 3378:
1.361 www 3379: sub linklog {
3380: my ($from,$to)=@_;
3381: $from=&declutter($from);
3382: $to=&declutter($to);
3383: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3384: $accesshash{$to.'___'.$from.'___goto'}=1;
3385: }
3386:
1.349 www 3387: sub userrolelog {
3388: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 3389: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 3390: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 3391: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 3392: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 3393: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3394: $userrolehash
3395: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3396: =$tend.':'.$tstart;
1.662 raeburn 3397: }
1.898 albertel 3398: if (($env{'request.role'} =~ /dc\./) &&
3399: (($trole=~/^au/) || ($trole=~/^in/) ||
3400: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 3401: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3402: ($trole=~/^co/))) {
1.898 albertel 3403: $userrolehash
3404: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3405: =$tend.':'.$tstart;
3406: }
1.662 raeburn 3407: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3408: ($trole=~/^li/) || ($trole=~/^li/) ||
3409: ($trole=~/^au/) || ($trole=~/^dg/) ||
3410: ($trole=~/^sc/)) {
3411: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3412: $domainrolehash
3413: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3414: = $tend.':'.$tstart;
3415: }
1.351 www 3416: }
3417:
1.957 raeburn 3418: sub courserolelog {
3419: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3420: if (($trole eq 'cc') || ($trole eq 'in') ||
3421: ($trole eq 'ep') || ($trole eq 'ad') ||
3422: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 3423: ($trole=~/^cr/) || ($trole eq 'gr') ||
3424: ($trole eq 'co')) {
1.957 raeburn 3425: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3426: my $cdom = $1;
3427: my $cnum = $2;
3428: my $sec = $3;
3429: my $namespace = 'rolelog';
3430: my %storehash = (
3431: role => $trole,
3432: start => $tstart,
3433: end => $tend,
3434: selfenroll => $selfenroll,
3435: context => $context,
3436: );
3437: if ($trole eq 'gr') {
3438: $namespace = 'groupslog';
3439: $storehash{'group'} = $sec;
3440: } else {
3441: $storehash{'section'} = $sec;
3442: }
3443: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 3444: if (($trole ne 'st') || ($sec ne '')) {
3445: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3446: }
1.957 raeburn 3447: }
3448: }
3449: return;
3450: }
3451:
1.351 www 3452: sub get_course_adv_roles {
1.948 raeburn 3453: my ($cid,$codes) = @_;
1.620 albertel 3454: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3455: my %coursehash=&coursedescription($cid);
1.988 raeburn 3456: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3457: my %nothide=();
1.800 albertel 3458: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3459: if ($user !~ /:/) {
3460: $nothide{join(':',split(/[\@]/,$user))}=1;
3461: } else {
3462: $nothide{$user}=1;
3463: }
1.470 www 3464: }
1.351 www 3465: my %returnhash=();
3466: my %dumphash=
3467: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3468: my $now=time;
1.997 raeburn 3469: my %privileged;
1.1000 raeburn 3470: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3471: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3472: if (($tstart) && ($tstart<0)) { next; }
3473: if (($tend) && ($tend<$now)) { next; }
3474: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3475: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3476: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3477: unless (ref($privileged{$domain}) eq 'HASH') {
3478: my %dompersonnel =
1.998 raeburn 3479: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3480: $privileged{$domain} = {};
3481: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3482: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3483: foreach my $user (keys(%{$dompersonnel{$server}})) {
3484: my ($trole,$uname,$udom) = split(/:/,$user);
3485: $privileged{$udom}{$uname} = 1;
3486: }
3487: }
3488: }
3489: }
3490: if ((exists($privileged{$domain}{$username})) &&
3491: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3492: if ($role eq 'cr') { next; }
1.948 raeburn 3493: if ($codes) {
3494: if ($section) { $role .= ':'.$section; }
3495: if ($returnhash{$role}) {
3496: $returnhash{$role}.=','.$username.':'.$domain;
3497: } else {
3498: $returnhash{$role}=$username.':'.$domain;
3499: }
1.351 www 3500: } else {
1.988 raeburn 3501: my $key=&plaintext($role,$crstype);
1.973 bisitz 3502: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3503: if ($returnhash{$key}) {
3504: $returnhash{$key}.=','.$username.':'.$domain;
3505: } else {
3506: $returnhash{$key}=$username.':'.$domain;
3507: }
1.351 www 3508: }
1.948 raeburn 3509: }
1.400 www 3510: return %returnhash;
3511: }
3512:
3513: sub get_my_roles {
1.937 raeburn 3514: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3515: unless (defined($uname)) { $uname=$env{'user.name'}; }
3516: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3517: my (%dumphash,%nothide);
1.1086 raeburn 3518: if ($context eq 'userroles') {
3519: my $extra = &freeze_escape({'skipcheck' => 1});
3520: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858 raeburn 3521: } else {
3522: %dumphash=
1.400 www 3523: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3524: if ($hidepriv) {
3525: my %coursehash=&coursedescription($udom.'_'.$uname);
3526: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3527: if ($user !~ /:/) {
3528: $nothide{join(':',split(/[\@]/,$user))} = 1;
3529: } else {
3530: $nothide{$user} = 1;
3531: }
3532: }
3533: }
1.858 raeburn 3534: }
1.400 www 3535: my %returnhash=();
3536: my $now=time;
1.999 raeburn 3537: my %privileged;
1.800 albertel 3538: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3539: my ($role,$tend,$tstart);
3540: if ($context eq 'userroles') {
1.1149 ! raeburn 3541: next if ($entry =~ /^rolesdef/);
1.867 raeburn 3542: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3543: } else {
3544: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3545: }
1.400 www 3546: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3547: my $status = 'active';
1.939 raeburn 3548: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3549: $status = 'previous';
3550: }
3551: if (($tstart) && ($now<$tstart)) {
3552: $status = 'future';
3553: }
3554: if (ref($types) eq 'ARRAY') {
3555: if (!grep(/^\Q$status\E$/,@{$types})) {
3556: next;
3557: }
3558: } else {
3559: if ($status ne 'active') {
3560: next;
3561: }
3562: }
1.867 raeburn 3563: my ($rolecode,$username,$domain,$section,$area);
3564: if ($context eq 'userroles') {
3565: ($area,$rolecode) = split(/_/,$entry);
3566: (undef,$domain,$username,$section) = split(/\//,$area);
3567: } else {
3568: ($role,$username,$domain,$section) = split(/\:/,$entry);
3569: }
1.832 raeburn 3570: if (ref($roledoms) eq 'ARRAY') {
3571: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3572: next;
3573: }
3574: }
3575: if (ref($roles) eq 'ARRAY') {
3576: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3577: if ($role =~ /^cr\//) {
3578: if (!grep(/^cr$/,@{$roles})) {
3579: next;
3580: }
1.1104 raeburn 3581: } elsif ($role =~ /^gr\//) {
3582: if (!grep(/^gr$/,@{$roles})) {
3583: next;
3584: }
1.922 raeburn 3585: } else {
3586: next;
3587: }
1.832 raeburn 3588: }
1.867 raeburn 3589: }
1.937 raeburn 3590: if ($hidepriv) {
1.999 raeburn 3591: if ($context eq 'userroles') {
3592: if ((&privileged($username,$domain)) &&
3593: (!$nothide{$username.':'.$domain})) {
3594: next;
3595: }
3596: } else {
3597: unless (ref($privileged{$domain}) eq 'HASH') {
3598: my %dompersonnel =
3599: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3600: $privileged{$domain} = {};
3601: if (keys(%dompersonnel)) {
3602: foreach my $server (keys(%dompersonnel)) {
3603: if (ref($dompersonnel{$server}) eq 'HASH') {
3604: foreach my $user (keys(%{$dompersonnel{$server}})) {
3605: my ($trole,$uname,$udom) = split(/:/,$user);
3606: $privileged{$udom}{$uname} = $trole;
3607: }
3608: }
3609: }
3610: }
3611: }
3612: if (exists($privileged{$domain}{$username})) {
3613: if (!$nothide{$username.':'.$domain}) {
3614: next;
3615: }
3616: }
1.937 raeburn 3617: }
3618: }
1.933 raeburn 3619: if ($withsec) {
3620: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3621: $tstart.':'.$tend;
3622: } else {
3623: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3624: }
1.832 raeburn 3625: }
1.373 www 3626: return %returnhash;
1.399 www 3627: }
3628:
3629: # ----------------------------------------------------- Frontpage Announcements
3630: #
3631: #
3632:
3633: sub postannounce {
3634: my ($server,$text)=@_;
1.844 albertel 3635: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3636: unless ($text=~/\w/) { $text=''; }
3637: return &reply('setannounce:'.&escape($text),$server);
3638: }
3639:
3640: sub getannounce {
1.448 albertel 3641:
3642: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3643: my $announcement='';
1.800 albertel 3644: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3645: close($fh);
1.399 www 3646: if ($announcement=~/\w/) {
3647: return
3648: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3649: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3650: } else {
3651: return '';
3652: }
3653: } else {
3654: return '';
3655: }
1.351 www 3656: }
1.353 www 3657:
3658: # ---------------------------------------------------------- Course ID routines
3659: # Deal with domain's nohist_courseid.db files
3660: #
3661:
3662: sub courseidput {
1.921 raeburn 3663: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3664: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3665: my $outcome;
3666: if ($caller eq 'timeonly') {
3667: my $cids = '';
3668: foreach my $item (keys(%$storehash)) {
3669: $cids.=&escape($item).'&';
3670: }
3671: $cids=~s/\&$//;
3672: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3673: $coursehome);
3674: } else {
3675: my $items = '';
3676: foreach my $item (keys(%$storehash)) {
3677: $items.= &escape($item).'='.
3678: &freeze_escape($$storehash{$item}).'&';
3679: }
3680: $items=~s/\&$//;
3681: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3682: $coursehome);
1.918 raeburn 3683: }
3684: if ($outcome eq 'unknown_cmd') {
3685: my $what;
3686: foreach my $cid (keys(%$storehash)) {
3687: $what .= &escape($cid).'=';
1.921 raeburn 3688: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3689: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3690: }
3691: $what =~ s/\:$/&/;
3692: }
3693: $what =~ s/\&$//;
3694: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3695: } else {
3696: return $outcome;
3697: }
1.353 www 3698: }
3699:
3700: sub courseiddump {
1.921 raeburn 3701: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3702: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3703: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3704: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3705: my $as_hash = 1;
3706: my %returnhash;
3707: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3708: my %libserv = &all_library();
3709: foreach my $tryserver (keys(%libserv)) {
3710: if ( ( $hostidflag == 1
3711: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3712: || (!defined($hostidflag)) ) {
3713:
1.918 raeburn 3714: if (($domfilter eq '') ||
3715: (&host_domain($tryserver) eq $domfilter)) {
3716: my $rep =
3717: &reply('courseiddump:'.&host_domain($tryserver).':'.
3718: $sincefilter.':'.&escape($descfilter).':'.
3719: &escape($instcodefilter).':'.&escape($ownerfilter).
3720: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3721: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3722: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3723: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3724: &escape($cc_clone).':'.$cloneonly.':'.
3725: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071 raeburn 3726: &escape($creationcontext).':'.$domcloner,
3727: $tryserver);
1.918 raeburn 3728: my @pairs=split(/\&/,$rep);
3729: foreach my $item (@pairs) {
3730: my ($key,$value)=split(/\=/,$item,2);
3731: $key = &unescape($key);
3732: next if ($key =~ /^error: 2 /);
3733: my $result = &thaw_unescape($value);
3734: if (ref($result) eq 'HASH') {
3735: $returnhash{$key}=$result;
3736: } else {
1.921 raeburn 3737: my @responses = split(/:/,$value);
3738: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3739: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3740: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3741: }
1.1008 raeburn 3742: }
1.353 www 3743: }
3744: }
3745: }
3746: }
3747: return %returnhash;
3748: }
3749:
1.1055 raeburn 3750: sub courselastaccess {
3751: my ($cdom,$cnum,$hostidref) = @_;
3752: my %returnhash;
3753: if ($cdom && $cnum) {
3754: my $chome = &homeserver($cnum,$cdom);
3755: if ($chome ne 'no_host') {
3756: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3757: &extract_lastaccess(\%returnhash,$rep);
3758: }
3759: } else {
3760: if (!$cdom) { $cdom=''; }
3761: my %libserv = &all_library();
3762: foreach my $tryserver (keys(%libserv)) {
3763: if (ref($hostidref) eq 'ARRAY') {
3764: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3765: }
3766: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3767: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3768: &extract_lastaccess(\%returnhash,$rep);
3769: }
3770: }
3771: }
3772: return %returnhash;
3773: }
3774:
3775: sub extract_lastaccess {
3776: my ($returnhash,$rep) = @_;
3777: if (ref($returnhash) eq 'HASH') {
3778: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3779: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3780: $rep eq '') {
3781: my @pairs=split(/\&/,$rep);
3782: foreach my $item (@pairs) {
3783: my ($key,$value)=split(/\=/,$item,2);
3784: $key = &unescape($key);
3785: next if ($key =~ /^error: 2 /);
3786: $returnhash->{$key} = &thaw_unescape($value);
3787: }
3788: }
3789: }
3790: return;
3791: }
3792:
1.658 raeburn 3793: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3794:
3795: sub dcmailput {
1.685 raeburn 3796: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3797: my $status = &Apache::lonnet::critical(
1.740 www 3798: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3799: &escape($message),$server);
1.662 raeburn 3800: return $status;
3801: }
3802:
1.658 raeburn 3803: sub dcmaildump {
3804: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3805: my %returnhash=();
1.846 albertel 3806:
3807: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3808: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3809: &escape($enddate).':';
3810: my @esc_senders=map { &escape($_)} @$senders;
3811: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3812: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3813: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3814: if (($key) && ($value)) {
3815: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3816: }
3817: }
3818: }
3819: return %returnhash;
3820: }
1.662 raeburn 3821: # ---------------------------------------------------------- Domain roles
3822:
3823: sub get_domain_roles {
3824: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3825: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3826: $startdate = '.';
3827: }
1.1018 raeburn 3828: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3829: $enddate = '.';
3830: }
1.922 raeburn 3831: my $rolelist;
3832: if (ref($roles) eq 'ARRAY') {
3833: $rolelist = join(':',@{$roles});
3834: }
1.662 raeburn 3835: my %personnel = ();
1.841 albertel 3836:
3837: my %servers = &get_servers($dom,'library');
3838: foreach my $tryserver (keys(%servers)) {
3839: %{$personnel{$tryserver}}=();
3840: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3841: &escape($startdate).':'.
3842: &escape($enddate).':'.
3843: &escape($rolelist), $tryserver))) {
3844: my ($key,$value) = split(/\=/,$line,2);
3845: if (($key) && ($value)) {
3846: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3847: }
3848: }
1.662 raeburn 3849: }
3850: return %personnel;
3851: }
1.658 raeburn 3852:
1.1057 www 3853: # ----------------------------------------------------------- Interval timing
1.149 www 3854:
1.504 albertel 3855: sub get_first_access {
3856: my ($type,$argsymb)=@_;
1.790 albertel 3857: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3858: if ($argsymb) { $symb=$argsymb; }
3859: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3860: if ($type eq 'course') {
3861: $res='course';
3862: } elsif ($type eq 'map') {
1.588 albertel 3863: $res=&symbread($map);
3864: } else {
3865: $res=$symb;
3866: }
3867: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3868: return $times{"$courseid\0$res"};
1.504 albertel 3869: }
3870:
3871: sub set_first_access {
3872: my ($type)=@_;
1.790 albertel 3873: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3874: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3875: if ($type eq 'course') {
3876: $res='course';
3877: } elsif ($type eq 'map') {
1.588 albertel 3878: $res=&symbread($map);
3879: } else {
3880: $res=$symb;
3881: }
3882: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3883: if (!$firstaccess) {
1.588 albertel 3884: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3885: }
3886: return 'already_set';
1.504 albertel 3887: }
3888:
1.110 www 3889: # --------------------------------------------- Set Expire Date for Spreadsheet
3890:
3891: sub expirespread {
3892: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3893: my $cid=$env{'request.course.id'};
1.110 www 3894: if ($cid) {
3895: my $now=time;
3896: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3897: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3898: $env{'course.'.$cid.'.num'}.
1.110 www 3899: ':nohist_expirationdates:'.
3900: &escape($key).'='.$now,
1.620 albertel 3901: $env{'course.'.$cid.'.home'})
1.110 www 3902: }
3903: return 'ok';
1.14 www 3904: }
3905:
1.109 www 3906: # ----------------------------------------------------- Devalidate Spreadsheets
3907:
3908: sub devalidate {
1.325 www 3909: my ($symb,$uname,$udom)=@_;
1.620 albertel 3910: my $cid=$env{'request.course.id'};
1.109 www 3911: if ($cid) {
1.391 matthew 3912: # delete the stored spreadsheets for
3913: # - the student level sheet of this user in course's homespace
3914: # - the assessment level sheet for this resource
3915: # for this user in user's homespace
1.553 albertel 3916: # - current conditional state info
1.325 www 3917: my $key=$uname.':'.$udom.':';
1.109 www 3918: my $status=
1.299 matthew 3919: &del('nohist_calculatedsheets',
1.391 matthew 3920: [$key.'studentcalc:'],
1.620 albertel 3921: $env{'course.'.$cid.'.domain'},
3922: $env{'course.'.$cid.'.num'})
1.133 albertel 3923: .' '.
3924: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3925: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3926: unless ($status eq 'ok ok') {
3927: &logthis('Could not devalidate spreadsheet '.
1.325 www 3928: $uname.' at '.$udom.' for '.
1.109 www 3929: $symb.': '.$status);
1.133 albertel 3930: }
1.553 albertel 3931: &delenv('user.state.'.$cid);
1.109 www 3932: }
3933: }
3934:
1.265 albertel 3935: sub get_scalar {
3936: my ($string,$end) = @_;
3937: my $value;
3938: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3939: $value = $1;
3940: } elsif ($$string =~ s/^([^&]*?)&//) {
3941: $value = $1;
3942: }
3943: return &unescape($value);
3944: }
3945:
3946: sub array2str {
3947: my (@array) = @_;
3948: my $result=&arrayref2str(\@array);
3949: $result=~s/^__ARRAY_REF__//;
3950: $result=~s/__END_ARRAY_REF__$//;
3951: return $result;
3952: }
3953:
1.204 albertel 3954: sub arrayref2str {
3955: my ($arrayref) = @_;
1.265 albertel 3956: my $result='__ARRAY_REF__';
1.204 albertel 3957: foreach my $elem (@$arrayref) {
1.265 albertel 3958: if(ref($elem) eq 'ARRAY') {
3959: $result.=&arrayref2str($elem).'&';
3960: } elsif(ref($elem) eq 'HASH') {
3961: $result.=&hashref2str($elem).'&';
3962: } elsif(ref($elem)) {
3963: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3964: } else {
3965: $result.=&escape($elem).'&';
3966: }
3967: }
3968: $result=~s/\&$//;
1.265 albertel 3969: $result .= '__END_ARRAY_REF__';
1.204 albertel 3970: return $result;
3971: }
3972:
1.168 albertel 3973: sub hash2str {
1.204 albertel 3974: my (%hash) = @_;
3975: my $result=&hashref2str(\%hash);
1.265 albertel 3976: $result=~s/^__HASH_REF__//;
3977: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3978: return $result;
3979: }
3980:
3981: sub hashref2str {
3982: my ($hashref)=@_;
1.265 albertel 3983: my $result='__HASH_REF__';
1.800 albertel 3984: foreach my $key (sort(keys(%$hashref))) {
3985: if (ref($key) eq 'ARRAY') {
3986: $result.=&arrayref2str($key).'=';
3987: } elsif (ref($key) eq 'HASH') {
3988: $result.=&hashref2str($key).'=';
3989: } elsif (ref($key)) {
1.265 albertel 3990: $result.='=';
1.800 albertel 3991: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3992: } else {
1.1132 raeburn 3993: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3994: }
3995:
1.800 albertel 3996: if(ref($hashref->{$key}) eq 'ARRAY') {
3997: $result.=&arrayref2str($hashref->{$key}).'&';
3998: } elsif(ref($hashref->{$key}) eq 'HASH') {
3999: $result.=&hashref2str($hashref->{$key}).'&';
4000: } elsif(ref($hashref->{$key})) {
1.265 albertel 4001: $result.='&';
1.800 albertel 4002: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4003: } else {
1.800 albertel 4004: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4005: }
4006: }
1.168 albertel 4007: $result=~s/\&$//;
1.265 albertel 4008: $result .= '__END_HASH_REF__';
1.168 albertel 4009: return $result;
4010: }
4011:
4012: sub str2hash {
1.265 albertel 4013: my ($string)=@_;
4014: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4015: return %$hash;
4016: }
4017:
4018: sub str2hashref {
1.168 albertel 4019: my ($string) = @_;
1.265 albertel 4020:
4021: my %hash;
4022:
4023: if($string !~ /^__HASH_REF__/) {
4024: if (! ($string eq '' || !defined($string))) {
4025: $hash{'error'}='Not hash reference';
4026: }
4027: return (\%hash, $string);
4028: }
4029:
4030: $string =~ s/^__HASH_REF__//;
4031:
4032: while($string !~ /^__END_HASH_REF__/) {
4033: #key
4034: my $key='';
4035: if($string =~ /^__HASH_REF__/) {
4036: ($key, $string)=&str2hashref($string);
4037: if(defined($key->{'error'})) {
4038: $hash{'error'}='Bad data';
4039: return (\%hash, $string);
4040: }
4041: } elsif($string =~ /^__ARRAY_REF__/) {
4042: ($key, $string)=&str2arrayref($string);
4043: if($key->[0] eq 'Array reference error') {
4044: $hash{'error'}='Bad data';
4045: return (\%hash, $string);
4046: }
4047: } else {
4048: $string =~ s/^(.*?)=//;
1.267 albertel 4049: $key=&unescape($1);
1.265 albertel 4050: }
4051: $string =~ s/^=//;
4052:
4053: #value
4054: my $value='';
4055: if($string =~ /^__HASH_REF__/) {
4056: ($value, $string)=&str2hashref($string);
4057: if(defined($value->{'error'})) {
4058: $hash{'error'}='Bad data';
4059: return (\%hash, $string);
4060: }
4061: } elsif($string =~ /^__ARRAY_REF__/) {
4062: ($value, $string)=&str2arrayref($string);
4063: if($value->[0] eq 'Array reference error') {
4064: $hash{'error'}='Bad data';
4065: return (\%hash, $string);
4066: }
4067: } else {
4068: $value=&get_scalar(\$string,'__END_HASH_REF__');
4069: }
4070: $string =~ s/^&//;
4071:
4072: $hash{$key}=$value;
1.204 albertel 4073: }
1.265 albertel 4074:
4075: $string =~ s/^__END_HASH_REF__//;
4076:
4077: return (\%hash, $string);
1.204 albertel 4078: }
4079:
4080: sub str2array {
1.265 albertel 4081: my ($string)=@_;
4082: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4083: return @$array;
4084: }
4085:
4086: sub str2arrayref {
1.204 albertel 4087: my ($string) = @_;
1.265 albertel 4088: my @array;
4089:
4090: if($string !~ /^__ARRAY_REF__/) {
4091: if (! ($string eq '' || !defined($string))) {
4092: $array[0]='Array reference error';
4093: }
4094: return (\@array, $string);
4095: }
4096:
4097: $string =~ s/^__ARRAY_REF__//;
4098:
4099: while($string !~ /^__END_ARRAY_REF__/) {
4100: my $value='';
4101: if($string =~ /^__HASH_REF__/) {
4102: ($value, $string)=&str2hashref($string);
4103: if(defined($value->{'error'})) {
4104: $array[0] ='Array reference error';
4105: return (\@array, $string);
4106: }
4107: } elsif($string =~ /^__ARRAY_REF__/) {
4108: ($value, $string)=&str2arrayref($string);
4109: if($value->[0] eq 'Array reference error') {
4110: $array[0] ='Array reference error';
4111: return (\@array, $string);
4112: }
4113: } else {
4114: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4115: }
4116: $string =~ s/^&//;
4117:
4118: push(@array, $value);
1.191 harris41 4119: }
1.265 albertel 4120:
4121: $string =~ s/^__END_ARRAY_REF__//;
4122:
4123: return (\@array, $string);
1.168 albertel 4124: }
4125:
1.167 albertel 4126: # -------------------------------------------------------------------Temp Store
4127:
1.168 albertel 4128: sub tmpreset {
4129: my ($symb,$namespace,$domain,$stuname) = @_;
4130: if (!$symb) {
4131: $symb=&symbread();
1.620 albertel 4132: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4133: }
4134: $symb=escape($symb);
4135:
1.620 albertel 4136: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4137: $namespace=~s/\//\_/g;
4138: $namespace=~s/\W//g;
4139:
1.620 albertel 4140: if (!$domain) { $domain=$env{'user.domain'}; }
4141: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4142: if ($domain eq 'public' && $stuname eq 'public') {
4143: $stuname=$ENV{'REMOTE_ADDR'};
4144: }
1.1117 foxr 4145: my $path=LONCAPA::tempdir();
1.168 albertel 4146: my %hash;
4147: if (tie(%hash,'GDBM_File',
4148: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4149: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4150: foreach my $key (keys(%hash)) {
1.180 albertel 4151: if ($key=~ /:$symb/) {
1.168 albertel 4152: delete($hash{$key});
4153: }
4154: }
4155: }
4156: }
4157:
1.167 albertel 4158: sub tmpstore {
1.168 albertel 4159: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4160:
4161: if (!$symb) {
4162: $symb=&symbread();
1.620 albertel 4163: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4164: }
4165: $symb=escape($symb);
4166:
4167: if (!$namespace) {
4168: # I don't think we would ever want to store this for a course.
4169: # it seems this will only be used if we don't have a course.
1.620 albertel 4170: #$namespace=$env{'request.course.id'};
1.168 albertel 4171: #if (!$namespace) {
1.620 albertel 4172: $namespace=$env{'request.state'};
1.168 albertel 4173: #}
4174: }
4175: $namespace=~s/\//\_/g;
4176: $namespace=~s/\W//g;
1.620 albertel 4177: if (!$domain) { $domain=$env{'user.domain'}; }
4178: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4179: if ($domain eq 'public' && $stuname eq 'public') {
4180: $stuname=$ENV{'REMOTE_ADDR'};
4181: }
1.168 albertel 4182: my $now=time;
4183: my %hash;
1.1117 foxr 4184: my $path=LONCAPA::tempdir();
1.168 albertel 4185: if (tie(%hash,'GDBM_File',
4186: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4187: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4188: $hash{"version:$symb"}++;
4189: my $version=$hash{"version:$symb"};
4190: my $allkeys='';
4191: foreach my $key (keys(%$storehash)) {
4192: $allkeys.=$key.':';
1.591 albertel 4193: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4194: }
4195: $hash{"$version:$symb:timestamp"}=$now;
4196: $allkeys.='timestamp';
4197: $hash{"$version:keys:$symb"}=$allkeys;
4198: if (untie(%hash)) {
4199: return 'ok';
4200: } else {
4201: return "error:$!";
4202: }
4203: } else {
4204: return "error:$!";
4205: }
4206: }
1.167 albertel 4207:
1.168 albertel 4208: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4209:
1.168 albertel 4210: sub tmprestore {
4211: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4212:
1.168 albertel 4213: if (!$symb) {
4214: $symb=&symbread();
1.620 albertel 4215: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4216: }
4217: $symb=escape($symb);
4218:
1.620 albertel 4219: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4220:
1.620 albertel 4221: if (!$domain) { $domain=$env{'user.domain'}; }
4222: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4223: if ($domain eq 'public' && $stuname eq 'public') {
4224: $stuname=$ENV{'REMOTE_ADDR'};
4225: }
1.168 albertel 4226: my %returnhash;
4227: $namespace=~s/\//\_/g;
4228: $namespace=~s/\W//g;
4229: my %hash;
1.1117 foxr 4230: my $path=LONCAPA::tempdir();
1.168 albertel 4231: if (tie(%hash,'GDBM_File',
4232: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4233: &GDBM_READER(),0640)) {
1.168 albertel 4234: my $version=$hash{"version:$symb"};
4235: $returnhash{'version'}=$version;
4236: my $scope;
4237: for ($scope=1;$scope<=$version;$scope++) {
4238: my $vkeys=$hash{"$scope:keys:$symb"};
4239: my @keys=split(/:/,$vkeys);
4240: my $key;
4241: $returnhash{"$scope:keys"}=$vkeys;
4242: foreach $key (@keys) {
1.591 albertel 4243: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4244: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4245: }
4246: }
1.168 albertel 4247: if (!(untie(%hash))) {
4248: return "error:$!";
4249: }
4250: } else {
4251: return "error:$!";
4252: }
4253: return %returnhash;
1.167 albertel 4254: }
4255:
1.9 www 4256: # ----------------------------------------------------------------------- Store
4257:
4258: sub store {
1.124 www 4259: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4260: my $home='';
4261:
1.168 albertel 4262: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4263:
1.213 www 4264: $symb=&symbclean($symb);
1.122 albertel 4265: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4266:
1.620 albertel 4267: if (!$domain) { $domain=$env{'user.domain'}; }
4268: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4269:
4270: &devalidate($symb,$stuname,$domain);
1.109 www 4271:
4272: $symb=escape($symb);
1.187 www 4273: if (!$namespace) {
1.620 albertel 4274: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4275: return '';
4276: }
4277: }
1.620 albertel 4278: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4279:
4280: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4281: $$storehash{'host'}=$perlvar{'lonHostID'};
4282:
1.12 www 4283: my $namevalue='';
1.800 albertel 4284: foreach my $key (keys(%$storehash)) {
4285: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4286: }
1.12 www 4287: $namevalue=~s/\&$//;
1.187 www 4288: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4289: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4290: }
4291:
1.47 www 4292: # -------------------------------------------------------------- Critical Store
4293:
4294: sub cstore {
1.124 www 4295: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4296: my $home='';
4297:
1.168 albertel 4298: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4299:
1.213 www 4300: $symb=&symbclean($symb);
1.122 albertel 4301: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4302:
1.620 albertel 4303: if (!$domain) { $domain=$env{'user.domain'}; }
4304: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4305:
4306: &devalidate($symb,$stuname,$domain);
1.109 www 4307:
4308: $symb=escape($symb);
1.187 www 4309: if (!$namespace) {
1.620 albertel 4310: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4311: return '';
4312: }
4313: }
1.620 albertel 4314: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4315:
4316: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4317: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4318:
1.47 www 4319: my $namevalue='';
1.800 albertel 4320: foreach my $key (keys(%$storehash)) {
4321: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4322: }
1.47 www 4323: $namevalue=~s/\&$//;
1.187 www 4324: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4325: return critical
4326: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4327: }
4328:
1.9 www 4329: # --------------------------------------------------------------------- Restore
4330:
4331: sub restore {
1.124 www 4332: my ($symb,$namespace,$domain,$stuname) = @_;
4333: my $home='';
4334:
1.168 albertel 4335: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4336:
1.122 albertel 4337: if (!$symb) {
4338: unless ($symb=escape(&symbread())) { return ''; }
4339: } else {
1.213 www 4340: $symb=&escape(&symbclean($symb));
1.122 albertel 4341: }
1.188 www 4342: if (!$namespace) {
1.620 albertel 4343: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4344: return '';
4345: }
4346: }
1.620 albertel 4347: if (!$domain) { $domain=$env{'user.domain'}; }
4348: if (!$stuname) { $stuname=$env{'user.name'}; }
4349: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4350: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4351:
1.12 www 4352: my %returnhash=();
1.800 albertel 4353: foreach my $line (split(/\&/,$answer)) {
4354: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4355: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4356: }
1.75 www 4357: my $version;
4358: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4359: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4360: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4361: }
1.75 www 4362: }
1.13 www 4363: return %returnhash;
1.34 www 4364: }
4365:
4366: # ---------------------------------------------------------- Course Description
1.1118 foxr 4367: #
4368: #
1.34 www 4369:
4370: sub coursedescription {
1.731 albertel 4371: my ($courseid,$args)=@_;
1.34 www 4372: $courseid=~s/^\///;
1.49 www 4373: $courseid=~s/\_/\//g;
1.34 www 4374: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4375: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4376: my $normalid=$cdomain.'_'.$cnum;
4377: # need to always cache even if we get errors otherwise we keep
4378: # trying and trying and trying to get the course description.
4379: my %envhash=();
4380: my %returnhash=();
1.731 albertel 4381:
4382: my $expiretime=600;
4383: if ($env{'request.course.id'} eq $normalid) {
4384: $expiretime=120;
4385: }
4386:
4387: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4388: if (!$args->{'freshen_cache'}
4389: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4390: foreach my $key (keys(%env)) {
4391: next if ($key !~ /^\Q$prefix\E(.*)/);
4392: my ($setting) = $1;
4393: $returnhash{$setting} = $env{$key};
4394: }
4395: return %returnhash;
4396: }
4397:
1.1118 foxr 4398: # get the data again
4399:
1.731 albertel 4400: if (!$args->{'one_time'}) {
4401: $envhash{'course.'.$normalid.'.last_cache'}=time;
4402: }
1.811 albertel 4403:
1.34 www 4404: if ($chome ne 'no_host') {
1.302 albertel 4405: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4406: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4407: my $username = $env{'user.name'}; # Defult username
4408: if(defined $args->{'user'}) {
4409: $username = $args->{'user'};
4410: }
1.129 albertel 4411: $returnhash{'home'}= $chome;
4412: $returnhash{'domain'} = $cdomain;
4413: $returnhash{'num'} = $cnum;
1.741 raeburn 4414: if (!defined($returnhash{'type'})) {
4415: $returnhash{'type'} = 'Course';
4416: }
1.130 albertel 4417: while (my ($name,$value) = each %returnhash) {
1.53 www 4418: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4419: }
1.270 www 4420: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4421: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4422: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4423: $envhash{'course.'.$normalid.'.home'}=$chome;
4424: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4425: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4426: }
4427: }
1.731 albertel 4428: if (!$args->{'one_time'}) {
1.949 raeburn 4429: &appenv(\%envhash);
1.731 albertel 4430: }
1.302 albertel 4431: return %returnhash;
1.461 www 4432: }
4433:
1.1080 raeburn 4434: sub update_released_required {
4435: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4436: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4437: $cid = $env{'request.course.id'};
4438: $cdom = $env{'course.'.$cid.'.domain'};
4439: $cnum = $env{'course.'.$cid.'.num'};
4440: $chome = $env{'course.'.$cid.'.home'};
4441: }
4442: if ($needsrelease) {
4443: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4444: my $needsupdate;
4445: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4446: $needsupdate = 1;
4447: } else {
4448: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4449: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4450: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4451: $needsupdate = 1;
4452: }
4453: }
4454: if ($needsupdate) {
4455: my %needshash = (
4456: 'internal.releaserequired' => $needsrelease,
4457: );
4458: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4459: if ($putresult eq 'ok') {
4460: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4461: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4462: if (ref($crsinfo{$cid}) eq 'HASH') {
4463: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4464: &courseidput($cdom,\%crsinfo,$chome,'notime');
4465: }
4466: }
4467: }
4468: }
4469: return;
4470: }
4471:
1.461 www 4472: # -------------------------------------------------See if a user is privileged
4473:
4474: sub privileged {
4475: my ($username,$domain)=@_;
4476: my $rolesdump=&reply("dump:$domain:$username:roles",
4477: &homeserver($username,$domain));
1.1033 raeburn 4478: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4479: ($rolesdump =~ /^error:/)) {
4480: return 0;
4481: }
1.461 www 4482: my $now=time;
4483: if ($rolesdump ne '') {
1.800 albertel 4484: foreach my $entry (split(/&/,$rolesdump)) {
4485: if ($entry!~/^rolesdef_/) {
4486: my ($area,$role)=split(/=/,$entry);
1.461 www 4487: $area=~s/\_\w\w$//;
4488: my ($trole,$tend,$tstart)=split(/_/,$role);
4489: if (($trole eq 'dc') || ($trole eq 'su')) {
4490: my $active=1;
4491: if ($tend) {
4492: if ($tend<$now) { $active=0; }
4493: }
4494: if ($tstart) {
4495: if ($tstart>$now) { $active=0; }
4496: }
4497: if ($active) { return 1; }
4498: }
4499: }
4500: }
4501: }
4502: return 0;
1.9 www 4503: }
1.1 albertel 4504:
1.103 harris41 4505: # -------------------------------------------------------- Get user privileges
1.11 www 4506:
4507: sub rolesinit {
4508: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4509: my $now=time;
4510: my %userroles = ('user.login.time' => $now);
1.1086 raeburn 4511: my $extra = &freeze_escape({'skipcheck' => 1});
1.1078 raeburn 4512: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4513: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1078 raeburn 4514: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4515: return \%userroles;
4516: }
1.11 www 4517: my %allroles=();
1.678 raeburn 4518: my %allgroups=();
1.11 www 4519:
4520: if ($rolesdump ne '') {
1.800 albertel 4521: foreach my $entry (split(/&/,$rolesdump)) {
4522: if ($entry!~/^rolesdef_/) {
4523: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4524: $area=~s/\_\w\w$//;
1.678 raeburn 4525: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4526: if ($role=~/^cr/) {
1.807 albertel 4527: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4528: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4529: ($tend,$tstart)=split('_',$trest);
4530: } else {
4531: $trole=$role;
4532: }
1.678 raeburn 4533: } elsif ($role =~ m|^gr/|) {
4534: ($trole,$tend,$tstart) = split(/_/,$role);
1.1104 raeburn 4535: next if ($tstart eq '-1');
1.678 raeburn 4536: ($trole,$group_privs) = split(/\//,$trole);
4537: $group_privs = &unescape($group_privs);
1.587 albertel 4538: } else {
4539: ($trole,$tend,$tstart)=split(/_/,$role);
4540: }
1.743 albertel 4541: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4542: $username);
4543: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4544: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4545: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4546: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4547: my $spec=$trole.'.'.$area;
4548: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4549: if ($trole =~ /^cr\//) {
1.567 raeburn 4550: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4551: } elsif ($trole eq 'gr') {
4552: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4553: } else {
1.567 raeburn 4554: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4555: }
1.12 www 4556: }
1.662 raeburn 4557: }
1.191 harris41 4558: }
1.743 albertel 4559: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4560: $userroles{'user.adv'} = $adv;
4561: $userroles{'user.author'} = $author;
1.620 albertel 4562: $env{'user.adv'}=$adv;
1.11 www 4563: }
1.743 albertel 4564: return \%userroles;
1.11 www 4565: }
4566:
1.567 raeburn 4567: sub set_arearole {
4568: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4569: # log the associated role with the area
4570: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4571: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4572: }
4573:
4574: sub custom_roleprivs {
4575: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4576: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4577: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4578: if (&hostname($homsvr) ne '') {
1.567 raeburn 4579: my ($rdummy,$roledef)=
4580: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4581: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4582: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4583: if (defined($syspriv)) {
1.1043 raeburn 4584: if ($trest =~ /^$match_community$/) {
4585: $syspriv =~ s/bre\&S//;
4586: }
1.567 raeburn 4587: $$allroles{'cm./'}.=':'.$syspriv;
4588: $$allroles{$spec.'./'}.=':'.$syspriv;
4589: }
4590: if ($tdomain ne '') {
4591: if (defined($dompriv)) {
4592: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4593: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4594: }
4595: if (($trest ne '') && (defined($coursepriv))) {
4596: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4597: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4598: }
4599: }
4600: }
4601: }
4602: }
4603:
1.678 raeburn 4604: sub group_roleprivs {
4605: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4606: my $access = 1;
4607: my $now = time;
4608: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4609: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4610: if ($access) {
1.811 albertel 4611: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4612: $$allgroups{$course}{$group} .=':'.$group_privs;
4613: }
4614: }
1.567 raeburn 4615:
4616: sub standard_roleprivs {
4617: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4618: if (defined($pr{$trole.':s'})) {
4619: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4620: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4621: }
4622: if ($tdomain ne '') {
4623: if (defined($pr{$trole.':d'})) {
4624: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4625: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4626: }
4627: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4628: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4629: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4630: }
4631: }
4632: }
4633:
4634: sub set_userprivs {
1.1064 raeburn 4635: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4636: my $author=0;
4637: my $adv=0;
1.678 raeburn 4638: my %grouproles = ();
4639: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4640: my @groupkeys;
1.1000 raeburn 4641: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4642: push(@groupkeys,$role);
4643: }
4644: if (ref($groups_roles) eq 'HASH') {
4645: foreach my $key (keys(%{$groups_roles})) {
4646: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4647: push(@groupkeys,$key);
4648: }
4649: }
4650: }
4651: if (@groupkeys > 0) {
4652: foreach my $role (@groupkeys) {
4653: my ($trole,$area,$sec,$extendedarea);
4654: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4655: $trole = $1;
4656: $area = $2;
4657: $sec = $3;
4658: $extendedarea = $area.$sec;
4659: if (exists($$allgroups{$area})) {
4660: foreach my $group (keys(%{$$allgroups{$area}})) {
4661: my $spec = $trole.'.'.$extendedarea;
4662: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4663: $$allgroups{$area}{$group};
1.1064 raeburn 4664: }
1.678 raeburn 4665: }
4666: }
4667: }
4668: }
4669: }
1.800 albertel 4670: foreach my $group (keys(%grouproles)) {
4671: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4672: }
1.800 albertel 4673: foreach my $role (keys(%{$allroles})) {
4674: my %thesepriv;
1.941 raeburn 4675: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4676: foreach my $item (split(/:/,$$allroles{$role})) {
4677: if ($item ne '') {
4678: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4679: if ($restrictions eq '') {
4680: $thesepriv{$privilege}='F';
4681: } elsif ($thesepriv{$privilege} ne 'F') {
4682: $thesepriv{$privilege}.=$restrictions;
4683: }
4684: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4685: }
4686: }
4687: my $thesestr='';
1.1104 raeburn 4688: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 4689: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4690: }
4691: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4692: }
4693: return ($author,$adv);
4694: }
4695:
1.994 raeburn 4696: sub role_status {
1.1104 raeburn 4697: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4698: my @pwhere = ();
4699: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4700: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4701: unless (!defined($$role) || $$role eq '') {
4702: $$where=join('.',@pwhere);
4703: $$trolecode=$$role.'.'.$$where;
4704: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4705: $$tstatus='is';
1.1104 raeburn 4706: if ($$tstart && $$tstart>$update) {
1.994 raeburn 4707: $$tstatus='future';
1.1034 raeburn 4708: if ($$tstart<$now) {
4709: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4710: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4711: my (%allroles,%allgroups,$group_privs,
4712: %groups_roles,@rolecodes);
1.1002 raeburn 4713: my %userroles = (
4714: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4715: );
1.1064 raeburn 4716: @rolecodes = ('cm');
1.1002 raeburn 4717: my $spec=$$role.'.'.$$where;
4718: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4719: if ($$role =~ /^cr\//) {
4720: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4721: push(@rolecodes,'cr');
1.1002 raeburn 4722: } elsif ($$role eq 'gr') {
1.1064 raeburn 4723: push(@rolecodes,$$role);
1.1002 raeburn 4724: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4725: $env{'user.name'});
1.1064 raeburn 4726: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4727: (undef,my $group_privs) = split(/\//,$trole);
4728: $group_privs = &unescape($group_privs);
4729: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4730: 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 4731: &get_groups_roles($tdomain,$trest,
4732: \%course_roles,\@rolecodes,
4733: \%groups_roles);
1.1002 raeburn 4734: } else {
1.1064 raeburn 4735: push(@rolecodes,$$role);
1.1002 raeburn 4736: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4737: }
1.1064 raeburn 4738: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4739: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4740: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4741: }
4742: }
1.1034 raeburn 4743: $$tstatus = 'is';
1.1002 raeburn 4744: }
1.994 raeburn 4745: }
4746: if ($$tend) {
1.1104 raeburn 4747: if ($$tend<$update) {
1.994 raeburn 4748: $$tstatus='expired';
4749: } elsif ($$tend<$now) {
4750: $$tstatus='will_not';
4751: }
4752: }
4753: }
4754: }
4755: }
4756:
1.1104 raeburn 4757: sub get_groups_roles {
4758: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4759: return unless((ref($cdom_courseroles) eq 'HASH') &&
4760: (ref($rolecodes) eq 'ARRAY') &&
4761: (ref($groups_roles) eq 'HASH'));
4762: if (keys(%{$cdom_courseroles}) > 0) {
4763: my ($cnum) = ($rest =~ /^($match_courseid)/);
4764: if ($cdom ne '' && $cnum ne '') {
4765: foreach my $key (keys(%{$cdom_courseroles})) {
4766: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4767: my $crsrole = $1;
4768: my $crssec = $2;
4769: if ($crsrole =~ /^cr/) {
4770: unless (grep(/^cr$/,@{$rolecodes})) {
4771: push(@{$rolecodes},'cr');
4772: }
4773: } else {
4774: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4775: push(@{$rolecodes},$crsrole);
4776: }
4777: }
4778: my $rolekey = "$crsrole./$cdom/$cnum";
4779: if ($crssec ne '') {
4780: $rolekey .= "/$crssec";
4781: }
4782: $rolekey .= './';
4783: $groups_roles->{$rolekey} = $rolecodes;
4784: }
4785: }
4786: }
4787: }
4788: return;
4789: }
4790:
4791: sub delete_env_groupprivs {
4792: my ($where,$courseroles,$possroles) = @_;
4793: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4794: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4795: unless (ref($courseroles->{$udom}) eq 'HASH') {
4796: %{$courseroles->{$udom}} =
4797: &get_my_roles('','','userroles',['active'],
4798: $possroles,[$udom],1);
4799: }
4800: if (ref($courseroles->{$udom}) eq 'HASH') {
4801: foreach my $item (keys(%{$courseroles->{$udom}})) {
4802: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4803: my $area = '/'.$cdom.'/'.$cnum;
4804: my $privkey = "user.priv.$crsrole.$area";
4805: if ($crssec ne '') {
4806: $privkey .= '/'.$crssec;
4807: }
4808: $privkey .= ".$area/$group";
4809: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4810: }
4811: }
4812: return;
4813: }
4814:
1.994 raeburn 4815: sub check_adhoc_privs {
1.1104 raeburn 4816: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4817: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4818: if ($env{$cckey}) {
4819: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 4820: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4821: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 4822: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4823: }
4824: } else {
1.1088 raeburn 4825: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4826: }
4827: }
4828:
4829: sub set_adhoc_privileges {
4830: # role can be cc or ca
1.1088 raeburn 4831: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 4832: my $area = '/'.$dcdom.'/'.$pickedcourse;
4833: my $spec = $role.'.'.$area;
4834: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4835: $env{'user.name'});
4836: my %ccrole = ();
4837: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4838: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4839: &appenv(\%userroles,[$role,'cm']);
4840: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 4841: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4842: &appenv( {'request.role' => $spec,
4843: 'request.role.domain' => $dcdom,
4844: 'request.course.sec' => ''
4845: }
4846: );
4847: my $tadv=0;
4848: if (&allowed('adv') eq 'F') { $tadv=1; }
4849: &appenv({'request.role.adv' => $tadv});
4850: }
1.994 raeburn 4851: }
4852:
1.12 www 4853: # --------------------------------------------------------------- get interface
4854:
4855: sub get {
1.131 albertel 4856: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4857: my $items='';
1.800 albertel 4858: foreach my $item (@$storearr) {
4859: $items.=&escape($item).'&';
1.191 harris41 4860: }
1.12 www 4861: $items=~s/\&$//;
1.620 albertel 4862: if (!$udomain) { $udomain=$env{'user.domain'}; }
4863: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4864: my $uhome=&homeserver($uname,$udomain);
4865:
1.133 albertel 4866: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4867: my @pairs=split(/\&/,$rep);
1.273 albertel 4868: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4869: return @pairs;
4870: }
1.15 www 4871: my %returnhash=();
1.42 www 4872: my $i=0;
1.800 albertel 4873: foreach my $item (@$storearr) {
4874: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4875: $i++;
1.191 harris41 4876: }
1.15 www 4877: return %returnhash;
1.27 www 4878: }
4879:
4880: # --------------------------------------------------------------- del interface
4881:
4882: sub del {
1.133 albertel 4883: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4884: my $items='';
1.800 albertel 4885: foreach my $item (@$storearr) {
4886: $items.=&escape($item).'&';
1.191 harris41 4887: }
1.984 neumanie 4888:
1.27 www 4889: $items=~s/\&$//;
1.620 albertel 4890: if (!$udomain) { $udomain=$env{'user.domain'}; }
4891: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4892: my $uhome=&homeserver($uname,$udomain);
4893: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4894: }
4895:
4896: # -------------------------------------------------------------- dump interface
4897:
4898: sub dump {
1.1086 raeburn 4899: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755 albertel 4900: if (!$udomain) { $udomain=$env{'user.domain'}; }
4901: if (!$uname) { $uname=$env{'user.name'}; }
4902: my $uhome=&homeserver($uname,$udomain);
4903: if ($regexp) {
4904: $regexp=&escape($regexp);
4905: } else {
4906: $regexp='.';
4907: }
1.1086 raeburn 4908: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755 albertel 4909: my @pairs=split(/\&/,$rep);
4910: my %returnhash=();
1.1098 foxr 4911: if (!($rep =~ /^error/ )) {
4912: foreach my $item (@pairs) {
4913: my ($key,$value)=split(/=/,$item,2);
4914: $key = &unescape($key);
4915: next if ($key =~ /^error: 2 /);
4916: $returnhash{$key}=&thaw_unescape($value);
4917: }
1.755 albertel 4918: }
4919: return %returnhash;
1.407 www 4920: }
4921:
1.1098 foxr 4922:
1.717 albertel 4923: # --------------------------------------------------------- dumpstore interface
4924:
4925: sub dumpstore {
4926: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4927: if (!$udomain) { $udomain=$env{'user.domain'}; }
4928: if (!$uname) { $uname=$env{'user.name'}; }
4929: my $uhome=&homeserver($uname,$udomain);
4930: if ($regexp) {
4931: $regexp=&escape($regexp);
4932: } else {
4933: $regexp='.';
4934: }
4935: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4936: my @pairs=split(/\&/,$rep);
4937: my %returnhash=();
4938: foreach my $item (@pairs) {
4939: my ($key,$value)=split(/=/,$item,2);
4940: next if ($key =~ /^error: 2 /);
4941: $returnhash{$key}=&thaw_unescape($value);
4942: }
4943: return %returnhash;
1.717 albertel 4944: }
4945:
1.407 www 4946: # -------------------------------------------------------------- keys interface
4947:
4948: sub getkeys {
4949: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4950: if (!$udomain) { $udomain=$env{'user.domain'}; }
4951: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4952: my $uhome=&homeserver($uname,$udomain);
4953: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4954: my @keyarray=();
1.800 albertel 4955: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4956: next if ($key =~ /^error: 2 /);
1.800 albertel 4957: push(@keyarray,&unescape($key));
1.407 www 4958: }
4959: return @keyarray;
1.318 matthew 4960: }
4961:
1.319 matthew 4962: # --------------------------------------------------------------- currentdump
4963: sub currentdump {
1.328 matthew 4964: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4965: $courseid = $env{'request.course.id'} if (! defined($courseid));
4966: $sdom = $env{'user.domain'} if (! defined($sdom));
4967: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4968: my $uhome = &homeserver($sname,$sdom);
4969: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4970: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4971: #
1.318 matthew 4972: my %returnhash=();
1.319 matthew 4973: #
4974: if ($rep eq "unknown_cmd") {
4975: # an old lond will not know currentdump
4976: # Do a dump and make it look like a currentdump
1.822 albertel 4977: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4978: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4979: my %hash = @tmp;
4980: @tmp=();
1.424 matthew 4981: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4982: } else {
4983: my @pairs=split(/\&/,$rep);
1.800 albertel 4984: foreach my $pair (@pairs) {
4985: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4986: my ($symb,$param) = split(/:/,$key);
4987: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4988: &thaw_unescape($value);
1.319 matthew 4989: }
1.191 harris41 4990: }
1.12 www 4991: return %returnhash;
1.424 matthew 4992: }
4993:
4994: sub convert_dump_to_currentdump{
4995: my %hash = %{shift()};
4996: my %returnhash;
4997: # Code ripped from lond, essentially. The only difference
4998: # here is the unescaping done by lonnet::dump(). Conceivably
4999: # we might run in to problems with parameter names =~ /^v\./
5000: while (my ($key,$value) = each(%hash)) {
5001: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5002: $symb = &unescape($symb);
5003: $param = &unescape($param);
1.424 matthew 5004: next if ($v eq 'version' || $symb eq 'keys');
5005: next if (exists($returnhash{$symb}) &&
5006: exists($returnhash{$symb}->{$param}) &&
5007: $returnhash{$symb}->{'v.'.$param} > $v);
5008: $returnhash{$symb}->{$param}=$value;
5009: $returnhash{$symb}->{'v.'.$param}=$v;
5010: }
5011: #
5012: # Remove all of the keys in the hashes which keep track of
5013: # the version of the parameter.
5014: while (my ($symb,$param_hash) = each(%returnhash)) {
5015: # use a foreach because we are going to delete from the hash.
5016: foreach my $key (keys(%$param_hash)) {
5017: delete($param_hash->{$key}) if ($key =~ /^v\./);
5018: }
5019: }
5020: return \%returnhash;
1.12 www 5021: }
5022:
1.627 albertel 5023: # ------------------------------------------------------ critical inc interface
5024:
5025: sub cinc {
5026: return &inc(@_,'critical');
5027: }
5028:
1.449 matthew 5029: # --------------------------------------------------------------- inc interface
5030:
5031: sub inc {
1.627 albertel 5032: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5033: if (!$udomain) { $udomain=$env{'user.domain'}; }
5034: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5035: my $uhome=&homeserver($uname,$udomain);
5036: my $items='';
5037: if (! ref($store)) {
5038: # got a single value, so use that instead
5039: $items = &escape($store).'=&';
5040: } elsif (ref($store) eq 'SCALAR') {
5041: $items = &escape($$store).'=&';
5042: } elsif (ref($store) eq 'ARRAY') {
5043: $items = join('=&',map {&escape($_);} @{$store});
5044: } elsif (ref($store) eq 'HASH') {
5045: while (my($key,$value) = each(%{$store})) {
5046: $items.= &escape($key).'='.&escape($value).'&';
5047: }
5048: }
5049: $items=~s/\&$//;
1.627 albertel 5050: if ($critical) {
5051: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5052: } else {
5053: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5054: }
1.449 matthew 5055: }
5056:
1.12 www 5057: # --------------------------------------------------------------- put interface
5058:
5059: sub put {
1.134 albertel 5060: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5061: if (!$udomain) { $udomain=$env{'user.domain'}; }
5062: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5063: my $uhome=&homeserver($uname,$udomain);
1.12 www 5064: my $items='';
1.800 albertel 5065: foreach my $item (keys(%$storehash)) {
5066: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5067: }
1.12 www 5068: $items=~s/\&$//;
1.134 albertel 5069: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5070: }
5071:
1.631 albertel 5072: # ------------------------------------------------------------ newput interface
5073:
5074: sub newput {
5075: my ($namespace,$storehash,$udomain,$uname)=@_;
5076: if (!$udomain) { $udomain=$env{'user.domain'}; }
5077: if (!$uname) { $uname=$env{'user.name'}; }
5078: my $uhome=&homeserver($uname,$udomain);
5079: my $items='';
5080: foreach my $key (keys(%$storehash)) {
5081: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5082: }
5083: $items=~s/\&$//;
5084: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5085: }
5086:
5087: # --------------------------------------------------------- putstore interface
5088:
1.524 raeburn 5089: sub putstore {
1.715 albertel 5090: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5091: if (!$udomain) { $udomain=$env{'user.domain'}; }
5092: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5093: my $uhome=&homeserver($uname,$udomain);
5094: my $items='';
1.715 albertel 5095: foreach my $key (keys(%$storehash)) {
5096: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5097: }
1.715 albertel 5098: $items=~s/\&$//;
1.716 albertel 5099: my $esc_symb=&escape($symb);
5100: my $esc_v=&escape($version);
1.715 albertel 5101: my $reply =
1.716 albertel 5102: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5103: $uhome);
5104: if ($reply eq 'unknown_cmd') {
1.716 albertel 5105: # gfall back to way things use to be done
1.715 albertel 5106: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5107: $uname);
1.524 raeburn 5108: }
1.715 albertel 5109: return $reply;
5110: }
5111:
5112: sub old_putstore {
1.716 albertel 5113: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5114: if (!$udomain) { $udomain=$env{'user.domain'}; }
5115: if (!$uname) { $uname=$env{'user.name'}; }
5116: my $uhome=&homeserver($uname,$udomain);
5117: my %newstorehash;
1.800 albertel 5118: foreach my $item (keys(%$storehash)) {
5119: my $key = $version.':'.&escape($symb).':'.$item;
5120: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5121: }
5122: my $items='';
5123: my %allitems = ();
1.800 albertel 5124: foreach my $item (keys(%newstorehash)) {
5125: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5126: my $key = $1.':keys:'.$2;
5127: $allitems{$key} .= $3.':';
5128: }
1.800 albertel 5129: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5130: }
1.800 albertel 5131: foreach my $item (keys(%allitems)) {
5132: $allitems{$item} =~ s/\:$//;
5133: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5134: }
5135: $items=~s/\&$//;
5136: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5137: }
5138:
1.47 www 5139: # ------------------------------------------------------ critical put interface
5140:
5141: sub cput {
1.134 albertel 5142: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5143: if (!$udomain) { $udomain=$env{'user.domain'}; }
5144: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5145: my $uhome=&homeserver($uname,$udomain);
1.47 www 5146: my $items='';
1.800 albertel 5147: foreach my $item (keys(%$storehash)) {
5148: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5149: }
1.47 www 5150: $items=~s/\&$//;
1.134 albertel 5151: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5152: }
5153:
5154: # -------------------------------------------------------------- eget interface
5155:
5156: sub eget {
1.133 albertel 5157: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5158: my $items='';
1.800 albertel 5159: foreach my $item (@$storearr) {
5160: $items.=&escape($item).'&';
1.191 harris41 5161: }
1.12 www 5162: $items=~s/\&$//;
1.620 albertel 5163: if (!$udomain) { $udomain=$env{'user.domain'}; }
5164: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5165: my $uhome=&homeserver($uname,$udomain);
5166: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5167: my @pairs=split(/\&/,$rep);
5168: my %returnhash=();
1.42 www 5169: my $i=0;
1.800 albertel 5170: foreach my $item (@$storearr) {
5171: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5172: $i++;
1.191 harris41 5173: }
1.12 www 5174: return %returnhash;
5175: }
5176:
1.667 albertel 5177: # ------------------------------------------------------------ tmpput interface
5178: sub tmpput {
1.802 raeburn 5179: my ($storehash,$server,$context)=@_;
1.667 albertel 5180: my $items='';
1.800 albertel 5181: foreach my $item (keys(%$storehash)) {
5182: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5183: }
5184: $items=~s/\&$//;
1.802 raeburn 5185: if (defined($context)) {
5186: $items .= ':'.&escape($context);
5187: }
1.667 albertel 5188: return &reply("tmpput:$items",$server);
5189: }
5190:
5191: # ------------------------------------------------------------ tmpget interface
5192: sub tmpget {
1.688 albertel 5193: my ($token,$server)=@_;
5194: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5195: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5196: my %returnhash;
5197: foreach my $item (split(/\&/,$rep)) {
5198: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5199: next if ($key =~ /^error: 2 /);
1.667 albertel 5200: $returnhash{&unescape($key)}=&thaw_unescape($value);
5201: }
5202: return %returnhash;
5203: }
5204:
1.1113 raeburn 5205: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5206: sub tmpdel {
5207: my ($token,$server)=@_;
5208: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5209: return &reply("tmpdel:$token",$server);
5210: }
5211:
1.765 albertel 5212: # -------------------------------------------------- portfolio access checking
5213:
5214: sub portfolio_access {
1.766 albertel 5215: my ($requrl) = @_;
1.765 albertel 5216: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5217: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 5218: if ($result) {
5219: my %setters;
5220: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5221: my ($startblock,$endblock) =
5222: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5223: if ($startblock && $endblock) {
5224: return 'B';
5225: }
5226: } else {
5227: my ($startblock,$endblock) =
5228: &Apache::loncommon::blockcheck(\%setters,'port');
5229: if ($startblock && $endblock) {
5230: return 'B';
5231: }
5232: }
5233: }
1.765 albertel 5234: if ($result eq 'ok') {
1.766 albertel 5235: return 'F';
1.765 albertel 5236: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 5237: return 'A';
1.765 albertel 5238: }
1.766 albertel 5239: return '';
1.765 albertel 5240: }
5241:
5242: sub get_portfolio_access {
1.767 albertel 5243: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5244:
5245: if (!ref($access_hash)) {
5246: my $current_perms = &get_portfile_permissions($udom,$unum);
5247: my %access_controls = &get_access_controls($current_perms,$group,
5248: $file_name);
5249: $access_hash = $access_controls{$file_name};
5250: }
5251:
1.765 albertel 5252: my ($public,$guest,@domains,@users,@courses,@groups);
5253: my $now = time;
5254: if (ref($access_hash) eq 'HASH') {
5255: foreach my $key (keys(%{$access_hash})) {
5256: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5257: if ($start > $now) {
5258: next;
5259: }
5260: if ($end && $end<$now) {
5261: next;
5262: }
5263: if ($scope eq 'public') {
5264: $public = $key;
5265: last;
5266: } elsif ($scope eq 'guest') {
5267: $guest = $key;
5268: } elsif ($scope eq 'domains') {
5269: push(@domains,$key);
5270: } elsif ($scope eq 'users') {
5271: push(@users,$key);
5272: } elsif ($scope eq 'course') {
5273: push(@courses,$key);
5274: } elsif ($scope eq 'group') {
5275: push(@groups,$key);
5276: }
5277: }
5278: if ($public) {
5279: return 'ok';
5280: }
5281: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5282: if ($guest) {
5283: return $guest;
5284: }
5285: } else {
5286: if (@domains > 0) {
5287: foreach my $domkey (@domains) {
5288: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5289: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5290: return 'ok';
5291: }
5292: }
5293: }
5294: }
5295: if (@users > 0) {
5296: foreach my $userkey (@users) {
1.865 raeburn 5297: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5298: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5299: if (ref($item) eq 'HASH') {
5300: if (($item->{'uname'} eq $env{'user.name'}) &&
5301: ($item->{'udom'} eq $env{'user.domain'})) {
5302: return 'ok';
5303: }
5304: }
5305: }
5306: }
1.765 albertel 5307: }
5308: }
5309: my %roleshash;
5310: my @courses_and_groups = @courses;
5311: push(@courses_and_groups,@groups);
5312: if (@courses_and_groups > 0) {
5313: my (%allgroups,%allroles);
5314: my ($start,$end,$role,$sec,$group);
5315: foreach my $envkey (%env) {
1.1060 raeburn 5316: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5317: my $cid = $2.'_'.$3;
5318: if ($1 eq 'gr') {
5319: $group = $4;
5320: $allgroups{$cid}{$group} = $env{$envkey};
5321: } else {
5322: if ($4 eq '') {
5323: $sec = 'none';
5324: } else {
5325: $sec = $4;
5326: }
5327: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5328: }
1.811 albertel 5329: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5330: my $cid = $2.'_'.$3;
5331: if ($4 eq '') {
5332: $sec = 'none';
5333: } else {
5334: $sec = $4;
5335: }
5336: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5337: }
5338: }
5339: if (keys(%allroles) == 0) {
5340: return;
5341: }
5342: foreach my $key (@courses_and_groups) {
5343: my %content = %{$$access_hash{$key}};
5344: my $cnum = $content{'number'};
5345: my $cdom = $content{'domain'};
5346: my $cid = $cdom.'_'.$cnum;
5347: if (!exists($allroles{$cid})) {
5348: next;
5349: }
5350: foreach my $role_id (keys(%{$content{'roles'}})) {
5351: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5352: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5353: my @status = @{$content{'roles'}{$role_id}{'access'}};
5354: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5355: foreach my $role (keys(%{$allroles{$cid}})) {
5356: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5357: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5358: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5359: if (grep/^all$/,@sections) {
5360: return 'ok';
5361: } else {
5362: if (grep/^$sec$/,@sections) {
5363: return 'ok';
5364: }
5365: }
5366: }
5367: }
5368: if (keys(%{$allgroups{$cid}}) == 0) {
5369: if (grep/^none$/,@groups) {
5370: return 'ok';
5371: }
5372: } else {
5373: if (grep/^all$/,@groups) {
5374: return 'ok';
5375: }
5376: foreach my $group (keys(%{$allgroups{$cid}})) {
5377: if (grep/^$group$/,@groups) {
5378: return 'ok';
5379: }
5380: }
5381: }
5382: }
5383: }
5384: }
5385: }
5386: }
5387: if ($guest) {
5388: return $guest;
5389: }
5390: }
5391: }
5392: return;
5393: }
5394:
5395: sub course_group_datechecker {
5396: my ($dates,$now,$status) = @_;
5397: my ($start,$end) = split(/\./,$dates);
5398: if (!$start && !$end) {
5399: return 'ok';
5400: }
5401: if (grep/^active$/,@{$status}) {
5402: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5403: return 'ok';
5404: }
5405: }
5406: if (grep/^previous$/,@{$status}) {
5407: if ($end > $now ) {
5408: return 'ok';
5409: }
5410: }
5411: if (grep/^future$/,@{$status}) {
5412: if ($start > $now) {
5413: return 'ok';
5414: }
5415: }
5416: return;
5417: }
5418:
5419: sub parse_portfolio_url {
5420: my ($url) = @_;
5421:
5422: my ($type,$udom,$unum,$group,$file_name);
5423:
1.823 albertel 5424: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5425: $type = 1;
5426: $udom = $1;
5427: $unum = $2;
5428: $file_name = $3;
1.823 albertel 5429: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5430: $type = 2;
5431: $udom = $1;
5432: $unum = $2;
5433: $group = $3;
5434: $file_name = $3.'/'.$4;
5435: }
5436: if (wantarray) {
5437: return ($type,$udom,$unum,$file_name,$group);
5438: }
5439: return $type;
5440: }
5441:
5442: sub is_portfolio_url {
5443: my ($url) = @_;
5444: return scalar(&parse_portfolio_url($url));
5445: }
5446:
1.798 raeburn 5447: sub is_portfolio_file {
5448: my ($file) = @_;
1.820 raeburn 5449: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5450: return 1;
5451: }
5452: return;
5453: }
5454:
1.976 raeburn 5455: sub usertools_access {
1.1084 raeburn 5456: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 5457: my ($access,%tools);
5458: if ($context eq '') {
5459: $context = 'tools';
5460: }
5461: if ($context eq 'requestcourses') {
5462: %tools = (
5463: official => 1,
5464: unofficial => 1,
1.1006 raeburn 5465: community => 1,
1.985 raeburn 5466: );
5467: } else {
5468: %tools = (
5469: aboutme => 1,
5470: blog => 1,
5471: portfolio => 1,
5472: );
5473: }
1.976 raeburn 5474: return if (!defined($tools{$tool}));
5475:
5476: if ((!defined($udom)) || (!defined($uname))) {
5477: $udom = $env{'user.domain'};
5478: $uname = $env{'user.name'};
5479: }
5480:
1.978 raeburn 5481: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5482: if ($action ne 'reload') {
1.985 raeburn 5483: if ($context eq 'requestcourses') {
5484: return $env{'environment.canrequest.'.$tool};
5485: } else {
5486: return $env{'environment.availabletools.'.$tool};
5487: }
5488: }
1.976 raeburn 5489: }
5490:
5491: my ($toolstatus,$inststatus);
5492:
1.985 raeburn 5493: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5494: ($action ne 'reload')) {
5495: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5496: $inststatus = $env{'environment.inststatus'};
5497: } else {
1.1084 raeburn 5498: if (ref($userenvref) eq 'HASH') {
5499: $toolstatus = $userenvref->{$context.'.'.$tool};
5500: $inststatus = $userenvref->{'inststatus'};
5501: } else {
5502: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5503: $toolstatus = $userenv{$context.'.'.$tool};
5504: $inststatus = $userenv{'inststatus'};
5505: }
1.976 raeburn 5506: }
5507:
5508: if ($toolstatus ne '') {
5509: if ($toolstatus) {
5510: $access = 1;
5511: } else {
5512: $access = 0;
5513: }
5514: return $access;
5515: }
5516:
1.1084 raeburn 5517: my ($is_adv,%domdef);
5518: if (ref($is_advref) eq 'HASH') {
5519: $is_adv = $is_advref->{'is_adv'};
5520: } else {
5521: $is_adv = &is_advanced_user($udom,$uname);
5522: }
5523: if (ref($domdefref) eq 'HASH') {
5524: %domdef = %{$domdefref};
5525: } else {
5526: %domdef = &get_domain_defaults($udom);
5527: }
1.976 raeburn 5528: if (ref($domdef{$tool}) eq 'HASH') {
5529: if ($is_adv) {
5530: if ($domdef{$tool}{'_LC_adv'} ne '') {
5531: if ($domdef{$tool}{'_LC_adv'}) {
5532: $access = 1;
5533: } else {
5534: $access = 0;
5535: }
5536: return $access;
5537: }
5538: }
5539: if ($inststatus ne '') {
5540: my ($hasaccess,$hasnoaccess);
5541: foreach my $affiliation (split(/:/,$inststatus)) {
5542: if ($domdef{$tool}{$affiliation} ne '') {
5543: if ($domdef{$tool}{$affiliation}) {
5544: $hasaccess = 1;
5545: } else {
5546: $hasnoaccess = 1;
5547: }
5548: }
5549: }
5550: if ($hasaccess || $hasnoaccess) {
5551: if ($hasaccess) {
5552: $access = 1;
5553: } elsif ($hasnoaccess) {
5554: $access = 0;
5555: }
5556: return $access;
5557: }
5558: } else {
5559: if ($domdef{$tool}{'default'} ne '') {
5560: if ($domdef{$tool}{'default'}) {
5561: $access = 1;
5562: } elsif ($domdef{$tool}{'default'} == 0) {
5563: $access = 0;
5564: }
5565: return $access;
5566: }
5567: }
5568: } else {
1.985 raeburn 5569: if ($context eq 'tools') {
5570: $access = 1;
5571: } else {
5572: $access = 0;
5573: }
1.976 raeburn 5574: return $access;
5575: }
5576: }
5577:
1.1050 raeburn 5578: sub is_course_owner {
5579: my ($cdom,$cnum,$udom,$uname) = @_;
5580: if (($udom eq '') || ($uname eq '')) {
5581: $udom = $env{'user.domain'};
5582: $uname = $env{'user.name'};
5583: }
5584: unless (($udom eq '') || ($uname eq '')) {
5585: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5586: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5587: return 1;
5588: } else {
5589: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5590: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5591: return 1;
5592: }
5593: }
5594: }
5595: }
5596: return;
5597: }
5598:
1.976 raeburn 5599: sub is_advanced_user {
5600: my ($udom,$uname) = @_;
1.1085 raeburn 5601: if ($udom ne '' && $uname ne '') {
5602: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 5603: if (wantarray) {
5604: return ($env{'user.adv'},$env{'user.author'});
5605: } else {
5606: return $env{'user.adv'};
5607: }
1.1085 raeburn 5608: }
5609: }
1.976 raeburn 5610: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5611: my %allroles;
1.1128 raeburn 5612: my ($is_adv,$is_author);
1.976 raeburn 5613: foreach my $role (keys(%roleshash)) {
5614: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5615: my $area = '/'.$tdomain.'/'.$trest;
5616: if ($sec ne '') {
5617: $area .= '/'.$sec;
5618: }
5619: if (($area ne '') && ($trole ne '')) {
5620: my $spec=$trole.'.'.$area;
5621: if ($trole =~ /^cr\//) {
5622: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5623: } elsif ($trole ne 'gr') {
5624: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5625: }
1.1128 raeburn 5626: if ($trole eq 'au') {
5627: $is_author = 1;
5628: }
1.976 raeburn 5629: }
5630: }
5631: foreach my $role (keys(%allroles)) {
5632: last if ($is_adv);
5633: foreach my $item (split(/:/,$allroles{$role})) {
5634: if ($item ne '') {
5635: my ($privilege,$restrictions)=split(/&/,$item);
5636: if ($privilege eq 'adv') {
5637: $is_adv = 1;
5638: last;
5639: }
5640: }
5641: }
5642: }
1.1128 raeburn 5643: if (wantarray) {
5644: return ($is_adv,$is_author);
5645: }
1.976 raeburn 5646: return $is_adv;
5647: }
1.798 raeburn 5648:
1.1035 raeburn 5649: sub check_can_request {
1.1036 raeburn 5650: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5651: my $canreq = 0;
5652: my ($types,$typename) = &Apache::loncommon::course_types();
5653: my @options = ('approval','validate','autolimit');
5654: my $optregex = join('|',@options);
5655: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5656: foreach my $type (@{$types}) {
5657: if (&usertools_access($env{'user.name'},
5658: $env{'user.domain'},
5659: $type,undef,'requestcourses')) {
5660: $canreq ++;
1.1036 raeburn 5661: if (ref($request_domains) eq 'HASH') {
5662: push(@{$request_domains->{$type}},$env{'user.domain'});
5663: }
1.1035 raeburn 5664: if ($dom eq $env{'user.domain'}) {
5665: $can_request->{$type} = 1;
5666: }
5667: }
5668: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5669: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5670: if (@curr > 0) {
1.1036 raeburn 5671: foreach my $item (@curr) {
5672: if (ref($request_domains) eq 'HASH') {
5673: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5674: if ($otherdom ne '') {
5675: if (ref($request_domains->{$type}) eq 'ARRAY') {
5676: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5677: push(@{$request_domains->{$type}},$otherdom);
5678: }
5679: } else {
5680: push(@{$request_domains->{$type}},$otherdom);
5681: }
5682: }
5683: }
5684: }
5685: unless($dom eq $env{'user.domain'}) {
5686: $canreq ++;
1.1035 raeburn 5687: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5688: $can_request->{$type} = 1;
5689: }
5690: }
5691: }
5692: }
5693: }
5694: }
5695: return $canreq;
5696: }
5697:
1.341 www 5698: # ---------------------------------------------- Custom access rule evaluation
5699:
5700: sub customaccess {
5701: my ($priv,$uri)=@_;
1.807 albertel 5702: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5703: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5704: $udom = &LONCAPA::clean_domain($udom);
5705: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5706: my $access=0;
1.800 albertel 5707: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5708: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5709: if ($type eq 'user') {
5710: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5711: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5712: if ($tdom) {
5713: if ($tdom ne $env{'user.domain'}) { next; }
5714: }
1.896 albertel 5715: if ($tuname) {
5716: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5717: }
5718: $access=($effect eq 'allow');
5719: last;
5720: }
5721: } else {
5722: if ($role) {
5723: if ($role ne $urole) { next; }
5724: }
5725: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5726: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5727: if ($tdom) {
5728: if ($tdom ne $udom) { next; }
5729: }
5730: if ($tcrs) {
5731: if ($tcrs ne $ucrs) { next; }
5732: }
5733: if ($tsec) {
5734: if ($tsec ne $usec) { next; }
5735: }
5736: $access=($effect eq 'allow');
5737: last;
5738: }
5739: if ($realm eq '' && $role eq '') {
5740: $access=($effect eq 'allow');
5741: }
1.402 bowersj2 5742: }
1.341 www 5743: }
5744: return $access;
5745: }
5746:
1.103 harris41 5747: # ------------------------------------------------- Check for a user privilege
1.12 www 5748:
5749: sub allowed {
1.810 raeburn 5750: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5751: my $ver_orguri=$uri;
1.439 www 5752: $uri=&deversion($uri);
1.152 www 5753: my $orguri=$uri;
1.52 www 5754: $uri=&declutter($uri);
1.809 raeburn 5755:
1.810 raeburn 5756: if ($priv eq 'evb') {
5757: # Evade communication block restrictions for specified role in a course
5758: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5759: return $1;
5760: } else {
5761: return;
5762: }
5763: }
5764:
1.620 albertel 5765: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5766: # Free bre access to adm and meta resources
1.775 albertel 5767: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5768: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5769: && ($priv eq 'bre')) {
1.14 www 5770: return 'F';
1.159 www 5771: }
5772:
1.545 banghart 5773: # Free bre access to user's own portfolio contents
1.714 raeburn 5774: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5775: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5776: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5777: my %setters;
5778: my ($startblock,$endblock) =
5779: &Apache::loncommon::blockcheck(\%setters,'port');
5780: if ($startblock && $endblock) {
5781: return 'B';
5782: } else {
5783: return 'F';
5784: }
1.545 banghart 5785: }
5786:
1.762 raeburn 5787: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5788: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5789: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5790: if (exists($env{'request.course.id'})) {
5791: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5792: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5793: if (($domain eq $cdom) && ($name eq $cnum)) {
5794: my $courseprivid=$env{'request.course.id'};
5795: $courseprivid=~s/\_/\//;
5796: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5797: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5798: return $1;
1.762 raeburn 5799: } else {
5800: if ($env{'request.course.sec'}) {
5801: $courseprivid.='/'.$env{'request.course.sec'};
5802: }
5803: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5804: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5805: return $2;
5806: }
1.714 raeburn 5807: }
5808: }
5809: }
5810: }
5811:
1.159 www 5812: # Free bre to public access
5813:
5814: if ($priv eq 'bre') {
1.238 www 5815: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5816: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5817: return 'F';
5818: }
1.238 www 5819: if ($copyright eq 'priv') {
5820: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5821: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5822: return '';
5823: }
5824: }
5825: if ($copyright eq 'domain') {
5826: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5827: unless (($env{'user.domain'} eq $1) ||
5828: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5829: return '';
5830: }
1.262 matthew 5831: }
1.620 albertel 5832: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5833: # Library role, so allow browsing of resources in this domain.
5834: return 'F';
1.238 www 5835: }
1.341 www 5836: if ($copyright eq 'custom') {
5837: unless (&customaccess($priv,$uri)) { return ''; }
5838: }
1.14 www 5839: }
1.264 matthew 5840: # Domain coordinator is trying to create a course
1.620 albertel 5841: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5842: # uri is the requested domain in this case.
5843: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5844: # a role of dc for the domain in question.
1.620 albertel 5845: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5846: }
1.29 www 5847:
1.52 www 5848: my $thisallowed='';
5849: my $statecond=0;
5850: my $courseprivid='';
5851:
1.1039 raeburn 5852: my $ownaccess;
1.1043 raeburn 5853: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5854: if (($priv eq 'bro') && ($env{'user.author'})) {
5855: if ($uri eq '') {
5856: $ownaccess = 1;
5857: } else {
5858: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5859: my $udom = $env{'user.domain'};
5860: my $uname = $env{'user.name'};
5861: if ($uri =~ m{^\Q$udom\E/?$}) {
5862: $ownaccess = 1;
1.1040 raeburn 5863: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5864: unless ($uri =~ m{\.\./}) {
5865: $ownaccess = 1;
5866: }
5867: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5868: my $now = time;
5869: if ($uri =~ m{^([^/]+)/?$}) {
5870: my $adom = $1;
5871: foreach my $key (keys(%env)) {
1.1042 raeburn 5872: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5873: my ($start,$end) = split('.',$env{$key});
5874: if (($now >= $start) && (!$end || $end < $now)) {
5875: $ownaccess = 1;
5876: last;
5877: }
5878: }
5879: }
5880: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5881: my $adom = $1;
5882: my $aname = $2;
1.1042 raeburn 5883: foreach my $role ('ca','aa') {
5884: if ($env{"user.role.$role./$adom/$aname"}) {
5885: my ($start,$end) =
5886: split('.',$env{"user.role.$role./$adom/$aname"});
5887: if (($now >= $start) && (!$end || $end < $now)) {
5888: $ownaccess = 1;
5889: last;
5890: }
1.1039 raeburn 5891: }
5892: }
5893: }
5894: }
5895: }
5896: }
5897: }
5898:
1.52 www 5899: # Course
5900:
1.620 albertel 5901: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5902: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5903: $thisallowed.=$1;
5904: }
1.52 www 5905: }
1.29 www 5906:
1.52 www 5907: # Domain
5908:
1.620 albertel 5909: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5910: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5911: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5912: $thisallowed.=$1;
5913: }
1.12 www 5914: }
1.52 www 5915:
1.1141 raeburn 5916: # User who is not author or co-author might still be able to edit
5917: # resource of an author in the domain (e.g., if Domain Coordinator).
5918: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
5919: (&allowed('mdc',$env{'request.course.id'}))) {
5920: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
5921: $thisallowed.=$1;
5922: }
5923: }
5924:
1.52 www 5925: # Course: uri itself is a course
1.66 www 5926: my $courseuri=$uri;
5927: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5928: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5929:
1.620 albertel 5930: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5931: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5932: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5933: $thisallowed.=$1;
5934: }
1.12 www 5935: }
1.29 www 5936:
1.665 albertel 5937: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5938: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5939: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5940: $thisallowed='';
1.671 raeburn 5941: my ($match)=&is_on_map($uri);
5942: if ($match) {
5943: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5944: =~/\Q$priv\E\&([^\:]*)/) {
5945: $thisallowed.=$1;
5946: }
5947: } else {
1.705 albertel 5948: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5949: if ($refuri) {
5950: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5951: $thisallowed='F';
1.671 raeburn 5952: } else {
5953: $refuri=&declutter($refuri);
5954: my ($match) = &is_on_map($refuri);
5955: if ($match) {
5956: $thisallowed='F';
5957: }
1.669 raeburn 5958: }
1.671 raeburn 5959: }
5960: }
1.314 www 5961: }
1.492 albertel 5962:
1.766 albertel 5963: if ($priv eq 'bre'
5964: && $thisallowed ne 'F'
5965: && $thisallowed ne '2'
5966: && &is_portfolio_url($uri)) {
5967: $thisallowed = &portfolio_access($uri);
5968: }
5969:
1.52 www 5970: # Full access at system, domain or course-wide level? Exit.
1.29 www 5971: if ($thisallowed=~/F/) {
5972: return 'F';
5973: }
5974:
1.52 www 5975: # If this is generating or modifying users, exit with special codes
1.29 www 5976:
1.643 www 5977: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5978: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5979: my ($audom,$auname)=split('/',$uri);
1.643 www 5980: # no author name given, so this just checks on the general right to make a co-author in this domain
5981: unless ($auname) { return $thisallowed; }
5982: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5983: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5984: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5985: ($audom ne $env{'request.role.domain'}))) { return ''; }
5986: }
1.52 www 5987: return $thisallowed;
5988: }
5989: #
1.103 harris41 5990: # Gathered so far: system, domain and course wide privileges
1.52 www 5991: #
5992: # Course: See if uri or referer is an individual resource that is part of
5993: # the course
5994:
1.620 albertel 5995: if ($env{'request.course.id'}) {
1.232 www 5996:
1.620 albertel 5997: $courseprivid=$env{'request.course.id'};
5998: if ($env{'request.course.sec'}) {
5999: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6000: }
6001: $courseprivid=~s/\_/\//;
6002: my $checkreferer=1;
1.232 www 6003: my ($match,$cond)=&is_on_map($uri);
6004: if ($match) {
6005: $statecond=$cond;
1.620 albertel 6006: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6007: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 6008: $thisallowed.=$1;
6009: $checkreferer=0;
6010: }
1.29 www 6011: }
1.83 www 6012:
1.148 www 6013: if ($checkreferer) {
1.620 albertel 6014: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6015: unless ($refuri) {
1.800 albertel 6016: foreach my $key (keys(%env)) {
6017: if ($key=~/^httpref\..*\*/) {
6018: my $pattern=$key;
1.156 www 6019: $pattern=~s/^httpref\.\/res\///;
1.148 www 6020: $pattern=~s/\*/\[\^\/\]\+/g;
6021: $pattern=~s/\//\\\//g;
1.152 www 6022: if ($orguri=~/$pattern/) {
1.800 albertel 6023: $refuri=$env{$key};
1.148 www 6024: }
6025: }
1.191 harris41 6026: }
1.148 www 6027: }
1.232 www 6028:
1.148 www 6029: if ($refuri) {
1.152 www 6030: $refuri=&declutter($refuri);
1.232 www 6031: my ($match,$cond)=&is_on_map($refuri);
6032: if ($match) {
6033: my $refstatecond=$cond;
1.620 albertel 6034: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6035: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 6036: $thisallowed.=$1;
1.53 www 6037: $uri=$refuri;
6038: $statecond=$refstatecond;
1.52 www 6039: }
6040: }
1.148 www 6041: }
1.29 www 6042: }
1.52 www 6043: }
1.29 www 6044:
1.52 www 6045: #
1.103 harris41 6046: # Gathered now: all privileges that could apply, and condition number
1.52 www 6047: #
6048: #
6049: # Full or no access?
6050: #
1.29 www 6051:
1.52 www 6052: if ($thisallowed=~/F/) {
6053: return 'F';
6054: }
1.29 www 6055:
1.52 www 6056: unless ($thisallowed) {
6057: return '';
6058: }
1.29 www 6059:
1.52 www 6060: # Restrictions exist, deal with them
6061: #
6062: # C:according to course preferences
6063: # R:according to resource settings
6064: # L:unless locked
6065: # X:according to user session state
6066: #
6067:
6068: # Possibly locked functionality, check all courses
1.54 www 6069: # Locks might take effect only after 10 minutes cache expiration for other
6070: # courses, and 2 minutes for current course
1.52 www 6071:
6072: my $envkey;
6073: if ($thisallowed=~/L/) {
1.1000 raeburn 6074: foreach $envkey (keys(%env)) {
1.54 www 6075: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6076: my $courseid=$2;
6077: my $roleid=$1.'.'.$2;
1.92 www 6078: $courseid=~s/^\///;
1.54 www 6079: my $expiretime=600;
1.620 albertel 6080: if ($env{'request.role'} eq $roleid) {
1.54 www 6081: $expiretime=120;
6082: }
6083: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6084: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6085: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6086: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6087: }
1.620 albertel 6088: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6089: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6090: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6091: &log($env{'user.domain'},$env{'user.name'},
6092: $env{'user.home'},
1.57 www 6093: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6094: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6095: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6096: return '';
6097: }
6098: }
1.620 albertel 6099: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6100: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6101: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6102: &log($env{'user.domain'},$env{'user.name'},
6103: $env{'user.home'},
1.57 www 6104: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6105: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6106: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6107: return '';
6108: }
6109: }
6110: }
1.29 www 6111: }
1.52 www 6112: }
6113:
6114: #
6115: # Rest of the restrictions depend on selected course
6116: #
6117:
1.620 albertel 6118: unless ($env{'request.course.id'}) {
1.766 albertel 6119: if ($thisallowed eq 'A') {
6120: return 'A';
1.814 raeburn 6121: } elsif ($thisallowed eq 'B') {
6122: return 'B';
1.766 albertel 6123: } else {
6124: return '1';
6125: }
1.52 www 6126: }
1.29 www 6127:
1.52 www 6128: #
6129: # Now user is definitely in a course
6130: #
1.53 www 6131:
6132:
6133: # Course preferences
6134:
6135: if ($thisallowed=~/C/) {
1.620 albertel 6136: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6137: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6138: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6139: =~/\Q$rolecode\E/) {
1.1103 raeburn 6140: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6141: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6142: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6143: $env{'request.course.id'});
6144: }
1.237 www 6145: return '';
6146: }
6147:
1.620 albertel 6148: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6149: =~/\Q$unamedom\E/) {
1.1103 raeburn 6150: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6151: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6152: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6153: $env{'request.course.id'});
6154: }
1.54 www 6155: return '';
6156: }
1.53 www 6157: }
6158:
6159: # Resource preferences
6160:
6161: if ($thisallowed=~/R/) {
1.620 albertel 6162: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6163: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6164: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6165: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6166: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6167: }
6168: return '';
1.54 www 6169: }
1.53 www 6170: }
1.30 www 6171:
1.246 www 6172: # Restricted by state or randomout?
1.30 www 6173:
1.52 www 6174: if ($thisallowed=~/X/) {
1.620 albertel 6175: if ($env{'acc.randomout'}) {
1.579 albertel 6176: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 6177: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 6178: return '';
6179: }
1.247 www 6180: }
6181: if (&condval($statecond)) {
1.52 www 6182: return '2';
6183: } else {
6184: return '';
6185: }
6186: }
1.30 www 6187:
1.766 albertel 6188: if ($thisallowed eq 'A') {
6189: return 'A';
1.814 raeburn 6190: } elsif ($thisallowed eq 'B') {
6191: return 'B';
1.766 albertel 6192: }
1.52 www 6193: return 'F';
1.232 www 6194: }
1.1133 foxr 6195: #
6196: # Removes the versino from a URI and
6197: # splits it in to its filename and path to the filename.
6198: # Seems like File::Basename could have done this more clearly.
6199: # Parameters:
6200: # $uri - input URI
6201: # Returns:
6202: # Two element list consisting of
6203: # $pathname - the URI up to and excluding the trailing /
6204: # $filename - The part of the URI following the last /
6205: # NOTE:
6206: # Another realization of this is simply:
6207: # use File::Basename;
6208: # ...
6209: # $uri = shift;
6210: # $filename = basename($uri);
6211: # $path = dirname($uri);
6212: # return ($filename, $path);
6213: #
6214: # The implementation below is probably faster however.
6215: #
1.710 albertel 6216: sub split_uri_for_cond {
6217: my $uri=&deversion(&declutter(shift));
6218: my @uriparts=split(/\//,$uri);
6219: my $filename=pop(@uriparts);
6220: my $pathname=join('/',@uriparts);
6221: return ($pathname,$filename);
6222: }
1.232 www 6223: # --------------------------------------------------- Is a resource on the map?
6224:
6225: sub is_on_map {
1.710 albertel 6226: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 6227: #Trying to find the conditional for the file
1.620 albertel 6228: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 6229: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 6230: if ($match) {
1.289 bowersj2 6231: return (1,$1);
6232: } else {
1.434 www 6233: return (0,0);
1.289 bowersj2 6234: }
1.12 www 6235: }
6236:
1.427 www 6237: # --------------------------------------------------------- Get symb from alias
6238:
6239: sub get_symb_from_alias {
6240: my $symb=shift;
6241: my ($map,$resid,$url)=&decode_symb($symb);
6242: # Already is a symb
6243: if ($url) { return $symb; }
6244: # Must be an alias
6245: my $aliassymb='';
6246: my %bighash;
1.620 albertel 6247: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 6248: &GDBM_READER(),0640)) {
6249: my $rid=$bighash{'mapalias_'.$symb};
6250: if ($rid) {
6251: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 6252: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6253: $resid,$bighash{'src_'.$rid});
1.427 www 6254: }
6255: untie %bighash;
6256: }
6257: return $aliassymb;
6258: }
6259:
1.12 www 6260: # ----------------------------------------------------------------- Define Role
6261:
6262: sub definerole {
6263: if (allowed('mcr','/')) {
6264: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 6265: foreach my $role (split(':',$sysrole)) {
6266: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6267: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6268: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6269: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6270: return "refused:s:$crole&$cqual";
6271: }
6272: }
1.191 harris41 6273: }
1.800 albertel 6274: foreach my $role (split(':',$domrole)) {
6275: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6276: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6277: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6278: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 6279: return "refused:d:$crole&$cqual";
6280: }
6281: }
1.191 harris41 6282: }
1.800 albertel 6283: foreach my $role (split(':',$courole)) {
6284: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6285: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6286: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6287: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6288: return "refused:c:$crole&$cqual";
6289: }
6290: }
1.191 harris41 6291: }
1.620 albertel 6292: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6293: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6294: "rolesdef_$rolename=".
6295: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 6296: return reply($command,$env{'user.home'});
1.12 www 6297: } else {
6298: return 'refused';
6299: }
1.105 harris41 6300: }
6301:
6302: # ---------------- Make a metadata query against the network of library servers
6303:
6304: sub metadata_query {
1.244 matthew 6305: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 6306: my %rhash;
1.845 albertel 6307: my %libserv = &all_library();
1.244 matthew 6308: my @server_list = (defined($server_array) ? @$server_array
6309: : keys(%libserv) );
6310: for my $server (@server_list) {
1.118 harris41 6311: unless ($custom or $customshow) {
6312: my $reply=&reply("querysend:".&escape($query),$server);
6313: $rhash{$server}=$reply;
6314: }
6315: else {
6316: my $reply=&reply("querysend:".&escape($query).':'.
6317: &escape($custom).':'.&escape($customshow),
6318: $server);
6319: $rhash{$server}=$reply;
6320: }
1.112 harris41 6321: }
1.118 harris41 6322: return \%rhash;
1.240 www 6323: }
6324:
6325: # ----------------------------------------- Send log queries and wait for reply
6326:
6327: sub log_query {
6328: my ($uname,$udom,$query,%filters)=@_;
6329: my $uhome=&homeserver($uname,$udom);
6330: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 6331: my $uhost=&hostname($uhome);
1.800 albertel 6332: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 6333: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6334: $uhome);
1.479 albertel 6335: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 6336: return get_query_reply($queryid);
6337: }
6338:
1.818 raeburn 6339: # -------------------------- Update MySQL table for portfolio file
6340:
6341: sub update_portfolio_table {
1.821 raeburn 6342: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 6343: if ($group ne '') {
6344: $file_name =~s /^\Q$group\E//;
6345: }
1.818 raeburn 6346: my $homeserver = &homeserver($uname,$udom);
6347: my $queryid=
1.821 raeburn 6348: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6349: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 6350: my $reply = &get_query_reply($queryid);
6351: return $reply;
6352: }
6353:
1.899 raeburn 6354: # -------------------------- Update MySQL allusers table
6355:
6356: sub update_allusers_table {
6357: my ($uname,$udom,$names) = @_;
6358: my $homeserver = &homeserver($uname,$udom);
6359: my $queryid=
6360: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6361: 'lastname='.&escape($names->{'lastname'}).'%%'.
6362: 'firstname='.&escape($names->{'firstname'}).'%%'.
6363: 'middlename='.&escape($names->{'middlename'}).'%%'.
6364: 'generation='.&escape($names->{'generation'}).'%%'.
6365: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6366: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 6367: return;
1.899 raeburn 6368: }
6369:
1.508 raeburn 6370: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 6371:
6372: sub fetch_enrollment_query {
1.511 raeburn 6373: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 6374: my $homeserver;
1.547 raeburn 6375: my $maxtries = 1;
1.508 raeburn 6376: if ($context eq 'automated') {
6377: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 6378: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 6379: } else {
6380: $homeserver = &homeserver($cnum,$dom);
6381: }
1.838 albertel 6382: my $host=&hostname($homeserver);
1.506 raeburn 6383: my $cmd = '';
1.1000 raeburn 6384: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 6385: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 6386: }
6387: $cmd =~ s/%%$//;
6388: $cmd = &escape($cmd);
6389: my $query = 'fetchenrollment';
1.620 albertel 6390: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 6391: unless ($queryid=~/^\Q$host\E\_/) {
6392: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6393: return 'error: '.$queryid;
6394: }
1.506 raeburn 6395: my $reply = &get_query_reply($queryid);
1.547 raeburn 6396: my $tries = 1;
6397: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6398: $reply = &get_query_reply($queryid);
6399: $tries ++;
6400: }
1.526 raeburn 6401: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 6402: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 6403: } else {
1.901 albertel 6404: my @responses = split(/:/,$reply);
1.515 raeburn 6405: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 6406: foreach my $line (@responses) {
6407: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 6408: $$replyref{$key} = $value;
6409: }
6410: } else {
1.1117 foxr 6411: my $pathname = LONCAPA::tempdir();
1.800 albertel 6412: foreach my $line (@responses) {
6413: my ($key,$value) = split(/=/,$line);
1.506 raeburn 6414: $$replyref{$key} = $value;
6415: if ($value > 0) {
1.800 albertel 6416: foreach my $item (@{$$affiliatesref{$key}}) {
6417: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 6418: my $destname = $pathname.'/'.$filename;
6419: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 6420: if ($xml_classlist =~ /^error/) {
6421: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6422: } else {
1.506 raeburn 6423: if ( open(FILE,">$destname") ) {
6424: print FILE &unescape($xml_classlist);
6425: close(FILE);
1.526 raeburn 6426: } else {
6427: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6428: }
6429: }
6430: }
6431: }
6432: }
6433: }
6434: return 'ok';
6435: }
6436: return 'error';
6437: }
6438:
1.242 www 6439: sub get_query_reply {
6440: my $queryid=shift;
1.1117 foxr 6441: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 6442: my $reply='';
6443: for (1..100) {
6444: sleep 2;
6445: if (-e $replyfile.'.end') {
1.448 albertel 6446: if (open(my $fh,$replyfile)) {
1.904 albertel 6447: $reply = join('',<$fh>);
6448: close($fh);
1.240 www 6449: } else { return 'error: reply_file_error'; }
1.242 www 6450: return &unescape($reply);
6451: }
1.240 www 6452: }
1.242 www 6453: return 'timeout:'.$queryid;
1.240 www 6454: }
6455:
6456: sub courselog_query {
1.241 www 6457: #
6458: # possible filters:
6459: # url: url or symb
6460: # username
6461: # domain
6462: # action: view, submit, grade
6463: # start: timestamp
6464: # end: timestamp
6465: #
1.240 www 6466: my (%filters)=@_;
1.620 albertel 6467: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6468: if ($filters{'url'}) {
6469: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6470: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6471: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6472: }
1.620 albertel 6473: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6474: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6475: return &log_query($cname,$cdom,'courselog',%filters);
6476: }
6477:
6478: sub userlog_query {
1.858 raeburn 6479: #
6480: # possible filters:
6481: # action: log check role
6482: # start: timestamp
6483: # end: timestamp
6484: #
1.240 www 6485: my ($uname,$udom,%filters)=@_;
6486: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6487: }
6488:
1.506 raeburn 6489: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6490:
6491: sub auto_run {
1.508 raeburn 6492: my ($cnum,$cdom) = @_;
1.876 raeburn 6493: my $response = 0;
6494: my $settings;
6495: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6496: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6497: $settings = $domconfig{'autoenroll'};
6498: if ($settings->{'run'} eq '1') {
6499: $response = 1;
6500: }
6501: } else {
1.934 raeburn 6502: my $homeserver;
6503: if (&is_course($cdom,$cnum)) {
6504: $homeserver = &homeserver($cnum,$cdom);
6505: } else {
6506: $homeserver = &domain($cdom,'primary');
6507: }
6508: if ($homeserver ne 'no_host') {
6509: $response = &reply('autorun:'.$cdom,$homeserver);
6510: }
1.876 raeburn 6511: }
1.506 raeburn 6512: return $response;
6513: }
1.776 albertel 6514:
1.506 raeburn 6515: sub auto_get_sections {
1.508 raeburn 6516: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6517: my $homeserver;
6518: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6519: $homeserver = &homeserver($cnum,$cdom);
6520: }
6521: if (!defined($homeserver)) {
6522: if ($cdom =~ /^$match_domain$/) {
6523: $homeserver = &domain($cdom,'primary');
6524: }
6525: }
6526: my @secs;
6527: if (defined($homeserver)) {
6528: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6529: unless ($response eq 'refused') {
6530: @secs = split(/:/,$response);
6531: }
1.506 raeburn 6532: }
6533: return @secs;
6534: }
1.776 albertel 6535:
1.506 raeburn 6536: sub auto_new_course {
1.1099 raeburn 6537: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6538: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 6539: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6540: return $response;
6541: }
1.776 albertel 6542:
1.506 raeburn 6543: sub auto_validate_courseID {
1.508 raeburn 6544: my ($cnum,$cdom,$inst_course_id) = @_;
6545: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6546: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6547: return $response;
6548: }
1.776 albertel 6549:
1.1007 raeburn 6550: sub auto_validate_instcode {
1.1020 raeburn 6551: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6552: my ($homeserver,$response);
6553: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6554: $homeserver = &homeserver($cnum,$cdom);
6555: }
6556: if (!defined($homeserver)) {
6557: if ($cdom =~ /^$match_domain$/) {
6558: $homeserver = &domain($cdom,'primary');
6559: }
6560: }
1.1065 raeburn 6561: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6562: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6563: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6564: return ($outcome,$description);
1.1007 raeburn 6565: }
6566:
1.506 raeburn 6567: sub auto_create_password {
1.873 raeburn 6568: my ($cnum,$cdom,$authparam,$udom) = @_;
6569: my ($homeserver,$response);
1.506 raeburn 6570: my $create_passwd = 0;
6571: my $authchk = '';
1.873 raeburn 6572: if ($udom =~ /^$match_domain$/) {
6573: $homeserver = &domain($udom,'primary');
6574: }
6575: if ($homeserver eq '') {
6576: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6577: $homeserver = &homeserver($cnum,$cdom);
6578: }
6579: }
6580: if ($homeserver eq '') {
6581: $authchk = 'nodomain';
1.506 raeburn 6582: } else {
1.873 raeburn 6583: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6584: if ($response eq 'refused') {
6585: $authchk = 'refused';
6586: } else {
1.901 albertel 6587: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6588: }
1.506 raeburn 6589: }
6590: return ($authparam,$create_passwd,$authchk);
6591: }
6592:
1.706 raeburn 6593: sub auto_photo_permission {
6594: my ($cnum,$cdom,$students) = @_;
6595: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6596: my ($outcome,$perm_reqd,$conditions) =
6597: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6598: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6599: return (undef,undef);
6600: }
1.706 raeburn 6601: return ($outcome,$perm_reqd,$conditions);
6602: }
6603:
6604: sub auto_checkphotos {
6605: my ($uname,$udom,$pid) = @_;
6606: my $homeserver = &homeserver($uname,$udom);
6607: my ($result,$resulttype);
6608: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6609: &escape($uname).':'.&escape($pid),
6610: $homeserver));
1.709 albertel 6611: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6612: return (undef,undef);
6613: }
1.706 raeburn 6614: if ($outcome) {
6615: ($result,$resulttype) = split(/:/,$outcome);
6616: }
6617: return ($result,$resulttype);
6618: }
6619:
6620: sub auto_photochoice {
6621: my ($cnum,$cdom) = @_;
6622: my $homeserver = &homeserver($cnum,$cdom);
6623: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6624: &escape($cdom),
6625: $homeserver)));
1.709 albertel 6626: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6627: return (undef,undef);
6628: }
1.706 raeburn 6629: return ($update,$comment);
6630: }
6631:
6632: sub auto_photoupdate {
6633: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6634: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6635: my $host=&hostname($homeserver);
1.706 raeburn 6636: my $cmd = '';
6637: my $maxtries = 1;
1.800 albertel 6638: foreach my $affiliate (keys(%{$affiliatesref})) {
6639: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6640: }
6641: $cmd =~ s/%%$//;
6642: $cmd = &escape($cmd);
6643: my $query = 'institutionalphotos';
6644: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6645: unless ($queryid=~/^\Q$host\E\_/) {
6646: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6647: return 'error: '.$queryid;
6648: }
6649: my $reply = &get_query_reply($queryid);
6650: my $tries = 1;
6651: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6652: $reply = &get_query_reply($queryid);
6653: $tries ++;
6654: }
6655: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6656: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6657: } else {
6658: my @responses = split(/:/,$reply);
6659: my $outcome = shift(@responses);
6660: foreach my $item (@responses) {
6661: my ($key,$value) = split(/=/,$item);
6662: $$photo{$key} = $value;
6663: }
6664: return $outcome;
6665: }
6666: return 'error';
6667: }
6668:
1.521 raeburn 6669: sub auto_instcode_format {
1.793 albertel 6670: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6671: $cat_order) = @_;
1.521 raeburn 6672: my $courses = '';
1.772 raeburn 6673: my @homeservers;
1.521 raeburn 6674: if ($caller eq 'global') {
1.841 albertel 6675: my %servers = &get_servers($codedom,'library');
6676: foreach my $tryserver (keys(%servers)) {
6677: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6678: push(@homeservers,$tryserver);
6679: }
1.584 raeburn 6680: }
1.1022 raeburn 6681: } elsif ($caller eq 'requests') {
6682: if ($codedom =~ /^$match_domain$/) {
6683: my $chome = &domain($codedom,'primary');
6684: unless ($chome eq 'no_host') {
6685: push(@homeservers,$chome);
6686: }
6687: }
1.521 raeburn 6688: } else {
1.772 raeburn 6689: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6690: }
1.793 albertel 6691: foreach my $code (keys(%{$instcodes})) {
6692: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6693: }
6694: chop($courses);
1.772 raeburn 6695: my $ok_response = 0;
6696: my $response;
6697: while (@homeservers > 0 && $ok_response == 0) {
6698: my $server = shift(@homeservers);
6699: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6700: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6701: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6702: split(/:/,$response);
1.772 raeburn 6703: %{$codes} = (%{$codes},&str2hash($codes_str));
6704: push(@{$codetitles},&str2array($codetitles_str));
6705: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6706: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6707: $ok_response = 1;
6708: }
6709: }
6710: if ($ok_response) {
1.521 raeburn 6711: return 'ok';
1.772 raeburn 6712: } else {
6713: return $response;
1.521 raeburn 6714: }
6715: }
6716:
1.792 raeburn 6717: sub auto_instcode_defaults {
6718: my ($domain,$returnhash,$code_order) = @_;
6719: my @homeservers;
1.841 albertel 6720:
6721: my %servers = &get_servers($domain,'library');
6722: foreach my $tryserver (keys(%servers)) {
6723: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6724: push(@homeservers,$tryserver);
6725: }
1.792 raeburn 6726: }
1.841 albertel 6727:
1.792 raeburn 6728: my $response;
1.841 albertel 6729: foreach my $server (@homeservers) {
1.792 raeburn 6730: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6731: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6732:
6733: foreach my $pair (split(/\&/,$response)) {
6734: my ($name,$value)=split(/\=/,$pair);
6735: if ($name eq 'code_order') {
6736: @{$code_order} = split(/\&/,&unescape($value));
6737: } else {
6738: $returnhash->{&unescape($name)}=&unescape($value);
6739: }
6740: }
6741: return 'ok';
1.792 raeburn 6742: }
1.841 albertel 6743:
6744: return $response;
1.1003 raeburn 6745: }
6746:
6747: sub auto_possible_instcodes {
1.1007 raeburn 6748: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6749: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6750: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6751: return;
6752: }
1.1003 raeburn 6753: my (@homeservers,$uhome);
6754: if (defined(&domain($domain,'primary'))) {
6755: $uhome=&domain($domain,'primary');
6756: push(@homeservers,&domain($domain,'primary'));
6757: } else {
6758: my %servers = &get_servers($domain,'library');
6759: foreach my $tryserver (keys(%servers)) {
6760: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6761: push(@homeservers,$tryserver);
6762: }
6763: }
6764: }
6765: my $response;
6766: foreach my $server (@homeservers) {
6767: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6768: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6769: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6770: split(':',$response);
6771: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6772: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6773: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6774: my ($name,$value)=split('=',$item);
6775: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6776: }
6777: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6778: my ($name,$value)=split('=',$item);
6779: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6780: }
6781: return 'ok';
6782: }
6783: return $response;
6784: }
1.792 raeburn 6785:
1.1010 raeburn 6786: sub auto_courserequest_checks {
6787: my ($dom) = @_;
1.1020 raeburn 6788: my ($homeserver,%validations);
6789: if ($dom =~ /^$match_domain$/) {
6790: $homeserver = &domain($dom,'primary');
6791: }
6792: unless ($homeserver eq 'no_host') {
6793: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6794: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6795: my @items = split(/&/,$response);
6796: foreach my $item (@items) {
6797: my ($key,$value) = split('=',$item);
6798: $validations{&unescape($key)} = &thaw_unescape($value);
6799: }
6800: }
6801: }
1.1010 raeburn 6802: return %validations;
6803: }
6804:
1.1020 raeburn 6805: sub auto_courserequest_validation {
6806: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6807: my ($homeserver,$response);
6808: if ($dom =~ /^$match_domain$/) {
6809: $homeserver = &domain($dom,'primary');
6810: }
6811: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6812:
1.1020 raeburn 6813: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6814: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6815: ':'.&escape($instcode).':'.&escape($instseclist),
6816: $homeserver));
6817: }
6818: return $response;
6819: }
6820:
1.777 albertel 6821: sub auto_validate_class_sec {
1.918 raeburn 6822: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6823: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6824: my $ownerlist;
6825: if (ref($owners) eq 'ARRAY') {
6826: $ownerlist = join(',',@{$owners});
6827: } else {
6828: $ownerlist = $owners;
6829: }
1.773 raeburn 6830: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6831: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6832: return $response;
6833: }
6834:
1.679 raeburn 6835: # ------------------------------------------------------- Course Group routines
6836:
6837: sub get_coursegroups {
1.809 raeburn 6838: my ($cdom,$cnum,$group,$namespace) = @_;
6839: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6840: }
6841:
1.679 raeburn 6842: sub modify_coursegroup {
6843: my ($cdom,$cnum,$groupsettings) = @_;
6844: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6845: }
6846:
1.809 raeburn 6847: sub toggle_coursegroup_status {
6848: my ($cdom,$cnum,$group,$action) = @_;
6849: my ($from_namespace,$to_namespace);
6850: if ($action eq 'delete') {
6851: $from_namespace = 'coursegroups';
6852: $to_namespace = 'deleted_groups';
6853: } else {
6854: $from_namespace = 'deleted_groups';
6855: $to_namespace = 'coursegroups';
6856: }
6857: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6858: if (my $tmp = &error(%curr_group)) {
6859: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6860: return ('read error',$tmp);
6861: } else {
6862: my %savedsettings = %curr_group;
1.809 raeburn 6863: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6864: my $deloutcome;
6865: if ($result eq 'ok') {
1.809 raeburn 6866: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6867: } else {
6868: return ('write error',$result);
6869: }
6870: if ($deloutcome eq 'ok') {
6871: return 'ok';
6872: } else {
6873: return ('delete error',$deloutcome);
6874: }
6875: }
6876: }
6877:
1.679 raeburn 6878: sub modify_group_roles {
1.957 raeburn 6879: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6880: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6881: my $role = 'gr/'.&escape($userprivs);
6882: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6883: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6884: if ($result eq 'ok') {
6885: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6886: }
1.679 raeburn 6887: return $result;
6888: }
6889:
6890: sub modify_coursegroup_membership {
6891: my ($cdom,$cnum,$membership) = @_;
6892: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6893: return $result;
6894: }
6895:
1.682 raeburn 6896: sub get_active_groups {
6897: my ($udom,$uname,$cdom,$cnum) = @_;
6898: my $now = time;
6899: my %groups = ();
6900: foreach my $key (keys(%env)) {
1.811 albertel 6901: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6902: my ($start,$end) = split(/\./,$env{$key});
6903: if (($end!=0) && ($end<$now)) { next; }
6904: if (($start!=0) && ($start>$now)) { next; }
6905: if ($1 eq $cdom && $2 eq $cnum) {
6906: $groups{$3} = $env{$key} ;
6907: }
6908: }
6909: }
6910: return %groups;
6911: }
6912:
1.683 raeburn 6913: sub get_group_membership {
6914: my ($cdom,$cnum,$group) = @_;
6915: return(&dump('groupmembership',$cdom,$cnum,$group));
6916: }
6917:
6918: sub get_users_groups {
6919: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6920: my @usersgroups;
1.683 raeburn 6921: my $cachetime=1800;
6922:
6923: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6924: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6925: if (defined($cached)) {
1.734 albertel 6926: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6927: } else {
6928: $grouplist = '';
1.816 raeburn 6929: my $courseurl = &courseid_to_courseurl($courseid);
1.1086 raeburn 6930: my $extra = &freeze_escape({'skipcheck' => 1});
6931: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817 raeburn 6932: my $access_end = $env{'course.'.$courseid.
6933: '.default_enrollment_end_date'};
6934: my $now = time;
6935: foreach my $key (keys(%roleshash)) {
6936: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6937: my $group = $1;
6938: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6939: my $start = $2;
6940: my $end = $1;
6941: if ($start == -1) { next; } # deleted from group
6942: if (($start!=0) && ($start>$now)) { next; }
6943: if (($end!=0) && ($end<$now)) {
6944: if ($access_end && $access_end < $now) {
6945: if ($access_end - $end < 86400) {
6946: push(@usersgroups,$group);
1.733 raeburn 6947: }
6948: }
1.817 raeburn 6949: next;
1.733 raeburn 6950: }
1.817 raeburn 6951: push(@usersgroups,$group);
1.683 raeburn 6952: }
6953: }
6954: }
1.817 raeburn 6955: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6956: $grouplist = join(':',@usersgroups);
6957: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6958: }
1.733 raeburn 6959: return @usersgroups;
1.683 raeburn 6960: }
6961:
6962: sub devalidate_getgroups_cache {
6963: my ($udom,$uname,$cdom,$cnum)=@_;
6964: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6965:
1.683 raeburn 6966: my $hashid="$udom:$uname:$courseid";
6967: &devalidate_cache_new('getgroups',$hashid);
6968: }
6969:
1.12 www 6970: # ------------------------------------------------------------------ Plain Text
6971:
6972: sub plaintext {
1.988 raeburn 6973: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6974: if ($short =~ m{^cr/}) {
1.758 albertel 6975: return (split('/',$short))[-1];
6976: }
1.742 raeburn 6977: if (!defined($cid)) {
6978: $cid = $env{'request.course.id'};
6979: }
6980: my %rolenames = (
1.1008 raeburn 6981: Course => 'std',
6982: Community => 'alt1',
1.742 raeburn 6983: );
1.1037 raeburn 6984: if ($cid ne '') {
6985: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6986: unless ($forcedefault) {
6987: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6988: &Apache::lonlocal::mt_escape(\$roletext);
6989: return &Apache::lonlocal::mt($roletext);
6990: }
6991: }
6992: }
6993: if ((defined($type)) && (defined($rolenames{$type})) &&
6994: (defined($rolenames{$type})) &&
6995: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6996: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6997: } elsif ($cid ne '') {
6998: my $crstype = $env{'course.'.$cid.'.type'};
6999: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7000: (defined($prp{$short}{$rolenames{$crstype}}))) {
7001: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7002: }
1.742 raeburn 7003: }
1.1037 raeburn 7004: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 7005: }
7006:
7007: # ----------------------------------------------------------------- Assign Role
7008:
7009: sub assignrole {
1.957 raeburn 7010: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7011: $context)=@_;
1.21 www 7012: my $mrole;
7013: if ($role =~ /^cr\//) {
1.393 www 7014: my $cwosec=$url;
1.811 albertel 7015: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 7016: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 7017: my $refused = 1;
7018: if ($context eq 'requestcourses') {
7019: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7020: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7021: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7022: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7023: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7024: if ($crsenv{'internal.courseowner'} eq
7025: $env{'user.name'}.':'.$env{'user.domain'}) {
7026: $refused = '';
7027: }
7028: }
7029: }
7030: }
7031: }
7032: if ($refused) {
7033: &logthis('Refused custom assignrole: '.
7034: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7035: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7036: return 'refused';
7037: }
1.104 www 7038: }
1.21 www 7039: $mrole='cr';
1.678 raeburn 7040: } elsif ($role =~ /^gr\//) {
7041: my $cwogrp=$url;
1.811 albertel 7042: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 7043: unless (&allowed('mdg',$cwogrp)) {
7044: &logthis('Refused group assignrole: '.
7045: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7046: $env{'user.name'}.' at '.$env{'user.domain'});
7047: return 'refused';
7048: }
7049: $mrole='gr';
1.21 www 7050: } else {
1.82 www 7051: my $cwosec=$url;
1.811 albertel 7052: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 7053: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7054: my $refused;
7055: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7056: if (!(&allowed('c'.$role,$url))) {
7057: $refused = 1;
7058: }
7059: } else {
7060: $refused = 1;
7061: }
1.947 raeburn 7062: if ($refused) {
1.1045 raeburn 7063: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7064: if (!$selfenroll && $context eq 'course') {
7065: my %crsenv;
7066: if ($role eq 'cc' || $role eq 'co') {
7067: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7068: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7069: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7070: if ($crsenv{'internal.courseowner'} eq
7071: $env{'user.name'}.':'.$env{'user.domain'}) {
7072: $refused = '';
7073: }
7074: }
7075: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7076: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7077: if ($crsenv{'internal.courseowner'} eq
7078: $env{'user.name'}.':'.$env{'user.domain'}) {
7079: $refused = '';
7080: }
7081: }
7082: }
7083: }
7084: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 7085: $refused = '';
1.1017 raeburn 7086: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 7087: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 7088: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 7089: my $wrongcc;
7090: if ($cnum =~ /^$match_community$/) {
7091: $wrongcc = 1 if ($role eq 'cc');
7092: } else {
7093: $wrongcc = 1 if ($role eq 'co');
7094: }
7095: unless ($wrongcc) {
7096: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7097: if ($crsenv{'internal.courseowner'} eq
7098: $env{'user.name'}.':'.$env{'user.domain'}) {
7099: $refused = '';
7100: }
1.1017 raeburn 7101: }
7102: }
7103: }
7104: if ($refused) {
1.947 raeburn 7105: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7106: ' '.$role.' '.$end.' '.$start.' by '.
7107: $env{'user.name'}.' at '.$env{'user.domain'});
7108: return 'refused';
7109: }
1.932 raeburn 7110: }
1.1131 raeburn 7111: } elsif ($role eq 'au') {
7112: if ($url ne '/'.$udom.'/') {
7113: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
7114: ' to assign author role for '.$uname.':'.$udom.
7115: ' in domain: '.$url.' refused (wrong domain).');
7116: return 'refused';
7117: }
1.104 www 7118: }
1.21 www 7119: $mrole=$role;
7120: }
1.620 albertel 7121: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7122: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 7123: if ($end) { $command.='_'.$end; }
1.21 www 7124: if ($start) {
7125: if ($end) {
1.81 www 7126: $command.='_'.$start;
1.21 www 7127: } else {
1.81 www 7128: $command.='_0_'.$start;
1.21 www 7129: }
7130: }
1.739 raeburn 7131: my $origstart = $start;
7132: my $origend = $end;
1.957 raeburn 7133: my $delflag;
1.357 www 7134: # actually delete
7135: if ($deleteflag) {
1.373 www 7136: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 7137: # modify command to delete the role
1.620 albertel 7138: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 7139: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 7140: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 7141: # set start and finish to negative values for userrolelog
7142: $start=-1;
7143: $end=-1;
1.957 raeburn 7144: $delflag = 1;
1.357 www 7145: }
7146: }
7147: # send command
1.349 www 7148: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 7149: # log new user role if status is ok
1.349 www 7150: if ($answer eq 'ok') {
1.663 raeburn 7151: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 7152: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 7153: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 7154: unless ($role =~ /^gr/) {
7155: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 7156: $origstart,$selfenroll,$context);
1.739 raeburn 7157: }
1.1053 raeburn 7158: if ($role eq 'cc') {
7159: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7160: }
1.349 www 7161: }
7162: return $answer;
1.169 harris41 7163: }
7164:
1.1053 raeburn 7165: sub autoupdate_coowners {
7166: my ($url,$end,$start,$uname,$udom) = @_;
7167: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7168: if (($cdom ne '') && ($cnum ne '')) {
7169: my $now = time;
7170: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7171: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7172: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7173: my $instcode = $coursehash{'internal.coursecode'};
7174: if ($instcode ne '') {
1.1056 raeburn 7175: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7176: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 7177: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 7178: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7179: if ($result eq 'valid') {
7180: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 7181: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7182: push(@newcoowners,$coowner);
7183: }
7184: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7185: push(@newcoowners,$uname.':'.$udom);
7186: }
7187: @newcoowners = sort(@newcoowners);
7188: } else {
7189: push(@newcoowners,$uname.':'.$udom);
7190: }
7191: } else {
7192: if ($coursehash{'internal.co-owners'}) {
7193: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7194: unless ($coowner eq $uname.':'.$udom) {
7195: push(@newcoowners,$coowner);
7196: }
7197: }
7198: unless (@newcoowners > 0) {
7199: $delcoowners = 1;
7200: $coowners = '';
7201: }
7202: }
7203: }
7204: if (@newcoowners || $delcoowners) {
7205: &store_coowners($cdom,$cnum,$coursehash{'home'},
7206: $delcoowners,@newcoowners);
7207: }
7208: }
7209: }
7210: }
7211: }
7212: }
7213: }
7214:
7215: sub store_coowners {
7216: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7217: my $cid = $cdom.'_'.$cnum;
7218: my ($coowners,$delresult,$putresult);
7219: if (@newcoowners) {
7220: $coowners = join(',',@newcoowners);
7221: my %coownershash = (
7222: 'internal.co-owners' => $coowners,
7223: );
7224: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7225: if ($putresult eq 'ok') {
7226: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7227: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7228: }
7229: }
7230: }
7231: if ($delcoowners) {
7232: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7233: if ($delresult eq 'ok') {
7234: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7235: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7236: }
7237: }
7238: }
7239: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7240: my %crsinfo =
7241: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7242: if (ref($crsinfo{$cid}) eq 'HASH') {
7243: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7244: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7245: }
7246: }
7247: }
7248:
1.169 harris41 7249: # -------------------------------------------------- Modify user authentication
1.197 www 7250: # Overrides without validation
7251:
1.169 harris41 7252: sub modifyuserauth {
7253: my ($udom,$uname,$umode,$upass)=@_;
7254: my $uhome=&homeserver($uname,$udom);
1.197 www 7255: unless (&allowed('mau',$udom)) { return 'refused'; }
7256: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 7257: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7258: ' in domain '.$env{'request.role.domain'});
1.169 harris41 7259: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7260: &escape($upass),$uhome);
1.620 albertel 7261: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 7262: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7263: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7264: &log($udom,,$uname,$uhome,
1.620 albertel 7265: 'Authentication changed by '.$env{'user.domain'}.', '.
7266: $env{'user.name'}.', '.$umode.
1.197 www 7267: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 7268: unless ($reply eq 'ok') {
1.197 www 7269: &logthis('Authentication mode error: '.$reply);
1.169 harris41 7270: return 'error: '.$reply;
7271: }
1.170 harris41 7272: return 'ok';
1.80 www 7273: }
7274:
1.81 www 7275: # --------------------------------------------------------------- Modify a user
1.80 www 7276:
1.81 www 7277: sub modifyuser {
1.206 matthew 7278: my ($udom, $uname, $uid,
7279: $umode, $upass, $first,
7280: $middle, $last, $gene,
1.1058 raeburn 7281: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 7282: $udom= &LONCAPA::clean_domain($udom);
7283: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 7284: my $showcandelete = 'none';
7285: if (ref($candelete) eq 'ARRAY') {
7286: if (@{$candelete} > 0) {
7287: $showcandelete = join(', ',@{$candelete});
7288: }
7289: }
1.81 www 7290: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 7291: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 7292: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 7293: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7294: ' desiredhome not specified').
1.620 albertel 7295: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7296: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 7297: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 7298: my $newuser;
7299: if ($uhome eq 'no_host') {
7300: $newuser = 1;
7301: }
1.80 www 7302: # ----------------------------------------------------------------- Create User
1.406 albertel 7303: if (($uhome eq 'no_host') &&
7304: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 7305: my $unhome='';
1.844 albertel 7306: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 7307: $unhome = $desiredhome;
1.620 albertel 7308: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7309: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 7310: } else { # load balancing routine for determining $unhome
1.81 www 7311: my $loadm=10000000;
1.841 albertel 7312: my %servers = &get_servers($udom,'library');
7313: foreach my $tryserver (keys(%servers)) {
7314: my $answer=reply('load',$tryserver);
7315: if (($answer=~/\d+/) && ($answer<$loadm)) {
7316: $loadm=$answer;
7317: $unhome=$tryserver;
7318: }
1.80 www 7319: }
7320: }
7321: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 7322: return 'error: unable to find a home server for '.$uname.
7323: ' in domain '.$udom;
1.80 www 7324: }
7325: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7326: &escape($upass),$unhome);
7327: unless ($reply eq 'ok') {
7328: return 'error: '.$reply;
7329: }
1.230 stredwic 7330: $uhome=&homeserver($uname,$udom,'true');
1.80 www 7331: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 7332: return 'error: unable verify users home machine.';
1.80 www 7333: }
1.209 matthew 7334: } # End of creation of new user
1.80 www 7335: # ---------------------------------------------------------------------- Add ID
7336: if ($uid) {
7337: $uid=~tr/A-Z/a-z/;
7338: my %uidhash=&idrget($udom,$uname);
1.196 www 7339: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7340: && (!$forceid)) {
1.80 www 7341: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 7342: return 'error: user id "'.$uid.'" does not match '.
7343: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 7344: }
7345: } else {
7346: &idput($udom,($uname => $uid));
7347: }
7348: }
7349: # -------------------------------------------------------------- Add names, etc
1.313 matthew 7350: my @tmp=&get('environment',
1.899 raeburn 7351: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 7352: 'permanentemail','inststatus'],
1.134 albertel 7353: $udom,$uname);
1.1075 raeburn 7354: my (%names,%oldnames);
1.313 matthew 7355: if ($tmp[0] =~ m/^error:.*/) {
7356: %names=();
7357: } else {
7358: %names = @tmp;
1.1075 raeburn 7359: %oldnames = %names;
1.313 matthew 7360: }
1.388 www 7361: #
1.1058 raeburn 7362: # If name, email and/or uid are blank (e.g., because an uploaded file
7363: # of users did not contain them), do not overwrite existing values
7364: # unless field is in $candelete array ref.
7365: #
7366:
7367: my @fields = ('firstname','middlename','lastname','generation',
7368: 'permanentemail','id');
7369: my %newvalues;
7370: if (ref($candelete) eq 'ARRAY') {
7371: foreach my $field (@fields) {
7372: if (grep(/^\Q$field\E$/,@{$candelete})) {
7373: if ($field eq 'firstname') {
7374: $names{$field} = $first;
7375: } elsif ($field eq 'middlename') {
7376: $names{$field} = $middle;
7377: } elsif ($field eq 'lastname') {
7378: $names{$field} = $last;
7379: } elsif ($field eq 'generation') {
7380: $names{$field} = $gene;
7381: } elsif ($field eq 'permanentemail') {
7382: $names{$field} = $email;
7383: } elsif ($field eq 'id') {
7384: $names{$field} = $uid;
7385: }
7386: }
7387: }
7388: }
1.388 www 7389: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 7390: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 7391: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 7392: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 7393: if ($email) {
7394: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 7395: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 7396: }
1.899 raeburn 7397: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 7398: if (defined($inststatus)) {
7399: $names{'inststatus'} = '';
7400: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7401: if (ref($usertypes) eq 'HASH') {
7402: my @okstatuses;
7403: foreach my $item (split(/:/,$inststatus)) {
7404: if (defined($usertypes->{$item})) {
7405: push(@okstatuses,$item);
7406: }
7407: }
7408: if (@okstatuses) {
7409: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7410: }
7411: }
7412: }
1.1075 raeburn 7413: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 7414: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 7415: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 7416: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7417: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7418: } else {
7419: $logmsg .= ' during self creation';
7420: }
1.1075 raeburn 7421: my $changed;
7422: if ($newuser) {
7423: $changed = 1;
7424: } else {
7425: foreach my $field (@fields) {
7426: if ($names{$field} ne $oldnames{$field}) {
7427: $changed = 1;
7428: last;
7429: }
7430: }
7431: }
7432: unless ($changed) {
7433: $logmsg = 'No changes in user information needed for: '.$logmsg;
7434: &logthis($logmsg);
7435: return 'ok';
7436: }
7437: my $reply = &put('environment', \%names, $udom,$uname);
7438: if ($reply ne 'ok') {
7439: return 'error: '.$reply;
7440: }
1.1087 raeburn 7441: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7442: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7443: }
1.1075 raeburn 7444: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7445: &devalidate_cache_new('namescache',$uname.':'.$udom);
7446: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7447: &logthis($logmsg);
1.134 albertel 7448: return 'ok';
1.80 www 7449: }
7450:
1.81 www 7451: # -------------------------------------------------------------- Modify student
1.80 www 7452:
1.81 www 7453: sub modifystudent {
7454: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7455: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7456: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7457: if (!$cid) {
1.620 albertel 7458: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7459: return 'not_in_class';
7460: }
1.80 www 7461: }
7462: # --------------------------------------------------------------- Make the user
1.81 www 7463: my $reply=&modifyuser
1.209 matthew 7464: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7465: $desiredhome,$email,$inststatus);
1.80 www 7466: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7467: # This will cause &modify_student_enrollment to get the uid from the
7468: # students environment
7469: $uid = undef if (!$forceid);
1.455 albertel 7470: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7471: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7472: return $reply;
7473: }
7474:
7475: sub modify_student_enrollment {
1.957 raeburn 7476: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7477: my ($cdom,$cnum,$chome);
7478: if (!$cid) {
1.620 albertel 7479: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7480: return 'not_in_class';
7481: }
1.620 albertel 7482: $cdom=$env{'course.'.$cid.'.domain'};
7483: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7484: } else {
7485: ($cdom,$cnum)=split(/_/,$cid);
7486: }
1.620 albertel 7487: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7488: if (!$chome) {
1.457 raeburn 7489: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7490: }
1.455 albertel 7491: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7492: # Make sure the user exists
1.81 www 7493: my $uhome=&homeserver($uname,$udom);
7494: if (($uhome eq '') || ($uhome eq 'no_host')) {
7495: return 'error: no such user';
7496: }
1.297 matthew 7497: # Get student data if we were not given enough information
7498: if (!defined($first) || $first eq '' ||
7499: !defined($last) || $last eq '' ||
7500: !defined($uid) || $uid eq '' ||
7501: !defined($middle) || $middle eq '' ||
7502: !defined($gene) || $gene eq '') {
1.294 matthew 7503: # They did not supply us with enough data to enroll the student, so
7504: # we need to pick up more information.
1.297 matthew 7505: my %tmp = &get('environment',
1.294 matthew 7506: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7507: ,$udom,$uname);
7508:
1.800 albertel 7509: #foreach my $key (keys(%tmp)) {
7510: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7511: #}
1.294 matthew 7512: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7513: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7514: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7515: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7516: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7517: }
1.556 albertel 7518: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 7519: my $user = "$uname:$udom";
7520: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 7521: my $reply=cput('classlist',
1.1148 raeburn 7522: {$user =>
1.515 raeburn 7523: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7524: $cdom,$cnum);
1.1148 raeburn 7525: if (($reply eq 'ok') || ($reply eq 'delayed')) {
7526: &devalidate_getsection_cache($udom,$uname,$cid);
7527: } else {
1.81 www 7528: return 'error: '.$reply;
7529: }
1.297 matthew 7530: # Add student role to user
1.83 www 7531: my $uurl='/'.$cid;
1.81 www 7532: $uurl=~s/\_/\//g;
7533: if ($usec) {
7534: $uurl.='/'.$usec;
7535: }
1.1148 raeburn 7536: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
7537: $selfenroll,$context);
7538: if ($result ne 'ok') {
7539: if ($old_entry{$user} ne '') {
7540: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
7541: } else {
7542: $reply = &del('classlist',[$user],$cdom,$cnum);
7543: }
7544: }
7545: return $result;
1.21 www 7546: }
7547:
1.556 albertel 7548: sub format_name {
7549: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7550: my $name;
7551: if ($first ne 'lastname') {
7552: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7553: } else {
7554: if ($lastname=~/\S/) {
7555: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7556: $name=~s/\s+,/,/;
7557: } else {
7558: $name.= $firstname.' '.$middlename.' '.$generation;
7559: }
7560: }
7561: $name=~s/^\s+//;
7562: $name=~s/\s+$//;
7563: $name=~s/\s+/ /g;
7564: return $name;
7565: }
7566:
1.84 www 7567: # ------------------------------------------------- Write to course preferences
7568:
7569: sub writecoursepref {
7570: my ($courseid,%prefs)=@_;
7571: $courseid=~s/^\///;
7572: $courseid=~s/\_/\//g;
7573: my ($cdomain,$cnum)=split(/\//,$courseid);
7574: my $chome=homeserver($cnum,$cdomain);
7575: if (($chome eq '') || ($chome eq 'no_host')) {
7576: return 'error: no such course';
7577: }
7578: my $cstring='';
1.800 albertel 7579: foreach my $pref (keys(%prefs)) {
7580: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7581: }
1.84 www 7582: $cstring=~s/\&$//;
7583: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7584: }
7585:
7586: # ---------------------------------------------------------- Make/modify course
7587:
7588: sub createcourse {
1.741 raeburn 7589: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7590: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7591: $url=&declutter($url);
7592: my $cid='';
1.1028 raeburn 7593: if ($context eq 'requestcourses') {
7594: my $can_create = 0;
7595: my ($ownername,$ownerdom) = split(':',$course_owner);
7596: if ($udom eq $ownerdom) {
7597: if (&usertools_access($ownername,$ownerdom,$category,undef,
7598: $context)) {
7599: $can_create = 1;
7600: }
7601: } else {
7602: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7603: $category);
7604: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7605: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7606: if (@curr > 0) {
7607: my @options = qw(approval validate autolimit);
7608: my $optregex = join('|',@options);
7609: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7610: $can_create = 1;
7611: }
7612: }
7613: }
7614: }
7615: if ($can_create) {
7616: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7617: unless (&allowed('ccc',$udom)) {
7618: return 'refused';
7619: }
1.1017 raeburn 7620: }
7621: } else {
7622: return 'refused';
7623: }
1.1028 raeburn 7624: } elsif (!&allowed('ccc',$udom)) {
7625: return 'refused';
1.84 www 7626: }
1.1011 raeburn 7627: # --------------------------------------------------------------- Get Unique ID
7628: my $uname;
7629: if ($cnum =~ /^$match_courseid$/) {
7630: my $chome=&homeserver($cnum,$udom,'true');
7631: if (($chome eq '') || ($chome eq 'no_host')) {
7632: $uname = $cnum;
7633: } else {
1.1038 raeburn 7634: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7635: }
7636: } else {
1.1038 raeburn 7637: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7638: }
7639: return $uname if ($uname =~ /^error/);
7640: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7641: if (!defined($course_server)) {
7642: if (defined(&domain($udom,'primary'))) {
7643: $course_server = &domain($udom,'primary');
7644: } else {
7645: $course_server = $env{'user.home'};
7646: }
7647: }
7648: my %host_servers =
7649: &Apache::lonnet::get_servers($udom,'library');
7650: unless ($host_servers{$course_server}) {
7651: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7652: }
1.84 www 7653: # ------------------------------------------------------------- Make the course
7654: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7655: $course_server);
1.84 www 7656: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7657: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7658: if (($uhome eq '') || ($uhome eq 'no_host')) {
7659: return 'error: no such course';
7660: }
1.271 www 7661: # ----------------------------------------------------------------- Course made
1.516 raeburn 7662: # log existence
1.1029 raeburn 7663: my $now = time;
1.918 raeburn 7664: my $newcourse = {
7665: $udom.'_'.$uname => {
1.921 raeburn 7666: description => $description,
7667: inst_code => $inst_code,
7668: owner => $course_owner,
7669: type => $crstype,
1.1029 raeburn 7670: creator => $env{'user.name'}.':'.
7671: $env{'user.domain'},
7672: created => $now,
7673: context => $context,
1.918 raeburn 7674: },
7675: };
1.921 raeburn 7676: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7677: # set toplevel url
1.271 www 7678: my $topurl=$url;
7679: unless ($nonstandard) {
7680: # ------------------------------------------ For standard courses, make top url
7681: my $mapurl=&clutter($url);
1.278 www 7682: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7683: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7684: <map>
7685: <resource id="1" type="start"></resource>
7686: <resource id="2" src="$mapurl"></resource>
7687: <resource id="3" type="finish"></resource>
7688: <link index="1" from="1" to="2"></link>
7689: <link index="2" from="2" to="3"></link>
7690: </map>
7691: ENDINITMAP
7692: $topurl=&declutter(
1.638 albertel 7693: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7694: );
7695: }
7696: # ----------------------------------------------------------- Write preferences
1.84 www 7697: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7698: ('description' => $description,
7699: 'url' => $topurl,
7700: 'internal.creator' => $env{'user.name'}.':'.
7701: $env{'user.domain'},
7702: 'internal.created' => $now,
7703: 'internal.creationcontext' => $context)
7704: );
1.84 www 7705: return '/'.$udom.'/'.$uname;
7706: }
7707:
1.1011 raeburn 7708: # ------------------------------------------------------------------- Create ID
7709: sub generate_coursenum {
1.1038 raeburn 7710: my ($udom,$crstype) = @_;
1.1011 raeburn 7711: my $domdesc = &domain($udom);
7712: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7713: my $first;
7714: if ($crstype eq 'Community') {
7715: $first = '0';
7716: } else {
7717: $first = int(1+rand(9));
7718: }
7719: my $uname=$first.
1.1011 raeburn 7720: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7721: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7722: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7723: # ----------------------------------------------- Make sure that does not exist
7724: my $uhome=&homeserver($uname,$udom,'true');
7725: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7726: if ($crstype eq 'Community') {
7727: $first = '0';
7728: } else {
7729: $first = int(1+rand(9));
7730: }
7731: $uname=$first.
1.1011 raeburn 7732: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7733: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7734: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7735: $uhome=&homeserver($uname,$udom,'true');
7736: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7737: return 'error: unable to generate unique course-ID';
7738: }
7739: }
7740: return $uname;
7741: }
7742:
1.813 albertel 7743: sub is_course {
7744: my ($cdom,$cnum) = @_;
7745: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7746: undef,'.');
1.813 albertel 7747: if (exists($courses{$cdom.'_'.$cnum})) {
7748: return 1;
7749: }
7750: return 0;
7751: }
7752:
1.1015 raeburn 7753: sub store_userdata {
7754: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7755: my $result;
1.1016 raeburn 7756: if ($datakey ne '') {
1.1013 raeburn 7757: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7758: if ($udom eq '' || $uname eq '') {
7759: $udom = $env{'user.domain'};
7760: $uname = $env{'user.name'};
7761: }
7762: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7763: if (($uhome eq '') || ($uhome eq 'no_host')) {
7764: $result = 'error: no_host';
7765: } else {
7766: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7767: $storehash->{'host'} = $perlvar{'lonHostID'};
7768:
7769: my $namevalue='';
7770: foreach my $key (keys(%{$storehash})) {
7771: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7772: }
7773: $namevalue=~s/\&$//;
1.1105 raeburn 7774: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
7775: $namevalue,$uhome);
1.1013 raeburn 7776: }
7777: } else {
7778: $result = 'error: data to store was not a hash reference';
7779: }
7780: } else {
7781: $result= 'error: invalid requestkey';
7782: }
7783: return $result;
7784: }
7785:
1.21 www 7786: # ---------------------------------------------------------- Assign Custom Role
7787:
7788: sub assigncustomrole {
1.957 raeburn 7789: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7790: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7791: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7792: }
7793:
7794: # ----------------------------------------------------------------- Revoke Role
7795:
7796: sub revokerole {
1.957 raeburn 7797: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7798: my $now=time;
1.965 raeburn 7799: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7800: }
7801:
7802: # ---------------------------------------------------------- Revoke Custom Role
7803:
7804: sub revokecustomrole {
1.957 raeburn 7805: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7806: my $now=time;
1.357 www 7807: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7808: $deleteflag,$selfenroll,$context);
1.17 www 7809: }
7810:
1.533 banghart 7811: # ------------------------------------------------------------ Disk usage
1.535 albertel 7812: sub diskusage {
1.955 raeburn 7813: my ($udom,$uname,$directorypath,$getpropath)=@_;
7814: $directorypath =~ s/\/$//;
7815: my $listing=&reply('du2:'.&escape($directorypath).':'
7816: .&escape($getpropath).':'.&escape($uname).':'
7817: .&escape($udom),homeserver($uname,$udom));
7818: if ($listing eq 'unknown_cmd') {
7819: if ($getpropath) {
7820: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7821: }
7822: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7823: }
1.514 albertel 7824: return $listing;
1.512 banghart 7825: }
7826:
1.566 banghart 7827: sub is_locked {
1.1096 raeburn 7828: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 7829: my @check;
7830: my $is_locked;
1.1093 raeburn 7831: push (@check,$file_name);
1.613 albertel 7832: my %locked = &get('file_permissions',\@check,
1.620 albertel 7833: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7834: my ($tmp)=keys(%locked);
7835: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7836:
1.566 banghart 7837: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7838: $is_locked = 'false';
7839: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 7840: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7841: $is_locked = 'true';
1.1096 raeburn 7842: if (ref($which) eq 'ARRAY') {
7843: push(@{$which},$entry);
7844: } else {
7845: last;
7846: }
1.745 raeburn 7847: }
7848: }
1.566 banghart 7849: } else {
7850: $is_locked = 'false';
7851: }
1.1093 raeburn 7852: return $is_locked;
1.566 banghart 7853: }
7854:
1.759 albertel 7855: sub declutter_portfile {
7856: my ($file) = @_;
1.833 albertel 7857: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7858: return $file;
7859: }
7860:
1.559 banghart 7861: # ------------------------------------------------------------- Mark as Read Only
7862:
7863: sub mark_as_readonly {
7864: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7865: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7866: my ($tmp)=keys(%current_permissions);
7867: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7868: foreach my $file (@{$files}) {
1.759 albertel 7869: $file = &declutter_portfile($file);
1.561 banghart 7870: push(@{$current_permissions{$file}},$what);
1.559 banghart 7871: }
1.613 albertel 7872: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7873: return;
7874: }
7875:
1.572 banghart 7876: # ------------------------------------------------------------Save Selected Files
7877:
7878: sub save_selected_files {
7879: my ($user, $path, @files) = @_;
7880: my $filename = $user."savedfiles";
1.573 banghart 7881: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7882: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7883: foreach my $file (@files) {
1.620 albertel 7884: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7885: }
7886: foreach my $file (@other_files) {
1.574 banghart 7887: print (OUT $file."\n");
1.572 banghart 7888: }
1.574 banghart 7889: close (OUT);
1.572 banghart 7890: return 'ok';
7891: }
7892:
1.574 banghart 7893: sub clear_selected_files {
7894: my ($user) = @_;
7895: my $filename = $user."savedfiles";
1.1117 foxr 7896: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 7897: print (OUT undef);
7898: close (OUT);
7899: return ("ok");
7900: }
7901:
1.572 banghart 7902: sub files_in_path {
7903: my ($user, $path) = @_;
7904: my $filename = $user."savedfiles";
7905: my %return_files;
1.1117 foxr 7906: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 7907: while (my $line_in = <IN>) {
1.574 banghart 7908: chomp ($line_in);
7909: my @paths_and_file = split (m!/!, $line_in);
7910: my $file_part = pop (@paths_and_file);
7911: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7912: $path_part.='/';
7913: my $path_and_file = $path_part.$file_part;
7914: if ($path_part eq $path) {
7915: $return_files{$file_part}= 'selected';
7916: }
7917: }
1.574 banghart 7918: close (IN);
7919: return (\%return_files);
1.572 banghart 7920: }
7921:
7922: # called in portfolio select mode, to show files selected NOT in current directory
7923: sub files_not_in_path {
7924: my ($user, $path) = @_;
7925: my $filename = $user."savedfiles";
7926: my @return_files;
7927: my $path_part;
1.1117 foxr 7928: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 7929: while (my $line = <IN>) {
1.572 banghart 7930: #ok, I know it's clunky, but I want it to work
1.800 albertel 7931: my @paths_and_file = split(m|/|, $line);
7932: my $file_part = pop(@paths_and_file);
7933: chomp($file_part);
7934: my $path_part = join('/', @paths_and_file);
1.572 banghart 7935: $path_part .= '/';
7936: my $path_and_file = $path_part.$file_part;
7937: if ($path_part ne $path) {
1.800 albertel 7938: push(@return_files, ($path_and_file));
1.572 banghart 7939: }
7940: }
1.800 albertel 7941: close(OUT);
1.574 banghart 7942: return (@return_files);
1.572 banghart 7943: }
7944:
1.745 raeburn 7945: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7946:
1.745 raeburn 7947: sub get_portfile_permissions {
7948: my ($domain,$user) = @_;
1.613 albertel 7949: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7950: my ($tmp)=keys(%current_permissions);
7951: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7952: return \%current_permissions;
7953: }
7954:
7955: #---------------------------------------------Get portfolio file access controls
7956:
1.749 raeburn 7957: sub get_access_controls {
1.745 raeburn 7958: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7959: my %access;
7960: my $real_file = $file;
7961: $file =~ s/\.meta$//;
1.745 raeburn 7962: if (defined($file)) {
1.749 raeburn 7963: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7964: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7965: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7966: }
7967: }
1.745 raeburn 7968: } else {
1.749 raeburn 7969: foreach my $key (keys(%{$current_permissions})) {
7970: if ($key =~ /\0accesscontrol$/) {
7971: if (defined($group)) {
7972: if ($key !~ m-^\Q$group\E/-) {
7973: next;
7974: }
7975: }
7976: my ($fullpath) = split(/\0/,$key);
7977: if (ref($$current_permissions{$key}) eq 'HASH') {
7978: foreach my $control (keys(%{$$current_permissions{$key}})) {
7979: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7980: }
7981: }
7982: }
7983: }
7984: }
7985: return %access;
7986: }
7987:
7988: sub modify_access_controls {
7989: my ($file_name,$changes,$domain,$user)=@_;
7990: my ($outcome,$deloutcome);
7991: my %store_permissions;
7992: my %new_values;
7993: my %new_control;
7994: my %translation;
7995: my @deletions = ();
7996: my $now = time;
7997: if (exists($$changes{'activate'})) {
7998: if (ref($$changes{'activate'}) eq 'HASH') {
7999: my @newitems = sort(keys(%{$$changes{'activate'}}));
8000: my $numnew = scalar(@newitems);
8001: for (my $i=0; $i<$numnew; $i++) {
8002: my $newkey = $newitems[$i];
8003: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 8004: if ($newkey =~ /^\d+:/) {
8005: $newkey =~ s/^(\d+)/$newid/;
8006: $translation{$1} = $newid;
8007: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
8008: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
8009: $translation{$1} = $newid;
8010: }
1.749 raeburn 8011: $new_values{$file_name."\0".$newkey} =
8012: $$changes{'activate'}{$newitems[$i]};
8013: $new_control{$newkey} = $now;
8014: }
8015: }
8016: }
8017: my %todelete;
8018: my %changed_items;
8019: foreach my $action ('delete','update') {
8020: if (exists($$changes{$action})) {
8021: if (ref($$changes{$action}) eq 'HASH') {
8022: foreach my $key (keys(%{$$changes{$action}})) {
8023: my ($itemnum) = ($key =~ /^([^:]+):/);
8024: if ($action eq 'delete') {
8025: $todelete{$itemnum} = 1;
8026: } else {
8027: $changed_items{$itemnum} = $key;
8028: }
8029: }
1.745 raeburn 8030: }
8031: }
1.749 raeburn 8032: }
8033: # get lock on access controls for file.
8034: my $lockhash = {
8035: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8036: ':'.$env{'user.domain'},
8037: };
8038: my $tries = 0;
8039: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8040:
8041: while (($gotlock ne 'ok') && $tries <3) {
8042: $tries ++;
8043: sleep 1;
8044: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8045: }
8046: if ($gotlock eq 'ok') {
8047: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8048: my ($tmp)=keys(%curr_permissions);
8049: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8050: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8051: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8052: if (ref($curr_controls) eq 'HASH') {
8053: foreach my $control_item (keys(%{$curr_controls})) {
8054: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8055: if (defined($todelete{$itemnum})) {
8056: push(@deletions,$file_name."\0".$control_item);
8057: } else {
8058: if (defined($changed_items{$itemnum})) {
8059: $new_control{$changed_items{$itemnum}} = $now;
8060: push(@deletions,$file_name."\0".$control_item);
8061: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8062: } else {
8063: $new_control{$control_item} = $$curr_controls{$control_item};
8064: }
8065: }
1.745 raeburn 8066: }
8067: }
8068: }
1.970 raeburn 8069: my ($group);
8070: if (&is_course($domain,$user)) {
8071: ($group,my $file) = split(/\//,$file_name,2);
8072: }
1.749 raeburn 8073: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8074: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8075: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8076: # remove lock
8077: my @del_lock = ($file_name."\0".'locked_access_records');
8078: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 8079: my $sqlresult =
1.970 raeburn 8080: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 8081: $group);
1.749 raeburn 8082: } else {
8083: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 8084: }
1.749 raeburn 8085: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 8086: }
8087:
1.827 raeburn 8088: sub make_public_indefinitely {
8089: my ($requrl) = @_;
8090: my $now = time;
8091: my $action = 'activate';
8092: my $aclnum = 0;
8093: if (&is_portfolio_url($requrl)) {
8094: my (undef,$udom,$unum,$file_name,$group) =
8095: &parse_portfolio_url($requrl);
8096: my $current_perms = &get_portfile_permissions($udom,$unum);
8097: my %access_controls = &get_access_controls($current_perms,
8098: $group,$file_name);
8099: foreach my $key (keys(%{$access_controls{$file_name}})) {
8100: my ($num,$scope,$end,$start) =
8101: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8102: if ($scope eq 'public') {
8103: if ($start <= $now && $end == 0) {
8104: $action = 'none';
8105: } else {
8106: $action = 'update';
8107: $aclnum = $num;
8108: }
8109: last;
8110: }
8111: }
8112: if ($action eq 'none') {
8113: return 'ok';
8114: } else {
8115: my %changes;
8116: my $newend = 0;
8117: my $newstart = $now;
8118: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8119: $changes{$action}{$newkey} = {
8120: type => 'public',
8121: time => {
8122: start => $newstart,
8123: end => $newend,
8124: },
8125: };
8126: my ($outcome,$deloutcome,$new_values,$translation) =
8127: &modify_access_controls($file_name,\%changes,$udom,$unum);
8128: return $outcome;
8129: }
8130: } else {
8131: return 'invalid';
8132: }
8133: }
8134:
1.745 raeburn 8135: #------------------------------------------------------Get Marked as Read Only
8136:
8137: sub get_marked_as_readonly {
8138: my ($domain,$user,$what,$group) = @_;
8139: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 8140: my @readonly_files;
1.629 banghart 8141: my $cmp1=$what;
8142: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 8143: while (my ($file_name,$value) = each(%{$current_permissions})) {
8144: if (defined($group)) {
8145: if ($file_name !~ m-^\Q$group\E/-) {
8146: next;
8147: }
8148: }
1.561 banghart 8149: if (ref($value) eq "ARRAY"){
8150: foreach my $stored_what (@{$value}) {
1.629 banghart 8151: my $cmp2=$stored_what;
1.759 albertel 8152: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 8153: $cmp2=join('',@{$stored_what});
1.745 raeburn 8154: }
1.629 banghart 8155: if ($cmp1 eq $cmp2) {
1.561 banghart 8156: push(@readonly_files, $file_name);
1.745 raeburn 8157: last;
1.563 banghart 8158: } elsif (!defined($what)) {
8159: push(@readonly_files, $file_name);
1.745 raeburn 8160: last;
1.561 banghart 8161: }
8162: }
1.745 raeburn 8163: }
1.561 banghart 8164: }
8165: return @readonly_files;
8166: }
1.577 banghart 8167: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 8168:
1.577 banghart 8169: sub get_marked_as_readonly_hash {
1.745 raeburn 8170: my ($current_permissions,$group,$what) = @_;
1.577 banghart 8171: my %readonly_files;
1.745 raeburn 8172: while (my ($file_name,$value) = each(%{$current_permissions})) {
8173: if (defined($group)) {
8174: if ($file_name !~ m-^\Q$group\E/-) {
8175: next;
8176: }
8177: }
1.577 banghart 8178: if (ref($value) eq "ARRAY"){
8179: foreach my $stored_what (@{$value}) {
1.745 raeburn 8180: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 8181: foreach my $lock_descriptor(@{$stored_what}) {
8182: if ($lock_descriptor eq 'graded') {
8183: $readonly_files{$file_name} = 'graded';
8184: } elsif ($lock_descriptor eq 'handback') {
8185: $readonly_files{$file_name} = 'handback';
8186: } else {
8187: if (!exists($readonly_files{$file_name})) {
8188: $readonly_files{$file_name} = 'locked';
8189: }
8190: }
1.745 raeburn 8191: }
1.750 banghart 8192: }
1.577 banghart 8193: }
8194: }
8195: }
8196: return %readonly_files;
8197: }
1.559 banghart 8198: # ------------------------------------------------------------ Unmark as Read Only
8199:
8200: sub unmark_as_readonly {
1.629 banghart 8201: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8202: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 8203: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 8204: $file_name = &declutter_portfile($file_name);
1.634 albertel 8205: my $symb_crs = $what;
8206: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 8207: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 8208: my ($tmp)=keys(%current_permissions);
8209: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8210: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 8211: foreach my $file (@readonly_files) {
1.759 albertel 8212: my $clean_file = &declutter_portfile($file);
8213: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 8214: my $current_locks = $current_permissions{$file};
1.563 banghart 8215: my @new_locks;
8216: my @del_keys;
8217: if (ref($current_locks) eq "ARRAY"){
8218: foreach my $locker (@{$current_locks}) {
1.632 albertel 8219: my $compare=$locker;
1.749 raeburn 8220: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 8221: $compare=join('',@{$locker});
1.746 raeburn 8222: if ($compare ne $symb_crs) {
8223: push(@new_locks, $locker);
8224: }
1.563 banghart 8225: }
8226: }
1.650 albertel 8227: if (scalar(@new_locks) > 0) {
1.563 banghart 8228: $current_permissions{$file} = \@new_locks;
8229: } else {
8230: push(@del_keys, $file);
1.613 albertel 8231: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 8232: delete($current_permissions{$file});
1.563 banghart 8233: }
8234: }
1.561 banghart 8235: }
1.613 albertel 8236: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8237: return;
8238: }
1.512 banghart 8239:
1.17 www 8240: # ------------------------------------------------------------ Directory lister
8241:
8242: sub dirlist {
1.955 raeburn 8243: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 8244: $uri=~s/^\///;
8245: $uri=~s/\/$//;
1.253 stredwic 8246: my ($udom, $uname);
1.955 raeburn 8247: if ($getuserdir) {
1.253 stredwic 8248: $udom = $userdomain;
8249: $uname = $username;
1.955 raeburn 8250: } else {
8251: (undef,$udom,$uname)=split(/\//,$uri);
8252: if(defined($userdomain)) {
8253: $udom = $userdomain;
8254: }
8255: if(defined($username)) {
8256: $uname = $username;
8257: }
1.253 stredwic 8258: }
1.955 raeburn 8259: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 8260:
1.955 raeburn 8261: $dirRoot = $perlvar{'lonDocRoot'};
8262: if (defined($getpropath)) {
8263: $dirRoot = &propath($udom,$uname);
1.253 stredwic 8264: $dirRoot =~ s/\/$//;
1.955 raeburn 8265: } elsif (defined($getuserdir)) {
8266: my $subdir=$uname.'__';
8267: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8268: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8269: ."/$udom/$subdir/$uname";
8270: } elsif (defined($alternateRoot)) {
8271: $dirRoot = $alternateRoot;
1.751 banghart 8272: }
1.253 stredwic 8273:
8274: if($udom) {
8275: if($uname) {
1.1135 raeburn 8276: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 8277: if ($uhome eq 'no_host') {
8278: return ([],'no_host');
8279: }
1.955 raeburn 8280: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 8281: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 8282: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 8283: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8284: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 8285: } else {
8286: @listing_results = map { &unescape($_); } split(/:/,$listing);
8287: }
1.605 matthew 8288: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8289: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 8290: @listing_results = split(/:/,$listing);
8291: } else {
8292: @listing_results = map { &unescape($_); } split(/:/,$listing);
8293: }
1.1135 raeburn 8294: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 8295: ($listing eq 'rejected') || ($listing eq 'refused') ||
8296: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8297: return ([],$listing);
8298: } else {
8299: return (\@listing_results);
1.1135 raeburn 8300: }
1.955 raeburn 8301: } elsif(!$alternateRoot) {
1.1136 raeburn 8302: my (%allusers,%listerror);
1.841 albertel 8303: my %servers = &get_servers($udom,'library');
1.955 raeburn 8304: foreach my $tryserver (keys(%servers)) {
8305: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8306: &escape($udom),$tryserver);
8307: if ($listing eq 'unknown_cmd') {
8308: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8309: $udom, $tryserver);
8310: } else {
8311: @listing_results = map { &unescape($_); } split(/:/,$listing);
8312: }
1.841 albertel 8313: if ($listing eq 'unknown_cmd') {
8314: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8315: $udom, $tryserver);
8316: @listing_results = split(/:/,$listing);
8317: } else {
8318: @listing_results =
8319: map { &unescape($_); } split(/:/,$listing);
8320: }
1.1136 raeburn 8321: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8322: ($listing eq 'rejected') || ($listing eq 'refused') ||
8323: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8324: $listerror{$tryserver} = $listing;
8325: } else {
1.841 albertel 8326: foreach my $line (@listing_results) {
8327: my ($entry) = split(/&/,$line,2);
8328: $allusers{$entry} = 1;
8329: }
8330: }
1.253 stredwic 8331: }
1.1136 raeburn 8332: my @alluserslist=();
1.800 albertel 8333: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 8334: push(@alluserslist,$user.'&user');
1.253 stredwic 8335: }
1.1136 raeburn 8336: return (\@alluserslist);
1.253 stredwic 8337: } else {
1.1136 raeburn 8338: return ([],'missing username');
1.253 stredwic 8339: }
1.955 raeburn 8340: } elsif(!defined($getpropath)) {
1.1136 raeburn 8341: my $path = $perlvar{'lonDocRoot'}.'/res/';
8342: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
8343: return (\@all_domains);
1.955 raeburn 8344: } else {
1.1136 raeburn 8345: return ([],'missing domain');
1.275 stredwic 8346: }
8347: }
8348:
8349: # --------------------------------------------- GetFileTimestamp
8350: # This function utilizes dirlist and returns the date stamp for
8351: # when it was last modified. It will also return an error of -1
8352: # if an error occurs
8353:
8354: sub GetFileTimestamp {
1.955 raeburn 8355: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 8356: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8357: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 8358: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
8359: undef,$getuserdir);
8360: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8361: return -1;
8362: }
8363: if (ref($fileref) eq 'ARRAY') {
8364: my @stats = split('&',$fileref->[0]);
1.375 matthew 8365: # @stats contains first the filename, then the stat output
8366: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 8367: } else {
8368: return -1;
1.253 stredwic 8369: }
1.26 www 8370: }
8371:
1.712 albertel 8372: sub stat_file {
8373: my ($uri) = @_;
1.787 albertel 8374: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 8375:
1.955 raeburn 8376: my ($udom,$uname,$file);
1.712 albertel 8377: if ($uri =~ m-^/(uploaded|editupload)/-) {
8378: ($udom,$uname,$file) =
1.811 albertel 8379: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 8380: $file = 'userfiles/'.$file;
8381: }
8382: if ($uri =~ m-^/res/-) {
8383: ($udom,$uname) =
1.807 albertel 8384: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 8385: $file = $uri;
8386: }
8387:
8388: if (!$udom || !$uname || !$file) {
8389: # unable to handle the uri
8390: return ();
8391: }
1.956 raeburn 8392: my $getpropath;
8393: if ($file =~ /^userfiles\//) {
8394: $getpropath = 1;
8395: }
1.1136 raeburn 8396: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
8397: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8398: return ();
8399: } else {
8400: if (ref($listref) eq 'ARRAY') {
8401: my @stats = split('&',$listref->[0]);
8402: shift(@stats); #filename is first
8403: return @stats;
8404: }
1.712 albertel 8405: }
8406: return ();
8407: }
8408:
1.26 www 8409: # -------------------------------------------------------- Value of a Condition
8410:
1.713 albertel 8411: # gets the value of a specific preevaluated condition
8412: # stored in the string $env{user.state.<cid>}
8413: # or looks up a condition reference in the bighash and if if hasn't
8414: # already been evaluated recurses into docondval to get the value of
8415: # the condition, then memoizing it to
8416: # $env{user.state.<cid>.<condition>}
1.40 www 8417: sub directcondval {
8418: my $number=shift;
1.620 albertel 8419: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 8420: &Apache::lonuserstate::evalstate();
8421: }
1.713 albertel 8422: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8423: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8424: } elsif ($number =~ /^_/) {
8425: my $sub_condition;
8426: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8427: &GDBM_READER(),0640)) {
8428: $sub_condition=$bighash{'conditions'.$number};
8429: untie(%bighash);
8430: }
8431: my $value = &docondval($sub_condition);
1.949 raeburn 8432: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 8433: return $value;
8434: }
1.620 albertel 8435: if ($env{'user.state.'.$env{'request.course.id'}}) {
8436: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 8437: } else {
8438: return 2;
8439: }
8440: }
8441:
1.713 albertel 8442: # get the collection of conditions for this resource
1.26 www 8443: sub condval {
8444: my $condidx=shift;
1.54 www 8445: my $allpathcond='';
1.713 albertel 8446: foreach my $cond (split(/\|/,$condidx)) {
8447: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8448: $allpathcond.=
8449: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8450: }
1.191 harris41 8451: }
1.54 www 8452: $allpathcond=~s/\|$//;
1.713 albertel 8453: return &docondval($allpathcond);
8454: }
8455:
8456: #evaluates an expression of conditions
8457: sub docondval {
8458: my ($allpathcond) = @_;
8459: my $result=0;
8460: if ($env{'request.course.id'}
8461: && defined($allpathcond)) {
8462: my $operand='|';
8463: my @stack;
8464: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8465: if ($chunk eq '(') {
8466: push @stack,($operand,$result);
8467: } elsif ($chunk eq ')') {
8468: my $before=pop @stack;
8469: if (pop @stack eq '&') {
8470: $result=$result>$before?$before:$result;
8471: } else {
8472: $result=$result>$before?$result:$before;
8473: }
8474: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8475: $operand=$chunk;
8476: } else {
8477: my $new=directcondval($chunk);
8478: if ($operand eq '&') {
8479: $result=$result>$new?$new:$result;
8480: } else {
8481: $result=$result>$new?$result:$new;
8482: }
8483: }
8484: }
1.26 www 8485: }
8486: return $result;
1.421 albertel 8487: }
8488:
8489: # ---------------------------------------------------- Devalidate courseresdata
8490:
8491: sub devalidatecourseresdata {
8492: my ($coursenum,$coursedomain)=@_;
8493: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8494: &devalidate_cache_new('courseres',$hashid);
1.28 www 8495: }
8496:
1.763 www 8497:
1.200 www 8498: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8499: #
8500: # Parameters:
8501: # $coursenum - Number of the course.
8502: # $coursedomain - Domain at which the course was created.
8503: # Returns:
8504: # A hash of the course parameters along (I think) with timestamps
8505: # and version info.
1.877 foxr 8506:
1.624 albertel 8507: sub get_courseresdata {
8508: my ($coursenum,$coursedomain)=@_;
1.200 www 8509: my $coursehom=&homeserver($coursenum,$coursedomain);
8510: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8511: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8512: my %dumpreply;
1.417 albertel 8513: unless (defined($cached)) {
1.624 albertel 8514: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 8515: $result=\%dumpreply;
1.251 albertel 8516: my ($tmp) = keys(%dumpreply);
8517: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 8518: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 8519: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8520: return $tmp;
1.416 albertel 8521: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8522: $result=undef;
1.599 albertel 8523: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8524: }
8525: }
1.624 albertel 8526: return $result;
8527: }
8528:
1.633 albertel 8529: sub devalidateuserresdata {
8530: my ($uname,$udom)=@_;
8531: my $hashid="$udom:$uname";
8532: &devalidate_cache_new('userres',$hashid);
8533: }
8534:
1.624 albertel 8535: sub get_userresdata {
8536: my ($uname,$udom)=@_;
8537: #most student don\'t have any data set, check if there is some data
8538: if (&EXT_cache_status($udom,$uname)) { return undef; }
8539:
8540: my $hashid="$udom:$uname";
8541: my ($result,$cached)=&is_cached_new('userres',$hashid);
8542: if (!defined($cached)) {
8543: my %resourcedata=&dump('resourcedata',$udom,$uname);
8544: $result=\%resourcedata;
8545: &do_cache_new('userres',$hashid,$result,600);
8546: }
8547: my ($tmp)=keys(%$result);
8548: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8549: return $result;
8550: }
8551: #error 2 occurs when the .db doesn't exist
8552: if ($tmp!~/error: 2 /) {
1.672 albertel 8553: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8554: " Trying to get resource data for ".
8555: $uname." at ".$udom.": ".
8556: $tmp."</font>");
8557: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8558: #&EXT_cache_set($udom,$uname);
8559: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8560: undef($tmp); # not really an error so don't send it back
1.624 albertel 8561: }
8562: return $tmp;
8563: }
1.879 foxr 8564: #----------------------------------------------- resdata - return resource data
8565: # Purpose:
8566: # Return resource data for either users or for a course.
8567: # Parameters:
8568: # $name - Course/user name.
8569: # $domain - Name of the domain the user/course is registered on.
8570: # $type - Type of thing $name is (must be 'course' or 'user'
8571: # @which - Array of names of resources desired.
8572: # Returns:
8573: # The value of the first reasource in @which that is found in the
8574: # resource hash.
8575: # Exceptional Conditions:
8576: # If the $type passed in is not valid (not the string 'course' or
8577: # 'user', an undefined reference is returned.
8578: # If none of the resources are found, an undef is returned
1.624 albertel 8579: sub resdata {
8580: my ($name,$domain,$type,@which)=@_;
8581: my $result;
8582: if ($type eq 'course') {
8583: $result=&get_courseresdata($name,$domain);
8584: } elsif ($type eq 'user') {
8585: $result=&get_userresdata($name,$domain);
8586: }
8587: if (!ref($result)) { return $result; }
1.251 albertel 8588: foreach my $item (@which) {
1.927 albertel 8589: if (defined($result->{$item->[0]})) {
8590: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8591: }
1.250 albertel 8592: }
1.291 albertel 8593: return undef;
1.200 www 8594: }
8595:
1.379 matthew 8596: #
8597: # EXT resource caching routines
8598: #
8599:
8600: sub clear_EXT_cache_status {
1.383 albertel 8601: &delenv('cache.EXT.');
1.379 matthew 8602: }
8603:
8604: sub EXT_cache_status {
8605: my ($target_domain,$target_user) = @_;
1.383 albertel 8606: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8607: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8608: # We know already the user has no data
8609: return 1;
8610: } else {
8611: return 0;
8612: }
8613: }
8614:
8615: sub EXT_cache_set {
8616: my ($target_domain,$target_user) = @_;
1.383 albertel 8617: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8618: #&appenv({$cachename => time});
1.379 matthew 8619: }
8620:
1.28 www 8621: # --------------------------------------------------------- Value of a Variable
1.58 www 8622: sub EXT {
1.715 albertel 8623:
1.395 albertel 8624: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8625: unless ($varname) { return ''; }
1.218 albertel 8626: #get real user name/domain, courseid and symb
8627: my $courseid;
1.359 albertel 8628: my $publicuser;
1.427 www 8629: if ($symbparm) {
8630: $symbparm=&get_symb_from_alias($symbparm);
8631: }
1.218 albertel 8632: if (!($uname && $udom)) {
1.790 albertel 8633: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8634: if (!$symbparm) { $symbparm=$cursymb; }
8635: } else {
1.620 albertel 8636: $courseid=$env{'request.course.id'};
1.218 albertel 8637: }
1.48 www 8638: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8639: my $rest;
1.320 albertel 8640: if (defined($therest[0])) {
1.48 www 8641: $rest=join('.',@therest);
8642: } else {
8643: $rest='';
8644: }
1.320 albertel 8645:
1.57 www 8646: my $qualifierrest=$qualifier;
8647: if ($rest) { $qualifierrest.='.'.$rest; }
8648: my $spacequalifierrest=$space;
8649: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8650: if ($realm eq 'user') {
1.48 www 8651: # --------------------------------------------------------------- user.resource
8652: if ($space eq 'resource') {
1.651 albertel 8653: if ( (defined($Apache::lonhomework::parsing_a_problem)
8654: || defined($Apache::lonhomework::parsing_a_task))
8655: &&
1.744 albertel 8656: ($symbparm eq &symbread()) ) {
8657: # if we are in the middle of processing the resource the
8658: # get the value we are planning on committing
8659: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8660: return $Apache::lonhomework::results{$qualifierrest};
8661: } else {
8662: return $Apache::lonhomework::history{$qualifierrest};
8663: }
1.335 albertel 8664: } else {
1.359 albertel 8665: my %restored;
1.620 albertel 8666: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8667: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8668: } else {
8669: %restored=&restore($symbparm,$courseid,$udom,$uname);
8670: }
1.335 albertel 8671: return $restored{$qualifierrest};
8672: }
1.48 www 8673: # ----------------------------------------------------------------- user.access
8674: } elsif ($space eq 'access') {
1.218 albertel 8675: # FIXME - not supporting calls for a specific user
1.48 www 8676: return &allowed($qualifier,$rest);
8677: # ------------------------------------------ user.preferences, user.environment
8678: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8679: if (($uname eq $env{'user.name'}) &&
8680: ($udom eq $env{'user.domain'})) {
8681: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8682: } else {
1.359 albertel 8683: my %returnhash;
8684: if (!$publicuser) {
8685: %returnhash=&userenvironment($udom,$uname,
8686: $qualifierrest);
8687: }
1.218 albertel 8688: return $returnhash{$qualifierrest};
8689: }
1.48 www 8690: # ----------------------------------------------------------------- user.course
8691: } elsif ($space eq 'course') {
1.218 albertel 8692: # FIXME - not supporting calls for a specific user
1.620 albertel 8693: return $env{join('.',('request.course',$qualifier))};
1.48 www 8694: # ------------------------------------------------------------------- user.role
8695: } elsif ($space eq 'role') {
1.218 albertel 8696: # FIXME - not supporting calls for a specific user
1.620 albertel 8697: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8698: if ($qualifier eq 'value') {
8699: return $role;
8700: } elsif ($qualifier eq 'extent') {
8701: return $where;
8702: }
8703: # ----------------------------------------------------------------- user.domain
8704: } elsif ($space eq 'domain') {
1.218 albertel 8705: return $udom;
1.48 www 8706: # ------------------------------------------------------------------- user.name
8707: } elsif ($space eq 'name') {
1.218 albertel 8708: return $uname;
1.48 www 8709: # ---------------------------------------------------- Any other user namespace
1.29 www 8710: } else {
1.359 albertel 8711: my %reply;
8712: if (!$publicuser) {
8713: %reply=&get($space,[$qualifierrest],$udom,$uname);
8714: }
8715: return $reply{$qualifierrest};
1.48 www 8716: }
1.236 www 8717: } elsif ($realm eq 'query') {
8718: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8719: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8720: [$spacequalifierrest]);
1.620 albertel 8721: return $env{'form.'.$spacequalifierrest};
1.236 www 8722: } elsif ($realm eq 'request') {
1.48 www 8723: # ------------------------------------------------------------- request.browser
8724: if ($space eq 'browser') {
1.1145 bisitz 8725: return $env{'browser.'.$qualifier};
1.57 www 8726: # ------------------------------------------------------------ request.filename
8727: } else {
1.620 albertel 8728: return $env{'request.'.$spacequalifierrest};
1.29 www 8729: }
1.28 www 8730: } elsif ($realm eq 'course') {
1.48 www 8731: # ---------------------------------------------------------- course.description
1.620 albertel 8732: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8733: } elsif ($realm eq 'resource') {
1.165 www 8734:
1.620 albertel 8735: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8736: if (!$symbparm) { $symbparm=&symbread(); }
8737: }
1.693 albertel 8738:
8739: if ($space eq 'title') {
8740: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8741: return &gettitle($symbparm);
8742: }
8743:
8744: if ($space eq 'map') {
8745: my ($map) = &decode_symb($symbparm);
8746: return &symbread($map);
8747: }
1.905 albertel 8748: if ($space eq 'filename') {
8749: if ($symbparm) {
8750: return &clutter((&decode_symb($symbparm))[2]);
8751: }
8752: return &hreflocation('',$env{'request.filename'});
8753: }
1.693 albertel 8754:
8755: my ($section, $group, @groups);
1.593 albertel 8756: my ($courselevelm,$courselevel);
1.539 albertel 8757: if ($symbparm && defined($courseid) &&
1.620 albertel 8758: $courseid eq $env{'request.course.id'}) {
1.165 www 8759:
1.218 albertel 8760: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8761:
1.60 www 8762: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8763: my $symbp=$symbparm;
1.735 albertel 8764: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8765:
8766: my $symbparm=$symbp.'.'.$spacequalifierrest;
8767: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8768:
1.620 albertel 8769: if (($env{'user.name'} eq $uname) &&
8770: ($env{'user.domain'} eq $udom)) {
8771: $section=$env{'request.course.sec'};
1.733 raeburn 8772: @groups = split(/:/,$env{'request.course.groups'});
8773: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8774: } else {
1.539 albertel 8775: if (! defined($usection)) {
1.551 albertel 8776: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8777: } else {
8778: $section = $usection;
8779: }
1.733 raeburn 8780: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8781: }
8782:
8783: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8784: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8785: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8786:
1.593 albertel 8787: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8788: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8789: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8790:
1.60 www 8791: # ----------------------------------------------------------- first, check user
1.624 albertel 8792:
8793: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8794: ([$courselevelr,'resource'],
8795: [$courselevelm,'map' ],
8796: [$courselevel, 'course' ]));
1.931 albertel 8797: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8798:
1.594 albertel 8799: # ------------------------------------------------ second, check some of course
1.684 raeburn 8800: my $coursereply;
1.691 raeburn 8801: if (@groups > 0) {
8802: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8803: $mapparm,$spacequalifierrest);
1.927 albertel 8804: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8805: }
1.96 www 8806:
1.684 raeburn 8807: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8808: $env{'course.'.$courseid.'.domain'},
8809: 'course',
8810: ([$seclevelr, 'resource'],
8811: [$seclevelm, 'map' ],
8812: [$seclevel, 'course' ],
8813: [$courselevelr,'resource']));
8814: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8815:
1.60 www 8816: # ------------------------------------------------------ third, check map parms
1.218 albertel 8817: my %parmhash=();
8818: my $thisparm='';
8819: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8820: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8821: &GDBM_READER(),0640)) {
1.218 albertel 8822: $thisparm=$parmhash{$symbparm};
8823: untie(%parmhash);
8824: }
1.927 albertel 8825: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8826: }
1.594 albertel 8827: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8828:
1.218 albertel 8829: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8830: my $filename;
8831: if (!$symbparm) { $symbparm=&symbread(); }
8832: if ($symbparm) {
1.409 www 8833: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8834: } else {
1.620 albertel 8835: $filename=$env{'request.filename'};
1.282 albertel 8836: }
8837: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8838: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8839: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8840: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8841:
1.927 albertel 8842: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8843: if ($symbparm && defined($courseid) &&
1.620 albertel 8844: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8845: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8846: $env{'course.'.$courseid.'.domain'},
8847: 'course',
1.927 albertel 8848: ([$courselevelm,'map' ],
8849: [$courselevel, 'course']));
8850: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8851: }
1.145 www 8852: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8853: unless ($space eq '0') {
1.336 albertel 8854: my @parts=split(/_/,$space);
8855: my $id=pop(@parts);
8856: my $part=join('_',@parts);
8857: if ($part eq '') { $part='0'; }
1.927 albertel 8858: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8859: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8860: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8861: }
1.395 albertel 8862: if ($recurse) { return undef; }
8863: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8864: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8865: # ---------------------------------------------------- Any other user namespace
8866: } elsif ($realm eq 'environment') {
8867: # ----------------------------------------------------------------- environment
1.620 albertel 8868: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8869: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8870: } else {
1.770 albertel 8871: if ($uname eq 'anonymous' && $udom eq '') {
8872: return '';
8873: }
1.219 albertel 8874: my %returnhash=&userenvironment($udom,$uname,
8875: $spacequalifierrest);
8876: return $returnhash{$spacequalifierrest};
8877: }
1.28 www 8878: } elsif ($realm eq 'system') {
1.48 www 8879: # ----------------------------------------------------------------- system.time
8880: if ($space eq 'time') {
8881: return time;
8882: }
1.696 albertel 8883: } elsif ($realm eq 'server') {
8884: # ----------------------------------------------------------------- system.time
8885: if ($space eq 'name') {
8886: return $ENV{'SERVER_NAME'};
8887: }
1.28 www 8888: }
1.48 www 8889: return '';
1.61 www 8890: }
8891:
1.927 albertel 8892: sub get_reply {
8893: my ($reply_value) = @_;
1.940 raeburn 8894: if (ref($reply_value) eq 'ARRAY') {
8895: if (wantarray) {
8896: return @$reply_value;
8897: }
8898: return $reply_value->[0];
8899: } else {
8900: return $reply_value;
1.927 albertel 8901: }
8902: }
8903:
1.691 raeburn 8904: sub check_group_parms {
8905: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8906: my @groupitems = ();
8907: my $resultitem;
1.927 albertel 8908: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8909: foreach my $group (@{$groups}) {
8910: foreach my $level (@levels) {
1.927 albertel 8911: my $item = $courseid.'.['.$group.'].'.$level->[0];
8912: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8913: }
8914: }
8915: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8916: $env{'course.'.$courseid.'.domain'},
8917: 'course',@groupitems);
8918: return $coursereply;
8919: }
8920:
8921: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8922: my ($courseid,@groups) = @_;
8923: @groups = sort(@groups);
1.691 raeburn 8924: return @groups;
8925: }
8926:
1.395 albertel 8927: sub packages_tab_default {
8928: my ($uri,$varname)=@_;
8929: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8930:
8931: my (@extension,@specifics,$do_default);
8932: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8933: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8934: if ($pack_type eq 'default') {
8935: $do_default=1;
8936: } elsif ($pack_type eq 'extension') {
8937: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8938: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8939: # only look at packages defaults for packages that this id is
1.738 albertel 8940: push(@specifics,[$package,$pack_type,$pack_part]);
8941: }
8942: }
8943: # first look for a package that matches the requested part id
8944: foreach my $package (@specifics) {
8945: my (undef,$pack_type,$pack_part)=@{$package};
8946: next if ($pack_part ne $part);
8947: if (defined($packagetab{"$pack_type&$name&default"})) {
8948: return $packagetab{"$pack_type&$name&default"};
8949: }
8950: }
8951: # look for any possible matching non extension_ package
8952: foreach my $package (@specifics) {
8953: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8954: if (defined($packagetab{"$pack_type&$name&default"})) {
8955: return $packagetab{"$pack_type&$name&default"};
8956: }
1.585 albertel 8957: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8958: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8959: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8960: }
8961: }
1.738 albertel 8962: # look for any posible extension_ match
8963: foreach my $package (@extension) {
8964: my ($package,$pack_type)=@{$package};
8965: if (defined($packagetab{"$pack_type&$name&default"})) {
8966: return $packagetab{"$pack_type&$name&default"};
8967: }
8968: if (defined($packagetab{$package."&$name&default"})) {
8969: return $packagetab{$package."&$name&default"};
8970: }
8971: }
8972: # look for a global default setting
8973: if ($do_default && defined($packagetab{"default&$name&default"})) {
8974: return $packagetab{"default&$name&default"};
8975: }
1.395 albertel 8976: return undef;
8977: }
8978:
1.334 albertel 8979: sub add_prefix_and_part {
8980: my ($prefix,$part)=@_;
8981: my $keyroot;
8982: if (defined($prefix) && $prefix !~ /^__/) {
8983: # prefix that has a part already
8984: $keyroot=$prefix;
8985: } elsif (defined($prefix)) {
8986: # prefix that is missing a part
8987: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8988: } else {
8989: # no prefix at all
8990: if (defined($part)) { $keyroot='_'.$part; }
8991: }
8992: return $keyroot;
8993: }
8994:
1.71 www 8995: # ---------------------------------------------------------------- Get metadata
8996:
1.599 albertel 8997: my %metaentry;
1.1070 www 8998: my %importedpartids;
1.71 www 8999: sub metadata {
1.176 www 9000: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 9001: $uri=&declutter($uri);
1.288 albertel 9002: # if it is a non metadata possible uri return quickly
1.529 albertel 9003: if (($uri eq '') ||
9004: (($uri =~ m|^/*adm/|) &&
1.698 albertel 9005: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108 raeburn 9006: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 9007: return undef;
9008: }
1.1140 www 9009: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 9010: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 9011: return undef;
1.288 albertel 9012: }
1.73 www 9013: my $filename=$uri;
9014: $uri=~s/\.meta$//;
1.172 www 9015: #
9016: # Is the metadata already cached?
1.177 www 9017: # Look at timestamp of caching
1.172 www 9018: # Everything is cached by the main uri, libraries are never directly cached
9019: #
1.428 albertel 9020: if (!defined($liburi)) {
1.599 albertel 9021: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 9022: if (defined($cached)) { return $result->{':'.$what}; }
9023: }
9024: {
1.1069 www 9025: # Imported parts would go here
1.1070 www 9026: my %importedids=();
9027: my @origfileimportpartids=();
1.1069 www 9028: my $importedparts=0;
1.172 www 9029: #
9030: # Is this a recursive call for a library?
9031: #
1.599 albertel 9032: # if (! exists($metacache{$uri})) {
9033: # $metacache{$uri}={};
9034: # }
1.924 albertel 9035: my $cachetime = 60*60;
1.171 www 9036: if ($liburi) {
9037: $liburi=&declutter($liburi);
9038: $filename=$liburi;
1.401 bowersj2 9039: } else {
1.599 albertel 9040: &devalidate_cache_new('meta',$uri);
9041: undef(%metaentry);
1.401 bowersj2 9042: }
1.140 www 9043: my %metathesekeys=();
1.73 www 9044: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 9045: my $metastring;
1.1140 www 9046: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 9047: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 9048: $metastring =
1.929 albertel 9049: &Apache::lonnet::ssi_body($which,
1.924 albertel 9050: ('grade_target' => 'meta'));
9051: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 9052: } elsif (($uri !~ m -^(editupload)/-) &&
9053: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 9054: my $file=&filelocation('',&clutter($filename));
1.599 albertel 9055: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 9056: $metastring=&getfile($file);
1.489 albertel 9057: }
1.208 albertel 9058: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 9059: my $token;
1.140 www 9060: undef %metathesekeys;
1.71 www 9061: while ($token=$parser->get_token) {
1.339 albertel 9062: if ($token->[0] eq 'S') {
9063: if (defined($token->[2]->{'package'})) {
1.172 www 9064: #
9065: # This is a package - get package info
9066: #
1.339 albertel 9067: my $package=$token->[2]->{'package'};
9068: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9069: if (defined($token->[2]->{'id'})) {
9070: $keyroot.='_'.$token->[2]->{'id'};
9071: }
1.599 albertel 9072: if ($metaentry{':packages'}) {
9073: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 9074: } else {
1.599 albertel 9075: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 9076: }
1.736 albertel 9077: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 9078: my $part=$keyroot;
9079: $part=~s/^\_//;
1.736 albertel 9080: if ($pack_entry=~/^\Q$package\E\&/ ||
9081: $pack_entry=~/^\Q$package\E_0\&/) {
9082: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 9083: # ignore package.tab specified default values
9084: # here &package_tab_default() will fetch those
9085: if ($subp eq 'default') { next; }
1.736 albertel 9086: my $value=$packagetab{$pack_entry};
1.432 albertel 9087: my $unikey;
9088: if ($pack =~ /_0$/) {
9089: $unikey='parameter_0_'.$name;
9090: $part=0;
9091: } else {
9092: $unikey='parameter'.$keyroot.'_'.$name;
9093: }
1.339 albertel 9094: if ($subp eq 'display') {
9095: $value.=' [Part: '.$part.']';
9096: }
1.599 albertel 9097: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 9098: $metathesekeys{$unikey}=1;
1.599 albertel 9099: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9100: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 9101: }
1.599 albertel 9102: if (defined($metaentry{':'.$unikey.'.default'})) {
9103: $metaentry{':'.$unikey}=
9104: $metaentry{':'.$unikey.'.default'};
1.356 albertel 9105: }
1.339 albertel 9106: }
9107: }
9108: } else {
1.172 www 9109: #
9110: # This is not a package - some other kind of start tag
1.339 albertel 9111: #
9112: my $entry=$token->[1];
1.1068 www 9113: my $unikey='';
1.175 www 9114:
1.339 albertel 9115: if ($entry eq 'import') {
1.175 www 9116: #
9117: # Importing a library here
1.339 albertel 9118: #
1.1067 www 9119: my $location=$parser->get_text('/import');
9120: my $dir=$filename;
9121: $dir=~s|[^/]*$||;
9122: $location=&filelocation($dir,$location);
1.1069 www 9123:
1.1068 www 9124: my $importmode=$token->[2]->{'importmode'};
9125: if ($importmode eq 'problem') {
1.1069 www 9126: # Import as problem/response
1.1068 www 9127: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9128: } elsif ($importmode eq 'part') {
9129: # Import as part(s)
1.1069 www 9130: $importedparts=1;
9131: # We need to get the original file and the imported file to get the part order correct
9132: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9133: # Load and inspect original file
1.1070 www 9134: if ($#origfileimportpartids<0) {
9135: undef(%importedpartids);
9136: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9137: my $origfile=&getfile($origfilelocation);
9138: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9139: }
9140:
1.1069 www 9141: # Load and inspect imported file
9142: my $impfile=&getfile($location);
9143: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9144: if ($#impfilepartids>=0) {
9145: # This problem had parts
1.1070 www 9146: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 9147: } else {
9148: # Importing by turning a single problem into a problem part
9149: # It gets the import-tags ID as part-ID
9150: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 9151: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 9152: }
1.1068 www 9153: } else {
9154: # Normal import
9155: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9156: if (defined($token->[2]->{'id'})) {
9157: $unikey.='_'.$token->[2]->{'id'};
9158: }
1.1067 www 9159: }
9160:
1.339 albertel 9161: if ($depthcount<20) {
1.736 albertel 9162: my $metadata =
9163: &metadata($uri,'keys', $location,$unikey,
9164: $depthcount+1);
9165: foreach my $meta (split(',',$metadata)) {
9166: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9167: $metathesekeys{$meta}=1;
1.339 albertel 9168: }
1.1068 www 9169:
9170: }
1.1067 www 9171: } else {
9172: #
9173: # Not importing, some other kind of non-package, non-library start tag
9174: #
9175: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9176: if (defined($token->[2]->{'id'})) {
9177: $unikey.='_'.$token->[2]->{'id'};
9178: }
1.339 albertel 9179: if (defined($token->[2]->{'name'})) {
9180: $unikey.='_'.$token->[2]->{'name'};
9181: }
9182: $metathesekeys{$unikey}=1;
1.736 albertel 9183: foreach my $param (@{$token->[3]}) {
9184: $metaentry{':'.$unikey.'.'.$param} =
9185: $token->[2]->{$param};
1.339 albertel 9186: }
9187: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 9188: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 9189: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9190: # only ws inside the tag, and not in default, so use default
9191: # as value
1.599 albertel 9192: $metaentry{':'.$unikey}=$default;
1.908 albertel 9193: } elsif ( $internaltext =~ /\S/ ) {
9194: # something interesting inside the tag
9195: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 9196: } else {
1.908 albertel 9197: # no interesting values, don't set a default
1.339 albertel 9198: }
1.172 www 9199: # end of not-a-package not-a-library import
1.339 albertel 9200: }
1.172 www 9201: # end of not-a-package start tag
1.339 albertel 9202: }
1.172 www 9203: # the next is the end of "start tag"
1.339 albertel 9204: }
9205: }
1.483 albertel 9206: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 9207: $extension = lc($extension);
9208: if ($extension eq 'htm') { $extension='html'; }
9209:
1.737 albertel 9210: foreach my $key (keys(%packagetab)) {
1.483 albertel 9211: #no specific packages #how's our extension
9212: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 9213: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 9214: \%metathesekeys);
9215: }
1.883 albertel 9216:
9217: if (!exists($metaentry{':packages'})
9218: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 9219: foreach my $key (keys(%packagetab)) {
1.483 albertel 9220: #no specific packages well let's get default then
9221: if ($key!~/^default&/) { next; }
1.488 albertel 9222: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 9223: \%metathesekeys);
9224: }
9225: }
1.338 www 9226: # are there custom rights to evaluate
1.599 albertel 9227: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 9228:
1.338 www 9229: #
9230: # Importing a rights file here
1.339 albertel 9231: #
9232: unless ($depthcount) {
1.599 albertel 9233: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 9234: my $dir=$filename;
9235: $dir=~s|[^/]*$||;
9236: $location=&filelocation($dir,$location);
1.736 albertel 9237: my $rights_metadata =
9238: &metadata($uri,'keys',$location,'_rights',
9239: $depthcount+1);
9240: foreach my $rights (split(',',$rights_metadata)) {
9241: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9242: $metathesekeys{$rights}=1;
1.339 albertel 9243: }
9244: }
9245: }
1.737 albertel 9246: # uniqifiy package listing
9247: my %seen;
9248: my @uniq_packages =
9249: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9250: $metaentry{':packages'} = join(',',@uniq_packages);
9251:
1.1070 www 9252: if ($importedparts) {
9253: # We had imported parts and need to rebuild partorder
9254: $metaentry{':partorder'}='';
9255: $metathesekeys{'partorder'}=1;
9256: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9257: if ($origfileimportpartids[$index] eq 'part') {
9258: # original part, part of the problem
9259: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9260: } else {
9261: # we have imported parts at this position
9262: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9263: }
9264: }
9265: $metaentry{':partorder'}=~s/^\,//;
9266: }
9267:
1.737 albertel 9268: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 9269: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9270: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 9271: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 9272: # this is the end of "was not already recently cached
1.71 www 9273: }
1.599 albertel 9274: return $metaentry{':'.$what};
1.261 albertel 9275: }
9276:
1.488 albertel 9277: sub metadata_create_package_def {
1.483 albertel 9278: my ($uri,$key,$package,$metathesekeys)=@_;
9279: my ($pack,$name,$subp)=split(/\&/,$key);
9280: if ($subp eq 'default') { next; }
9281:
1.599 albertel 9282: if (defined($metaentry{':packages'})) {
9283: $metaentry{':packages'}.=','.$package;
1.483 albertel 9284: } else {
1.599 albertel 9285: $metaentry{':packages'}=$package;
1.483 albertel 9286: }
9287: my $value=$packagetab{$key};
9288: my $unikey;
9289: $unikey='parameter_0_'.$name;
1.599 albertel 9290: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 9291: $$metathesekeys{$unikey}=1;
1.599 albertel 9292: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9293: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 9294: }
1.599 albertel 9295: if (defined($metaentry{':'.$unikey.'.default'})) {
9296: $metaentry{':'.$unikey}=
9297: $metaentry{':'.$unikey.'.default'};
1.483 albertel 9298: }
9299: }
9300:
1.261 albertel 9301: sub metadata_generate_part0 {
9302: my ($metadata,$metacache,$uri) = @_;
9303: my %allnames;
1.737 albertel 9304: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 9305: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 9306: my $part=$$metacache{':'.$metakey.'.part'};
9307: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 9308: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 9309: $allnames{$name}=$part;
9310: }
9311: }
9312: }
9313: foreach my $name (keys(%allnames)) {
9314: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 9315: my $key=":parameter_0_$name";
1.261 albertel 9316: $$metacache{"$key.part"}='0';
9317: $$metacache{"$key.name"}=$name;
1.428 albertel 9318: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 9319: $allnames{$name}.'_'.$name.
9320: '.type'};
1.428 albertel 9321: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 9322: '.display'};
1.644 www 9323: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 9324: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 9325: $$metacache{"$key.display"}=$olddis;
9326: }
1.71 www 9327: }
9328:
1.764 albertel 9329: # ------------------------------------------------------ Devalidate title cache
9330:
9331: sub devalidate_title_cache {
9332: my ($url)=@_;
9333: if (!$env{'request.course.id'}) { return; }
9334: my $symb=&symbread($url);
9335: if (!$symb) { return; }
9336: my $key=$env{'request.course.id'}."\0".$symb;
9337: &devalidate_cache_new('title',$key);
9338: }
9339:
1.1014 droeschl 9340: # ------------------------------------------------- Get the title of a course
9341:
9342: sub current_course_title {
9343: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9344: }
1.301 www 9345: # ------------------------------------------------- Get the title of a resource
9346:
9347: sub gettitle {
9348: my $urlsymb=shift;
9349: my $symb=&symbread($urlsymb);
1.534 albertel 9350: if ($symb) {
1.620 albertel 9351: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 9352: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 9353: if (defined($cached)) {
9354: return $result;
9355: }
1.534 albertel 9356: my ($map,$resid,$url)=&decode_symb($symb);
9357: my $title='';
1.907 albertel 9358: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9359: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9360: } else {
9361: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9362: &GDBM_READER(),0640)) {
9363: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9364: $title=$bighash{'title_'.$mapid.'.'.$resid};
9365: untie(%bighash);
9366: }
1.534 albertel 9367: }
9368: $title=~s/\&colon\;/\:/gs;
9369: if ($title) {
1.599 albertel 9370: return &do_cache_new('title',$key,$title,600);
1.534 albertel 9371: }
9372: $urlsymb=$url;
9373: }
9374: my $title=&metadata($urlsymb,'title');
9375: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9376: return $title;
1.301 www 9377: }
1.613 albertel 9378:
1.614 albertel 9379: sub get_slot {
9380: my ($which,$cnum,$cdom)=@_;
9381: if (!$cnum || !$cdom) {
1.790 albertel 9382: (undef,my $courseid)=&whichuser();
1.620 albertel 9383: $cdom=$env{'course.'.$courseid.'.domain'};
9384: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 9385: }
1.703 albertel 9386: my $key=join("\0",'slots',$cdom,$cnum,$which);
9387: my %slotinfo;
9388: if (exists($remembered{$key})) {
9389: $slotinfo{$which} = $remembered{$key};
9390: } else {
9391: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9392: &Apache::lonhomework::showhash(%slotinfo);
9393: my ($tmp)=keys(%slotinfo);
9394: if ($tmp=~/^error:/) { return (); }
9395: $remembered{$key} = $slotinfo{$which};
9396: }
1.616 albertel 9397: if (ref($slotinfo{$which}) eq 'HASH') {
9398: return %{$slotinfo{$which}};
9399: }
9400: return $slotinfo{$which};
1.614 albertel 9401: }
1.31 www 9402: # ------------------------------------------------- Update symbolic store links
9403:
9404: sub symblist {
9405: my ($mapname,%newhash)=@_;
1.438 www 9406: $mapname=&deversion(&declutter($mapname));
1.31 www 9407: my %hash;
1.620 albertel 9408: if (($env{'request.course.fn'}) && (%newhash)) {
9409: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9410: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 9411: foreach my $url (keys(%newhash)) {
1.711 albertel 9412: next if ($url eq 'last_known'
9413: && $env{'form.no_update_last_known'});
9414: $hash{declutter($url)}=&encode_symb($mapname,
9415: $newhash{$url}->[1],
9416: $newhash{$url}->[0]);
1.191 harris41 9417: }
1.31 www 9418: if (untie(%hash)) {
9419: return 'ok';
9420: }
9421: }
9422: }
9423: return 'error';
1.212 www 9424: }
9425:
9426: # --------------------------------------------------------------- Verify a symb
9427:
9428: sub symbverify {
1.510 www 9429: my ($symb,$thisurl)=@_;
9430: my $thisfn=$thisurl;
1.439 www 9431: $thisfn=&declutter($thisfn);
1.215 www 9432: # direct jump to resource in page or to a sequence - will construct own symbs
9433: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9434: # check URL part
1.409 www 9435: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 9436:
1.431 www 9437: unless ($url eq $thisfn) { return 0; }
1.213 www 9438:
1.216 www 9439: $symb=&symbclean($symb);
1.510 www 9440: $thisurl=&deversion($thisurl);
1.439 www 9441: $thisfn=&deversion($thisfn);
1.213 www 9442:
9443: my %bighash;
9444: my $okay=0;
1.431 www 9445:
1.620 albertel 9446: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9447: &GDBM_READER(),0640)) {
1.1032 raeburn 9448: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9449: $thisurl =~ s/\?.+$//;
9450: }
1.510 www 9451: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102 raeburn 9452: unless ($ids) {
9453: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9454: $ids=$bighash{$idkey};
1.216 www 9455: }
9456: if ($ids) {
9457: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 9458: foreach my $id (split(/\,/,$ids)) {
9459: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 9460: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9461: $symb =~ s/\?.+$//;
9462: }
1.216 www 9463: if (
9464: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9465: eq $symb) {
1.620 albertel 9466: if (($env{'request.role.adv'}) ||
1.1101 raeburn 9467: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9468: ($thisurl eq '/adm/navmaps')) {
1.582 albertel 9469: $okay=1;
9470: }
9471: }
1.216 www 9472: }
9473: }
1.213 www 9474: untie(%bighash);
9475: }
9476: return $okay;
1.31 www 9477: }
9478:
1.210 www 9479: # --------------------------------------------------------------- Clean-up symb
9480:
9481: sub symbclean {
9482: my $symb=shift;
1.568 albertel 9483: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 9484: # remove version from map
9485: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 9486:
1.210 www 9487: # remove version from URL
9488: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 9489:
1.507 www 9490: # remove wrapper
9491:
1.510 www 9492: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 9493: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 9494: return $symb;
1.409 www 9495: }
9496:
9497: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 9498:
9499: sub encode_symb {
9500: my ($map,$resid,$url)=@_;
9501: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9502: }
1.409 www 9503:
9504: sub decode_symb {
1.568 albertel 9505: my $symb=shift;
9506: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9507: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 9508: return (&fixversion($map),$resid,&fixversion($url));
9509: }
9510:
9511: sub fixversion {
9512: my $fn=shift;
1.609 banghart 9513: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 9514: my %bighash;
9515: my $uri=&clutter($fn);
1.620 albertel 9516: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 9517: # is this cached?
1.599 albertel 9518: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 9519: if (defined($cached)) { return $result; }
9520: # unfortunately not cached, or expired
1.620 albertel 9521: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 9522: &GDBM_READER(),0640)) {
9523: if ($bighash{'version_'.$uri}) {
9524: my $version=$bighash{'version_'.$uri};
1.444 www 9525: unless (($version eq 'mostrecent') ||
9526: ($version==&getversion($uri))) {
1.440 www 9527: $uri=~s/\.(\w+)$/\.$version\.$1/;
9528: }
9529: }
9530: untie %bighash;
1.413 www 9531: }
1.599 albertel 9532: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 9533: }
9534:
9535: sub deversion {
9536: my $url=shift;
9537: $url=~s/\.\d+\.(\w+)$/\.$1/;
9538: return $url;
1.210 www 9539: }
9540:
1.31 www 9541: # ------------------------------------------------------ Return symb list entry
9542:
9543: sub symbread {
1.249 www 9544: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 9545: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 9546: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 9547: # no filename provided? try from environment
1.44 www 9548: unless ($thisfn) {
1.620 albertel 9549: if ($env{'request.symb'}) {
9550: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 9551: }
1.620 albertel 9552: $thisfn=$env{'request.filename'};
1.44 www 9553: }
1.569 albertel 9554: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 9555: # is that filename actually a symb? Verify, clean, and return
9556: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 9557: if (&symbverify($thisfn,$1)) {
1.620 albertel 9558: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 9559: }
1.242 www 9560: }
1.44 www 9561: $thisfn=declutter($thisfn);
1.31 www 9562: my %hash;
1.37 www 9563: my %bighash;
9564: my $syval='';
1.620 albertel 9565: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 9566: my $targetfn = $thisfn;
1.609 banghart 9567: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 9568: $targetfn = 'adm/wrapper/'.$thisfn;
9569: }
1.687 albertel 9570: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9571: $targetfn=$1;
9572: }
1.620 albertel 9573: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9574: &GDBM_READER(),0640)) {
1.481 raeburn 9575: $syval=$hash{$targetfn};
1.37 www 9576: untie(%hash);
9577: }
9578: # ---------------------------------------------------------- There was an entry
9579: if ($syval) {
1.601 albertel 9580: #unless ($syval=~/\_\d+$/) {
1.620 albertel 9581: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 9582: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9583: #return $env{$cache_str}='';
1.601 albertel 9584: #}
9585: #$syval.=$1;
9586: #}
1.37 www 9587: } else {
9588: # ------------------------------------------------------- Was not in symb table
1.620 albertel 9589: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9590: &GDBM_READER(),0640)) {
1.37 www 9591: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 9592: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 9593: unless ($ids) {
9594: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 9595: }
9596: unless ($ids) {
9597: # alias?
9598: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 9599: }
1.37 www 9600: if ($ids) {
9601: # ------------------------------------------------------------------- Has ID(s)
9602: my @possibilities=split(/\,/,$ids);
1.39 www 9603: if ($#possibilities==0) {
9604: # ----------------------------------------------- There is only one possibility
1.37 www 9605: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 9606: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9607: $resid,$thisfn);
1.249 www 9608: } elsif (!$donotrecurse) {
1.39 www 9609: # ------------------------------------------ There is more than one possibility
9610: my $realpossible=0;
1.800 albertel 9611: foreach my $id (@possibilities) {
9612: my $file=$bighash{'src_'.$id};
1.39 www 9613: if (&allowed('bre',$file)) {
1.800 albertel 9614: my ($mapid,$resid)=split(/\./,$id);
1.39 www 9615: if ($bighash{'map_type_'.$mapid} ne 'page') {
9616: $realpossible++;
1.626 albertel 9617: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9618: $resid,$thisfn);
1.39 www 9619: }
9620: }
1.191 harris41 9621: }
1.39 www 9622: if ($realpossible!=1) { $syval=''; }
1.249 www 9623: } else {
9624: $syval='';
1.37 www 9625: }
9626: }
9627: untie(%bighash)
1.481 raeburn 9628: }
1.31 www 9629: }
1.62 www 9630: if ($syval) {
1.620 albertel 9631: return $env{$cache_str}=$syval;
1.62 www 9632: }
1.31 www 9633: }
1.949 raeburn 9634: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9635: return $env{$cache_str}='';
1.31 www 9636: }
9637:
9638: # ---------------------------------------------------------- Return random seed
9639:
1.32 www 9640: sub numval {
9641: my $txt=shift;
9642: $txt=~tr/A-J/0-9/;
9643: $txt=~tr/a-j/0-9/;
9644: $txt=~tr/K-T/0-9/;
9645: $txt=~tr/k-t/0-9/;
9646: $txt=~tr/U-Z/0-5/;
9647: $txt=~tr/u-z/0-5/;
9648: $txt=~s/\D//g;
1.564 albertel 9649: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 9650: return int($txt);
1.368 albertel 9651: }
9652:
1.484 albertel 9653: sub numval2 {
9654: my $txt=shift;
9655: $txt=~tr/A-J/0-9/;
9656: $txt=~tr/a-j/0-9/;
9657: $txt=~tr/K-T/0-9/;
9658: $txt=~tr/k-t/0-9/;
9659: $txt=~tr/U-Z/0-5/;
9660: $txt=~tr/u-z/0-5/;
9661: $txt=~s/\D//g;
9662: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9663: my $total;
9664: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9665: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9666: return int($total);
9667: }
9668:
1.575 albertel 9669: sub numval3 {
9670: use integer;
9671: my $txt=shift;
9672: $txt=~tr/A-J/0-9/;
9673: $txt=~tr/a-j/0-9/;
9674: $txt=~tr/K-T/0-9/;
9675: $txt=~tr/k-t/0-9/;
9676: $txt=~tr/U-Z/0-5/;
9677: $txt=~tr/u-z/0-5/;
9678: $txt=~s/\D//g;
9679: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9680: my $total;
9681: foreach my $val (@txts) { $total+=$val; }
9682: if ($_64bit) { $total=(($total<<32)>>32); }
9683: return $total;
9684: }
9685:
1.675 albertel 9686: sub digest {
9687: my ($data)=@_;
9688: my $digest=&Digest::MD5::md5($data);
9689: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9690: my ($e,$f);
9691: {
9692: use integer;
9693: $e=($a+$b);
9694: $f=($c+$d);
9695: if ($_64bit) {
9696: $e=(($e<<32)>>32);
9697: $f=(($f<<32)>>32);
9698: }
9699: }
9700: if (wantarray) {
9701: return ($e,$f);
9702: } else {
9703: my $g;
9704: {
9705: use integer;
9706: $g=($e+$f);
9707: if ($_64bit) {
9708: $g=(($g<<32)>>32);
9709: }
9710: }
9711: return $g;
9712: }
9713: }
9714:
1.368 albertel 9715: sub latest_rnd_algorithm_id {
1.675 albertel 9716: return '64bit5';
1.366 albertel 9717: }
1.32 www 9718:
1.503 albertel 9719: sub get_rand_alg {
9720: my ($courseid)=@_;
1.790 albertel 9721: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9722: if ($courseid) {
1.620 albertel 9723: return $env{"course.$courseid.rndseed"};
1.503 albertel 9724: }
9725: return &latest_rnd_algorithm_id();
9726: }
9727:
1.562 albertel 9728: sub validCODE {
9729: my ($CODE)=@_;
9730: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9731: return 0;
9732: }
9733:
1.491 albertel 9734: sub getCODE {
1.620 albertel 9735: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9736: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9737: defined($Apache::lonhomework::parsing_a_task) ) &&
9738: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9739: return $Apache::lonhomework::history{'resource.CODE'};
9740: }
9741: return undef;
9742: }
1.1133 foxr 9743: #
9744: # Determines the random seed for a specific context:
9745: #
9746: # parameters:
9747: # symb - in course context the symb for the seed.
9748: # course_id - The course id of the form domain_coursenum.
9749: # domain - Domain for the user.
9750: # course - Course for the user.
9751: # cenv - environment of the course.
9752: #
9753: # NOTE:
9754: # All parameters are picked out of the environment if missing
9755: # or not defined.
9756: # If a symb cannot be determined the current time is used instead.
9757: #
9758: # For a given well defined symb, courside, domain, username,
9759: # and course environment, the seed is reproducible.
9760: #
1.31 www 9761: sub rndseed {
1.1133 foxr 9762: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 9763: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9764: if (!defined($symb)) {
1.366 albertel 9765: unless ($symb=$wsymb) { return time; }
9766: }
1.1146 foxr 9767: if (!defined $courseid) {
9768: $courseid=$wcourseid;
9769: }
9770: if (!defined $domain) { $domain=$wdomain; }
9771: if (!defined $username) { $username=$wusername }
1.1133 foxr 9772:
9773: my $which;
9774: if (defined($cenv->{'rndseed'})) {
9775: $which = $cenv->{'rndseed'};
9776: } else {
9777: $which =&get_rand_alg($courseid);
9778: }
1.491 albertel 9779: if (defined(&getCODE())) {
1.1133 foxr 9780:
1.675 albertel 9781: if ($which eq '64bit5') {
9782: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9783: } elsif ($which eq '64bit4') {
1.575 albertel 9784: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9785: } else {
9786: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9787: }
1.675 albertel 9788: } elsif ($which eq '64bit5') {
9789: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9790: } elsif ($which eq '64bit4') {
9791: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9792: } elsif ($which eq '64bit3') {
9793: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9794: } elsif ($which eq '64bit2') {
9795: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9796: } elsif ($which eq '64bit') {
9797: return &rndseed_64bit($symb,$courseid,$domain,$username);
9798: }
9799: return &rndseed_32bit($symb,$courseid,$domain,$username);
9800: }
9801:
9802: sub rndseed_32bit {
9803: my ($symb,$courseid,$domain,$username)=@_;
9804: {
9805: use integer;
9806: my $symbchck=unpack("%32C*",$symb) << 27;
9807: my $symbseed=numval($symb) << 22;
9808: my $namechck=unpack("%32C*",$username) << 17;
9809: my $nameseed=numval($username) << 12;
9810: my $domainseed=unpack("%32C*",$domain) << 7;
9811: my $courseseed=unpack("%32C*",$courseid);
9812: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9813: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9814: #&logthis("rndseed :$num:$symb");
1.564 albertel 9815: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9816: return $num;
9817: }
9818: }
9819:
9820: sub rndseed_64bit {
9821: my ($symb,$courseid,$domain,$username)=@_;
9822: {
9823: use integer;
9824: my $symbchck=unpack("%32S*",$symb) << 21;
9825: my $symbseed=numval($symb) << 10;
9826: my $namechck=unpack("%32S*",$username);
9827:
9828: my $nameseed=numval($username) << 21;
9829: my $domainseed=unpack("%32S*",$domain) << 10;
9830: my $courseseed=unpack("%32S*",$courseid);
9831:
9832: my $num1=$symbchck+$symbseed+$namechck;
9833: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9834: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9835: #&logthis("rndseed :$num:$symb");
1.564 albertel 9836: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9837: return "$num1,$num2";
1.155 albertel 9838: }
1.366 albertel 9839: }
9840:
1.443 albertel 9841: sub rndseed_64bit2 {
9842: my ($symb,$courseid,$domain,$username)=@_;
9843: {
9844: use integer;
9845: # strings need to be an even # of cahracters long, it it is odd the
9846: # last characters gets thrown away
9847: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9848: my $symbseed=numval($symb) << 10;
9849: my $namechck=unpack("%32S*",$username.' ');
9850:
9851: my $nameseed=numval($username) << 21;
1.501 albertel 9852: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9853: my $courseseed=unpack("%32S*",$courseid.' ');
9854:
9855: my $num1=$symbchck+$symbseed+$namechck;
9856: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9857: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9858: #&logthis("rndseed :$num:$symb");
1.803 albertel 9859: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9860: return "$num1,$num2";
9861: }
9862: }
9863:
9864: sub rndseed_64bit3 {
9865: my ($symb,$courseid,$domain,$username)=@_;
9866: {
9867: use integer;
9868: # strings need to be an even # of cahracters long, it it is odd the
9869: # last characters gets thrown away
9870: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9871: my $symbseed=numval2($symb) << 10;
9872: my $namechck=unpack("%32S*",$username.' ');
9873:
9874: my $nameseed=numval2($username) << 21;
1.443 albertel 9875: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9876: my $courseseed=unpack("%32S*",$courseid.' ');
9877:
9878: my $num1=$symbchck+$symbseed+$namechck;
9879: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9880: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9881: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9882: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 9883:
1.503 albertel 9884: return "$num1:$num2";
1.443 albertel 9885: }
9886: }
9887:
1.575 albertel 9888: sub rndseed_64bit4 {
9889: my ($symb,$courseid,$domain,$username)=@_;
9890: {
9891: use integer;
9892: # strings need to be an even # of cahracters long, it it is odd the
9893: # last characters gets thrown away
9894: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9895: my $symbseed=numval3($symb) << 10;
9896: my $namechck=unpack("%32S*",$username.' ');
9897:
9898: my $nameseed=numval3($username) << 21;
9899: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9900: my $courseseed=unpack("%32S*",$courseid.' ');
9901:
9902: my $num1=$symbchck+$symbseed+$namechck;
9903: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9904: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9905: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9906: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 9907:
1.575 albertel 9908: return "$num1:$num2";
9909: }
9910: }
9911:
1.675 albertel 9912: sub rndseed_64bit5 {
9913: my ($symb,$courseid,$domain,$username)=@_;
9914: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9915: return "$num1:$num2";
9916: }
9917:
1.366 albertel 9918: sub rndseed_CODE_64bit {
9919: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9920: {
1.366 albertel 9921: use integer;
1.443 albertel 9922: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9923: my $symbseed=numval2($symb);
1.491 albertel 9924: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9925: my $CODEseed=numval(&getCODE());
1.443 albertel 9926: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9927: my $num1=$symbseed+$CODEchck;
9928: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9929: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9930: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9931: if ($_64bit) { $num1=(($num1<<32)>>32); }
9932: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9933: return "$num1:$num2";
1.366 albertel 9934: }
9935: }
9936:
1.575 albertel 9937: sub rndseed_CODE_64bit4 {
9938: my ($symb,$courseid,$domain,$username)=@_;
9939: {
9940: use integer;
9941: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9942: my $symbseed=numval3($symb);
9943: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9944: my $CODEseed=numval3(&getCODE());
9945: my $courseseed=unpack("%32S*",$courseid.' ');
9946: my $num1=$symbseed+$CODEchck;
9947: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9948: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9949: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9950: if ($_64bit) { $num1=(($num1<<32)>>32); }
9951: if ($_64bit) { $num2=(($num2<<32)>>32); }
9952: return "$num1:$num2";
9953: }
9954: }
9955:
1.675 albertel 9956: sub rndseed_CODE_64bit5 {
9957: my ($symb,$courseid,$domain,$username)=@_;
9958: my $code = &getCODE();
9959: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9960: return "$num1:$num2";
9961: }
9962:
1.366 albertel 9963: sub setup_random_from_rndseed {
9964: my ($rndseed)=@_;
1.503 albertel 9965: if ($rndseed =~/([,:])/) {
9966: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9967: &Math::Random::random_set_seed(abs($num1),abs($num2));
9968: } else {
9969: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9970: }
1.36 albertel 9971: }
9972:
1.474 albertel 9973: sub latest_receipt_algorithm_id {
1.835 albertel 9974: return 'receipt3';
1.474 albertel 9975: }
9976:
1.480 www 9977: sub recunique {
9978: my $fucourseid=shift;
9979: my $unique;
1.835 albertel 9980: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9981: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9982: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9983: } else {
9984: $unique=$perlvar{'lonReceipt'};
9985: }
9986: return unpack("%32C*",$unique);
9987: }
9988:
9989: sub recprefix {
9990: my $fucourseid=shift;
9991: my $prefix;
1.835 albertel 9992: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9993: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9994: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9995: } else {
9996: $prefix=$perlvar{'lonHostID'};
9997: }
9998: return unpack("%32C*",$prefix);
9999: }
10000:
1.76 www 10001: sub ireceipt {
1.474 albertel 10002: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 10003:
10004: my $return =&recprefix($fucourseid).'-';
10005:
10006: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10007: $env{'request.state'} eq 'construct') {
10008: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10009: return $return;
10010: }
10011:
1.76 www 10012: my $cuname=unpack("%32C*",$funame);
10013: my $cudom=unpack("%32C*",$fudom);
10014: my $cucourseid=unpack("%32C*",$fucourseid);
10015: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 10016: my $cunique=&recunique($fucourseid);
1.474 albertel 10017: my $cpart=unpack("%32S*",$part);
1.835 albertel 10018: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10019:
1.790 albertel 10020: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 10021:
10022: $return.= ($cunique%$cuname+
10023: $cunique%$cudom+
10024: $cusymb%$cuname+
10025: $cusymb%$cudom+
10026: $cucourseid%$cuname+
10027: $cucourseid%$cudom+
10028: $cpart%$cuname+
10029: $cpart%$cudom);
10030: } else {
10031: $return.= ($cunique%$cuname+
10032: $cunique%$cudom+
10033: $cusymb%$cuname+
10034: $cusymb%$cudom+
10035: $cucourseid%$cuname+
10036: $cucourseid%$cudom);
10037: }
10038: return $return;
1.76 www 10039: }
10040:
10041: sub receipt {
1.474 albertel 10042: my ($part)=@_;
1.790 albertel 10043: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 10044: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 10045: }
1.260 ng 10046:
1.790 albertel 10047: sub whichuser {
10048: my ($passedsymb)=@_;
10049: my ($symb,$courseid,$domain,$name,$publicuser);
10050: if (defined($env{'form.grade_symb'})) {
10051: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10052: my $allowed=&allowed('vgr',$tmp_courseid);
10053: if (!$allowed &&
10054: exists($env{'request.course.sec'}) &&
10055: $env{'request.course.sec'} !~ /^\s*$/) {
10056: $allowed=&allowed('vgr',$tmp_courseid.
10057: '/'.$env{'request.course.sec'});
10058: }
10059: if ($allowed) {
10060: ($symb)=&get_env_multiple('form.grade_symb');
10061: $courseid=$tmp_courseid;
10062: ($domain)=&get_env_multiple('form.grade_domain');
10063: ($name)=&get_env_multiple('form.grade_username');
10064: return ($symb,$courseid,$domain,$name,$publicuser);
10065: }
10066: }
10067: if (!$passedsymb) {
10068: $symb=&symbread();
10069: } else {
10070: $symb=$passedsymb;
10071: }
10072: $courseid=$env{'request.course.id'};
10073: $domain=$env{'user.domain'};
10074: $name=$env{'user.name'};
10075: if ($name eq 'public' && $domain eq 'public') {
10076: if (!defined($env{'form.username'})) {
10077: $env{'form.username'}.=time.rand(10000000);
10078: }
10079: $name.=$env{'form.username'};
10080: }
10081: return ($symb,$courseid,$domain,$name,$publicuser);
10082:
10083: }
10084:
1.36 albertel 10085: # ------------------------------------------------------------ Serves up a file
1.472 albertel 10086: # returns either the contents of the file or
10087: # -1 if the file doesn't exist
1.481 raeburn 10088: #
10089: # if the target is a file that was uploaded via DOCS,
10090: # a check will be made to see if a current copy exists on the local server,
10091: # if it does this will be served, otherwise a copy will be retrieved from
10092: # the home server for the course and stored in /home/httpd/html/userfiles on
10093: # the local server.
1.472 albertel 10094:
1.36 albertel 10095: sub getfile {
1.538 albertel 10096: my ($file) = @_;
1.609 banghart 10097: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 10098: &repcopy($file);
10099: return &readfile($file);
10100: }
10101:
10102: sub repcopy_userfile {
10103: my ($file)=@_;
1.1142 raeburn 10104: my $londocroot = $perlvar{'lonDocRoot'};
10105: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10106: if ($file =~ m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
1.538 albertel 10107: my ($cdom,$cnum,$filename) =
1.811 albertel 10108: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 10109: my $uri="/uploaded/$cdom/$cnum/$filename";
10110: if (-e "$file") {
1.828 www 10111: # we already have a local copy, check it out
1.538 albertel 10112: my @fileinfo = stat($file);
1.828 www 10113: my $rtncode;
10114: my $info;
1.538 albertel 10115: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 10116: if ($lwpresp ne 'ok') {
1.828 www 10117: # there is no such file anymore, even though we had a local copy
1.482 albertel 10118: if ($rtncode eq '404') {
1.538 albertel 10119: unlink($file);
1.482 albertel 10120: }
10121: return -1;
10122: }
10123: if ($info < $fileinfo[9]) {
1.828 www 10124: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 10125: return 'ok';
1.828 www 10126: } else {
10127: # the file is outdated, get rid of it
10128: unlink($file);
1.482 albertel 10129: }
1.828 www 10130: }
10131: # one way or the other, at this point, we don't have the file
10132: # construct the correct path for the file
10133: my @parts = ($cdom,$cnum);
10134: if ($filename =~ m|^(.+)/[^/]+$|) {
10135: push @parts, split(/\//,$1);
10136: }
10137: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10138: foreach my $part (@parts) {
10139: $path .= '/'.$part;
10140: if (!-e $path) {
10141: mkdir($path,0770);
1.482 albertel 10142: }
10143: }
1.828 www 10144: # now the path exists for sure
10145: # get a user agent
10146: my $ua=new LWP::UserAgent;
10147: my $transferfile=$file.'.in.transfer';
10148: # FIXME: this should flock
10149: if (-e $transferfile) { return 'ok'; }
10150: my $request;
10151: $uri=~s/^\///;
1.980 raeburn 10152: my $homeserver = &homeserver($cnum,$cdom);
10153: my $protocol = $protocol{$homeserver};
10154: $protocol = 'http' if ($protocol ne 'https');
10155: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 10156: my $response=$ua->request($request,$transferfile);
10157: # did it work?
10158: if ($response->is_error()) {
10159: unlink($transferfile);
10160: &logthis("Userfile repcopy failed for $uri");
10161: return -1;
10162: }
10163: # worked, rename the transfer file
10164: rename($transferfile,$file);
1.607 raeburn 10165: return 'ok';
1.481 raeburn 10166: }
10167:
1.517 albertel 10168: sub tokenwrapper {
10169: my $uri=shift;
1.980 raeburn 10170: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 10171: $uri=~s|^/||;
1.620 albertel 10172: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 10173: my $token=$1;
1.552 albertel 10174: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10175: if ($udom && $uname && $file) {
10176: $file=~s|(\?\.*)*$||;
1.949 raeburn 10177: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 10178: my $homeserver = &homeserver($uname,$udom);
10179: my $protocol = $protocol{$homeserver};
10180: $protocol = 'http' if ($protocol ne 'https');
10181: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 10182: (($uri=~/\?/)?'&':'?').'token='.$token.
10183: '&tokenissued='.$perlvar{'lonHostID'};
10184: } else {
10185: return '/adm/notfound.html';
10186: }
10187: }
10188:
1.828 www 10189: # call with reqtype HEAD: get last modification time
10190: # call with reqtype GET: get the file contents
10191: # Do not call this with reqtype GET for large files! It loads everything into memory
10192: #
1.481 raeburn 10193: sub getuploaded {
10194: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10195: $uri=~s/^\///;
1.980 raeburn 10196: my $homeserver = &homeserver($cnum,$cdom);
10197: my $protocol = $protocol{$homeserver};
10198: $protocol = 'http' if ($protocol ne 'https');
10199: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 10200: my $ua=new LWP::UserAgent;
10201: my $request=new HTTP::Request($reqtype,$uri);
10202: my $response=$ua->request($request);
10203: $$rtncode = $response->code;
1.482 albertel 10204: if (! $response->is_success()) {
10205: return 'failed';
10206: }
10207: if ($reqtype eq 'HEAD') {
1.486 www 10208: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 10209: } elsif ($reqtype eq 'GET') {
10210: $$info = $response->content;
1.472 albertel 10211: }
1.482 albertel 10212: return 'ok';
1.36 albertel 10213: }
10214:
1.481 raeburn 10215: sub readfile {
10216: my $file = shift;
10217: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10218: my $fh;
10219: open($fh,"<$file");
10220: my $a='';
1.800 albertel 10221: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 10222: return $a;
10223: }
10224:
1.36 albertel 10225: sub filelocation {
1.590 banghart 10226: my ($dir,$file) = @_;
10227: my $location;
10228: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 10229:
10230: if ($file =~ m-^/adm/-) {
10231: $file=~s-^/adm/wrapper/-/-;
10232: $file=~s-^/adm/coursedocs/showdoc/-/-;
10233: }
1.882 albertel 10234:
1.1139 www 10235: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 10236: $location = $file;
1.609 banghart 10237: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 10238: my ($udom,$uname,$filename)=
1.811 albertel 10239: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 10240: my $home=&homeserver($uname,$udom);
10241: my $is_me=0;
10242: my @ids=¤t_machine_ids();
10243: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10244: if ($is_me) {
1.1117 foxr 10245: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 10246: } else {
10247: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10248: $udom.'/'.$uname.'/'.$filename;
10249: }
1.882 albertel 10250: } elsif ($file =~ m-^/adm/-) {
10251: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 10252: } else {
10253: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 10254: $file=~s:^/(res|priv)/:/:;
10255: my $space=$1;
1.590 banghart 10256: if ( !( $file =~ m:^/:) ) {
10257: $location = $dir. '/'.$file;
10258: } else {
1.1142 raeburn 10259: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 10260: }
1.59 albertel 10261: }
1.590 banghart 10262: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 10263: while ($location=~m{/\.\./}) {
10264: if ($location =~ m{/[^/]+/\.\./}) {
10265: $location=~ s{/[^/]+/\.\./}{/}g;
10266: } else {
10267: $location=~ s{/\.\./}{/}g;
10268: }
10269: } #remove dir/..
1.590 banghart 10270: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10271: return $location;
1.46 www 10272: }
1.36 albertel 10273:
1.46 www 10274: sub hreflocation {
10275: my ($dir,$file)=@_;
1.980 raeburn 10276: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 10277: $file=filelocation($dir,$file);
1.700 albertel 10278: } elsif ($file=~m-^/adm/-) {
10279: $file=~s-^/adm/wrapper/-/-;
10280: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 10281: }
10282: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10283: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10284: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 10285: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10286: {/uploaded/$1/$2/}x;
1.46 www 10287: }
1.913 albertel 10288: if ($file=~ m{^/userfiles/}) {
10289: $file =~ s{^/userfiles/}{/uploaded/};
10290: }
1.462 albertel 10291: return $file;
1.465 albertel 10292: }
10293:
1.1139 www 10294:
10295:
10296:
10297:
1.465 albertel 10298: sub current_machine_domains {
1.853 albertel 10299: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10300: }
10301:
10302: sub machine_domains {
10303: my ($hostname) = @_;
1.465 albertel 10304: my @domains;
1.838 albertel 10305: my %hostname = &all_hostnames();
1.465 albertel 10306: while( my($id, $name) = each(%hostname)) {
1.467 matthew 10307: # &logthis("-$id-$name-$hostname-");
1.465 albertel 10308: if ($hostname eq $name) {
1.844 albertel 10309: push(@domains,&host_domain($id));
1.465 albertel 10310: }
10311: }
10312: return @domains;
10313: }
10314:
10315: sub current_machine_ids {
1.853 albertel 10316: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10317: }
10318:
10319: sub machine_ids {
10320: my ($hostname) = @_;
10321: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 10322: my @ids;
1.888 albertel 10323: my %name_to_host = &all_names();
1.889 albertel 10324: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10325: return @{ $name_to_host{$hostname} };
10326: }
10327: return;
1.31 www 10328: }
10329:
1.824 raeburn 10330: sub additional_machine_domains {
10331: my @domains;
10332: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10333: while( my $line = <$fh>) {
10334: $line =~ s/\s//g;
10335: push(@domains,$line);
10336: }
10337: return @domains;
10338: }
10339:
10340: sub default_login_domain {
10341: my $domain = $perlvar{'lonDefDomain'};
10342: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10343: foreach my $posdom (¤t_machine_domains(),
10344: &additional_machine_domains()) {
10345: if (lc($posdom) eq lc($testdomain)) {
10346: $domain=$posdom;
10347: last;
10348: }
10349: }
10350: return $domain;
10351: }
10352:
1.31 www 10353: # ------------------------------------------------------------- Declutters URLs
10354:
10355: sub declutter {
10356: my $thisfn=shift;
1.569 albertel 10357: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 10358: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 10359: $thisfn=~s/^\///;
1.697 albertel 10360: $thisfn=~s|^adm/wrapper/||;
10361: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 10362: $thisfn=~s/^res\///;
1.1032 raeburn 10363: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10364: $thisfn=~s/\?.+$//;
10365: }
1.268 www 10366: return $thisfn;
10367: }
10368:
10369: # ------------------------------------------------------------- Clutter up URLs
10370:
10371: sub clutter {
10372: my $thisfn='/'.&declutter(shift);
1.887 albertel 10373: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 10374: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 10375: $thisfn='/res'.$thisfn;
10376: }
1.1031 raeburn 10377: if ($thisfn !~m|^/adm|) {
10378: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 10379: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 10380: } else {
10381: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10382: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 10383: if ($embstyle eq 'ssi'
10384: || ($embstyle eq 'hdn')
10385: || ($embstyle eq 'rat')
10386: || ($embstyle eq 'prv')
10387: || ($embstyle eq 'ign')) {
10388: #do nothing with these
10389: } elsif (($embstyle eq 'img')
1.695 albertel 10390: || ($embstyle eq 'emb')
10391: || ($embstyle eq 'wrp')) {
10392: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 10393: } elsif ($embstyle eq 'unk'
10394: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 10395: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 10396: } else {
1.718 www 10397: # &logthis("Got a blank emb style");
1.695 albertel 10398: }
1.694 albertel 10399: }
10400: }
1.31 www 10401: return $thisfn;
1.12 www 10402: }
10403:
1.787 albertel 10404: sub clutter_with_no_wrapper {
10405: my $uri = &clutter(shift);
10406: if ($uri =~ m-^/adm/-) {
10407: $uri =~ s-^/adm/wrapper/-/-;
10408: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
10409: }
10410: return $uri;
10411: }
10412:
1.557 albertel 10413: sub freeze_escape {
10414: my ($value)=@_;
10415: if (ref($value)) {
10416: $value=&nfreeze($value);
10417: return '__FROZEN__'.&escape($value);
10418: }
10419: return &escape($value);
10420: }
10421:
1.11 www 10422:
1.557 albertel 10423: sub thaw_unescape {
10424: my ($value)=@_;
10425: if ($value =~ /^__FROZEN__/) {
10426: substr($value,0,10,undef);
10427: $value=&unescape($value);
10428: return &thaw($value);
10429: }
10430: return &unescape($value);
10431: }
10432:
1.436 albertel 10433: sub correct_line_ends {
10434: my ($result)=@_;
10435: $$result =~s/\r\n/\n/mg;
10436: $$result =~s/\r/\n/mg;
1.415 albertel 10437: }
1.1 albertel 10438: # ================================================================ Main Program
10439:
1.184 www 10440: sub goodbye {
1.204 albertel 10441: &logthis("Starting Shut down");
1.443 albertel 10442: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 10443: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 10444: #converted
1.599 albertel 10445: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 10446: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10447: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10448: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 10449: #1.1 only
1.870 albertel 10450: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10451: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10452: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10453: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10454: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 10455: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10456: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 10457: &flushcourselogs();
10458: &logthis("Shutting down");
10459: }
10460:
1.852 albertel 10461: sub get_dns {
1.869 albertel 10462: my ($url,$func,$ignore_cache) = @_;
10463: if (!$ignore_cache) {
10464: my ($content,$cached)=
10465: &Apache::lonnet::is_cached_new('dns',$url);
10466: if ($cached) {
10467: &$func($content);
10468: return;
10469: }
10470: }
10471:
10472: my %alldns;
1.852 albertel 10473: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10474: foreach my $dns (<$config>) {
10475: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 10476: my $line = $1;
10477: my ($host,$protocol) = split(/:/,$line);
10478: if ($protocol ne 'https') {
10479: $protocol = 'http';
10480: }
10481: $alldns{$host} = $protocol;
1.869 albertel 10482: }
10483: while (%alldns) {
10484: my ($dns) = keys(%alldns);
1.852 albertel 10485: my $ua=new LWP::UserAgent;
1.1134 raeburn 10486: $ua->timeout(30);
1.979 raeburn 10487: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 10488: my $response=$ua->request($request);
1.979 raeburn 10489: delete($alldns{$dns});
1.852 albertel 10490: next if ($response->is_error());
10491: my @content = split("\n",$response->content);
1.869 albertel 10492: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 10493: &$func(\@content);
1.869 albertel 10494: return;
1.852 albertel 10495: }
10496: close($config);
1.871 albertel 10497: my $which = (split('/',$url))[3];
10498: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10499: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 10500: my @content = <$config>;
10501: &$func(\@content);
10502: return;
1.852 albertel 10503: }
1.327 albertel 10504: # ------------------------------------------------------------ Read domain file
10505: {
1.852 albertel 10506: my $loaded;
1.846 albertel 10507: my %domain;
10508:
1.852 albertel 10509: sub parse_domain_tab {
10510: my ($lines) = @_;
10511: foreach my $line (@$lines) {
10512: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 10513:
1.846 albertel 10514: chomp($line);
1.852 albertel 10515: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 10516: my %this_domain;
10517: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10518: 'lang_def', 'city', 'longi', 'lati',
10519: 'primary') {
10520: $this_domain{$field} = shift(@elements);
10521: }
10522: $domain{$name} = \%this_domain;
1.852 albertel 10523: }
10524: }
1.864 albertel 10525:
10526: sub reset_domain_info {
10527: undef($loaded);
10528: undef(%domain);
10529: }
10530:
1.852 albertel 10531: sub load_domain_tab {
1.869 albertel 10532: my ($ignore_cache) = @_;
10533: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 10534: my $fh;
10535: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10536: my @lines = <$fh>;
10537: &parse_domain_tab(\@lines);
1.448 albertel 10538: }
1.852 albertel 10539: close($fh);
10540: $loaded = 1;
1.327 albertel 10541: }
1.846 albertel 10542:
10543: sub domain {
1.852 albertel 10544: &load_domain_tab() if (!$loaded);
10545:
1.846 albertel 10546: my ($name,$what) = @_;
10547: return if ( !exists($domain{$name}) );
10548:
10549: if (!$what) {
10550: return $domain{$name}{'description'};
10551: }
10552: return $domain{$name}{$what};
10553: }
1.974 raeburn 10554:
10555: sub domain_info {
10556: &load_domain_tab() if (!$loaded);
10557: return %domain;
10558: }
10559:
1.327 albertel 10560: }
10561:
10562:
1.1 albertel 10563: # ------------------------------------------------------------- Read hosts file
10564: {
1.838 albertel 10565: my %hostname;
1.844 albertel 10566: my %hostdom;
1.845 albertel 10567: my %libserv;
1.852 albertel 10568: my $loaded;
1.888 albertel 10569: my %name_to_host;
1.1074 raeburn 10570: my %internetdom;
1.1107 raeburn 10571: my %LC_dns_serv;
1.852 albertel 10572:
10573: sub parse_hosts_tab {
10574: my ($file) = @_;
10575: foreach my $configline (@$file) {
10576: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 10577: chomp($configline);
10578: if ($configline =~ /^\^/) {
10579: if ($configline =~ /^\^([\w.\-]+)/) {
10580: $LC_dns_serv{$1} = 1;
10581: }
10582: next;
10583: }
1.1074 raeburn 10584: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 10585: $name=~s/\s//g;
10586: if ($id && $domain && $role && $name) {
10587: $hostname{$id}=$name;
1.888 albertel 10588: push(@{$name_to_host{$name}}, $id);
1.852 albertel 10589: $hostdom{$id}=$domain;
10590: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 10591: if (defined($protocol)) {
10592: if ($protocol eq 'https') {
10593: $protocol{$id} = $protocol;
10594: } else {
10595: $protocol{$id} = 'http';
10596: }
1.968 raeburn 10597: } else {
1.969 raeburn 10598: $protocol{$id} = 'http';
1.968 raeburn 10599: }
1.1074 raeburn 10600: if (defined($intdom)) {
10601: $internetdom{$id} = $intdom;
10602: }
1.852 albertel 10603: }
10604: }
10605: }
1.864 albertel 10606:
10607: sub reset_hosts_info {
1.897 albertel 10608: &purge_remembered();
1.864 albertel 10609: &reset_domain_info();
10610: &reset_hosts_ip_info();
1.892 albertel 10611: undef(%name_to_host);
1.864 albertel 10612: undef(%hostname);
10613: undef(%hostdom);
10614: undef(%libserv);
10615: undef($loaded);
10616: }
1.1 albertel 10617:
1.852 albertel 10618: sub load_hosts_tab {
1.869 albertel 10619: my ($ignore_cache) = @_;
10620: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 10621: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10622: my @config = <$config>;
10623: &parse_hosts_tab(\@config);
10624: close($config);
10625: $loaded=1;
1.1 albertel 10626: }
1.852 albertel 10627:
1.838 albertel 10628: sub hostname {
1.852 albertel 10629: &load_hosts_tab() if (!$loaded);
10630:
1.838 albertel 10631: my ($lonid) = @_;
10632: return $hostname{$lonid};
10633: }
1.845 albertel 10634:
1.838 albertel 10635: sub all_hostnames {
1.852 albertel 10636: &load_hosts_tab() if (!$loaded);
10637:
1.838 albertel 10638: return %hostname;
10639: }
1.845 albertel 10640:
1.888 albertel 10641: sub all_names {
10642: &load_hosts_tab() if (!$loaded);
10643:
10644: return %name_to_host;
10645: }
10646:
1.974 raeburn 10647: sub all_host_domain {
10648: &load_hosts_tab() if (!$loaded);
10649: return %hostdom;
10650: }
10651:
1.845 albertel 10652: sub is_library {
1.852 albertel 10653: &load_hosts_tab() if (!$loaded);
10654:
1.845 albertel 10655: return exists($libserv{$_[0]});
10656: }
10657:
10658: sub all_library {
1.852 albertel 10659: &load_hosts_tab() if (!$loaded);
10660:
1.845 albertel 10661: return %libserv;
10662: }
10663:
1.1062 droeschl 10664: sub unique_library {
10665: #2x reverse removes all hostnames that appear more than once
10666: my %unique = reverse &all_library();
10667: return reverse %unique;
10668: }
10669:
1.841 albertel 10670: sub get_servers {
1.852 albertel 10671: &load_hosts_tab() if (!$loaded);
10672:
1.841 albertel 10673: my ($domain,$type) = @_;
10674: my %possible_hosts = ($type eq 'library') ? %libserv
10675: : %hostname;
10676: my %result;
1.842 albertel 10677: if (ref($domain) eq 'ARRAY') {
10678: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 10679: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 10680: $result{$host} = $hostname;
10681: }
10682: }
10683: } else {
10684: while ( my ($host,$hostname) = each(%possible_hosts)) {
10685: if ($hostdom{$host} eq $domain) {
10686: $result{$host} = $hostname;
10687: }
1.841 albertel 10688: }
10689: }
10690: return %result;
10691: }
1.845 albertel 10692:
1.1062 droeschl 10693: sub get_unique_servers {
10694: my %unique = reverse &get_servers(@_);
10695: return reverse %unique;
10696: }
10697:
1.844 albertel 10698: sub host_domain {
1.852 albertel 10699: &load_hosts_tab() if (!$loaded);
10700:
1.844 albertel 10701: my ($lonid) = @_;
10702: return $hostdom{$lonid};
10703: }
10704:
1.841 albertel 10705: sub all_domains {
1.852 albertel 10706: &load_hosts_tab() if (!$loaded);
10707:
1.841 albertel 10708: my %seen;
10709: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10710: return @uniq;
10711: }
1.1074 raeburn 10712:
10713: sub internet_dom {
10714: &load_hosts_tab() if (!$loaded);
10715:
10716: my ($lonid) = @_;
10717: return $internetdom{$lonid};
10718: }
1.1107 raeburn 10719:
10720: sub is_LC_dns {
10721: &load_hosts_tab() if (!$loaded);
10722:
10723: my ($hostname) = @_;
10724: return exists($LC_dns_serv{$hostname});
10725: }
10726:
1.1 albertel 10727: }
10728:
1.847 albertel 10729: {
10730: my %iphost;
1.856 albertel 10731: my %name_to_ip;
10732: my %lonid_to_ip;
1.869 albertel 10733:
1.847 albertel 10734: sub get_hosts_from_ip {
10735: my ($ip) = @_;
10736: my %iphosts = &get_iphost();
10737: if (ref($iphosts{$ip})) {
10738: return @{$iphosts{$ip}};
10739: }
10740: return;
1.839 albertel 10741: }
1.864 albertel 10742:
10743: sub reset_hosts_ip_info {
10744: undef(%iphost);
10745: undef(%name_to_ip);
10746: undef(%lonid_to_ip);
10747: }
1.856 albertel 10748:
10749: sub get_host_ip {
10750: my ($lonid) = @_;
10751: if (exists($lonid_to_ip{$lonid})) {
10752: return $lonid_to_ip{$lonid};
10753: }
10754: my $name=&hostname($lonid);
10755: my $ip = gethostbyname($name);
10756: return if (!$ip || length($ip) ne 4);
10757: $ip=inet_ntoa($ip);
10758: $name_to_ip{$name} = $ip;
10759: $lonid_to_ip{$lonid} = $ip;
10760: return $ip;
10761: }
1.847 albertel 10762:
10763: sub get_iphost {
1.869 albertel 10764: my ($ignore_cache) = @_;
1.894 albertel 10765:
1.869 albertel 10766: if (!$ignore_cache) {
10767: if (%iphost) {
10768: return %iphost;
10769: }
10770: my ($ip_info,$cached)=
10771: &Apache::lonnet::is_cached_new('iphost','iphost');
10772: if ($cached) {
10773: %iphost = %{$ip_info->[0]};
10774: %name_to_ip = %{$ip_info->[1]};
10775: %lonid_to_ip = %{$ip_info->[2]};
10776: return %iphost;
10777: }
10778: }
1.894 albertel 10779:
10780: # get yesterday's info for fallback
10781: my %old_name_to_ip;
10782: my ($ip_info,$cached)=
10783: &Apache::lonnet::is_cached_new('iphost','iphost');
10784: if ($cached) {
10785: %old_name_to_ip = %{$ip_info->[1]};
10786: }
10787:
1.888 albertel 10788: my %name_to_host = &all_names();
10789: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10790: my $ip;
10791: if (!exists($name_to_ip{$name})) {
10792: $ip = gethostbyname($name);
10793: if (!$ip || length($ip) ne 4) {
1.894 albertel 10794: if (defined($old_name_to_ip{$name})) {
10795: $ip = $old_name_to_ip{$name};
10796: &logthis("Can't find $name defaulting to old $ip");
10797: } else {
10798: &logthis("Name $name no IP found");
10799: next;
10800: }
10801: } else {
10802: $ip=inet_ntoa($ip);
1.847 albertel 10803: }
10804: $name_to_ip{$name} = $ip;
10805: } else {
10806: $ip = $name_to_ip{$name};
1.653 albertel 10807: }
1.888 albertel 10808: foreach my $id (@{ $name_to_host{$name} }) {
10809: $lonid_to_ip{$id} = $ip;
10810: }
10811: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10812: }
1.869 albertel 10813: &Apache::lonnet::do_cache_new('iphost','iphost',
10814: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10815: 48*60*60);
1.869 albertel 10816:
1.847 albertel 10817: return %iphost;
1.598 albertel 10818: }
10819:
1.992 raeburn 10820: #
10821: # Given a DNS returns the loncapa host name for that DNS
10822: #
10823: sub host_from_dns {
10824: my ($dns) = @_;
10825: my @hosts;
10826: my $ip;
10827:
1.993 raeburn 10828: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10829: $ip = $name_to_ip{$dns};
10830: }
10831: if (!$ip) {
10832: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10833: if (length($ip) == 4) {
10834: $ip = &IO::Socket::inet_ntoa($ip);
10835: }
10836: }
10837: if ($ip) {
10838: @hosts = get_hosts_from_ip($ip);
10839: return $hosts[0];
10840: }
10841: return undef;
1.986 foxr 10842: }
1.992 raeburn 10843:
1.1074 raeburn 10844: sub get_internet_names {
10845: my ($lonid) = @_;
10846: return if ($lonid eq '');
10847: my ($idnref,$cached)=
10848: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10849: if ($cached) {
10850: return $idnref;
10851: }
10852: my $ip = &get_host_ip($lonid);
10853: my @hosts = &get_hosts_from_ip($ip);
10854: my %iphost = &get_iphost();
10855: my (@idns,%seen);
10856: foreach my $id (@hosts) {
10857: my $dom = &host_domain($id);
10858: my $prim_id = &domain($dom,'primary');
10859: my $prim_ip = &get_host_ip($prim_id);
10860: next if ($seen{$prim_ip});
10861: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10862: foreach my $id (@{$iphost{$prim_ip}}) {
10863: my $intdom = &internet_dom($id);
10864: unless (grep(/^\Q$intdom\E$/,@idns)) {
10865: push(@idns,$intdom);
10866: }
10867: }
10868: }
10869: $seen{$prim_ip} = 1;
10870: }
10871: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10872: }
10873:
1.986 foxr 10874: }
10875:
1.1079 raeburn 10876: sub all_loncaparevs {
10877: 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);
10878: }
10879:
1.862 albertel 10880: BEGIN {
10881:
10882: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10883: unless ($readit) {
10884: {
10885: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10886: %perlvar = (%perlvar,%{$configvars});
10887: }
10888:
10889:
1.1 albertel 10890: # ------------------------------------------------------ Read spare server file
10891: {
1.448 albertel 10892: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10893:
10894: while (my $configline=<$config>) {
10895: chomp($configline);
1.284 matthew 10896: if ($configline) {
1.784 albertel 10897: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10898: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10899: push(@{ $spareid{$type} }, $host);
1.1 albertel 10900: }
10901: }
1.448 albertel 10902: close($config);
1.1 albertel 10903: }
1.11 www 10904: # ------------------------------------------------------------ Read permissions
10905: {
1.448 albertel 10906: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10907:
10908: while (my $configline=<$config>) {
1.448 albertel 10909: chomp($configline);
10910: if ($configline) {
10911: my ($role,$perm)=split(/ /,$configline);
10912: if ($perm ne '') { $pr{$role}=$perm; }
10913: }
1.11 www 10914: }
1.448 albertel 10915: close($config);
1.11 www 10916: }
10917:
10918: # -------------------------------------------- Read plain texts for permissions
10919: {
1.448 albertel 10920: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10921:
10922: while (my $configline=<$config>) {
1.448 albertel 10923: chomp($configline);
10924: if ($configline) {
1.742 raeburn 10925: my ($short,@plain)=split(/:/,$configline);
10926: %{$prp{$short}} = ();
10927: if (@plain > 0) {
10928: $prp{$short}{'std'} = $plain[0];
10929: for (my $i=1; $i<@plain; $i++) {
10930: $prp{$short}{'alt'.$i} = $plain[$i];
10931: }
10932: }
1.448 albertel 10933: }
1.135 www 10934: }
1.448 albertel 10935: close($config);
1.135 www 10936: }
10937:
10938: # ---------------------------------------------------------- Read package table
10939: {
1.448 albertel 10940: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10941:
10942: while (my $configline=<$config>) {
1.483 albertel 10943: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10944: chomp($configline);
10945: my ($short,$plain)=split(/:/,$configline);
10946: my ($pack,$name)=split(/\&/,$short);
10947: if ($plain ne '') {
10948: $packagetab{$pack.'&'.$name.'&name'}=$name;
10949: $packagetab{$short}=$plain;
10950: }
1.11 www 10951: }
1.448 albertel 10952: close($config);
1.329 matthew 10953: }
10954:
1.1073 raeburn 10955: # ---------------------------------------------------------- Read loncaparev table
10956: {
10957: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10958: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10959: while (my $configline=<$config>) {
10960: chomp($configline);
10961: my ($hostid,$loncaparev)=split(/:/,$configline);
10962: $loncaparevs{$hostid}=$loncaparev;
10963: }
10964: close($config);
10965: }
10966: }
10967: }
10968:
1.1074 raeburn 10969: # ---------------------------------------------------------- Read serverhostID table
10970: {
10971: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10972: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10973: while (my $configline=<$config>) {
10974: chomp($configline);
10975: my ($name,$id)=split(/:/,$configline);
10976: $serverhomeIDs{$name}=$id;
10977: }
10978: close($config);
10979: }
10980: }
10981: }
10982:
1.1079 raeburn 10983: {
10984: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10985: if (-e $file) {
10986: my $parser = HTML::LCParser->new($file);
10987: while (my $token = $parser->get_token()) {
10988: if ($token->[0] eq 'S') {
10989: my $item = $token->[1];
10990: my $name = $token->[2]{'name'};
10991: my $value = $token->[2]{'value'};
10992: if ($item ne '' && $name ne '' && $value ne '') {
10993: my $release = $parser->get_text();
10994: $release =~ s/(^\s*|\s*$ )//gx;
10995: $needsrelease{$item.':'.$name.':'.$value} = $release;
10996: }
10997: }
10998: }
10999: }
1.1073 raeburn 11000: }
11001:
1.1138 raeburn 11002: # ---------------------------------------------------------- Read managers table
11003: {
11004: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11005: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11006: while (my $configline=<$config>) {
11007: chomp($configline);
11008: next if ($configline =~ /^\#/);
11009: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11010: $managerstab{$configline} = 1;
11011: }
11012: }
11013: close($config);
11014: }
11015: }
11016: }
11017:
1.329 matthew 11018: # ------------- set up temporary directory
11019: {
1.1117 foxr 11020: $tmpdir = LONCAPA::tempdir();
1.329 matthew 11021:
1.11 www 11022: }
11023:
1.794 albertel 11024: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
11025: 'compress_threshold'=> 20_000,
11026: });
1.185 www 11027:
1.281 www 11028: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 11029: $dumpcount=0;
1.958 www 11030: $locknum=0;
1.22 www 11031:
1.163 harris41 11032: &logtouch();
1.672 albertel 11033: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 11034: $readit=1;
1.564 albertel 11035: {
11036: use integer;
11037: my $test=(2**32)+1;
1.568 albertel 11038: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 11039: &logthis(" Detected 64bit platform ($_64bit)");
11040: }
1.195 www 11041: }
1.1 albertel 11042: }
1.179 www 11043:
1.1 albertel 11044: 1;
1.191 harris41 11045: __END__
11046:
1.243 albertel 11047: =pod
11048:
1.191 harris41 11049: =head1 NAME
11050:
1.243 albertel 11051: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 11052:
11053: =head1 SYNOPSIS
11054:
1.243 albertel 11055: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 11056:
11057: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11058:
1.243 albertel 11059: Common parameters:
11060:
11061: =over 4
11062:
11063: =item *
11064:
11065: $uname : an internal username (if $cname expecting a course Id specifically)
11066:
11067: =item *
11068:
11069: $udom : a domain (if $cdom expecting a course's domain specifically)
11070:
11071: =item *
11072:
11073: $symb : a resource instance identifier
11074:
11075: =item *
11076:
11077: $namespace : the name of a .db file that contains the data needed or
11078: being set.
11079:
11080: =back
11081:
1.394 bowersj2 11082: =head1 OVERVIEW
1.191 harris41 11083:
1.394 bowersj2 11084: lonnet provides subroutines which interact with the
11085: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11086: about classes, users, and resources.
1.243 albertel 11087:
11088: For many of these objects you can also use this to store data about
11089: them or modify them in various ways.
1.191 harris41 11090:
1.394 bowersj2 11091: =head2 Symbs
1.191 harris41 11092:
1.394 bowersj2 11093: To identify a specific instance of a resource, LON-CAPA uses symbols
11094: or "symbs"X<symb>. These identifiers are built from the URL of the
11095: map, the resource number of the resource in the map, and the URL of
11096: the resource itself. The latter is somewhat redundant, but might help
11097: if maps change.
11098:
11099: An example is
11100:
11101: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11102:
11103: The respective map entry is
11104:
11105: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11106: title="Problem 2">
11107: </resource>
11108:
11109: Symbs are used by the random number generator, as well as to store and
11110: restore data specific to a certain instance of for example a problem.
11111:
11112: =head2 Storing And Retrieving Data
11113:
11114: X<store()>X<cstore()>X<restore()>Three of the most important functions
11115: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11116: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11117: is is the non-critical message twin of cstore. These functions are for
11118: handlers to store a perl hash to a user's permanent data space in an
11119: easy manner, and to retrieve it again on another call. It is expected
11120: that a handler would use this once at the beginning to retrieve data,
11121: and then again once at the end to send only the new data back.
11122:
11123: The data is stored in the user's data directory on the user's
11124: homeserver under the ID of the course.
11125:
11126: The hash that is returned by restore will have all of the previous
11127: value for all of the elements of the hash.
11128:
11129: Example:
11130:
11131: #creating a hash
11132: my %hash;
11133: $hash{'foo'}='bar';
11134:
11135: #storing it
11136: &Apache::lonnet::cstore(\%hash);
11137:
11138: #changing a value
11139: $hash{'foo'}='notbar';
11140:
11141: #adding a new value
11142: $hash{'bar'}='foo';
11143: &Apache::lonnet::cstore(\%hash);
11144:
11145: #retrieving the hash
11146: my %history=&Apache::lonnet::restore();
11147:
11148: #print the hash
11149: foreach my $key (sort(keys(%history))) {
11150: print("\%history{$key} = $history{$key}");
11151: }
11152:
11153: Will print out:
1.191 harris41 11154:
1.394 bowersj2 11155: %history{1:foo} = bar
11156: %history{1:keys} = foo:timestamp
11157: %history{1:timestamp} = 990455579
11158: %history{2:bar} = foo
11159: %history{2:foo} = notbar
11160: %history{2:keys} = foo:bar:timestamp
11161: %history{2:timestamp} = 990455580
11162: %history{bar} = foo
11163: %history{foo} = notbar
11164: %history{timestamp} = 990455580
11165: %history{version} = 2
11166:
11167: Note that the special hash entries C<keys>, C<version> and
11168: C<timestamp> were added to the hash. C<version> will be equal to the
11169: total number of versions of the data that have been stored. The
11170: C<timestamp> attribute will be the UNIX time the hash was
11171: stored. C<keys> is available in every historical section to list which
11172: keys were added or changed at a specific historical revision of a
11173: hash.
11174:
11175: B<Warning>: do not store the hash that restore returns directly. This
11176: will cause a mess since it will restore the historical keys as if the
11177: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 11178:
1.394 bowersj2 11179: Calling convention:
1.191 harris41 11180:
1.394 bowersj2 11181: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11182: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 11183:
1.394 bowersj2 11184: For more detailed information, see lonnet specific documentation.
1.191 harris41 11185:
1.394 bowersj2 11186: =head1 RETURN MESSAGES
1.191 harris41 11187:
1.394 bowersj2 11188: =over 4
1.191 harris41 11189:
1.394 bowersj2 11190: =item * B<con_lost>: unable to contact remote host
1.191 harris41 11191:
1.394 bowersj2 11192: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11193: when the connection is brought back up
1.191 harris41 11194:
1.394 bowersj2 11195: =item * B<con_failed>: unable to contact remote host and unable to save message
11196: for later delivery
1.191 harris41 11197:
1.967 bisitz 11198: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 11199:
1.394 bowersj2 11200: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 11201: that was requested
1.191 harris41 11202:
1.243 albertel 11203: =back
1.191 harris41 11204:
1.243 albertel 11205: =head1 PUBLIC SUBROUTINES
1.191 harris41 11206:
1.243 albertel 11207: =head2 Session Environment Functions
1.191 harris41 11208:
1.243 albertel 11209: =over 4
1.191 harris41 11210:
1.394 bowersj2 11211: =item *
11212: X<appenv()>
1.949 raeburn 11213: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 11214: the user envirnoment file, and will be restored for each access this
1.620 albertel 11215: user makes during this session, also modifies the %env for the current
1.949 raeburn 11216: process. Optional rolesarrayref - if defined contains a reference to an array
11217: of roles which are exempt from the restriction on modifying user.role entries
11218: in the user's environment.db and in %env.
1.191 harris41 11219:
11220: =item *
1.394 bowersj2 11221: X<delenv()>
1.987 raeburn 11222: B<delenv($delthis,$regexp)>: removes all items from the session
11223: environment file that begin with $delthis. If the
11224: optional second arg - $regexp - is true, $delthis is treated as a
11225: regular expression, otherwise \Q$delthis\E is used.
11226: The values are also deleted from the current processes %env.
1.191 harris41 11227:
1.795 albertel 11228: =item * get_env_multiple($name)
11229:
11230: gets $name from the %env hash, it seemlessly handles the cases where multiple
11231: values may be defined and end up as an array ref.
11232:
11233: returns an array of values
11234:
1.243 albertel 11235: =back
11236:
11237: =head2 User Information
1.191 harris41 11238:
1.243 albertel 11239: =over 4
1.191 harris41 11240:
11241: =item *
1.394 bowersj2 11242: X<queryauthenticate()>
11243: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 11244: authentication scheme
11245:
11246: =item *
1.394 bowersj2 11247: X<authenticate()>
1.1073 raeburn 11248: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 11249: authenticate user from domain's lib servers (first use the current
11250: one). C<$upass> should be the users password.
1.1073 raeburn 11251: $checkdefauth is optional (value is 1 if a check should be made to
11252: authenticate user using default authentication method, and allow
11253: account creation if username does not have account in the domain).
11254: $clientcancheckhost is optional (value is 1 if checking whether the
11255: server can host will occur on the client side in lonauth.pm).
1.191 harris41 11256:
11257: =item *
1.394 bowersj2 11258: X<homeserver()>
11259: B<homeserver($uname,$udom)>: find the server which has
11260: the user's directory and files (there must be only one), this caches
11261: the answer, and also caches if there is a borken connection.
1.191 harris41 11262:
11263: =item *
1.394 bowersj2 11264: X<idget()>
11265: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11266: (IDs are a unique resource in a domain, there must be only 1 ID per
11267: username, and only 1 username per ID in a specific domain) (returns
11268: hash: id=>name,id=>name)
1.191 harris41 11269:
11270: =item *
1.394 bowersj2 11271: X<idrget()>
11272: B<idrget($udom,@unames)>: find the IDs behind a list of
11273: usernames (returns hash: name=>id,name=>id)
1.191 harris41 11274:
11275: =item *
1.394 bowersj2 11276: X<idput()>
11277: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 11278:
11279: =item *
1.394 bowersj2 11280: X<rolesinit()>
11281: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 11282:
11283: =item *
1.551 albertel 11284: X<getsection()>
11285: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 11286: course $cname, return section name/number or '' for "not in course"
11287: and '-1' for "no section"
11288:
11289: =item *
1.394 bowersj2 11290: X<userenvironment()>
11291: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 11292: passed in @what from the requested user's environment, returns a hash
11293:
1.858 raeburn 11294: =item *
11295: X<userlog_query()>
1.859 albertel 11296: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11297: activity.log file. %filters defines filters applied when parsing the
11298: log file. These can be start or end timestamps, or the type of action
11299: - log to look for Login or Logout events, check for Checkin or
11300: Checkout, role for role selection. The response is in the form
11301: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11302: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 11303:
1.243 albertel 11304: =back
11305:
11306: =head2 User Roles
11307:
11308: =over 4
11309:
11310: =item *
11311:
1.810 raeburn 11312: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 11313: F: full access
11314: U,I,K: authentication modes (cxx only)
11315: '': forbidden
11316: 1: user needs to choose course
11317: 2: browse allowed
1.766 albertel 11318: A: passphrase authentication needed
1.243 albertel 11319:
11320: =item *
11321:
11322: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11323: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11324: and course level
11325:
11326: =item *
11327:
1.988 raeburn 11328: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11329: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 11330: $type is Course (default) or Community.
1.988 raeburn 11331: If $forcedefault evaluates to true, text returned will be default
11332: text for $type. Otherwise, if this is a course, the text returned
11333: will be a custom name for the role (if defined in the course's
11334: environment). If no custom name is defined the default is returned.
11335:
1.832 raeburn 11336: =item *
11337:
1.935 raeburn 11338: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 11339: All arguments are optional. Returns a hash of a roles, either for
11340: co-author/assistant author roles for a user's Construction Space
1.906 albertel 11341: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 11342: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11343: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11344: For each key, value is set to colon-separated start and end times for
11345: the role. If no username and domain are specified, will default to
1.934 raeburn 11346: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 11347: of role statuses (active, future or previous), roles
11348: (e.g., cc,in, st etc.) and domains of the roles which can be used
11349: to restrict the list of roles reported. If no array ref is
11350: provided for types, will default to return only active roles.
1.834 albertel 11351:
1.243 albertel 11352: =back
11353:
11354: =head2 User Modification
11355:
11356: =over 4
11357:
11358: =item *
11359:
1.957 raeburn 11360: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 11361: user for the level given by URL. Optional start and end dates (leave empty
11362: string or zero for "no date")
1.191 harris41 11363:
11364: =item *
11365:
1.243 albertel 11366: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11367: change a users, password, possible return values are: ok,
11368: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11369: refused
1.191 harris41 11370:
11371: =item *
11372:
1.243 albertel 11373: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 11374:
11375: =item *
11376:
1.1058 raeburn 11377: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11378: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11379:
11380: will update user information (firstname,middlename,lastname,generation,
11381: permanentemail), and if forceid is true, student/employee ID also.
11382: A user's institutional affiliation(s) can also be updated.
11383: User information fields will not be overwritten with empty entries
11384: unless the field is included in the $candelete array reference.
11385: This array is included when a single user is modified via "Manage Users",
11386: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 11387:
11388: =item *
11389:
1.286 matthew 11390: modifystudent
11391:
1.957 raeburn 11392: modify a student's enrollment and identification information.
1.286 matthew 11393: The course id is resolved based on the current users environment.
11394: This means the envoking user must be a course coordinator or otherwise
11395: associated with a course.
11396:
1.297 matthew 11397: This call is essentially a wrapper for lonnet::modifyuser and
11398: lonnet::modify_student_enrollment
1.286 matthew 11399:
11400: Inputs:
11401:
11402: =over 4
11403:
1.957 raeburn 11404: =item B<$udom> Student's loncapa domain
1.286 matthew 11405:
1.957 raeburn 11406: =item B<$uname> Student's loncapa login name
1.286 matthew 11407:
1.964 bisitz 11408: =item B<$uid> Student/Employee ID
1.286 matthew 11409:
1.957 raeburn 11410: =item B<$umode> Student's authentication mode
1.286 matthew 11411:
1.957 raeburn 11412: =item B<$upass> Student's password
1.286 matthew 11413:
1.957 raeburn 11414: =item B<$first> Student's first name
1.286 matthew 11415:
1.957 raeburn 11416: =item B<$middle> Student's middle name
1.286 matthew 11417:
1.957 raeburn 11418: =item B<$last> Student's last name
1.286 matthew 11419:
1.957 raeburn 11420: =item B<$gene> Student's generation
1.286 matthew 11421:
1.957 raeburn 11422: =item B<$usec> Student's section in course
1.286 matthew 11423:
11424: =item B<$end> Unix time of the roles expiration
11425:
11426: =item B<$start> Unix time of the roles start date
11427:
11428: =item B<$forceid> If defined, allow $uid to be changed
11429:
11430: =item B<$desiredhome> server to use as home server for student
11431:
1.957 raeburn 11432: =item B<$email> Student's permanent e-mail address
11433:
11434: =item B<$type> Type of enrollment (auto or manual)
11435:
1.963 raeburn 11436: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
11437:
11438: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 11439:
1.963 raeburn 11440: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 11441:
1.963 raeburn 11442: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 11443:
1.963 raeburn 11444: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 11445:
1.286 matthew 11446: =back
1.297 matthew 11447:
11448: =item *
11449:
11450: modify_student_enrollment
11451:
11452: Change a students enrollment status in a class. The environment variable
11453: 'role.request.course' must be defined for this function to proceed.
11454:
11455: Inputs:
11456:
11457: =over 4
11458:
11459: =item $udom, students domain
11460:
11461: =item $uname, students name
11462:
11463: =item $uid, students user id
11464:
11465: =item $first, students first name
11466:
11467: =item $middle
11468:
11469: =item $last
11470:
11471: =item $gene
11472:
11473: =item $usec
11474:
11475: =item $end
11476:
11477: =item $start
11478:
1.957 raeburn 11479: =item $type
11480:
11481: =item $locktype
11482:
11483: =item $cid
11484:
11485: =item $selfenroll
11486:
11487: =item $context
11488:
1.297 matthew 11489: =back
11490:
1.191 harris41 11491:
11492: =item *
11493:
1.243 albertel 11494: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11495: custom role; give a custom role to a user for the level given by URL. Specify
11496: name and domain of role author, and role name
1.191 harris41 11497:
11498: =item *
11499:
1.243 albertel 11500: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 11501:
11502: =item *
11503:
1.243 albertel 11504: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11505:
11506: =back
11507:
11508: =head2 Course Infomation
11509:
11510: =over 4
1.191 harris41 11511:
11512: =item *
11513:
1.1118 foxr 11514: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 11515: specified course id, including all environment settings for the
11516: course, the description of the course will be in the hash under the
11517: key 'description'
1.191 harris41 11518:
1.1118 foxr 11519: $options is an optional parameter that if supplied is a hash reference that controls
11520: what how this function works. It has the following key/values:
11521:
11522: =over 4
11523:
11524: =item freshen_cache
11525:
11526: If defined, and the environment cache for the course is valid, it is
11527: returned in the returned hash.
11528:
11529: =item one_time
11530:
11531: If defined, the last cache time is set to _now_
11532:
11533: =item user
11534:
11535: If defined, the supplied username is used instead of the current user.
11536:
11537:
11538: =back
11539:
1.191 harris41 11540: =item *
11541:
1.624 albertel 11542: resdata($name,$domain,$type,@which) : request for current parameter
11543: setting for a specific $type, where $type is either 'course' or 'user',
11544: @what should be a list of parameters to ask about. This routine caches
11545: answers for 5 minutes.
1.243 albertel 11546:
1.877 foxr 11547: =item *
11548:
11549: get_courseresdata($courseid, $domain) : dump the entire course resource
11550: data base, returning a hash that is keyed by the resource name and has
11551: values that are the resource value. I believe that the timestamps and
11552: versions are also returned.
11553:
11554:
1.243 albertel 11555: =back
11556:
11557: =head2 Course Modification
11558:
11559: =over 4
1.191 harris41 11560:
11561: =item *
11562:
1.243 albertel 11563: writecoursepref($courseid,%prefs) : write preferences (environment
11564: database) for a course
1.191 harris41 11565:
11566: =item *
11567:
1.1011 raeburn 11568: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11569:
11570: =item *
11571:
1.1038 raeburn 11572: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 11573:
11574: =back
11575:
11576: =head2 Resource Subroutines
11577:
11578: =over 4
1.191 harris41 11579:
11580: =item *
11581:
1.243 albertel 11582: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 11583:
11584: =item *
11585:
1.243 albertel 11586: repcopy($filename) : subscribes to the requested file, and attempts to
11587: replicate from the owning library server, Might return
1.607 raeburn 11588: 'unavailable', 'not_found', 'forbidden', 'ok', or
11589: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 11590: resource. Expects the local filesystem pathname
11591: (/home/httpd/html/res/....)
11592:
11593: =back
11594:
11595: =head2 Resource Information
11596:
11597: =over 4
1.191 harris41 11598:
11599: =item *
11600:
1.243 albertel 11601: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11602: a vairety of different possible values, $varname should be a request
11603: string, and the other parameters can be used to specify who and what
11604: one is asking about.
11605:
11606: Possible values for $varname are environment.lastname (or other item
11607: from the envirnment hash), user.name (or someother aspect about the
11608: user), resource.0.maxtries (or some other part and parameter of a
11609: resource)
1.204 albertel 11610:
11611: =item *
11612:
1.243 albertel 11613: directcondval($number) : get current value of a condition; reads from a state
11614: string
1.204 albertel 11615:
11616: =item *
11617:
1.243 albertel 11618: condval($condidx) : value of condition index based on state
1.204 albertel 11619:
11620: =item *
11621:
1.243 albertel 11622: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11623: resource's metadata, $what should be either a specific key, or either
11624: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11625: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11626:
11627: this function automatically caches all requests
1.191 harris41 11628:
11629: =item *
11630:
1.243 albertel 11631: metadata_query($query,$custom,$customshow) : make a metadata query against the
11632: network of library servers; returns file handle of where SQL and regex results
11633: will be stored for query
1.191 harris41 11634:
11635: =item *
11636:
1.243 albertel 11637: symbread($filename) : return symbolic list entry (filename argument optional);
11638: returns the data handle
1.191 harris41 11639:
11640: =item *
11641:
1.243 albertel 11642: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 11643: a possible symb for the URL in $thisfn, and if is an encryypted
11644: resource that the user accessed using /enc/ returns a 1 on success, 0
11645: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 11646: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 11647:
1.191 harris41 11648:
11649: =item *
11650:
1.243 albertel 11651: symbclean($symb) : removes versions numbers from a symb, returns the
11652: cleaned symb
1.191 harris41 11653:
11654: =item *
11655:
1.243 albertel 11656: is_on_map($uri) : checks if the $uri is somewhere on the current
11657: course map, user must be in a course for it to work.
1.191 harris41 11658:
11659: =item *
11660:
1.243 albertel 11661: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 11662:
11663: =item *
11664:
1.243 albertel 11665: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11666: a random seed, all arguments are optional, if they aren't sent it uses the
11667: environment to derive them. Note: if symb isn't sent and it can't get one
11668: from &symbread it will use the current time as its return value
1.191 harris41 11669:
11670: =item *
11671:
1.243 albertel 11672: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11673: unfakeable, receipt
1.191 harris41 11674:
11675: =item *
11676:
1.620 albertel 11677: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 11678:
11679: =item *
11680:
1.243 albertel 11681: countacc($url) : count the number of accesses to a given URL
1.191 harris41 11682:
11683: =item *
11684:
1.243 albertel 11685: 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 11686:
11687: =item *
11688:
1.243 albertel 11689: 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 11690:
11691: =item *
11692:
1.243 albertel 11693: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 11694:
11695: =item *
11696:
1.243 albertel 11697: devalidate($symb) : devalidate temporary spreadsheet calculations,
11698: forcing spreadsheet to reevaluate the resource scores next time.
11699:
11700: =back
11701:
11702: =head2 Storing/Retreiving Data
11703:
11704: =over 4
1.191 harris41 11705:
11706: =item *
11707:
1.243 albertel 11708: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11709: for this url; hashref needs to be given and should be a \%hashname; the
11710: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 11711: be derived from the env
1.191 harris41 11712:
11713: =item *
11714:
1.243 albertel 11715: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11716: uses critical subroutine
1.191 harris41 11717:
11718: =item *
11719:
1.243 albertel 11720: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11721: all args are optional
1.191 harris41 11722:
11723: =item *
11724:
1.717 albertel 11725: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11726: dumps the complete (or key matching regexp) namespace into a hash
11727: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11728: normally &store()ed into
11729:
11730: $range should be either an integer '100' (give me the first 100
11731: matching records)
11732: or be two integers sperated by a - with no spaces
11733: '30-50' (give me the 30th through the 50th matching
11734: records)
11735:
11736:
11737: =item *
11738:
11739: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11740: replaces a &store() version of data with a replacement set of data
11741: for a particular resource in a namespace passed in the $storehash hash
11742: reference
11743:
11744: =item *
11745:
1.243 albertel 11746: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11747: works very similar to store/cstore, but all data is stored in a
11748: temporary location and can be reset using tmpreset, $storehash should
11749: be a hash reference, returns nothing on success
1.191 harris41 11750:
11751: =item *
11752:
1.243 albertel 11753: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11754: similar to restore, but all data is stored in a temporary location and
11755: can be reset using tmpreset. Returns a hash of values on success,
11756: error string otherwise.
1.191 harris41 11757:
11758: =item *
11759:
1.243 albertel 11760: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11761: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 11762:
11763: =item *
11764:
1.243 albertel 11765: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11766: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11767:
11768: =item *
11769:
1.243 albertel 11770: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11771: namesp ($udom and $uname are optional)
1.191 harris41 11772:
11773: =item *
11774:
1.702 albertel 11775: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11776: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11777: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11778:
1.702 albertel 11779: $range should be either an integer '100' (give me the first 100
11780: matching records)
11781: or be two integers sperated by a - with no spaces
11782: '30-50' (give me the 30th through the 50th matching
11783: records)
1.449 matthew 11784: =item *
11785:
11786: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11787: $store can be a scalar, an array reference, or if the amount to be
11788: incremented is > 1, a hash reference.
11789:
11790: ($udom and $uname are optional)
1.191 harris41 11791:
11792: =item *
11793:
1.243 albertel 11794: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11795: ($udom and $uname are optional)
1.191 harris41 11796:
11797: =item *
11798:
1.243 albertel 11799: cput($namespace,$storehash,$udom,$uname) : critical put
11800: ($udom and $uname are optional)
1.191 harris41 11801:
11802: =item *
11803:
1.748 albertel 11804: newput($namespace,$storehash,$udom,$uname) :
11805:
11806: Attempts to store the items in the $storehash, but only if they don't
11807: currently exist, if this succeeds you can be certain that you have
11808: successfully created a new key value pair in the $namespace db.
11809:
11810:
11811: Args:
11812: $namespace: name of database to store values to
11813: $storehash: hashref to store to the db
11814: $udom: (optional) domain of user containing the db
11815: $uname: (optional) name of user caontaining the db
11816:
11817: Returns:
11818: 'ok' -> succeeded in storing all keys of $storehash
11819: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11820: least <key> already existed in the db (other
11821: requested keys may also already exist)
1.967 bisitz 11822: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11823: 'con_lost' -> unable to contact request server
11824: 'refused' -> action was not allowed by remote machine
11825:
11826:
11827: =item *
11828:
1.243 albertel 11829: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11830: reference filled in from namesp (encrypts the return communication)
11831: ($udom and $uname are optional)
1.191 harris41 11832:
11833: =item *
11834:
1.243 albertel 11835: log($udom,$name,$home,$message) : write to permanent log for user; use
11836: critical subroutine
11837:
1.806 raeburn 11838: =item *
11839:
1.860 raeburn 11840: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11841: array reference filled in from namespace found in domain level on either
11842: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11843:
11844: =item *
11845:
1.860 raeburn 11846: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11847: domain level either on specified domain server ($uhome) or primary domain
11848: server ($udom and $uhome are optional)
1.806 raeburn 11849:
1.943 raeburn 11850: =item *
11851:
11852: get_domain_defaults($target_domain) : returns hash with defaults for
11853: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11854: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11855: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11856: Values are retrieved from cache (if current), or from domain's configuration.db
11857: (if available), or lastly from values in lonTabs/dns_domain,tab,
11858: or lonTabs/domain.tab.
11859:
11860: %domdefaults = &get_auth_defaults($target_domain);
11861:
1.243 albertel 11862: =back
11863:
11864: =head2 Network Status Functions
11865:
11866: =over 4
1.191 harris41 11867:
11868: =item *
11869:
1.1137 raeburn 11870: dirlist() : return directory list based on URI (first arg).
11871:
11872: Inputs: 1 required, 5 optional.
11873:
11874: =over
11875:
11876: =item
11877: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
11878:
11879: =item
11880: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
11881:
11882: =item
11883: $username - username of user/course to be listed. Extracted from $uri if absent.
11884:
11885: =item
11886: $getpropath - boolean: 1 if prepend path using &propath().
11887:
11888: =item
11889: $getuserdir - boolean: 1 if prepend path for "userfiles".
11890:
11891: =item
11892: $alternateRoot - path to prepend in place of path from $uri.
11893:
11894: =back
11895:
11896: Returns: Array of up to two items.
11897:
11898: =over
11899:
11900: a reference to an array of files/subdirectories
11901:
11902: =over
11903:
11904: Each element in the array of files/subdirectories is a & separated list of
11905: item name and the result of running stat on the item. If dirlist was requested
11906: for a file instead of a directory, the item name will be ''. For a directory
11907: listing, if the item is a metadata file, the element will end &N&M
11908: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
11909: default copyright set (1).
11910:
11911: =back
11912:
11913: a scalar containing error condition (if encountered).
11914:
11915: =over
11916:
11917: =item
11918: no_host (no homeserver identified for $username:$domain).
11919:
11920: =item
11921: no_such_host (server contacted for listing not identified as valid host).
11922:
11923: =item
11924: con_lost (connection to remote server failed).
11925:
11926: =item
11927: refused (invalid $username:$domain received on lond side).
11928:
11929: =item
11930: no_such_dir (directory at specified path on lond side does not exist).
11931:
11932: =item
11933: empty (directory at specified path on lond side is empty).
11934:
11935: =over
11936:
11937: This is currently not encountered because the &ls3, &ls2,
11938: &ls (_handler) routines on the lond side do not filter out
11939: . and .. from a directory listing.
11940:
11941: =back
11942:
11943: =back
11944:
11945: =back
1.191 harris41 11946:
11947: =item *
11948:
1.243 albertel 11949: spareserver() : find server with least workload from spare.tab
11950:
1.986 foxr 11951:
11952: =item *
11953:
11954: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11955: if there is no corresponding loncapa host.
11956:
1.243 albertel 11957: =back
11958:
1.986 foxr 11959:
1.243 albertel 11960: =head2 Apache Request
11961:
11962: =over 4
1.191 harris41 11963:
11964: =item *
11965:
1.243 albertel 11966: ssi($url,%hash) : server side include, does a complete request cycle on url to
11967: localhost, posts hash
11968:
11969: =back
11970:
11971: =head2 Data to String to Data
11972:
11973: =over 4
1.191 harris41 11974:
11975: =item *
11976:
1.243 albertel 11977: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11978: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11979:
11980: =item *
11981:
1.243 albertel 11982: hashref2str($hashref) : convert a hashref into a string complete with
11983: escaping and '=' and '&' separators, supports elements that are
11984: arrayrefs and hashrefs
1.191 harris41 11985:
11986: =item *
11987:
1.243 albertel 11988: arrayref2str($arrayref) : convert an arrayref into a string complete
11989: with escaping and '&' separators, supports elements that are arrayrefs
11990: and hashrefs
1.191 harris41 11991:
11992: =item *
11993:
1.243 albertel 11994: str2hash($string) : convert string to hash using unescaping and
11995: splitting on '=' and '&', supports elements that are arrayrefs and
11996: hashrefs
1.191 harris41 11997:
11998: =item *
11999:
1.243 albertel 12000: str2array($string) : convert string to hash using unescaping and
12001: splitting on '&', supports elements that are arrayrefs and hashrefs
12002:
12003: =back
12004:
12005: =head2 Logging Routines
12006:
12007:
12008: These routines allow one to make log messages in the lonnet.log and
12009: lonnet.perm logfiles.
1.191 harris41 12010:
1.1119 foxr 12011: =over 4
12012:
1.191 harris41 12013: =item *
12014:
1.243 albertel 12015: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 12016:
12017: =item *
12018:
1.243 albertel 12019: logthis() : append message to the normal lonnet.log file, it gets
12020: preiodically rolled over and deleted.
1.191 harris41 12021:
12022: =item *
12023:
1.243 albertel 12024: logperm() : append a permanent message to lonnet.perm.log, this log
12025: file never gets deleted by any automated portion of the system, only
12026: messages of critical importance should go in here.
12027:
1.1119 foxr 12028:
1.243 albertel 12029: =back
12030:
12031: =head2 General File Helper Routines
12032:
12033: =over 4
1.191 harris41 12034:
12035: =item *
12036:
1.481 raeburn 12037: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12038: (a) files in /uploaded
12039: (i) If a local copy of the file exists -
12040: compares modification date of local copy with last-modified date for
12041: definitive version stored on home server for course. If local copy is
12042: stale, requests a new version from the home server and stores it.
12043: If the original has been removed from the home server, then local copy
12044: is unlinked.
12045: (ii) If local copy does not exist -
12046: requests the file from the home server and stores it.
12047:
12048: If $caller is 'uploadrep':
12049: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12050: for request for files originally uploaded via DOCS.
12051: - returns 'ok' if fresh local copy now available, -1 otherwise.
12052:
12053: Otherwise:
12054: This indicates a call from the content generation phase of the request.
12055: - returns the entire contents of the file or -1.
12056:
12057: (b) files in /res
12058: - returns the entire contents of a file or -1;
12059: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 12060:
1.712 albertel 12061:
12062: =item *
12063:
12064: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12065: reference
12066:
12067: returns either a stat() list of data about the file or an empty list
12068: if the file doesn't exist or couldn't find out about it (connection
12069: problems or user unknown)
12070:
1.191 harris41 12071: =item *
12072:
1.243 albertel 12073: filelocation($dir,$file) : returns file system location of a file
12074: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12075: directory that relative $file lookups are to looked in ($dir of /a/dir
12076: and a file of ../bob will become /a/bob)
1.191 harris41 12077:
12078: =item *
12079:
12080: hreflocation($dir,$file) : returns file system location or a URL; same as
12081: filelocation except for hrefs
12082:
12083: =item *
12084:
12085: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12086:
1.243 albertel 12087: =back
12088:
1.608 albertel 12089: =head2 Usererfile file routines (/uploaded*)
12090:
12091: =over 4
12092:
12093: =item *
12094:
12095: userfileupload(): main rotine for putting a file in a user or course's
12096: filespace, arguments are,
12097:
1.620 albertel 12098: formname - required - this is the name of the element in $env where the
1.608 albertel 12099: filename, and the contents of the file to create/modifed exist
1.620 albertel 12100: the filename is in $env{'form.'.$formname.'.filename'} and the
12101: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 12102: context - if coursedoc, store the file in the course of the active role
12103: of the current user;
12104: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12105: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 12106: subdir - required - subdirectory to put the file in under ../userfiles/
12107: if undefined, it will be placed in "unknown"
12108:
12109: (This routine calls clean_filename() to remove any dangerous
12110: characters from the filename, and then calls finuserfileupload() to
12111: complete the transaction)
12112:
12113: returns either the url of the uploaded file (/uploaded/....) if successful
12114: and /adm/notfound.html if unsuccessful
12115:
12116: =item *
12117:
12118: clean_filename(): routine for cleaing a filename up for storage in
12119: userfile space, argument is:
12120:
12121: filename - proposed filename
12122:
12123: returns: the new clean filename
12124:
12125: =item *
12126:
1.1090 raeburn 12127: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 12128: userspace, probably shouldn't be called directly
12129:
12130: docuname: username or courseid of destination for the file
12131: docudom: domain of user/course of destination for the file
12132: formname: same as for userfileupload()
1.1090 raeburn 12133: fname: filename (including subdirectories) for the file
12134: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12135: allfiles: reference to hash used to store objects found by parser
12136: codebase: reference to hash used for codebases of java objects found by parser
12137: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12138: thumbheight: height (pixels) of thumbnail to be created for uploaded image
12139: resizewidth: width to be used to resize image using resizeImage from ImageMagick
12140: resizeheight: height to be used to resize image using resizeImage from ImageMagick
12141: context: if 'overwrite', will move the uploaded file from its temporary location to
12142: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 12143: mimetype: reference to scalar to accommodate mime type determined
12144: from File::MMagic if $parser = parse.
1.608 albertel 12145:
12146: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 12147: and /adm/notfound.html if unsuccessful (or an error message if context
12148: was 'overwrite').
12149:
1.608 albertel 12150:
12151: =item *
12152:
12153: renameuserfile(): renames an existing userfile to a new name
12154:
12155: Args:
12156: docuname: username or courseid of destination for the file
12157: docudom: domain of user/course of destination for the file
12158: old: current file name (including any subdirs under userfiles)
12159: new: desired file name (including any subdirs under userfiles)
12160:
12161: =item *
12162:
12163: mkdiruserfile(): creates a directory is a userfiles dir
12164:
12165: Args:
12166: docuname: username or courseid of destination for the file
12167: docudom: domain of user/course of destination for the file
12168: dir: dir to create (including any subdirs under userfiles)
12169:
12170: =item *
12171:
12172: removeuserfile(): removes a file that exists in userfiles
12173:
12174: Args:
12175: docuname: username or courseid of destination for the file
12176: docudom: domain of user/course of destination for the file
12177: fname: filname to delete (including any subdirs under userfiles)
12178:
12179: =item *
12180:
12181: removeuploadedurl(): convience function for removeuserfile()
12182:
12183: Args:
12184: url: a full /uploaded/... url to delete
12185:
1.747 albertel 12186: =item *
12187:
12188: get_portfile_permissions():
12189: Args:
12190: domain: domain of user or course contain the portfolio files
12191: user: name of user or num of course contain the portfolio files
12192: Returns:
12193: hashref of a dump of the proper file_permissions.db
12194:
12195:
12196: =item *
12197:
12198: get_access_controls():
12199:
12200: Args:
12201: current_permissions: the hash ref returned from get_portfile_permissions()
12202: group: (optional) the group you want the files associated with
12203: file: (optional) the file you want access info on
12204:
12205: Returns:
1.749 raeburn 12206: a hash (keys are file names) of hashes containing
12207: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12208: values are XML containing access control settings (see below)
1.747 albertel 12209:
12210: Internal notes:
12211:
1.749 raeburn 12212: access controls are stored in file_permissions.db as key=value pairs.
12213: key -> path to file/file_name\0uniqueID:scope_end_start
12214: where scope -> public,guest,course,group,domains or users.
12215: end -> UNIX time for end of access (0 -> no end date)
12216: start -> UNIX time for start of access
12217:
12218: value -> XML description of access control
12219: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12220: <start></start>
12221: <end></end>
12222:
12223: <password></password> for scope type = guest
12224:
12225: <domain></domain> for scope type = course or group
12226: <number></number>
12227: <roles id="">
12228: <role></role>
12229: <access></access>
12230: <section></section>
12231: <group></group>
12232: </roles>
12233:
12234: <dom></dom> for scope type = domains
12235:
12236: <users> for scope type = users
12237: <user>
12238: <uname></uname>
12239: <udom></udom>
12240: </user>
12241: </users>
12242: </scope>
12243:
12244: Access data is also aggregated for each file in an additional key=value pair:
12245: key -> path to file/file_name\0accesscontrol
12246: value -> reference to hash
12247: hash contains key = value pairs
12248: where key = uniqueID:scope_end_start
12249: value = UNIX time record was last updated
12250:
12251: Used to improve speed of look-ups of access controls for each file.
12252:
12253: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12254:
12255: modify_access_controls():
12256:
12257: Modifies access controls for a portfolio file
12258: Args
12259: 1. file name
12260: 2. reference to hash of required changes,
12261: 3. domain
12262: 4. username
12263: where domain,username are the domain of the portfolio owner
12264: (either a user or a course)
12265:
12266: Returns:
12267: 1. result of additions or updates ('ok' or 'error', with error message).
12268: 2. result of deletions ('ok' or 'error', with error message).
12269: 3. reference to hash of any new or updated access controls.
12270: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12271: key = integer (inbound ID)
12272: value = uniqueID
1.747 albertel 12273:
1.608 albertel 12274: =back
12275:
1.243 albertel 12276: =head2 HTTP Helper Routines
12277:
12278: =over 4
12279:
1.191 harris41 12280: =item *
12281:
12282: escape() : unpack non-word characters into CGI-compatible hex codes
12283:
12284: =item *
12285:
12286: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12287:
1.243 albertel 12288: =back
12289:
12290: =head1 PRIVATE SUBROUTINES
12291:
12292: =head2 Underlying communication routines (Shouldn't call)
12293:
12294: =over 4
12295:
12296: =item *
12297:
12298: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12299:
12300: =item *
12301:
12302: reply() : uses subreply to send a message to remote machine, logs all failures
12303:
12304: =item *
12305:
12306: critical() : passes a critical message to another server; if cannot
12307: get through then place message in connection buffer directory and
12308: returns con_delayed, if incapable of saving message, returns
12309: con_failed
12310:
12311: =item *
12312:
12313: reconlonc() : tries to reconnect lonc client processes.
12314:
12315: =back
12316:
12317: =head2 Resource Access Logging
12318:
12319: =over 4
12320:
12321: =item *
12322:
12323: flushcourselogs() : flush (save) buffer logs and access logs
12324:
12325: =item *
12326:
12327: courselog($what) : save message for course in hash
12328:
12329: =item *
12330:
12331: courseacclog($what) : save message for course using &courselog(). Perform
12332: special processing for specific resource types (problems, exams, quizzes, etc).
12333:
1.191 harris41 12334: =item *
12335:
12336: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12337: as a PerlChildExitHandler
1.243 albertel 12338:
12339: =back
12340:
12341: =head2 Other
12342:
12343: =over 4
12344:
12345: =item *
12346:
12347: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 12348:
12349: =back
12350:
12351: =cut
1.877 foxr 12352:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>