Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1129
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1129 ! raeburn 4: # $Id: lonnet.pm,v 1.1128 2011/08/09 01:06:33 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1079 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
1.871 albertel 80:
81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
82: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
83: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 84: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 85:
1.1 albertel 86: use IO::Socket;
1.31 www 87: use GDBM_File;
1.208 albertel 88: use HTML::LCParser;
1.88 www 89: use Fcntl qw(:flock);
1.870 albertel 90: use Storable qw(thaw nfreeze);
1.539 albertel 91: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 92: use Cache::Memcached;
1.676 albertel 93: use Digest::MD5;
1.790 albertel 94: use Math::Random;
1.1024 raeburn 95: use File::MMagic;
1.807 albertel 96: use LONCAPA qw(:DEFAULT :match);
1.740 www 97: use LONCAPA::Configuration;
1.1117 foxr 98:
1.1090 raeburn 99: use File::Copy;
1.676 albertel 100:
1.195 www 101: my $readit;
1.550 foxr 102: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 103:
1.619 albertel 104: require Exporter;
105:
106: our @ISA = qw (Exporter);
107: our @EXPORT = qw(%env);
108:
1.449 matthew 109:
1.1 albertel 110: # --------------------------------------------------------------------- Logging
1.729 www 111: {
112: my $logid;
113: sub instructor_log {
1.957 raeburn 114: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
115: if (($cnum eq '') || ($cdom eq '')) {
116: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
117: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
118: }
1.729 www 119: $logid++;
1.957 raeburn 120: my $now = time();
121: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 122: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 123: { $id => {
124: 'exe_uname' => $env{'user.name'},
125: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 126: 'exe_time' => $now,
1.730 www 127: 'exe_ip' => $ENV{'REMOTE_ADDR'},
128: 'delflag' => $delflag,
129: 'logentry' => $storehash,
130: 'uname' => $uname,
131: 'udom' => $udom,
132: }
1.957 raeburn 133: },$cdom,$cnum);
1.729 www 134: }
135: }
1.1 albertel 136:
1.163 harris41 137: sub logtouch {
138: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 139: unless (-e "$execdir/logs/lonnet.log") {
140: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 141: close $fh;
142: }
143: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
144: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
145: }
146:
1.1 albertel 147: sub logthis {
148: my $message=shift;
149: my $execdir=$perlvar{'lonDaemons'};
150: my $now=time;
151: my $local=localtime($now);
1.448 albertel 152: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 153: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
154: print $fh $logstring;
1.448 albertel 155: close($fh);
156: }
1.1 albertel 157: return 1;
158: }
159:
160: sub logperm {
161: my $message=shift;
162: my $execdir=$perlvar{'lonDaemons'};
163: my $now=time;
164: my $local=localtime($now);
1.448 albertel 165: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
166: print $fh "$now:$message:$local\n";
167: close($fh);
168: }
1.1 albertel 169: return 1;
170: }
171:
1.850 albertel 172: sub create_connection {
1.853 albertel 173: my ($hostname,$lonid) = @_;
1.851 albertel 174: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 175: Type => SOCK_STREAM,
176: Timeout => 10);
177: return 0 if (!$client);
1.890 albertel 178: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 179: my $result = <$client>;
180: chomp($result);
181: return 1 if ($result eq 'done');
182: return 0;
183: }
184:
1.983 raeburn 185: sub get_server_timezone {
186: my ($cnum,$cdom) = @_;
187: my $home=&homeserver($cnum,$cdom);
188: if ($home ne 'no_host') {
189: my $cachetime = 24*3600;
190: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
191: if (defined($cached)) {
192: return $timezone;
193: } else {
194: my $timezone = &reply('servertimezone',$home);
195: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
196: }
197: }
198: }
1.850 albertel 199:
1.1106 raeburn 200: sub get_server_distarch {
201: my ($lonhost,$ignore_cache) = @_;
202: if (defined($lonhost)) {
203: if (!defined(&hostname($lonhost))) {
204: return;
205: }
206: my $cachetime = 12*3600;
207: if (!$ignore_cache) {
208: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
209: if (defined($cached)) {
210: return $distarch;
211: }
212: }
213: my $rep = &reply('serverdistarch',$lonhost);
214: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
215: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
216: $rep eq '') {
217: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
218: }
219: }
220: return;
221: }
222:
1.993 raeburn 223: sub get_server_loncaparev {
1.1073 raeburn 224: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 225: if (defined($lonhost)) {
226: if (!defined(&hostname($lonhost))) {
227: undef($lonhost);
228: }
229: }
230: if (!defined($lonhost)) {
231: if (defined(&domain($dom,'primary'))) {
232: $lonhost=&domain($dom,'primary');
233: if ($lonhost eq 'no_host') {
234: undef($lonhost);
235: }
236: }
237: }
238: if (defined($lonhost)) {
1.1073 raeburn 239: my $cachetime = 12*3600;
240: if (!$ignore_cache) {
241: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
242: if (defined($cached)) {
243: return $loncaparev;
244: }
245: }
246: my ($answer,$loncaparev);
247: my @ids=¤t_machine_ids();
248: if (grep(/^\Q$lonhost\E$/,@ids)) {
249: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 250: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 251: $loncaparev = $1;
252: }
253: } else {
254: $answer = &reply('serverloncaparev',$lonhost);
255: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
256: if ($caller eq 'loncron') {
257: my $ua=new LWP::UserAgent;
1.1082 raeburn 258: $ua->timeout(4);
1.1073 raeburn 259: my $protocol = $protocol{$lonhost};
260: $protocol = 'http' if ($protocol ne 'https');
261: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
262: my $request=new HTTP::Request('GET',$url);
263: my $response=$ua->request($request);
264: unless ($response->is_error()) {
265: my $content = $response->content;
1.1081 raeburn 266: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 267: $loncaparev = $1;
268: }
269: }
270: } else {
271: $loncaparev = $loncaparevs{$lonhost};
272: }
1.1081 raeburn 273: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 274: $loncaparev = $1;
275: }
1.993 raeburn 276: }
1.1073 raeburn 277: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 278: }
279: }
280:
1.1074 raeburn 281: sub get_server_homeID {
282: my ($hostname,$ignore_cache,$caller) = @_;
283: unless ($ignore_cache) {
284: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
285: if (defined($cached)) {
286: return $serverhomeID;
287: }
288: }
289: my $cachetime = 12*3600;
290: my $serverhomeID;
291: if ($caller eq 'loncron') {
292: my @machine_ids = &machine_ids($hostname);
293: foreach my $id (@machine_ids) {
294: my $response = &reply('serverhomeID',$id);
295: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
296: $serverhomeID = $response;
297: last;
298: }
299: }
300: if ($serverhomeID eq '') {
301: $serverhomeID = $machine_ids[-1];
302: }
303: } else {
304: $serverhomeID = $serverhomeIDs{$hostname};
305: }
306: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
307: }
308:
1.1121 raeburn 309: sub get_remote_globals {
310: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 311: my ($result,%returnhash,%whatneeded);
312: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 313: foreach my $what (sort(keys(%{$whathash}))) {
314: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 315: my ($response,$cached);
1.1121 raeburn 316: unless ($ignore_cache) {
1.1125 raeburn 317: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 318: }
319: if (defined($cached)) {
1.1125 raeburn 320: $returnhash{$what} = $response;
1.1121 raeburn 321: } else {
1.1125 raeburn 322: $whatneeded{$what} = 1;
1.1121 raeburn 323: }
324: }
1.1125 raeburn 325: if (keys(%whatneeded) == 0) {
326: $result = 'ok';
327: } else {
1.1121 raeburn 328: my $requested = &freeze_escape(\%whatneeded);
329: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 330: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
331: ($rep eq 'unknown_cmd')) {
332: $result = $rep;
333: } else {
334: $result = 'ok';
1.1121 raeburn 335: my @pairs=split(/\&/,$rep);
1.1125 raeburn 336: foreach my $item (@pairs) {
337: my ($key,$value)=split(/=/,$item,2);
338: my $what = &unescape($key);
339: my $hashid = $lonhost.'-'.$what;
340: $returnhash{$what}=&thaw_unescape($value);
341: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 342: }
343: }
344: }
345: }
1.1125 raeburn 346: return ($result,\%returnhash);
1.1121 raeburn 347: }
348:
1.1124 raeburn 349: sub remote_devalidate_cache {
350: my ($lonhost,$name,$id) = @_;
351: my $response = &reply('devalidatecache',&escape($name).':'.&escape($id),$lonhost);
352: return $response;
353: }
354:
1.1 albertel 355: # -------------------------------------------------- Non-critical communication
356: sub subreply {
357: my ($cmd,$server)=@_;
1.838 albertel 358: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 359: #
360: # With loncnew process trimming, there's a timing hole between lonc server
361: # process exit and the master server picking up the listen on the AF_UNIX
362: # socket. In that time interval, a lock file will exist:
363:
364: my $lockfile=$peerfile.".lock";
365: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
366: sleep(1);
367: }
368: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 369: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 370: #
1.550 foxr 371: # We'll give the connection a few tries before abandoning it. If
372: # connection is not possible, we'll con_lost back to the client.
373: #
374: my $client;
375: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
376: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
377: Type => SOCK_STREAM,
378: Timeout => 10);
1.869 albertel 379: if ($client) {
1.550 foxr 380: last; # Connected!
1.850 albertel 381: } else {
1.853 albertel 382: &create_connection(&hostname($server),$server);
1.550 foxr 383: }
1.850 albertel 384: sleep(1); # Try again later if failed connection.
1.550 foxr 385: }
386: my $answer;
387: if ($client) {
1.704 albertel 388: print $client "sethost:$server:$cmd\n";
1.550 foxr 389: $answer=<$client>;
390: if (!$answer) { $answer="con_lost"; }
391: chomp($answer);
392: } else {
393: $answer = 'con_lost'; # Failed connection.
394: }
1.1 albertel 395: return $answer;
396: }
397:
398: sub reply {
399: my ($cmd,$server)=@_;
1.838 albertel 400: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 401: my $answer=subreply($cmd,$server);
1.65 www 402: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 403: &logthis("<font color=\"blue\">WARNING:".
1.12 www 404: " $cmd to $server returned $answer</font>");
405: }
1.1 albertel 406: return $answer;
407: }
408:
409: # ----------------------------------------------------------- Send USR1 to lonc
410:
411: sub reconlonc {
1.891 albertel 412: my ($lonid) = @_;
413: my $hostname = &hostname($lonid);
414: if ($lonid) {
415: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
416: if ($hostname && -e $peerfile) {
417: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
418: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
419: Type => SOCK_STREAM,
420: Timeout => 10);
421: if ($client) {
422: print $client ("reset_retries\n");
423: my $answer=<$client>;
424: #reset just this one.
425: }
426: }
427: return;
428: }
429:
1.836 www 430: &logthis("Trying to reconnect lonc");
1.1 albertel 431: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 432: if (open(my $fh,"<$loncfile")) {
1.1 albertel 433: my $loncpid=<$fh>;
434: chomp($loncpid);
435: if (kill 0 => $loncpid) {
436: &logthis("lonc at pid $loncpid responding, sending USR1");
437: kill USR1 => $loncpid;
438: sleep 1;
1.836 www 439: } else {
1.12 www 440: &logthis(
1.672 albertel 441: "<font color=\"blue\">WARNING:".
1.12 www 442: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 443: }
444: } else {
1.836 www 445: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 446: }
447: }
448:
449: # ------------------------------------------------------ Critical communication
1.12 www 450:
1.1 albertel 451: sub critical {
452: my ($cmd,$server)=@_;
1.838 albertel 453: unless (&hostname($server)) {
1.672 albertel 454: &logthis("<font color=\"blue\">WARNING:".
1.89 www 455: " Critical message to unknown server ($server)</font>");
456: return 'no_such_host';
457: }
1.1 albertel 458: my $answer=reply($cmd,$server);
459: if ($answer eq 'con_lost') {
460: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 461: my $answer=reply($cmd,$server);
1.1 albertel 462: if ($answer eq 'con_lost') {
463: my $now=time;
464: my $middlename=$cmd;
1.5 www 465: $middlename=substr($middlename,0,16);
1.1 albertel 466: $middlename=~s/\W//g;
467: my $dfilename=
1.305 www 468: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
469: $dumpcount++;
1.1 albertel 470: {
1.448 albertel 471: my $dfh;
472: if (open($dfh,">$dfilename")) {
473: print $dfh "$cmd\n";
474: close($dfh);
475: }
1.1 albertel 476: }
477: sleep 2;
478: my $wcmd='';
479: {
1.448 albertel 480: my $dfh;
481: if (open($dfh,"<$dfilename")) {
482: $wcmd=<$dfh>;
483: close($dfh);
484: }
1.1 albertel 485: }
486: chomp($wcmd);
1.7 www 487: if ($wcmd eq $cmd) {
1.672 albertel 488: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 489: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 490: &logperm("D:$server:$cmd");
491: return 'con_delayed';
492: } else {
1.672 albertel 493: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 494: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 495: &logperm("F:$server:$cmd");
496: return 'con_failed';
497: }
498: }
499: }
500: return $answer;
1.405 albertel 501: }
502:
1.755 albertel 503: # ------------------------------------------- check if return value is an error
504:
505: sub error {
506: my ($result) = @_;
1.756 albertel 507: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 508: if ($2 == 2) { return undef; }
509: return $1;
510: }
511: return undef;
512: }
513:
1.783 albertel 514: sub convert_and_load_session_env {
515: my ($lonidsdir,$handle)=@_;
516: my @profile;
517: {
1.917 albertel 518: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
519: if (!$opened) {
1.915 albertel 520: return 0;
521: }
1.783 albertel 522: flock($idf,LOCK_SH);
523: @profile=<$idf>;
524: close($idf);
525: }
526: my %temp_env;
527: foreach my $line (@profile) {
1.786 albertel 528: if ($line !~ m/=/) {
529: return 0;
530: }
1.783 albertel 531: chomp($line);
532: my ($envname,$envvalue)=split(/=/,$line,2);
533: $temp_env{&unescape($envname)} = &unescape($envvalue);
534: }
535: unlink("$lonidsdir/$handle.id");
536: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
537: 0640)) {
538: %disk_env = %temp_env;
539: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
540: untie(%disk_env);
541: }
1.786 albertel 542: return 1;
1.783 albertel 543: }
544:
1.374 www 545: # ------------------------------------------- Transfer profile into environment
1.780 albertel 546: my $env_loaded;
547: sub transfer_profile_to_env {
1.788 albertel 548: my ($lonidsdir,$handle,$force_transfer) = @_;
549: if (!$force_transfer && $env_loaded) { return; }
1.374 www 550:
1.720 albertel 551: if (!defined($lonidsdir)) {
552: $lonidsdir = $perlvar{'lonIDsDir'};
553: }
554: if (!defined($handle)) {
555: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
556: }
557:
1.786 albertel 558: my $convert;
559: {
1.917 albertel 560: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
561: if (!$opened) {
1.915 albertel 562: return;
563: }
1.786 albertel 564: flock($idf,LOCK_SH);
565: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
566: &GDBM_READER(),0640)) {
567: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
568: untie(%disk_env);
569: } else {
570: $convert = 1;
571: }
572: }
573: if ($convert) {
574: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
575: &logthis("Failed to load session, or convert session.");
576: }
1.374 www 577: }
1.783 albertel 578:
1.786 albertel 579: my %remove;
1.783 albertel 580: while ( my $envname = each(%env) ) {
1.433 matthew 581: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
582: if ($time < time-300) {
1.783 albertel 583: $remove{$key}++;
1.433 matthew 584: }
585: }
586: }
1.783 albertel 587:
1.619 albertel 588: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 589: $env_loaded=1;
1.783 albertel 590: foreach my $expired_key (keys(%remove)) {
1.433 matthew 591: &delenv($expired_key);
1.374 www 592: }
1.1 albertel 593: }
594:
1.916 albertel 595: # ---------------------------------------------------- Check for valid session
596: sub check_for_valid_session {
597: my ($r) = @_;
598: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
599: my $lonid=$cookies{'lonID'};
600: return undef if (!$lonid);
601:
602: my $handle=&LONCAPA::clean_handle($lonid->value);
603: my $lonidsdir=$r->dir_config('lonIDsDir');
604: return undef if (!-e "$lonidsdir/$handle.id");
605:
1.917 albertel 606: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
607: return undef if (!$opened);
1.916 albertel 608:
609: flock($idf,LOCK_SH);
610: my %disk_env;
611: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
612: &GDBM_READER(),0640)) {
613: return undef;
614: }
615:
616: if (!defined($disk_env{'user.name'})
617: || !defined($disk_env{'user.domain'})) {
618: return undef;
619: }
620: return $handle;
621: }
622:
1.830 albertel 623: sub timed_flock {
624: my ($file,$lock_type) = @_;
625: my $failed=0;
626: eval {
627: local $SIG{__DIE__}='DEFAULT';
628: local $SIG{ALRM}=sub {
629: $failed=1;
630: die("failed lock");
631: };
632: alarm(13);
633: flock($file,$lock_type);
634: alarm(0);
635: };
636: if ($failed) {
637: return undef;
638: } else {
639: return 1;
640: }
641: }
642:
1.5 www 643: # ---------------------------------------------------------- Append Environment
644:
645: sub appenv {
1.949 raeburn 646: my ($newenv,$roles) = @_;
647: if (ref($newenv) eq 'HASH') {
648: foreach my $key (keys(%{$newenv})) {
649: my $refused = 0;
650: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
651: $refused = 1;
652: if (ref($roles) eq 'ARRAY') {
653: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
654: if (grep(/^\Q$role\E$/,@{$roles})) {
655: $refused = 0;
656: }
657: }
658: }
659: if ($refused) {
660: &logthis("<font color=\"blue\">WARNING: ".
661: "Attempt to modify environment ".$key." to ".$newenv->{$key}
662: .'</font>');
663: delete($newenv->{$key});
664: } else {
665: $env{$key}=$newenv->{$key};
666: }
667: }
668: my $opened = open(my $env_file,'+<',$env{'user.environment'});
669: if ($opened
670: && &timed_flock($env_file,LOCK_EX)
671: &&
672: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
673: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
674: while (my ($key,$value) = each(%{$newenv})) {
675: $disk_env{$key} = $value;
676: }
677: untie(%disk_env);
1.35 www 678: }
1.191 harris41 679: }
1.56 www 680: return 'ok';
681: }
682: # ----------------------------------------------------- Delete from Environment
683:
684: sub delenv {
1.1104 raeburn 685: my ($delthis,$regexp,$roles) = @_;
686: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
687: my $refused = 1;
688: if (ref($roles) eq 'ARRAY') {
689: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
690: if (grep(/^\Q$role\E$/,@{$roles})) {
691: $refused = 0;
692: }
693: }
694: if ($refused) {
695: &logthis("<font color=\"blue\">WARNING: ".
696: "Attempt to delete from environment ".$delthis);
697: return 'error';
698: }
1.56 www 699: }
1.917 albertel 700: my $opened = open(my $env_file,'+<',$env{'user.environment'});
701: if ($opened
1.915 albertel 702: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 703: &&
704: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
705: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 706: foreach my $key (keys(%disk_env)) {
1.987 raeburn 707: if ($regexp) {
708: if ($key=~/^$delthis/) {
709: delete($env{$key});
710: delete($disk_env{$key});
711: }
712: } else {
713: if ($key=~/^\Q$delthis\E/) {
714: delete($env{$key});
715: delete($disk_env{$key});
716: }
717: }
1.448 albertel 718: }
1.783 albertel 719: untie(%disk_env);
1.5 www 720: }
721: return 'ok';
1.369 albertel 722: }
723:
1.790 albertel 724: sub get_env_multiple {
725: my ($name) = @_;
726: my @values;
727: if (defined($env{$name})) {
728: # exists is it an array
729: if (ref($env{$name})) {
730: @values=@{ $env{$name} };
731: } else {
732: $values[0]=$env{$name};
733: }
734: }
735: return(@values);
736: }
737:
1.958 www 738: # ------------------------------------------------------------------- Locking
739:
740: sub set_lock {
741: my ($text)=@_;
742: $locknum++;
743: my $id=$$.'-'.$locknum;
744: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
745: 'session.lock.'.$id => $text});
746: return $id;
747: }
748:
749: sub get_locks {
750: my $num=0;
751: my %texts=();
752: foreach my $lock (split(/\,/,$env{'session.locks'})) {
753: if ($lock=~/\w/) {
754: $num++;
755: $texts{$lock}=$env{'session.lock.'.$lock};
756: }
757: }
758: return ($num,%texts);
759: }
760:
761: sub remove_lock {
762: my ($id)=@_;
763: my $newlocks='';
764: foreach my $lock (split(/\,/,$env{'session.locks'})) {
765: if (($lock=~/\w/) && ($lock ne $id)) {
766: $newlocks.=','.$lock;
767: }
768: }
769: &appenv({'session.locks' => $newlocks});
770: &delenv('session.lock.'.$id);
771: }
772:
773: sub remove_all_locks {
774: my $activelocks=$env{'session.locks'};
775: foreach my $lock (split(/\,/,$env{'session.locks'})) {
776: if ($lock=~/\w/) {
777: &remove_lock($lock);
778: }
779: }
780: }
781:
782:
1.369 albertel 783: # ------------------------------------------ Find out current server userload
784: sub userload {
785: my $numusers=0;
786: {
787: opendir(LONIDS,$perlvar{'lonIDsDir'});
788: my $filename;
789: my $curtime=time;
790: while ($filename=readdir(LONIDS)) {
1.925 albertel 791: next if ($filename eq '.' || $filename eq '..');
792: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 793: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 794: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 795: }
796: closedir(LONIDS);
797: }
798: my $userloadpercent=0;
799: my $maxuserload=$perlvar{'lonUserLoadLim'};
800: if ($maxuserload) {
1.371 albertel 801: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 802: }
1.372 albertel 803: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 804: return $userloadpercent;
1.283 www 805: }
806:
1.1 albertel 807: # ------------------------------ Find server with least workload from spare.tab
1.11 www 808:
1.1 albertel 809: sub spareserver {
1.1083 raeburn 810: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 811: my $spare_server;
1.370 albertel 812: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 813: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
814: : $userloadpercent;
1.1083 raeburn 815: my ($uint_dom,$remotesessions);
816: if (($udom ne '') && (&domain($udom) ne '')) {
817: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
818: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
819: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
820: $remotesessions = $udomdefaults{'remotesessions'};
821: }
1.1123 raeburn 822: my $spareshash = &this_host_spares($udom);
823: if (ref($spareshash) eq 'HASH') {
824: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
825: foreach my $try_server (@{ $spareshash->{'primary'} }) {
826: if ($uint_dom) {
827: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
828: $try_server));
829: }
830: ($spare_server, $lowest_load) =
831: &compare_server_load($try_server, $spare_server, $lowest_load);
832: }
1.1083 raeburn 833: }
1.784 albertel 834:
1.1123 raeburn 835: my $found_server = ($spare_server ne '' && $lowest_load < 100);
836:
837: if (!$found_server) {
838: if (ref($spareshash->{'default'}) eq 'ARRAY') {
839: foreach my $try_server (@{ $spareshash->{'default'} }) {
840: if ($uint_dom) {
841: next unless (&spare_can_host($udom,$uint_dom,
842: $remotesessions,$try_server));
843: }
844: ($spare_server, $lowest_load) =
845: &compare_server_load($try_server, $spare_server, $lowest_load);
846: }
847: }
848: }
1.784 albertel 849: }
850:
851: if (!$want_server_name) {
1.968 raeburn 852: my $protocol = 'http';
853: if ($protocol{$spare_server} eq 'https') {
854: $protocol = $protocol{$spare_server};
855: }
1.1001 raeburn 856: if (defined($spare_server)) {
857: my $hostname = &hostname($spare_server);
1.1083 raeburn 858: if (defined($hostname)) {
1.1001 raeburn 859: $spare_server = $protocol.'://'.$hostname;
860: }
861: }
1.784 albertel 862: }
863: return $spare_server;
864: }
865:
866: sub compare_server_load {
867: my ($try_server, $spare_server, $lowest_load) = @_;
868:
869: my $loadans = &reply('load', $try_server);
870: my $userloadans = &reply('userload',$try_server);
871:
872: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 873: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 874: }
875:
876: my $load;
877: if ($loadans =~ /\d/) {
878: if ($userloadans =~ /\d/) {
879: #both are numbers, pick the bigger one
880: $load = ($loadans > $userloadans) ? $loadans
881: : $userloadans;
1.411 albertel 882: } else {
1.784 albertel 883: $load = $loadans;
1.411 albertel 884: }
1.784 albertel 885: } else {
886: $load = $userloadans;
887: }
888:
889: if (($load =~ /\d/) && ($load < $lowest_load)) {
890: $spare_server = $try_server;
891: $lowest_load = $load;
1.370 albertel 892: }
1.784 albertel 893: return ($spare_server,$lowest_load);
1.202 matthew 894: }
1.914 albertel 895:
896: # --------------------------- ask offload servers if user already has a session
897: sub find_existing_session {
898: my ($udom,$uname) = @_;
1.1123 raeburn 899: my $spareshash = &this_host_spares($udom);
900: if (ref($spareshash) eq 'HASH') {
901: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
902: foreach my $try_server (@{ $spareshash->{'primary'} }) {
903: return $try_server if (&has_user_session($try_server, $udom, $uname));
904: }
905: }
906: if (ref($spareshash->{'default'}) eq 'ARRAY') {
907: foreach my $try_server (@{ $spareshash->{'default'} }) {
908: return $try_server if (&has_user_session($try_server, $udom, $uname));
909: }
910: }
1.914 albertel 911: }
912: return;
913: }
914:
915: # -------------------------------- ask if server already has a session for user
916: sub has_user_session {
917: my ($lonid,$udom,$uname) = @_;
918: my $result = &reply(join(':','userhassession',
919: map {&escape($_)} ($udom,$uname)),$lonid);
920: return 1 if ($result eq 'ok');
921:
922: return 0;
923: }
924:
1.1076 raeburn 925: # --------- determine least loaded server in a user's domain which allows login
926:
927: sub choose_server {
1.1115 raeburn 928: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 929: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 930: my %servers = &get_servers($udom);
1.1076 raeburn 931: my $lowest_load = 30000;
1.1116 raeburn 932: my ($login_host,$hostname,$portal_path);
1.1076 raeburn 933: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 934: my $loginvia;
935: if ($checkloginvia) {
936: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 937: if ($loginvia) {
938: my ($server,$path) = split(/:/,$loginvia);
939: ($login_host, $lowest_load) =
940: &compare_server_load($server, $login_host, $lowest_load);
941: if ($login_host eq $server) {
942: $portal_path = $path;
943: }
944: } else {
945: ($login_host, $lowest_load) =
946: &compare_server_load($lonhost, $login_host, $lowest_load);
947: if ($login_host eq $lonhost) {
948: $portal_path = '';
949: }
950: }
951: } else {
1.1076 raeburn 952: ($login_host, $lowest_load) =
1.1116 raeburn 953: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 954: }
955: }
956: if ($login_host ne '') {
1.1116 raeburn 957: $hostname = &hostname($login_host);
1.1076 raeburn 958: }
1.1116 raeburn 959: return ($login_host,$hostname,$portal_path);
1.1076 raeburn 960: }
961:
1.202 matthew 962: # --------------------------------------------- Try to change a user's password
963:
964: sub changepass {
1.799 raeburn 965: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 966: $currentpass = &escape($currentpass);
967: $newpass = &escape($newpass);
1.1030 raeburn 968: my $lonhost = $perlvar{'lonHostID'};
969: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 970: $server);
971: if (! $answer) {
972: &logthis("No reply on password change request to $server ".
973: "by $uname in domain $udom.");
974: } elsif ($answer =~ "^ok") {
975: &logthis("$uname in $udom successfully changed their password ".
976: "on $server.");
977: } elsif ($answer =~ "^pwchange_failure") {
978: &logthis("$uname in $udom was unable to change their password ".
979: "on $server. The action was blocked by either lcpasswd ".
980: "or pwchange");
981: } elsif ($answer =~ "^non_authorized") {
982: &logthis("$uname in $udom did not get their password correct when ".
983: "attempting to change it on $server.");
984: } elsif ($answer =~ "^auth_mode_error") {
985: &logthis("$uname in $udom attempted to change their password despite ".
986: "not being locally or internally authenticated on $server.");
987: } elsif ($answer =~ "^unknown_user") {
988: &logthis("$uname in $udom attempted to change their password ".
989: "on $server but were unable to because $server is not ".
990: "their home server.");
991: } elsif ($answer =~ "^refused") {
992: &logthis("$server refused to change $uname in $udom password because ".
993: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 994: } elsif ($answer =~ "invalid_client") {
995: &logthis("$server refused to change $uname in $udom password because ".
996: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 997: }
998: return $answer;
1.1 albertel 999: }
1000:
1.169 harris41 1001: # ----------------------- Try to determine user's current authentication scheme
1002:
1003: sub queryauthenticate {
1004: my ($uname,$udom)=@_;
1.456 albertel 1005: my $uhome=&homeserver($uname,$udom);
1006: if (!$uhome) {
1007: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1008: return 'no_host';
1009: }
1010: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1011: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1012: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1013: }
1.456 albertel 1014: return $answer;
1.169 harris41 1015: }
1016:
1.1 albertel 1017: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1018:
1.1 albertel 1019: sub authenticate {
1.1073 raeburn 1020: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1021: $upass=&escape($upass);
1022: $uname= &LONCAPA::clean_username($uname);
1.836 www 1023: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1024: my $newhome;
1.836 www 1025: if ((!$uhome) || ($uhome eq 'no_host')) {
1026: # Maybe the machine was offline and only re-appeared again recently?
1027: &reconlonc();
1028: # One more
1.952 raeburn 1029: $uhome=&homeserver($uname,$udom,1);
1030: if (($uhome eq 'no_host') && $checkdefauth) {
1031: if (defined(&domain($udom,'primary'))) {
1032: $newhome=&domain($udom,'primary');
1033: }
1034: if ($newhome ne '') {
1035: $uhome = $newhome;
1036: }
1037: }
1.836 www 1038: if ((!$uhome) || ($uhome eq 'no_host')) {
1039: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1040: return 'no_host';
1041: }
1.1 albertel 1042: }
1.1073 raeburn 1043: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1044: if ($answer eq 'authorized') {
1.952 raeburn 1045: if ($newhome) {
1046: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1047: return 'no_account_on_host';
1048: } else {
1049: &logthis("User $uname at $udom authorized by $uhome");
1050: return $uhome;
1051: }
1.471 albertel 1052: }
1053: if ($answer eq 'non_authorized') {
1054: &logthis("User $uname at $udom rejected by $uhome");
1055: return 'no_host';
1.9 www 1056: }
1.471 albertel 1057: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1058: return 'no_host';
1059: }
1060:
1.1073 raeburn 1061: sub can_host_session {
1.1074 raeburn 1062: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1063: my $canhost = 1;
1.1074 raeburn 1064: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1065: if (ref($remotesessions) eq 'HASH') {
1066: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1067: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1068: $canhost = 0;
1069: } else {
1070: $canhost = 1;
1071: }
1072: }
1073: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1074: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1075: $canhost = 1;
1076: } else {
1077: $canhost = 0;
1078: }
1079: }
1080: if ($canhost) {
1081: if ($remotesessions->{'version'} ne '') {
1082: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1083: if ($reqmajor ne '' && $reqminor ne '') {
1084: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1085: my $major = $1;
1086: my $minor = $2;
1087: if (($major < $reqmajor ) ||
1088: (($major == $reqmajor) && ($minor < $reqminor))) {
1089: $canhost = 0;
1090: }
1091: } else {
1092: $canhost = 0;
1093: }
1094: }
1095: }
1096: }
1097: }
1098: if ($canhost) {
1099: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1100: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1101: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1102: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1103: if (($uint_dom ne '') &&
1104: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1105: $canhost = 0;
1106: } else {
1107: $canhost = 1;
1108: }
1109: }
1110: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1111: if (($uint_dom ne '') &&
1112: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1113: $canhost = 1;
1114: } else {
1115: $canhost = 0;
1116: }
1117: }
1118: }
1119: }
1120: return $canhost;
1121: }
1122:
1.1083 raeburn 1123: sub spare_can_host {
1124: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1125: my $canhost=1;
1126: my @intdoms;
1127: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1128: if (ref($internet_names) eq 'ARRAY') {
1129: @intdoms = @{$internet_names};
1130: }
1131: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1132: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1133: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1134: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1135: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1136: $canhost = &can_host_session($udom,$try_server,$remoterev,
1137: $remotesessions,
1138: $defdomdefaults{'hostedsessions'});
1139: }
1140: return $canhost;
1141: }
1142:
1.1123 raeburn 1143: sub this_host_spares {
1144: my ($dom) = @_;
1.1126 raeburn 1145: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1146: my @hosts = ¤t_machine_ids();
1147: foreach my $lonhost (@hosts) {
1148: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1149: $dom_in_use = $dom;
1150: $lonhost_in_use = $lonhost;
1.1123 raeburn 1151: last;
1152: }
1153: }
1.1126 raeburn 1154: if ($dom_in_use ne '') {
1155: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1156: }
1157: if (ref($result) ne 'HASH') {
1158: $lonhost_in_use = $perlvar{'lonHostID'};
1159: $dom_in_use = &host_domain($lonhost_in_use);
1160: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1161: if (ref($result) ne 'HASH') {
1162: $result = \%spareid;
1163: }
1164: }
1165: return $result;
1166: }
1167:
1168: sub spares_for_offload {
1169: my ($dom_in_use,$lonhost_in_use) = @_;
1170: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1171: if (defined($cached)) {
1172: return $result;
1173: } else {
1.1126 raeburn 1174: my $cachetime = 60*60*24;
1175: my %domconfig =
1176: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1177: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1178: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1179: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1180: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1181: }
1182: }
1183: }
1184: }
1.1126 raeburn 1185: return;
1.1123 raeburn 1186: }
1187:
1.1129 ! raeburn 1188: sub get_lonbalancer_config {
! 1189: my ($servers) = @_;
! 1190: my ($currbalancer,$currtargets);
! 1191: if (ref($servers) eq 'HASH') {
! 1192: foreach my $server (keys(%{$servers})) {
! 1193: my %what = (
! 1194: spareid => 1,
! 1195: perlvar => 1,
! 1196: );
! 1197: my ($result,$returnhash) = &get_remote_globals($server,\%what);
! 1198: if ($result eq 'ok') {
! 1199: if (ref($returnhash) eq 'HASH') {
! 1200: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
! 1201: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
! 1202: $currbalancer = $server;
! 1203: $currtargets = {};
! 1204: if (ref($returnhash->{'spareid'}) eq 'HASH') {
! 1205: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
! 1206: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
! 1207: }
! 1208: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
! 1209: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
! 1210: }
! 1211: }
! 1212: last;
! 1213: }
! 1214: }
! 1215: }
! 1216: }
! 1217: }
! 1218: }
! 1219: return ($currbalancer,$currtargets);
! 1220: }
! 1221:
! 1222: sub check_loadbalancing {
! 1223: my ($uname,$udom) = @_;
! 1224: my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
! 1225: $offloadto,$otherserver);
! 1226: my $lonhost = $perlvar{'lonHostID'};
! 1227: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
! 1228: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
! 1229: my $intdom = &Apache::lonnet::internet_dom($lonhost);
! 1230: my $serverhomedom = &host_domain($lonhost);
! 1231:
! 1232: my $cachetime = 60*60*24;
! 1233:
! 1234: if (($uintdom ne '') && ($uintdom eq $intdom)) {
! 1235: $dom_in_use = $udom;
! 1236: $homeintdom = 1;
! 1237: } else {
! 1238: $dom_in_use = $serverhomedom;
! 1239: }
! 1240: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
! 1241: unless (defined($cached)) {
! 1242: my %domconfig =
! 1243: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
! 1244: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
! 1245: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'usersessions'}{'loadbalancing'},$cachetime);
! 1246: }
! 1247: }
! 1248: if (ref($result) eq 'HASH') {
! 1249: my $currbalancer = $result->{'lonhost'};
! 1250: my $currtargets = $result->{'targets'};
! 1251: my $currrules = $result->{'rules'};
! 1252: if ($currbalancer ne '') {
! 1253: my @hosts = ¤t_machine_ids();
! 1254: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
! 1255: $is_balancer = 1;
! 1256: }
! 1257: }
! 1258: if ($is_balancer) {
! 1259: if (ref($currrules) eq 'HASH') {
! 1260: if ($homeintdom) {
! 1261: if ($uname ne '') {
! 1262: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
! 1263: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
! 1264: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
! 1265: $rule_in_effect = $currrules->{'_LC_author'};
! 1266: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
! 1267: $rule_in_effect = $currrules->{'_LC_adv'}
! 1268: }
! 1269: }
! 1270: if ($rule_in_effect eq '') {
! 1271: my %userenv = &userenvironment($udom,$uname,'inststatus');
! 1272: if ($userenv{'inststatus'} ne '') {
! 1273: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
! 1274: my ($othertitle,$usertypes,$types) =
! 1275: &Apache::loncommon::sorted_inst_types($udom);
! 1276: if (ref($types) eq 'ARRAY') {
! 1277: foreach my $type (@{$types}) {
! 1278: if (grep(/^\Q$type\E$/,@statuses)) {
! 1279: if (exists($currrules->{$type})) {
! 1280: $rule_in_effect = $currrules->{$type};
! 1281: }
! 1282: }
! 1283: }
! 1284: }
! 1285: } else {
! 1286: if (exists($currrules->{'default'})) {
! 1287: $rule_in_effect = $currrules->{'default'};
! 1288: }
! 1289: }
! 1290: }
! 1291: } else {
! 1292: if (exists($currrules->{'default'})) {
! 1293: $rule_in_effect = $currrules->{'default'};
! 1294: }
! 1295: }
! 1296: } else {
! 1297: if ($currrules->{'_LC_external'} ne '') {
! 1298: $rule_in_effect = $currrules->{'_LC_external'};
! 1299: }
! 1300: }
! 1301: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
! 1302: $uname,$udom);
! 1303: }
! 1304: }
! 1305: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
! 1306: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
! 1307: unless (defined($cached)) {
! 1308: my %domconfig =
! 1309: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
! 1310: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
! 1311: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'usersessions'}{'loadbalancing'},$cachetime);
! 1312: }
! 1313: }
! 1314: if (ref($result) eq 'HASH') {
! 1315: my $currbalancer = $result->{'lonhost'};
! 1316: my $currtargets = $result->{'targets'};
! 1317: my $currrules = $result->{'rules'};
! 1318:
! 1319: if ($currbalancer eq $lonhost) {
! 1320: $is_balancer = 1;
! 1321: if (ref($currrules) eq 'HASH') {
! 1322: if ($currrules->{'_LC_internetdom'} ne '') {
! 1323: $rule_in_effect = $currrules->{'_LC_internetdom'};
! 1324: }
! 1325: }
! 1326: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
! 1327: $uname,$udom);
! 1328: }
! 1329: } else {
! 1330: if ($perlvar{'lonBalancer'} eq 'yes') {
! 1331: $is_balancer = 1;
! 1332: $offloadto = &this_host_spares($dom_in_use);
! 1333: }
! 1334: }
! 1335: } else {
! 1336: if ($perlvar{'lonBalancer'} eq 'yes') {
! 1337: $is_balancer = 1;
! 1338: $offloadto = &this_host_spares($dom_in_use);
! 1339: }
! 1340: }
! 1341: my $lowest_load = 30000;
! 1342: if (ref($offloadto) eq 'HASH') {
! 1343: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
! 1344: foreach my $try_server (@{$offloadto->{'primary'}}) {
! 1345: ($otherserver,$lowest_load) =
! 1346: &compare_server_load($try_server,$otherserver,$lowest_load);
! 1347: }
! 1348: }
! 1349: my $found_server = ($otherserver ne '' && $lowest_load < 100);
! 1350:
! 1351: if (!$found_server) {
! 1352: if (ref($offloadto->{'default'}) eq 'ARRAY') {
! 1353: foreach my $try_server (@{$offloadto->{'default'}}) {
! 1354: ($otherserver,$lowest_load) =
! 1355: &compare_server_load($try_server,$otherserver,$lowest_load);
! 1356: }
! 1357: }
! 1358: }
! 1359: } elsif (ref($offloadto) eq 'ARRAY') {
! 1360: if (@{$offloadto} == 1) {
! 1361: $otherserver = $offloadto->[0];
! 1362: } elsif (@{$offloadto} > 1) {
! 1363: foreach my $try_server (@{$offloadto}) {
! 1364: ($otherserver,$lowest_load) =
! 1365: &compare_server_load($try_server,$otherserver,$lowest_load);
! 1366: }
! 1367: }
! 1368: }
! 1369: return ($is_balancer,$otherserver);
! 1370: }
! 1371:
! 1372: sub get_loadbalancer_targets {
! 1373: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
! 1374: my $offloadto;
! 1375: if ($rule_in_effect eq '') {
! 1376: $offloadto = $currtargets;
! 1377: } else {
! 1378: if ($rule_in_effect eq 'homeserver') {
! 1379: my $homeserver = &homeserver($uname,$udom);
! 1380: if ($homeserver ne 'no_host') {
! 1381: $offloadto = [$homeserver];
! 1382: }
! 1383: } elsif ($rule_in_effect eq 'externalbalancer') {
! 1384: my %domconfig =
! 1385: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
! 1386: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
! 1387: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
! 1388: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
! 1389: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
! 1390: }
! 1391: }
! 1392: } else {
! 1393: my %servers = &dom_servers($udom);
! 1394: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
! 1395: if (&hostname($remotebalancer) ne '') {
! 1396: $offloadto = [$remotebalancer];
! 1397: }
! 1398: }
! 1399: } elsif (&hostname($rule_in_effect) ne '') {
! 1400: $offloadto = [$rule_in_effect];
! 1401: }
! 1402: }
! 1403: return $offloadto;
! 1404: }
! 1405:
1.1127 raeburn 1406: sub internet_dom_servers {
1407: my ($dom) = @_;
1408: my (%uniqservers,%servers);
1409: my $primaryserver = &hostname(&domain($dom,'primary'));
1410: my @machinedoms = &machine_domains($primaryserver);
1411: foreach my $mdom (@machinedoms) {
1412: my %currservers = %servers;
1413: my %server = &get_servers($mdom);
1414: %servers = (%currservers,%server);
1415: }
1416: my %by_hostname;
1417: foreach my $id (keys(%servers)) {
1418: push(@{$by_hostname{$servers{$id}}},$id);
1419: }
1420: foreach my $hostname (sort(keys(%by_hostname))) {
1421: if (@{$by_hostname{$hostname}} > 1) {
1422: my $match = 0;
1423: foreach my $id (@{$by_hostname{$hostname}}) {
1424: if (&host_domain($id) eq $dom) {
1425: $uniqservers{$id} = $hostname;
1426: $match = 1;
1427: }
1428: }
1429: unless ($match) {
1430: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1431: }
1432: } else {
1433: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1434: }
1435: }
1436: return %uniqservers;
1437: }
1438:
1.1 albertel 1439: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1440:
1.599 albertel 1441: my %homecache;
1.1 albertel 1442: sub homeserver {
1.230 stredwic 1443: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1444: my $index="$uname:$udom";
1.426 albertel 1445:
1.599 albertel 1446: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1447:
1448: my %servers = &get_servers($udom,'library');
1449: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1450: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1451: exists($badServerCache{$tryserver}));
1.841 albertel 1452:
1453: my $answer=reply("home:$udom:$uname",$tryserver);
1454: if ($answer eq 'found') {
1455: delete($badServerCache{$tryserver});
1456: return $homecache{$index}=$tryserver;
1457: } elsif ($answer eq 'no_host') {
1458: $badServerCache{$tryserver}=1;
1459: }
1.1 albertel 1460: }
1461: return 'no_host';
1.70 www 1462: }
1463:
1464: # ------------------------------------- Find the usernames behind a list of IDs
1465:
1466: sub idget {
1467: my ($udom,@ids)=@_;
1468: my %returnhash=();
1469:
1.841 albertel 1470: my %servers = &get_servers($udom,'library');
1471: foreach my $tryserver (keys(%servers)) {
1472: my $idlist=join('&',@ids);
1473: $idlist=~tr/A-Z/a-z/;
1474: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1475: my @answer=();
1476: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1477: @answer=split(/\&/,$reply);
1478: } ;
1479: my $i;
1480: for ($i=0;$i<=$#ids;$i++) {
1481: if ($answer[$i]) {
1482: $returnhash{$ids[$i]}=$answer[$i];
1483: }
1484: }
1485: }
1.70 www 1486: return %returnhash;
1487: }
1488:
1489: # ------------------------------------- Find the IDs behind a list of usernames
1490:
1491: sub idrget {
1492: my ($udom,@unames)=@_;
1493: my %returnhash=();
1.800 albertel 1494: foreach my $uname (@unames) {
1495: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1496: }
1.70 www 1497: return %returnhash;
1498: }
1499:
1500: # ------------------------------- Store away a list of names and associated IDs
1501:
1502: sub idput {
1503: my ($udom,%ids)=@_;
1504: my %servers=();
1.800 albertel 1505: foreach my $uname (keys(%ids)) {
1506: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1507: my $uhom=&homeserver($uname,$udom);
1.70 www 1508: if ($uhom ne 'no_host') {
1.800 albertel 1509: my $id=&escape($ids{$uname});
1.70 www 1510: $id=~tr/A-Z/a-z/;
1.800 albertel 1511: my $esc_unam=&escape($uname);
1.70 www 1512: if ($servers{$uhom}) {
1.800 albertel 1513: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1514: } else {
1.800 albertel 1515: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1516: }
1517: }
1.191 harris41 1518: }
1.800 albertel 1519: foreach my $server (keys(%servers)) {
1520: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1521: }
1.344 www 1522: }
1523:
1.1023 raeburn 1524: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1525: sub dump_dom {
1.1023 raeburn 1526: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1527: if (!$udom) {
1528: $udom=$env{'user.domain'};
1529: }
1530: my %returnhash;
1.1023 raeburn 1531: if ($udom) {
1532: my $uname = &get_domainconfiguser($udom);
1533: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1534: }
1535: return %returnhash;
1536: }
1537:
1.1023 raeburn 1538: # ------------------------------------------ get items from domain db files
1.806 raeburn 1539:
1540: sub get_dom {
1.860 raeburn 1541: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1542: my $items='';
1543: foreach my $item (@$storearr) {
1544: $items.=&escape($item).'&';
1545: }
1546: $items=~s/\&$//;
1.860 raeburn 1547: if (!$udom) {
1548: $udom=$env{'user.domain'};
1549: if (defined(&domain($udom,'primary'))) {
1550: $uhome=&domain($udom,'primary');
1551: } else {
1.874 albertel 1552: undef($uhome);
1.860 raeburn 1553: }
1554: } else {
1555: if (!$uhome) {
1556: if (defined(&domain($udom,'primary'))) {
1557: $uhome=&domain($udom,'primary');
1558: }
1559: }
1560: }
1561: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1562: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1563: my %returnhash;
1.875 albertel 1564: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1565: return %returnhash;
1566: }
1.806 raeburn 1567: my @pairs=split(/\&/,$rep);
1568: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1569: return @pairs;
1570: }
1571: my $i=0;
1572: foreach my $item (@$storearr) {
1573: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1574: $i++;
1575: }
1576: return %returnhash;
1577: } else {
1.880 banghart 1578: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1579: }
1580: }
1581:
1582: # -------------------------------------------- put items in domain db files
1583:
1584: sub put_dom {
1.860 raeburn 1585: my ($namespace,$storehash,$udom,$uhome)=@_;
1586: if (!$udom) {
1587: $udom=$env{'user.domain'};
1588: if (defined(&domain($udom,'primary'))) {
1589: $uhome=&domain($udom,'primary');
1590: } else {
1.874 albertel 1591: undef($uhome);
1.860 raeburn 1592: }
1593: } else {
1594: if (!$uhome) {
1595: if (defined(&domain($udom,'primary'))) {
1596: $uhome=&domain($udom,'primary');
1597: }
1598: }
1599: }
1600: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1601: my $items='';
1602: foreach my $item (keys(%$storehash)) {
1603: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1604: }
1605: $items=~s/\&$//;
1606: return &reply("putdom:$udom:$namespace:$items",$uhome);
1607: } else {
1.860 raeburn 1608: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1609: }
1610: }
1611:
1.1023 raeburn 1612: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1613: sub newput_dom {
1.1023 raeburn 1614: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1615: my $result;
1616: if (!$udom) {
1617: $udom=$env{'user.domain'};
1618: }
1.1023 raeburn 1619: if ($udom) {
1620: my $uname = &get_domainconfiguser($udom);
1621: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1622: }
1623: return $result;
1624: }
1625:
1.1023 raeburn 1626: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1627: sub del_dom {
1.1023 raeburn 1628: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1629: if (ref($storearr) eq 'ARRAY') {
1630: if (!$udom) {
1631: $udom=$env{'user.domain'};
1632: }
1.1023 raeburn 1633: if ($udom) {
1634: my $uname = &get_domainconfiguser($udom);
1635: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1636: }
1637: }
1638: }
1639:
1.1023 raeburn 1640: # ----------------------------------construct domainconfig user for a domain
1641: sub get_domainconfiguser {
1642: my ($udom) = @_;
1643: return $udom.'-domainconfig';
1644: }
1645:
1.837 raeburn 1646: sub retrieve_inst_usertypes {
1647: my ($udom) = @_;
1648: my (%returnhash,@order);
1.989 raeburn 1649: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1650: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1651: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1652: %returnhash = %{$domdefs{'inststatustypes'}};
1653: @order = @{$domdefs{'inststatusorder'}};
1654: } else {
1655: if (defined(&domain($udom,'primary'))) {
1656: my $uhome=&domain($udom,'primary');
1657: my $rep=&reply("inst_usertypes:$udom",$uhome);
1658: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1659: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1660: return (\%returnhash,\@order);
1661: }
1662: my ($hashitems,$orderitems) = split(/:/,$rep);
1663: my @pairs=split(/\&/,$hashitems);
1664: foreach my $item (@pairs) {
1665: my ($key,$value)=split(/=/,$item,2);
1666: $key = &unescape($key);
1667: next if ($key =~ /^error: 2 /);
1668: $returnhash{$key}=&thaw_unescape($value);
1669: }
1670: my @esc_order = split(/\&/,$orderitems);
1671: foreach my $item (@esc_order) {
1672: push(@order,&unescape($item));
1673: }
1674: } else {
1675: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1676: }
1677: }
1678: return (\%returnhash,\@order);
1679: }
1680:
1.868 raeburn 1681: sub is_domainimage {
1682: my ($url) = @_;
1683: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1684: if (&domain($1) ne '') {
1685: return '1';
1686: }
1687: }
1688: return;
1689: }
1690:
1.899 raeburn 1691: sub inst_directory_query {
1692: my ($srch) = @_;
1693: my $udom = $srch->{'srchdomain'};
1694: my %results;
1695: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1696: my $outcome;
1.899 raeburn 1697: if ($homeserver ne '') {
1.904 albertel 1698: my $queryid=&reply("querysend:instdirsearch:".
1699: &escape($srch->{'srchby'}).':'.
1700: &escape($srch->{'srchterm'}).':'.
1701: &escape($srch->{'srchtype'}),$homeserver);
1702: my $host=&hostname($homeserver);
1703: if ($queryid !~/^\Q$host\E\_/) {
1704: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1705: return;
1706: }
1707: my $response = &get_query_reply($queryid);
1708: my $maxtries = 5;
1709: my $tries = 1;
1710: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1711: $response = &get_query_reply($queryid);
1712: $tries ++;
1713: }
1714:
1715: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1716: if ($response eq 'unavailable') {
1717: $outcome = $response;
1718: } else {
1719: $outcome = 'ok';
1720: my @matches = split(/\n/,$response);
1721: foreach my $match (@matches) {
1722: my ($key,$value) = split(/=/,$match);
1723: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1724: }
1.899 raeburn 1725: }
1726: }
1727: }
1.909 raeburn 1728: return ($outcome,%results);
1.899 raeburn 1729: }
1730:
1731: sub usersearch {
1732: my ($srch) = @_;
1733: my $dom = $srch->{'srchdomain'};
1734: my %results;
1735: my %libserv = &all_library();
1736: my $query = 'usersearch';
1737: foreach my $tryserver (keys(%libserv)) {
1738: if (&host_domain($tryserver) eq $dom) {
1739: my $host=&hostname($tryserver);
1740: my $queryid=
1.911 raeburn 1741: &reply("querysend:".&escape($query).':'.
1742: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1743: &escape($srch->{'srchtype'}).':'.
1744: &escape($srch->{'srchterm'}),$tryserver);
1745: if ($queryid !~/^\Q$host\E\_/) {
1746: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1747: next;
1.899 raeburn 1748: }
1749: my $reply = &get_query_reply($queryid);
1750: my $maxtries = 1;
1751: my $tries = 1;
1752: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1753: $reply = &get_query_reply($queryid);
1754: $tries ++;
1755: }
1756: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1757: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1758: } else {
1.911 raeburn 1759: my @matches;
1760: if ($reply =~ /\n/) {
1761: @matches = split(/\n/,$reply);
1762: } else {
1763: @matches = split(/\&/,$reply);
1764: }
1.899 raeburn 1765: foreach my $match (@matches) {
1766: my ($uname,$udom,%userhash);
1.911 raeburn 1767: foreach my $entry (split(/:/,$match)) {
1768: my ($key,$value) =
1769: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1770: $userhash{$key} = $value;
1771: if ($key eq 'username') {
1772: $uname = $value;
1773: } elsif ($key eq 'domain') {
1774: $udom = $value;
1.911 raeburn 1775: }
1.899 raeburn 1776: }
1777: $results{$uname.':'.$udom} = \%userhash;
1778: }
1779: }
1780: }
1781: }
1782: return %results;
1783: }
1784:
1.912 raeburn 1785: sub get_instuser {
1786: my ($udom,$uname,$id) = @_;
1787: my $homeserver = &domain($udom,'primary');
1788: my ($outcome,%results);
1789: if ($homeserver ne '') {
1790: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1791: &escape($id).':'.&escape($udom),$homeserver);
1792: my $host=&hostname($homeserver);
1793: if ($queryid !~/^\Q$host\E\_/) {
1794: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1795: return;
1796: }
1797: my $response = &get_query_reply($queryid);
1798: my $maxtries = 5;
1799: my $tries = 1;
1800: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1801: $response = &get_query_reply($queryid);
1802: $tries ++;
1803: }
1804: if (!&error($response) && $response ne 'refused') {
1805: if ($response eq 'unavailable') {
1806: $outcome = $response;
1807: } else {
1808: $outcome = 'ok';
1809: my @matches = split(/\n/,$response);
1810: foreach my $match (@matches) {
1811: my ($key,$value) = split(/=/,$match);
1812: $results{&unescape($key)} = &thaw_unescape($value);
1813: }
1814: }
1815: }
1816: }
1817: my %userinfo;
1818: if (ref($results{$uname}) eq 'HASH') {
1819: %userinfo = %{$results{$uname}};
1820: }
1821: return ($outcome,%userinfo);
1822: }
1823:
1824: sub inst_rulecheck {
1.923 raeburn 1825: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1826: my %returnhash;
1827: if ($udom ne '') {
1828: if (ref($rules) eq 'ARRAY') {
1829: @{$rules} = map {&escape($_);} (@{$rules});
1830: my $rulestr = join(':',@{$rules});
1831: my $homeserver=&domain($udom,'primary');
1832: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1833: my $response;
1834: if ($item eq 'username') {
1835: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1836: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1837: $homeserver));
1.923 raeburn 1838: } elsif ($item eq 'id') {
1839: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1840: ':'.&escape($id).':'.$rulestr,
1841: $homeserver));
1.945 raeburn 1842: } elsif ($item eq 'selfcreate') {
1843: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1844: &escape($udom).':'.&escape($uname).
1845: ':'.$rulestr,$homeserver));
1.923 raeburn 1846: }
1.912 raeburn 1847: if ($response ne 'refused') {
1848: my @pairs=split(/\&/,$response);
1849: foreach my $item (@pairs) {
1850: my ($key,$value)=split(/=/,$item,2);
1851: $key = &unescape($key);
1852: next if ($key =~ /^error: 2 /);
1853: $returnhash{$key}=&thaw_unescape($value);
1854: }
1855: }
1856: }
1857: }
1858: }
1859: return %returnhash;
1860: }
1861:
1862: sub inst_userrules {
1.923 raeburn 1863: my ($udom,$check) = @_;
1.912 raeburn 1864: my (%ruleshash,@ruleorder);
1865: if ($udom ne '') {
1866: my $homeserver=&domain($udom,'primary');
1867: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1868: my $response;
1869: if ($check eq 'id') {
1870: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1871: $homeserver);
1.943 raeburn 1872: } elsif ($check eq 'email') {
1873: $response=&reply('instemailrules:'.&escape($udom),
1874: $homeserver);
1.923 raeburn 1875: } else {
1876: $response=&reply('instuserrules:'.&escape($udom),
1877: $homeserver);
1878: }
1.912 raeburn 1879: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1880: ($response ne 'unknown_cmd') &&
1.912 raeburn 1881: ($response ne 'no_such_host')) {
1882: my ($hashitems,$orderitems) = split(/:/,$response);
1883: my @pairs=split(/\&/,$hashitems);
1884: foreach my $item (@pairs) {
1885: my ($key,$value)=split(/=/,$item,2);
1886: $key = &unescape($key);
1887: next if ($key =~ /^error: 2 /);
1888: $ruleshash{$key}=&thaw_unescape($value);
1889: }
1890: my @esc_order = split(/\&/,$orderitems);
1891: foreach my $item (@esc_order) {
1892: push(@ruleorder,&unescape($item));
1893: }
1894: }
1895: }
1896: }
1897: return (\%ruleshash,\@ruleorder);
1898: }
1899:
1.976 raeburn 1900: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1901:
1902: sub get_domain_defaults {
1903: my ($domain) = @_;
1904: my $cachetime = 60*60*24;
1905: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1906: if (defined($cached)) {
1907: if (ref($result) eq 'HASH') {
1908: return %{$result};
1909: }
1910: }
1911: my %domdefaults;
1912: my %domconfig =
1.989 raeburn 1913: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1914: 'requestcourses','inststatus',
1.1073 raeburn 1915: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1916: if (ref($domconfig{'defaults'}) eq 'HASH') {
1917: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1918: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1919: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1920: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1921: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1922: } else {
1923: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1924: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1925: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1926: }
1.976 raeburn 1927: if (ref($domconfig{'quotas'}) eq 'HASH') {
1928: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1929: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1930: } else {
1931: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1932: }
1933: my @usertools = ('aboutme','blog','portfolio');
1934: foreach my $item (@usertools) {
1935: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1936: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1937: }
1938: }
1939: }
1.985 raeburn 1940: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1941: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1942: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1943: }
1944: }
1.989 raeburn 1945: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1946: foreach my $item ('inststatustypes','inststatusorder') {
1947: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1948: }
1949: }
1.1047 raeburn 1950: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1951: foreach my $item ('canuse_pdfforms') {
1952: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1953: }
1954: }
1.1073 raeburn 1955: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1956: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1957: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1958: }
1959: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1960: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1961: }
1962: }
1.943 raeburn 1963: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1964: $cachetime);
1965: return %domdefaults;
1966: }
1967:
1.344 www 1968: # --------------------------------------------------- Assign a key to a student
1969:
1970: sub assign_access_key {
1.364 www 1971: #
1972: # a valid key looks like uname:udom#comments
1973: # comments are being appended
1974: #
1.498 www 1975: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1976: $kdom=
1.620 albertel 1977: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1978: $knum=
1.620 albertel 1979: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1980: $cdom=
1.620 albertel 1981: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1982: $cnum=
1.620 albertel 1983: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1984: $udom=$env{'user.name'} unless (defined($udom));
1985: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1986: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1987: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1988: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1989: # assigned to this person
1990: # - this should not happen,
1.345 www 1991: # unless something went wrong
1992: # the first time around
1993: # ready to assign
1.364 www 1994: $logentry=$1.'; '.$logentry;
1.496 www 1995: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1996: $kdom,$knum) eq 'ok') {
1.345 www 1997: # key now belongs to user
1.346 www 1998: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1999: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2000: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2001: return 'ok';
2002: } else {
2003: return
2004: 'error: Count not permanently assign key, will need to be re-entered later.';
2005: }
2006: } else {
2007: return 'error: Could not assign key, try again later.';
2008: }
1.364 www 2009: } elsif (!$existing{$ckey}) {
1.345 www 2010: # the key does not exist
2011: return 'error: The key does not exist';
2012: } else {
2013: # the key is somebody else's
2014: return 'error: The key is already in use';
2015: }
1.344 www 2016: }
2017:
1.364 www 2018: # ------------------------------------------ put an additional comment on a key
2019:
2020: sub comment_access_key {
2021: #
2022: # a valid key looks like uname:udom#comments
2023: # comments are being appended
2024: #
2025: my ($ckey,$cdom,$cnum,$logentry)=@_;
2026: $cdom=
1.620 albertel 2027: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2028: $cnum=
1.620 albertel 2029: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2030: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2031: if ($existing{$ckey}) {
2032: $existing{$ckey}.='; '.$logentry;
2033: # ready to assign
1.367 www 2034: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2035: $cdom,$cnum) eq 'ok') {
2036: return 'ok';
2037: } else {
2038: return 'error: Count not store comment.';
2039: }
2040: } else {
2041: # the key does not exist
2042: return 'error: The key does not exist';
2043: }
2044: }
2045:
1.344 www 2046: # ------------------------------------------------------ Generate a set of keys
2047:
2048: sub generate_access_keys {
1.364 www 2049: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2050: $cdom=
1.620 albertel 2051: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2052: $cnum=
1.620 albertel 2053: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2054: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2055: unless (($cdom) && ($cnum)) { return 0; }
2056: if ($number>10000) { return 0; }
2057: sleep(2); # make sure don't get same seed twice
2058: srand(time()^($$+($$<<15))); # from "Programming Perl"
2059: my $total=0;
2060: for (my $i=1;$i<=$number;$i++) {
2061: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2062: sprintf("%lx",int(100000*rand)).'-'.
2063: sprintf("%lx",int(100000*rand));
2064: $newkey=~s/1/g/g; # folks mix up 1 and l
2065: $newkey=~s/0/h/g; # and also 0 and O
2066: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2067: if ($existing{$newkey}) {
2068: $i--;
2069: } else {
1.364 www 2070: if (&put('accesskeys',
2071: { $newkey => '# generated '.localtime().
1.620 albertel 2072: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2073: '; '.$logentry },
2074: $cdom,$cnum) eq 'ok') {
1.344 www 2075: $total++;
2076: }
2077: }
2078: }
1.620 albertel 2079: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2080: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2081: return $total;
2082: }
2083:
2084: # ------------------------------------------------------- Validate an accesskey
2085:
2086: sub validate_access_key {
2087: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2088: $cdom=
1.620 albertel 2089: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2090: $cnum=
1.620 albertel 2091: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2092: $udom=$env{'user.domain'} unless (defined($udom));
2093: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2094: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2095: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2096: }
2097:
2098: # ------------------------------------- Find the section of student in a course
1.652 albertel 2099: sub devalidate_getsection_cache {
2100: my ($udom,$unam,$courseid)=@_;
2101: my $hashid="$udom:$unam:$courseid";
2102: &devalidate_cache_new('getsection',$hashid);
2103: }
1.298 matthew 2104:
1.815 albertel 2105: sub courseid_to_courseurl {
2106: my ($courseid) = @_;
2107: #already url style courseid
2108: return $courseid if ($courseid =~ m{^/});
2109:
2110: if (exists($env{'course.'.$courseid.'.num'})) {
2111: my $cnum = $env{'course.'.$courseid.'.num'};
2112: my $cdom = $env{'course.'.$courseid.'.domain'};
2113: return "/$cdom/$cnum";
2114: }
2115:
2116: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2117: if (exists($courseinfo{'num'})) {
2118: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2119: }
2120:
2121: return undef;
2122: }
2123:
1.298 matthew 2124: sub getsection {
2125: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2126: my $cachetime=1800;
1.551 albertel 2127:
2128: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2129: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2130: if (defined($cached)) { return $result; }
2131:
1.298 matthew 2132: my %Pending;
2133: my %Expired;
2134: #
2135: # Each role can either have not started yet (pending), be active,
2136: # or have expired.
2137: #
2138: # If there is an active role, we are done.
2139: #
2140: # If there is more than one role which has not started yet,
2141: # choose the one which will start sooner
2142: # If there is one role which has not started yet, return it.
2143: #
2144: # If there is more than one expired role, choose the one which ended last.
2145: # If there is a role which has expired, return it.
2146: #
1.815 albertel 2147: $courseid = &courseid_to_courseurl($courseid);
1.1086 raeburn 2148: my $extra = &freeze_escape({'skipcheck' => 1});
2149: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817 raeburn 2150: foreach my $key (keys(%roleshash)) {
1.479 albertel 2151: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2152: my $section=$1;
2153: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2154: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2155: my $now=time;
1.548 albertel 2156: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2157: $Expired{$end}=$section;
2158: next;
2159: }
1.548 albertel 2160: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2161: $Pending{$start}=$section;
2162: next;
2163: }
1.599 albertel 2164: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2165: }
2166: #
2167: # Presumedly there will be few matching roles from the above
2168: # loop and the sorting time will be negligible.
2169: if (scalar(keys(%Pending))) {
2170: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2171: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2172: }
2173: if (scalar(keys(%Expired))) {
2174: my @sorted = sort {$a <=> $b} keys(%Expired);
2175: my $time = pop(@sorted);
1.599 albertel 2176: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2177: }
1.599 albertel 2178: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2179: }
1.70 www 2180:
1.599 albertel 2181: sub save_cache {
2182: &purge_remembered();
1.722 albertel 2183: #&Apache::loncommon::validate_page();
1.620 albertel 2184: undef(%env);
1.780 albertel 2185: undef($env_loaded);
1.599 albertel 2186: }
1.452 albertel 2187:
1.599 albertel 2188: my $to_remember=-1;
2189: my %remembered;
2190: my %accessed;
2191: my $kicks=0;
2192: my $hits=0;
1.849 albertel 2193: sub make_key {
2194: my ($name,$id) = @_;
1.872 albertel 2195: if (length($id) > 65
2196: && length(&escape($id)) > 200) {
2197: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2198: }
1.849 albertel 2199: return &escape($name.':'.$id);
2200: }
2201:
1.599 albertel 2202: sub devalidate_cache_new {
2203: my ($name,$id,$debug) = @_;
2204: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2205: $id=&make_key($name,$id);
1.599 albertel 2206: $memcache->delete($id);
2207: delete($remembered{$id});
2208: delete($accessed{$id});
2209: }
2210:
2211: sub is_cached_new {
2212: my ($name,$id,$debug) = @_;
1.849 albertel 2213: $id=&make_key($name,$id);
1.599 albertel 2214: if (exists($remembered{$id})) {
2215: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
2216: $accessed{$id}=[&gettimeofday()];
2217: $hits++;
2218: return ($remembered{$id},1);
2219: }
2220: my $value = $memcache->get($id);
2221: if (!(defined($value))) {
2222: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2223: return (undef,undef);
1.416 albertel 2224: }
1.599 albertel 2225: if ($value eq '__undef__') {
2226: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2227: $value=undef;
2228: }
2229: &make_room($id,$value,$debug);
2230: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2231: return ($value,1);
2232: }
2233:
2234: sub do_cache_new {
2235: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2236: $id=&make_key($name,$id);
1.599 albertel 2237: my $setvalue=$value;
2238: if (!defined($setvalue)) {
2239: $setvalue='__undef__';
2240: }
1.623 albertel 2241: if (!defined($time) ) {
2242: $time=600;
2243: }
1.599 albertel 2244: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2245: my $result = $memcache->set($id,$setvalue,$time);
2246: if (! $result) {
1.872 albertel 2247: &logthis("caching of id -> $id failed");
1.910 albertel 2248: $memcache->disconnect_all();
1.872 albertel 2249: }
1.600 albertel 2250: # need to make a copy of $value
1.919 albertel 2251: &make_room($id,$value,$debug);
1.599 albertel 2252: return $value;
2253: }
2254:
2255: sub make_room {
2256: my ($id,$value,$debug)=@_;
1.919 albertel 2257:
2258: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2259: : $value;
1.599 albertel 2260: if ($to_remember<0) { return; }
2261: $accessed{$id}=[&gettimeofday()];
2262: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2263: my $to_kick;
2264: my $max_time=0;
2265: foreach my $other (keys(%accessed)) {
2266: if (&tv_interval($accessed{$other}) > $max_time) {
2267: $to_kick=$other;
2268: $max_time=&tv_interval($accessed{$other});
2269: }
2270: }
2271: delete($remembered{$to_kick});
2272: delete($accessed{$to_kick});
2273: $kicks++;
2274: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2275: return;
2276: }
2277:
1.599 albertel 2278: sub purge_remembered {
1.604 albertel 2279: #&logthis("Tossing ".scalar(keys(%remembered)));
2280: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2281: undef(%remembered);
2282: undef(%accessed);
1.428 albertel 2283: }
1.70 www 2284: # ------------------------------------- Read an entry from a user's environment
2285:
2286: sub userenvironment {
2287: my ($udom,$unam,@what)=@_;
1.976 raeburn 2288: my $items;
2289: foreach my $item (@what) {
2290: $items.=&escape($item).'&';
2291: }
2292: $items=~s/\&$//;
1.70 www 2293: my %returnhash=();
1.1009 raeburn 2294: my $uhome = &homeserver($unam,$udom);
2295: unless ($uhome eq 'no_host') {
2296: my @answer=split(/\&/,
2297: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2298: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2299: return %returnhash;
2300: }
1.1009 raeburn 2301: my $i;
2302: for ($i=0;$i<=$#what;$i++) {
2303: $returnhash{$what[$i]}=&unescape($answer[$i]);
2304: }
1.70 www 2305: }
2306: return %returnhash;
1.1 albertel 2307: }
2308:
1.617 albertel 2309: # ---------------------------------------------------------- Get a studentphoto
2310: sub studentphoto {
2311: my ($udom,$unam,$ext) = @_;
2312: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2313: if (defined($env{'request.course.id'})) {
1.708 raeburn 2314: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2315: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2316: return(&retrievestudentphoto($udom,$unam,$ext));
2317: } else {
2318: my ($result,$perm_reqd)=
1.707 albertel 2319: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2320: if ($result eq 'ok') {
2321: if (!($perm_reqd eq 'yes')) {
2322: return(&retrievestudentphoto($udom,$unam,$ext));
2323: }
2324: }
2325: }
2326: }
2327: } else {
2328: my ($result,$perm_reqd) =
1.707 albertel 2329: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2330: if ($result eq 'ok') {
2331: if (!($perm_reqd eq 'yes')) {
2332: return(&retrievestudentphoto($udom,$unam,$ext));
2333: }
2334: }
2335: }
2336: return '/adm/lonKaputt/lonlogo_broken.gif';
2337: }
2338:
2339: sub retrievestudentphoto {
2340: my ($udom,$unam,$ext,$type) = @_;
2341: my $home=&Apache::lonnet::homeserver($unam,$udom);
2342: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2343: if ($ret eq 'ok') {
2344: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2345: if ($type eq 'thumbnail') {
2346: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2347: }
2348: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2349: return $tokenurl;
2350: } else {
2351: if ($type eq 'thumbnail') {
2352: return '/adm/lonKaputt/genericstudent_tn.gif';
2353: } else {
2354: return '/adm/lonKaputt/lonlogo_broken.gif';
2355: }
1.617 albertel 2356: }
2357: }
2358:
1.263 www 2359: # -------------------------------------------------------------------- New chat
2360:
2361: sub chatsend {
1.724 raeburn 2362: my ($newentry,$anon,$group)=@_;
1.620 albertel 2363: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2364: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2365: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2366: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2367: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2368: &escape($newentry)).':'.$group,$chome);
1.292 www 2369: }
2370:
2371: # ------------------------------------------ Find current version of a resource
2372:
2373: sub getversion {
2374: my $fname=&clutter(shift);
2375: unless ($fname=~/^\/res\//) { return -1; }
2376: return ¤tversion(&filelocation('',$fname));
2377: }
2378:
2379: sub currentversion {
2380: my $fname=shift;
2381: my $author=$fname;
2382: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2383: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2384: my $home=&homeserver($uname,$udom);
1.292 www 2385: if ($home eq 'no_host') {
2386: return -1;
2387: }
1.1112 www 2388: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2389: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2390: return -1;
2391: }
1.1112 www 2392: return $answer;
1.263 www 2393: }
2394:
1.1111 www 2395: #
2396: # Return special version number of resource if set by override, empty otherwise
2397: #
2398: sub usedversion {
2399: my $fname=shift;
2400: unless ($fname) { $fname=$env{'request.uri'}; }
2401: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2402: if ($urlversion) { return $urlversion; }
2403: return '';
2404: }
2405:
1.1 albertel 2406: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2407:
1.1 albertel 2408: sub subscribe {
2409: my $fname=shift;
1.761 raeburn 2410: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2411: $fname=~s/[\n\r]//g;
1.1 albertel 2412: my $author=$fname;
2413: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2414: my ($udom,$uname)=split(/\//,$author);
2415: my $home=homeserver($uname,$udom);
1.335 albertel 2416: if ($home eq 'no_host') {
2417: return 'not_found';
1.1 albertel 2418: }
2419: my $answer=reply("sub:$fname",$home);
1.64 www 2420: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2421: $answer.=' by '.$home;
2422: }
1.1 albertel 2423: return $answer;
2424: }
2425:
1.8 www 2426: # -------------------------------------------------------------- Replicate file
2427:
2428: sub repcopy {
2429: my $filename=shift;
1.23 www 2430: $filename=~s/\/+/\//g;
1.607 raeburn 2431: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2432: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 2433: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 2434: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 2435: return &repcopy_userfile($filename);
2436: }
1.532 albertel 2437: $filename=~s/[\n\r]//g;
1.8 www 2438: my $transname="$filename.in.transfer";
1.828 www 2439: # FIXME: this should flock
1.607 raeburn 2440: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2441: my $remoteurl=subscribe($filename);
1.64 www 2442: if ($remoteurl =~ /^con_lost by/) {
2443: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2444: return 'unavailable';
1.8 www 2445: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2446: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2447: return 'not_found';
1.64 www 2448: } elsif ($remoteurl =~ /^rejected by/) {
2449: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2450: return 'forbidden';
1.20 www 2451: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2452: return 'ok';
1.8 www 2453: } else {
1.290 www 2454: my $author=$filename;
2455: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2456: my ($udom,$uname)=split(/\//,$author);
2457: my $home=homeserver($uname,$udom);
2458: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2459: my @parts=split(/\//,$filename);
2460: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2461: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2462: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2463: return 'bad_request';
1.8 www 2464: }
2465: my $count;
2466: for ($count=5;$count<$#parts;$count++) {
2467: $path.="/$parts[$count]";
2468: if ((-e $path)!=1) {
2469: mkdir($path,0777);
2470: }
2471: }
2472: my $ua=new LWP::UserAgent;
2473: my $request=new HTTP::Request('GET',"$remoteurl");
2474: my $response=$ua->request($request,$transname);
2475: if ($response->is_error()) {
2476: unlink($transname);
2477: my $message=$response->status_line;
1.672 albertel 2478: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2479: ." LWP get: $message: $filename</font>");
1.607 raeburn 2480: return 'unavailable';
1.8 www 2481: } else {
1.16 www 2482: if ($remoteurl!~/\.meta$/) {
2483: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2484: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2485: if ($mresponse->is_error()) {
2486: unlink($filename.'.meta');
2487: &logthis(
1.672 albertel 2488: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2489: }
2490: }
1.8 www 2491: rename($transname,$filename);
1.607 raeburn 2492: return 'ok';
1.8 www 2493: }
1.290 www 2494: }
1.8 www 2495: }
1.330 www 2496: }
2497:
2498: # ------------------------------------------------ Get server side include body
2499: sub ssi_body {
1.381 albertel 2500: my ($filelink,%form)=@_;
1.606 matthew 2501: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2502: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2503: }
1.953 www 2504: my $output='';
2505: my $response;
1.980 raeburn 2506: if ($filelink=~/^https?\:/) {
1.954 raeburn 2507: ($output,$response)=&externalssi($filelink);
1.953 www 2508: } else {
1.1004 droeschl 2509: $filelink .= $filelink=~/\?/ ? '&' : '?';
2510: $filelink .= 'inhibitmenu=yes';
1.953 www 2511: ($output,$response)=&ssi($filelink,%form);
2512: }
1.778 albertel 2513: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2514: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2515: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2516: if (wantarray) {
2517: return ($output, $response);
2518: } else {
2519: return $output;
2520: }
1.8 www 2521: }
2522:
1.15 www 2523: # --------------------------------------------------------- Server Side Include
2524:
1.782 albertel 2525: sub absolute_url {
2526: my ($host_name) = @_;
2527: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2528: if ($host_name eq '') {
2529: $host_name = $ENV{'SERVER_NAME'};
2530: }
2531: return $protocol.$host_name;
2532: }
2533:
1.942 foxr 2534: #
2535: # Server side include.
2536: # Parameters:
2537: # fn Possibly encrypted resource name/id.
2538: # form Hash that describes how the rendering should be done
2539: # and other things.
1.944 foxr 2540: # Returns:
1.950 raeburn 2541: # Scalar context: The content of the response.
2542: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2543: #
1.15 www 2544: sub ssi {
2545:
1.944 foxr 2546: my ($fn,%form)=@_;
1.15 www 2547: my $ua=new LWP::UserAgent;
1.23 www 2548: my $request;
1.711 albertel 2549:
2550: $form{'no_update_last_known'}=1;
1.895 albertel 2551: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2552: if (%form) {
1.782 albertel 2553: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2554: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2555: } else {
1.782 albertel 2556: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2557: }
2558:
1.15 www 2559: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2560: my $response=$ua->request($request);
2561:
1.944 foxr 2562: if (wantarray) {
2563: return ($response->content, $response);
2564: } else {
2565: return $response->content;
1.942 foxr 2566: }
1.324 www 2567: }
2568:
2569: sub externalssi {
2570: my ($url)=@_;
2571: my $ua=new LWP::UserAgent;
2572: my $request=new HTTP::Request('GET',$url);
2573: my $response=$ua->request($request);
1.954 raeburn 2574: if (wantarray) {
2575: return ($response->content, $response);
2576: } else {
2577: return $response->content;
2578: }
1.15 www 2579: }
1.254 www 2580:
1.492 albertel 2581: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2582:
2583: sub allowuploaded {
2584: my ($srcurl,$url)=@_;
2585: $url=&clutter(&declutter($url));
2586: my $dir=$url;
2587: $dir=~s/\/[^\/]+$//;
2588: my %httpref=();
2589: my $httpurl=&hreflocation('',$url);
2590: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2591: &Apache::lonnet::appenv(\%httpref);
1.254 www 2592: }
1.477 raeburn 2593:
1.478 albertel 2594: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2595: # input: action, courseID, current domain, intended
1.637 raeburn 2596: # path to file, source of file, instruction to parse file for objects,
2597: # ref to hash for embedded objects,
2598: # ref to hash for codebase of java objects.
1.1095 raeburn 2599: # reference to scalar to accommodate mime type determined
2600: # from File::MMagic if $parser = parse.
1.637 raeburn 2601: #
1.485 raeburn 2602: # output: url to file (if action was uploaddoc),
2603: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2604: #
1.478 albertel 2605: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2606: # course.
1.477 raeburn 2607: #
1.478 albertel 2608: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2609: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2610: # course's home server.
1.477 raeburn 2611: #
1.478 albertel 2612: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2613: # be copied from $source (current location) to
2614: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2615: # and will then be copied to
2616: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2617: # course's home server.
1.485 raeburn 2618: #
1.481 raeburn 2619: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2620: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2621: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2622: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2623: # in course's home server.
1.637 raeburn 2624: #
1.477 raeburn 2625:
2626: sub process_coursefile {
1.1095 raeburn 2627: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2628: $mimetype)=@_;
1.477 raeburn 2629: my $fetchresult;
1.638 albertel 2630: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2631: if ($action eq 'propagate') {
1.638 albertel 2632: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2633: $home);
1.481 raeburn 2634: } else {
1.477 raeburn 2635: my $fpath = '';
2636: my $fname = $file;
1.478 albertel 2637: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2638: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2639: my $filepath = &build_filepath($fpath);
1.481 raeburn 2640: if ($action eq 'copy') {
2641: if ($source eq '') {
2642: $fetchresult = 'no source file';
2643: return $fetchresult;
2644: } else {
2645: my $destination = $filepath.'/'.$fname;
2646: rename($source,$destination);
2647: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2648: $home);
1.481 raeburn 2649: }
2650: } elsif ($action eq 'uploaddoc') {
2651: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2652: print $fh $env{'form.'.$source};
1.481 raeburn 2653: close($fh);
1.637 raeburn 2654: if ($parser eq 'parse') {
1.1024 raeburn 2655: my $mm = new File::MMagic;
1.1095 raeburn 2656: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2657: if ($type eq 'text/html') {
1.1024 raeburn 2658: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2659: unless ($parse_result eq 'ok') {
2660: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2661: }
1.637 raeburn 2662: }
1.1095 raeburn 2663: if (ref($mimetype)) {
2664: $$mimetype = $type;
2665: }
1.637 raeburn 2666: }
1.477 raeburn 2667: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2668: $home);
1.481 raeburn 2669: if ($fetchresult eq 'ok') {
2670: return '/uploaded/'.$fpath.'/'.$fname;
2671: } else {
2672: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2673: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2674: return '/adm/notfound.html';
2675: }
1.477 raeburn 2676: }
2677: }
1.485 raeburn 2678: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2679: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2680: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2681: }
2682: return $fetchresult;
2683: }
2684:
1.637 raeburn 2685: sub build_filepath {
2686: my ($fpath) = @_;
2687: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2688: unless ($fpath eq '') {
2689: my @parts=split('/',$fpath);
2690: foreach my $part (@parts) {
2691: $filepath.= '/'.$part;
2692: if ((-e $filepath)!=1) {
2693: mkdir($filepath,0777);
2694: }
2695: }
2696: }
2697: return $filepath;
2698: }
2699:
2700: sub store_edited_file {
1.638 albertel 2701: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2702: my $file = $primary_url;
2703: $file =~ s#^/uploaded/$docudom/$docuname/##;
2704: my $fpath = '';
2705: my $fname = $file;
2706: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2707: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2708: my $filepath = &build_filepath($fpath);
2709: open(my $fh,'>'.$filepath.'/'.$fname);
2710: print $fh $content;
2711: close($fh);
1.638 albertel 2712: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2713: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2714: $home);
1.637 raeburn 2715: if ($$fetchresult eq 'ok') {
2716: return '/uploaded/'.$fpath.'/'.$fname;
2717: } else {
1.638 albertel 2718: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2719: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2720: return '/adm/notfound.html';
2721: }
2722: }
2723:
1.531 albertel 2724: sub clean_filename {
1.831 albertel 2725: my ($fname,$args)=@_;
1.315 www 2726: # Replace Windows backslashes by forward slashes
1.257 www 2727: $fname=~s/\\/\//g;
1.831 albertel 2728: if (!$args->{'keep_path'}) {
2729: # Get rid of everything but the actual filename
2730: $fname=~s/^.*\/([^\/]+)$/$1/;
2731: }
1.315 www 2732: # Replace spaces by underscores
2733: $fname=~s/\s+/\_/g;
2734: # Replace all other weird characters by nothing
1.831 albertel 2735: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2736: # Replace all .\d. sequences with _\d. so they no longer look like version
2737: # numbers
2738: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2739: return $fname;
2740: }
1.1051 raeburn 2741: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2742: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2743: # image with the same aspect ratio as the original, but with dimensions which do
2744: # not exceed $resizewidth and $resizeheight.
2745:
1.984 neumanie 2746: sub resizeImage {
1.1051 raeburn 2747: my ($img_path,$resizewidth,$resizeheight) = @_;
2748: my $ima = Image::Magick->new;
2749: my $resized;
2750: if (-e $img_path) {
2751: $ima->Read($img_path);
2752: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2753: my $width = $ima->Get('width');
2754: my $height = $ima->Get('height');
2755: if ($width > $resizewidth) {
2756: my $factor = $width/$resizewidth;
2757: my $newheight = $height/$factor;
2758: $ima->Scale(width=>$resizewidth,height=>$newheight);
2759: $resized = 1;
2760: }
2761: }
2762: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2763: my $width = $ima->Get('width');
2764: my $height = $ima->Get('height');
2765: if ($height > $resizeheight) {
2766: my $factor = $height/$resizeheight;
2767: my $newwidth = $width/$factor;
2768: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2769: $resized = 1;
2770: }
2771: }
2772: if ($resized) {
2773: $ima->Write($img_path);
2774: }
2775: }
2776: return;
1.977 amueller 2777: }
2778:
1.608 albertel 2779: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2780: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 2781: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 2782: # $context - possible values: coursedoc, existingfile, overwrite,
2783: # canceloverwrite, or ''.
2784: # if 'coursedoc': upload to the current course
2785: # if 'existingfile': write file to tmp/overwrites directory
2786: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2787: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2788: # $subdir - directory in userfile to store the file into
1.858 raeburn 2789: # $parser - instruction to parse file for objects ($parser = parse)
2790: # $allfiles - reference to hash for embedded objects
2791: # $codebase - reference to hash for codebase of java objects
2792: # $desuname - username for permanent storage of uploaded file
2793: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2794: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2795: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2796: # $resizewidth - width (pixels) to which to resize uploaded image
2797: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 2798: # $mimetype - reference to scalar to accommodate mime type determined
2799: # from File::MMagic if $parser = parse.
1.858 raeburn 2800: #
1.686 albertel 2801: # output: url of file in userspace, or error: <message>
2802: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2803:
1.531 albertel 2804: sub userfileupload {
1.1090 raeburn 2805: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 2806: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2807: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2808: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2809: $fname=&clean_filename($fname);
1.1090 raeburn 2810: # See if there is anything left
1.257 www 2811: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 2812: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2813: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2814: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2815: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2816: my $now = time;
1.1090 raeburn 2817: my $filepath;
1.1095 raeburn 2818: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 2819: $filepath = 'tmp/helprequests/'.$now;
2820: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2821: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2822: '_'.$env{'user.domain'}.'/pending';
2823: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2824: my ($docuname,$docudom);
2825: if ($destudom) {
2826: $docudom = $destudom;
2827: } else {
2828: $docudom = $env{'user.domain'};
2829: }
2830: if ($destuname) {
2831: $docuname = $destuname;
2832: } else {
2833: $docuname = $env{'user.name'};
2834: }
2835: if (exists($env{'form.group'})) {
2836: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2837: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2838: }
2839: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2840: if ($context eq 'canceloverwrite') {
2841: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2842: if (-e $tempfile) {
2843: my @info = stat($tempfile);
2844: if ($info[9] eq $env{'form.timestamp'}) {
2845: unlink($tempfile);
2846: }
2847: }
2848: return;
1.523 raeburn 2849: }
2850: }
1.1090 raeburn 2851: # Create the directory if not present
1.741 raeburn 2852: my @parts=split(/\//,$filepath);
2853: my $fullpath = $perlvar{'lonDaemons'};
2854: for (my $i=0;$i<@parts;$i++) {
2855: $fullpath .= '/'.$parts[$i];
2856: if ((-e $fullpath)!=1) {
2857: mkdir($fullpath,0777);
2858: }
2859: }
2860: open(my $fh,'>'.$fullpath.'/'.$fname);
2861: print $fh $env{'form.'.$formname};
2862: close($fh);
1.1090 raeburn 2863: if ($context eq 'existingfile') {
2864: my @info = stat($fullpath.'/'.$fname);
2865: return ($fullpath.'/'.$fname,$info[9]);
2866: } else {
2867: return $fullpath.'/'.$fname;
2868: }
1.523 raeburn 2869: }
1.995 raeburn 2870: if ($subdir eq 'scantron') {
2871: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 2872: } else {
1.995 raeburn 2873: $fname="$subdir/$fname";
2874: }
1.1090 raeburn 2875: if ($context eq 'coursedoc') {
1.638 albertel 2876: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2877: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2878: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2879: return &finishuserfileupload($docuname,$docudom,
2880: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2881: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 2882: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2883: } else {
1.620 albertel 2884: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2885: return &process_coursefile('uploaddoc',$docuname,$docudom,
2886: $fname,$formname,$parser,
1.1095 raeburn 2887: $allfiles,$codebase,$mimetype);
1.481 raeburn 2888: }
1.719 banghart 2889: } elsif (defined($destuname)) {
2890: my $docuname=$destuname;
2891: my $docudom=$destudom;
1.860 raeburn 2892: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2893: $parser,$allfiles,$codebase,
1.1051 raeburn 2894: $thumbwidth,$thumbheight,
1.1095 raeburn 2895: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2896: } else {
1.638 albertel 2897: my $docuname=$env{'user.name'};
2898: my $docudom=$env{'user.domain'};
1.714 raeburn 2899: if (exists($env{'form.group'})) {
2900: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2901: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2902: }
1.860 raeburn 2903: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2904: $parser,$allfiles,$codebase,
1.1051 raeburn 2905: $thumbwidth,$thumbheight,
1.1095 raeburn 2906: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2907: }
1.271 www 2908: }
2909:
2910: sub finishuserfileupload {
1.860 raeburn 2911: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 2912: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2913: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2914: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2915:
1.860 raeburn 2916: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2917: $file=$fname;
2918: if ($fname=~m|/|) {
2919: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2920: $path.=$fnamepath.'/';
2921: }
1.259 www 2922: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2923: my $count;
2924: for ($count=4;$count<=$#parts;$count++) {
2925: $filepath.="/$parts[$count]";
2926: if ((-e $filepath)!=1) {
2927: mkdir($filepath,0777);
2928: }
2929: }
1.984 neumanie 2930:
1.258 www 2931: # Save the file
2932: {
1.701 albertel 2933: if (!open(FH,'>'.$filepath.'/'.$file)) {
2934: &logthis('Failed to create '.$filepath.'/'.$file);
2935: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2936: return '/adm/notfound.html';
2937: }
1.1090 raeburn 2938: if ($context eq 'overwrite') {
1.1117 foxr 2939: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 2940: my $target = $filepath.'/'.$file;
2941: if (-e $source) {
2942: my @info = stat($source);
2943: if ($info[9] eq $env{'form.timestamp'}) {
2944: unless (&File::Copy::move($source,$target)) {
2945: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2946: return "Moving from $source failed";
2947: }
2948: } else {
2949: return "Temporary file: $source had unexpected date/time for last modification";
2950: }
2951: } else {
2952: return "Temporary file: $source missing";
2953: }
2954: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2955: &logthis('Failed to write to '.$filepath.'/'.$file);
2956: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2957: return '/adm/notfound.html';
2958: }
1.570 albertel 2959: close(FH);
1.1051 raeburn 2960: if ($resizewidth && $resizeheight) {
2961: my $mm = new File::MMagic;
2962: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2963: if ($mime_type =~ m{^image/}) {
2964: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2965: }
1.977 amueller 2966: }
1.258 www 2967: }
1.637 raeburn 2968: if ($parser eq 'parse') {
1.1024 raeburn 2969: my $mm = new File::MMagic;
1.1095 raeburn 2970: my $type = $mm->checktype_filename($filepath.'/'.$file);
2971: if ($type eq 'text/html') {
1.1024 raeburn 2972: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2973: $allfiles,$codebase);
2974: unless ($parse_result eq 'ok') {
2975: &logthis('Failed to parse '.$filepath.$file.
2976: ' for embedded media: '.$parse_result);
2977: }
1.637 raeburn 2978: }
1.1095 raeburn 2979: if (ref($mimetype)) {
2980: $$mimetype = $type;
2981: }
1.637 raeburn 2982: }
1.860 raeburn 2983: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2984: my $input = $filepath.'/'.$file;
2985: my $output = $filepath.'/'.'tn-'.$file;
2986: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2987: system("convert -sample $thumbsize $input $output");
2988: if (-e $filepath.'/'.'tn-'.$file) {
2989: $fetchthumb = 1;
2990: }
2991: }
1.858 raeburn 2992:
1.259 www 2993: # Notify homeserver to grep it
2994: #
1.984 neumanie 2995: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2996: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2997: if ($fetchresult eq 'ok') {
1.860 raeburn 2998: if ($fetchthumb) {
2999: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3000: if ($thumbresult ne 'ok') {
3001: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3002: $docuhome.': '.$thumbresult);
3003: }
3004: }
1.259 www 3005: #
1.258 www 3006: # Return the URL to it
1.494 albertel 3007: return '/uploaded/'.$path.$file;
1.263 www 3008: } else {
1.494 albertel 3009: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3010: ': '.$fetchresult);
1.263 www 3011: return '/adm/notfound.html';
1.858 raeburn 3012: }
1.493 albertel 3013: }
3014:
1.637 raeburn 3015: sub extract_embedded_items {
1.961 raeburn 3016: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3017: my @state = ();
3018: my %javafiles = (
3019: codebase => '',
3020: code => '',
3021: archive => ''
3022: );
3023: my %mediafiles = (
3024: src => '',
3025: movie => '',
3026: );
1.648 raeburn 3027: my $p;
3028: if ($content) {
3029: $p = HTML::LCParser->new($content);
3030: } else {
1.961 raeburn 3031: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3032: }
1.641 albertel 3033: while (my $t=$p->get_token()) {
1.640 albertel 3034: if ($t->[0] eq 'S') {
3035: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3036: push(@state, $tagname);
1.648 raeburn 3037: if (lc($tagname) eq 'allow') {
3038: &add_filetype($allfiles,$attr->{'src'},'src');
3039: }
1.640 albertel 3040: if (lc($tagname) eq 'img') {
3041: &add_filetype($allfiles,$attr->{'src'},'src');
3042: }
1.886 albertel 3043: if (lc($tagname) eq 'a') {
3044: &add_filetype($allfiles,$attr->{'href'},'href');
3045: }
1.645 raeburn 3046: if (lc($tagname) eq 'script') {
3047: if ($attr->{'archive'} =~ /\.jar$/i) {
3048: &add_filetype($allfiles,$attr->{'archive'},'archive');
3049: } else {
3050: &add_filetype($allfiles,$attr->{'src'},'src');
3051: }
3052: }
3053: if (lc($tagname) eq 'link') {
3054: if (lc($attr->{'rel'}) eq 'stylesheet') {
3055: &add_filetype($allfiles,$attr->{'href'},'href');
3056: }
3057: }
1.640 albertel 3058: if (lc($tagname) eq 'object' ||
3059: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3060: foreach my $item (keys(%javafiles)) {
3061: $javafiles{$item} = '';
3062: }
3063: }
3064: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3065: my $name = lc($attr->{'name'});
3066: foreach my $item (keys(%javafiles)) {
3067: if ($name eq $item) {
3068: $javafiles{$item} = $attr->{'value'};
3069: last;
3070: }
3071: }
3072: foreach my $item (keys(%mediafiles)) {
3073: if ($name eq $item) {
3074: &add_filetype($allfiles, $attr->{'value'}, 'value');
3075: last;
3076: }
3077: }
3078: }
3079: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3080: foreach my $item (keys(%javafiles)) {
3081: if ($attr->{$item}) {
3082: $javafiles{$item} = $attr->{$item};
3083: last;
3084: }
3085: }
3086: foreach my $item (keys(%mediafiles)) {
3087: if ($attr->{$item}) {
3088: &add_filetype($allfiles,$attr->{$item},$item);
3089: last;
3090: }
3091: }
3092: }
3093: } elsif ($t->[0] eq 'E') {
3094: my ($tagname) = ($t->[1]);
3095: if ($javafiles{'codebase'} ne '') {
3096: $javafiles{'codebase'} .= '/';
3097: }
3098: if (lc($tagname) eq 'applet' ||
3099: lc($tagname) eq 'object' ||
3100: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3101: ) {
3102: foreach my $item (keys(%javafiles)) {
3103: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3104: my $file=$javafiles{'codebase'}.$javafiles{$item};
3105: &add_filetype($allfiles,$file,$item);
3106: }
3107: }
3108: }
3109: pop @state;
3110: }
3111: }
1.637 raeburn 3112: return 'ok';
3113: }
3114:
1.639 albertel 3115: sub add_filetype {
3116: my ($allfiles,$file,$type)=@_;
3117: if (exists($allfiles->{$file})) {
3118: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3119: push(@{$allfiles->{$file}}, &escape($type));
3120: }
3121: } else {
3122: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3123: }
3124: }
3125:
1.493 albertel 3126: sub removeuploadedurl {
1.984 neumanie 3127: my ($url)=@_;
3128: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3129: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3130: }
3131:
3132: sub removeuserfile {
3133: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3134: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3135: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3136: if ($result eq 'ok') {
1.798 raeburn 3137: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3138: my $metafile = $fname.'.meta';
3139: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3140: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3141: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3142: my $sqlresult =
1.823 albertel 3143: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3144: 'portfolio_metadata',$group,
3145: 'delete');
1.798 raeburn 3146: }
3147: }
3148: return $result;
1.257 www 3149: }
1.15 www 3150:
1.530 albertel 3151: sub mkdiruserfile {
3152: my ($docuname,$docudom,$dir)=@_;
3153: my $home=&homeserver($docuname,$docudom);
3154: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3155: }
3156:
1.531 albertel 3157: sub renameuserfile {
3158: my ($docuname,$docudom,$old,$new)=@_;
3159: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3160: my $result = &reply("renameuserfile:$docudom:$docuname:".
3161: &escape("$old").':'.&escape("$new"),$home);
3162: if ($result eq 'ok') {
3163: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3164: my $oldmeta = $old.'.meta';
3165: my $newmeta = $new.'.meta';
3166: my $metaresult =
3167: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3168: my $url = "/uploaded/$docudom/$docuname/$old";
3169: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3170: my $sqlresult =
1.823 albertel 3171: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3172: 'portfolio_metadata',$group,
3173: 'delete');
1.798 raeburn 3174: }
3175: }
3176: return $result;
1.531 albertel 3177: }
3178:
1.14 www 3179: # ------------------------------------------------------------------------- Log
3180:
3181: sub log {
3182: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3183: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3184: }
3185:
3186: # ------------------------------------------------------------------ Course Log
1.352 www 3187: #
3188: # This routine flushes several buffers of non-mission-critical nature
3189: #
1.157 www 3190:
3191: sub flushcourselogs {
1.352 www 3192: &logthis('Flushing log buffers');
3193: #
3194: # course logs
3195: # This is a log of all transactions in a course, which can be used
3196: # for data mining purposes
3197: #
3198: # It also collects the courseid database, which lists last transaction
3199: # times and course titles for all courseids
3200: #
3201: my %courseidbuffer=();
1.921 raeburn 3202: foreach my $crsid (keys(%courselogs)) {
1.352 www 3203: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3204: &escape($courselogs{$crsid}),
3205: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3206: delete $courselogs{$crsid};
3207: } else {
3208: &logthis('Failed to flush log buffer for '.$crsid);
3209: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3210: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3211: " exceeded maximum size, deleting.</font>");
3212: delete $courselogs{$crsid};
3213: }
1.352 www 3214: }
1.920 raeburn 3215: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3216: 'description' => $coursedescrbuf{$crsid},
3217: 'inst_code' => $courseinstcodebuf{$crsid},
3218: 'type' => $coursetypebuf{$crsid},
3219: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3220: };
1.191 harris41 3221: }
1.352 www 3222: #
3223: # Write course id database (reverse lookup) to homeserver of courses
3224: # Is used in pickcourse
3225: #
1.840 albertel 3226: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3227: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3228: $courseidbuffer{$crs_home},
3229: $crs_home,'timeonly');
1.352 www 3230: }
3231: #
3232: # File accesses
3233: # Writes to the dynamic metadata of resources to get hit counts, etc.
3234: #
1.449 matthew 3235: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3236: if ($entry =~ /___count$/) {
3237: my ($dom,$name);
1.807 albertel 3238: ($dom,$name,undef)=
1.811 albertel 3239: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3240: if (! defined($dom) || $dom eq '' ||
3241: ! defined($name) || $name eq '') {
1.620 albertel 3242: my $cid = $env{'request.course.id'};
3243: $dom = $env{'request.'.$cid.'.domain'};
3244: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3245: }
1.450 matthew 3246: my $value = $accesshash{$entry};
3247: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3248: my %temphash=($url => $value);
1.449 matthew 3249: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3250: if ($result eq 'ok') {
3251: delete $accesshash{$entry};
3252: } elsif ($result eq 'unknown_cmd') {
3253: # Target server has old code running on it.
1.450 matthew 3254: my %temphash=($entry => $value);
1.449 matthew 3255: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3256: delete $accesshash{$entry};
3257: }
3258: }
3259: } else {
1.811 albertel 3260: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 3261: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3262: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3263: delete $accesshash{$entry};
3264: }
1.185 www 3265: }
1.191 harris41 3266: }
1.352 www 3267: #
3268: # Roles
3269: # Reverse lookup of user roles for course faculty/staff and co-authorship
3270: #
1.800 albertel 3271: foreach my $entry (keys(%userrolehash)) {
1.351 www 3272: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3273: split(/\:/,$entry);
3274: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3275: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3276: $rudom,$runame) eq 'ok') {
3277: delete $userrolehash{$entry};
3278: }
3279: }
1.662 raeburn 3280: #
3281: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3282: #
3283: my %domrolebuffer = ();
1.1000 raeburn 3284: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3285: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3286: if ($domrolebuffer{$rudom}) {
3287: $domrolebuffer{$rudom}.='&'.&escape($entry).
3288: '='.&escape($domainrolehash{$entry});
3289: } else {
3290: $domrolebuffer{$rudom}.=&escape($entry).
3291: '='.&escape($domainrolehash{$entry});
3292: }
3293: delete $domainrolehash{$entry};
3294: }
3295: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3296: my %servers = &get_servers($dom,'library');
3297: foreach my $tryserver (keys(%servers)) {
3298: unless (&reply('domroleput:'.$dom.':'.
3299: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3300: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3301: }
1.662 raeburn 3302: }
3303: }
1.186 www 3304: $dumpcount++;
1.157 www 3305: }
3306:
3307: sub courselog {
3308: my $what=shift;
1.158 www 3309: $what=time.':'.$what;
1.620 albertel 3310: unless ($env{'request.course.id'}) { return ''; }
3311: $coursedombuf{$env{'request.course.id'}}=
3312: $env{'course.'.$env{'request.course.id'}.'.domain'};
3313: $coursenumbuf{$env{'request.course.id'}}=
3314: $env{'course.'.$env{'request.course.id'}.'.num'};
3315: $coursehombuf{$env{'request.course.id'}}=
3316: $env{'course.'.$env{'request.course.id'}.'.home'};
3317: $coursedescrbuf{$env{'request.course.id'}}=
3318: $env{'course.'.$env{'request.course.id'}.'.description'};
3319: $courseinstcodebuf{$env{'request.course.id'}}=
3320: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3321: $courseownerbuf{$env{'request.course.id'}}=
3322: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3323: $coursetypebuf{$env{'request.course.id'}}=
3324: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3325: if (defined $courselogs{$env{'request.course.id'}}) {
3326: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3327: } else {
1.620 albertel 3328: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3329: }
1.620 albertel 3330: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3331: &flushcourselogs();
3332: }
1.158 www 3333: }
3334:
3335: sub courseacclog {
3336: my $fnsymb=shift;
1.620 albertel 3337: unless ($env{'request.course.id'}) { return ''; }
3338: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 3339: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 3340: $what.=':POST';
1.583 matthew 3341: # FIXME: Probably ought to escape things....
1.800 albertel 3342: foreach my $key (keys(%env)) {
3343: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3344: my $formitem = $1;
3345: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3346: $what.=':'.$formitem.'='.$env{$key};
3347: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3348: $what.=':'.$formitem.'='.$env{$key};
3349: }
1.158 www 3350: }
1.191 harris41 3351: }
1.583 matthew 3352: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3353: # FIXME: We should not be depending on a form parameter that someone
3354: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3355: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3356: $what.= ':POST';
3357: # FIXME: Probably ought to escape things....
3358: foreach my $element ('courseexp','crsfulltext','crsrelated',
3359: 'crsdiscuss') {
1.620 albertel 3360: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3361: }
3362: }
1.158 www 3363: }
3364: &courselog($what);
1.149 www 3365: }
3366:
1.185 www 3367: sub countacc {
3368: my $url=&declutter(shift);
1.458 matthew 3369: return if (! defined($url) || $url eq '');
1.620 albertel 3370: unless ($env{'request.course.id'}) { return ''; }
3371: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 3372: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3373: $accesshash{$key}++;
1.185 www 3374: }
1.349 www 3375:
1.361 www 3376: sub linklog {
3377: my ($from,$to)=@_;
3378: $from=&declutter($from);
3379: $to=&declutter($to);
3380: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3381: $accesshash{$to.'___'.$from.'___goto'}=1;
3382: }
3383:
1.349 www 3384: sub userrolelog {
3385: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 3386: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 3387: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 3388: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 3389: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 3390: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3391: $userrolehash
3392: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3393: =$tend.':'.$tstart;
1.662 raeburn 3394: }
1.898 albertel 3395: if (($env{'request.role'} =~ /dc\./) &&
3396: (($trole=~/^au/) || ($trole=~/^in/) ||
3397: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 3398: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3399: ($trole=~/^co/))) {
1.898 albertel 3400: $userrolehash
3401: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3402: =$tend.':'.$tstart;
3403: }
1.662 raeburn 3404: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3405: ($trole=~/^li/) || ($trole=~/^li/) ||
3406: ($trole=~/^au/) || ($trole=~/^dg/) ||
3407: ($trole=~/^sc/)) {
3408: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3409: $domainrolehash
3410: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3411: = $tend.':'.$tstart;
3412: }
1.351 www 3413: }
3414:
1.957 raeburn 3415: sub courserolelog {
3416: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3417: if (($trole eq 'cc') || ($trole eq 'in') ||
3418: ($trole eq 'ep') || ($trole eq 'ad') ||
3419: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 3420: ($trole=~/^cr/) || ($trole eq 'gr') ||
3421: ($trole eq 'co')) {
1.957 raeburn 3422: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3423: my $cdom = $1;
3424: my $cnum = $2;
3425: my $sec = $3;
3426: my $namespace = 'rolelog';
3427: my %storehash = (
3428: role => $trole,
3429: start => $tstart,
3430: end => $tend,
3431: selfenroll => $selfenroll,
3432: context => $context,
3433: );
3434: if ($trole eq 'gr') {
3435: $namespace = 'groupslog';
3436: $storehash{'group'} = $sec;
3437: } else {
3438: $storehash{'section'} = $sec;
3439: }
3440: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 3441: if (($trole ne 'st') || ($sec ne '')) {
3442: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3443: }
1.957 raeburn 3444: }
3445: }
3446: return;
3447: }
3448:
1.351 www 3449: sub get_course_adv_roles {
1.948 raeburn 3450: my ($cid,$codes) = @_;
1.620 albertel 3451: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3452: my %coursehash=&coursedescription($cid);
1.988 raeburn 3453: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3454: my %nothide=();
1.800 albertel 3455: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3456: if ($user !~ /:/) {
3457: $nothide{join(':',split(/[\@]/,$user))}=1;
3458: } else {
3459: $nothide{$user}=1;
3460: }
1.470 www 3461: }
1.351 www 3462: my %returnhash=();
3463: my %dumphash=
3464: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3465: my $now=time;
1.997 raeburn 3466: my %privileged;
1.1000 raeburn 3467: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3468: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3469: if (($tstart) && ($tstart<0)) { next; }
3470: if (($tend) && ($tend<$now)) { next; }
3471: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3472: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3473: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3474: unless (ref($privileged{$domain}) eq 'HASH') {
3475: my %dompersonnel =
1.998 raeburn 3476: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3477: $privileged{$domain} = {};
3478: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3479: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3480: foreach my $user (keys(%{$dompersonnel{$server}})) {
3481: my ($trole,$uname,$udom) = split(/:/,$user);
3482: $privileged{$udom}{$uname} = 1;
3483: }
3484: }
3485: }
3486: }
3487: if ((exists($privileged{$domain}{$username})) &&
3488: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3489: if ($role eq 'cr') { next; }
1.948 raeburn 3490: if ($codes) {
3491: if ($section) { $role .= ':'.$section; }
3492: if ($returnhash{$role}) {
3493: $returnhash{$role}.=','.$username.':'.$domain;
3494: } else {
3495: $returnhash{$role}=$username.':'.$domain;
3496: }
1.351 www 3497: } else {
1.988 raeburn 3498: my $key=&plaintext($role,$crstype);
1.973 bisitz 3499: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3500: if ($returnhash{$key}) {
3501: $returnhash{$key}.=','.$username.':'.$domain;
3502: } else {
3503: $returnhash{$key}=$username.':'.$domain;
3504: }
1.351 www 3505: }
1.948 raeburn 3506: }
1.400 www 3507: return %returnhash;
3508: }
3509:
3510: sub get_my_roles {
1.937 raeburn 3511: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3512: unless (defined($uname)) { $uname=$env{'user.name'}; }
3513: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3514: my (%dumphash,%nothide);
1.1086 raeburn 3515: if ($context eq 'userroles') {
3516: my $extra = &freeze_escape({'skipcheck' => 1});
3517: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858 raeburn 3518: } else {
3519: %dumphash=
1.400 www 3520: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3521: if ($hidepriv) {
3522: my %coursehash=&coursedescription($udom.'_'.$uname);
3523: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3524: if ($user !~ /:/) {
3525: $nothide{join(':',split(/[\@]/,$user))} = 1;
3526: } else {
3527: $nothide{$user} = 1;
3528: }
3529: }
3530: }
1.858 raeburn 3531: }
1.400 www 3532: my %returnhash=();
3533: my $now=time;
1.999 raeburn 3534: my %privileged;
1.800 albertel 3535: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3536: my ($role,$tend,$tstart);
3537: if ($context eq 'userroles') {
3538: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3539: } else {
3540: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3541: }
1.400 www 3542: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3543: my $status = 'active';
1.939 raeburn 3544: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3545: $status = 'previous';
3546: }
3547: if (($tstart) && ($now<$tstart)) {
3548: $status = 'future';
3549: }
3550: if (ref($types) eq 'ARRAY') {
3551: if (!grep(/^\Q$status\E$/,@{$types})) {
3552: next;
3553: }
3554: } else {
3555: if ($status ne 'active') {
3556: next;
3557: }
3558: }
1.867 raeburn 3559: my ($rolecode,$username,$domain,$section,$area);
3560: if ($context eq 'userroles') {
3561: ($area,$rolecode) = split(/_/,$entry);
3562: (undef,$domain,$username,$section) = split(/\//,$area);
3563: } else {
3564: ($role,$username,$domain,$section) = split(/\:/,$entry);
3565: }
1.832 raeburn 3566: if (ref($roledoms) eq 'ARRAY') {
3567: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3568: next;
3569: }
3570: }
3571: if (ref($roles) eq 'ARRAY') {
3572: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3573: if ($role =~ /^cr\//) {
3574: if (!grep(/^cr$/,@{$roles})) {
3575: next;
3576: }
1.1104 raeburn 3577: } elsif ($role =~ /^gr\//) {
3578: if (!grep(/^gr$/,@{$roles})) {
3579: next;
3580: }
1.922 raeburn 3581: } else {
3582: next;
3583: }
1.832 raeburn 3584: }
1.867 raeburn 3585: }
1.937 raeburn 3586: if ($hidepriv) {
1.999 raeburn 3587: if ($context eq 'userroles') {
3588: if ((&privileged($username,$domain)) &&
3589: (!$nothide{$username.':'.$domain})) {
3590: next;
3591: }
3592: } else {
3593: unless (ref($privileged{$domain}) eq 'HASH') {
3594: my %dompersonnel =
3595: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3596: $privileged{$domain} = {};
3597: if (keys(%dompersonnel)) {
3598: foreach my $server (keys(%dompersonnel)) {
3599: if (ref($dompersonnel{$server}) eq 'HASH') {
3600: foreach my $user (keys(%{$dompersonnel{$server}})) {
3601: my ($trole,$uname,$udom) = split(/:/,$user);
3602: $privileged{$udom}{$uname} = $trole;
3603: }
3604: }
3605: }
3606: }
3607: }
3608: if (exists($privileged{$domain}{$username})) {
3609: if (!$nothide{$username.':'.$domain}) {
3610: next;
3611: }
3612: }
1.937 raeburn 3613: }
3614: }
1.933 raeburn 3615: if ($withsec) {
3616: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3617: $tstart.':'.$tend;
3618: } else {
3619: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3620: }
1.832 raeburn 3621: }
1.373 www 3622: return %returnhash;
1.399 www 3623: }
3624:
3625: # ----------------------------------------------------- Frontpage Announcements
3626: #
3627: #
3628:
3629: sub postannounce {
3630: my ($server,$text)=@_;
1.844 albertel 3631: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3632: unless ($text=~/\w/) { $text=''; }
3633: return &reply('setannounce:'.&escape($text),$server);
3634: }
3635:
3636: sub getannounce {
1.448 albertel 3637:
3638: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3639: my $announcement='';
1.800 albertel 3640: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3641: close($fh);
1.399 www 3642: if ($announcement=~/\w/) {
3643: return
3644: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3645: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3646: } else {
3647: return '';
3648: }
3649: } else {
3650: return '';
3651: }
1.351 www 3652: }
1.353 www 3653:
3654: # ---------------------------------------------------------- Course ID routines
3655: # Deal with domain's nohist_courseid.db files
3656: #
3657:
3658: sub courseidput {
1.921 raeburn 3659: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3660: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3661: my $outcome;
3662: if ($caller eq 'timeonly') {
3663: my $cids = '';
3664: foreach my $item (keys(%$storehash)) {
3665: $cids.=&escape($item).'&';
3666: }
3667: $cids=~s/\&$//;
3668: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3669: $coursehome);
3670: } else {
3671: my $items = '';
3672: foreach my $item (keys(%$storehash)) {
3673: $items.= &escape($item).'='.
3674: &freeze_escape($$storehash{$item}).'&';
3675: }
3676: $items=~s/\&$//;
3677: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3678: $coursehome);
1.918 raeburn 3679: }
3680: if ($outcome eq 'unknown_cmd') {
3681: my $what;
3682: foreach my $cid (keys(%$storehash)) {
3683: $what .= &escape($cid).'=';
1.921 raeburn 3684: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3685: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3686: }
3687: $what =~ s/\:$/&/;
3688: }
3689: $what =~ s/\&$//;
3690: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3691: } else {
3692: return $outcome;
3693: }
1.353 www 3694: }
3695:
3696: sub courseiddump {
1.921 raeburn 3697: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3698: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3699: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3700: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3701: my $as_hash = 1;
3702: my %returnhash;
3703: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3704: my %libserv = &all_library();
3705: foreach my $tryserver (keys(%libserv)) {
3706: if ( ( $hostidflag == 1
3707: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3708: || (!defined($hostidflag)) ) {
3709:
1.918 raeburn 3710: if (($domfilter eq '') ||
3711: (&host_domain($tryserver) eq $domfilter)) {
3712: my $rep =
3713: &reply('courseiddump:'.&host_domain($tryserver).':'.
3714: $sincefilter.':'.&escape($descfilter).':'.
3715: &escape($instcodefilter).':'.&escape($ownerfilter).
3716: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3717: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3718: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3719: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3720: &escape($cc_clone).':'.$cloneonly.':'.
3721: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071 raeburn 3722: &escape($creationcontext).':'.$domcloner,
3723: $tryserver);
1.918 raeburn 3724: my @pairs=split(/\&/,$rep);
3725: foreach my $item (@pairs) {
3726: my ($key,$value)=split(/\=/,$item,2);
3727: $key = &unescape($key);
3728: next if ($key =~ /^error: 2 /);
3729: my $result = &thaw_unescape($value);
3730: if (ref($result) eq 'HASH') {
3731: $returnhash{$key}=$result;
3732: } else {
1.921 raeburn 3733: my @responses = split(/:/,$value);
3734: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3735: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3736: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3737: }
1.1008 raeburn 3738: }
1.353 www 3739: }
3740: }
3741: }
3742: }
3743: return %returnhash;
3744: }
3745:
1.1055 raeburn 3746: sub courselastaccess {
3747: my ($cdom,$cnum,$hostidref) = @_;
3748: my %returnhash;
3749: if ($cdom && $cnum) {
3750: my $chome = &homeserver($cnum,$cdom);
3751: if ($chome ne 'no_host') {
3752: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3753: &extract_lastaccess(\%returnhash,$rep);
3754: }
3755: } else {
3756: if (!$cdom) { $cdom=''; }
3757: my %libserv = &all_library();
3758: foreach my $tryserver (keys(%libserv)) {
3759: if (ref($hostidref) eq 'ARRAY') {
3760: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3761: }
3762: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3763: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3764: &extract_lastaccess(\%returnhash,$rep);
3765: }
3766: }
3767: }
3768: return %returnhash;
3769: }
3770:
3771: sub extract_lastaccess {
3772: my ($returnhash,$rep) = @_;
3773: if (ref($returnhash) eq 'HASH') {
3774: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3775: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3776: $rep eq '') {
3777: my @pairs=split(/\&/,$rep);
3778: foreach my $item (@pairs) {
3779: my ($key,$value)=split(/\=/,$item,2);
3780: $key = &unescape($key);
3781: next if ($key =~ /^error: 2 /);
3782: $returnhash->{$key} = &thaw_unescape($value);
3783: }
3784: }
3785: }
3786: return;
3787: }
3788:
1.658 raeburn 3789: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3790:
3791: sub dcmailput {
1.685 raeburn 3792: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3793: my $status = &Apache::lonnet::critical(
1.740 www 3794: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3795: &escape($message),$server);
1.662 raeburn 3796: return $status;
3797: }
3798:
1.658 raeburn 3799: sub dcmaildump {
3800: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3801: my %returnhash=();
1.846 albertel 3802:
3803: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3804: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3805: &escape($enddate).':';
3806: my @esc_senders=map { &escape($_)} @$senders;
3807: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3808: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3809: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3810: if (($key) && ($value)) {
3811: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3812: }
3813: }
3814: }
3815: return %returnhash;
3816: }
1.662 raeburn 3817: # ---------------------------------------------------------- Domain roles
3818:
3819: sub get_domain_roles {
3820: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3821: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3822: $startdate = '.';
3823: }
1.1018 raeburn 3824: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3825: $enddate = '.';
3826: }
1.922 raeburn 3827: my $rolelist;
3828: if (ref($roles) eq 'ARRAY') {
3829: $rolelist = join(':',@{$roles});
3830: }
1.662 raeburn 3831: my %personnel = ();
1.841 albertel 3832:
3833: my %servers = &get_servers($dom,'library');
3834: foreach my $tryserver (keys(%servers)) {
3835: %{$personnel{$tryserver}}=();
3836: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3837: &escape($startdate).':'.
3838: &escape($enddate).':'.
3839: &escape($rolelist), $tryserver))) {
3840: my ($key,$value) = split(/\=/,$line,2);
3841: if (($key) && ($value)) {
3842: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3843: }
3844: }
1.662 raeburn 3845: }
3846: return %personnel;
3847: }
1.658 raeburn 3848:
1.1057 www 3849: # ----------------------------------------------------------- Interval timing
1.149 www 3850:
1.504 albertel 3851: sub get_first_access {
3852: my ($type,$argsymb)=@_;
1.790 albertel 3853: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3854: if ($argsymb) { $symb=$argsymb; }
3855: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3856: if ($type eq 'course') {
3857: $res='course';
3858: } elsif ($type eq 'map') {
1.588 albertel 3859: $res=&symbread($map);
3860: } else {
3861: $res=$symb;
3862: }
3863: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3864: return $times{"$courseid\0$res"};
1.504 albertel 3865: }
3866:
3867: sub set_first_access {
3868: my ($type)=@_;
1.790 albertel 3869: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3870: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3871: if ($type eq 'course') {
3872: $res='course';
3873: } elsif ($type eq 'map') {
1.588 albertel 3874: $res=&symbread($map);
3875: } else {
3876: $res=$symb;
3877: }
3878: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3879: if (!$firstaccess) {
1.588 albertel 3880: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3881: }
3882: return 'already_set';
1.504 albertel 3883: }
3884:
1.110 www 3885: # --------------------------------------------- Set Expire Date for Spreadsheet
3886:
3887: sub expirespread {
3888: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3889: my $cid=$env{'request.course.id'};
1.110 www 3890: if ($cid) {
3891: my $now=time;
3892: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3893: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3894: $env{'course.'.$cid.'.num'}.
1.110 www 3895: ':nohist_expirationdates:'.
3896: &escape($key).'='.$now,
1.620 albertel 3897: $env{'course.'.$cid.'.home'})
1.110 www 3898: }
3899: return 'ok';
1.14 www 3900: }
3901:
1.109 www 3902: # ----------------------------------------------------- Devalidate Spreadsheets
3903:
3904: sub devalidate {
1.325 www 3905: my ($symb,$uname,$udom)=@_;
1.620 albertel 3906: my $cid=$env{'request.course.id'};
1.109 www 3907: if ($cid) {
1.391 matthew 3908: # delete the stored spreadsheets for
3909: # - the student level sheet of this user in course's homespace
3910: # - the assessment level sheet for this resource
3911: # for this user in user's homespace
1.553 albertel 3912: # - current conditional state info
1.325 www 3913: my $key=$uname.':'.$udom.':';
1.109 www 3914: my $status=
1.299 matthew 3915: &del('nohist_calculatedsheets',
1.391 matthew 3916: [$key.'studentcalc:'],
1.620 albertel 3917: $env{'course.'.$cid.'.domain'},
3918: $env{'course.'.$cid.'.num'})
1.133 albertel 3919: .' '.
3920: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3921: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3922: unless ($status eq 'ok ok') {
3923: &logthis('Could not devalidate spreadsheet '.
1.325 www 3924: $uname.' at '.$udom.' for '.
1.109 www 3925: $symb.': '.$status);
1.133 albertel 3926: }
1.553 albertel 3927: &delenv('user.state.'.$cid);
1.109 www 3928: }
3929: }
3930:
1.265 albertel 3931: sub get_scalar {
3932: my ($string,$end) = @_;
3933: my $value;
3934: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3935: $value = $1;
3936: } elsif ($$string =~ s/^([^&]*?)&//) {
3937: $value = $1;
3938: }
3939: return &unescape($value);
3940: }
3941:
3942: sub array2str {
3943: my (@array) = @_;
3944: my $result=&arrayref2str(\@array);
3945: $result=~s/^__ARRAY_REF__//;
3946: $result=~s/__END_ARRAY_REF__$//;
3947: return $result;
3948: }
3949:
1.204 albertel 3950: sub arrayref2str {
3951: my ($arrayref) = @_;
1.265 albertel 3952: my $result='__ARRAY_REF__';
1.204 albertel 3953: foreach my $elem (@$arrayref) {
1.265 albertel 3954: if(ref($elem) eq 'ARRAY') {
3955: $result.=&arrayref2str($elem).'&';
3956: } elsif(ref($elem) eq 'HASH') {
3957: $result.=&hashref2str($elem).'&';
3958: } elsif(ref($elem)) {
3959: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3960: } else {
3961: $result.=&escape($elem).'&';
3962: }
3963: }
3964: $result=~s/\&$//;
1.265 albertel 3965: $result .= '__END_ARRAY_REF__';
1.204 albertel 3966: return $result;
3967: }
3968:
1.168 albertel 3969: sub hash2str {
1.204 albertel 3970: my (%hash) = @_;
3971: my $result=&hashref2str(\%hash);
1.265 albertel 3972: $result=~s/^__HASH_REF__//;
3973: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3974: return $result;
3975: }
3976:
3977: sub hashref2str {
3978: my ($hashref)=@_;
1.265 albertel 3979: my $result='__HASH_REF__';
1.800 albertel 3980: foreach my $key (sort(keys(%$hashref))) {
3981: if (ref($key) eq 'ARRAY') {
3982: $result.=&arrayref2str($key).'=';
3983: } elsif (ref($key) eq 'HASH') {
3984: $result.=&hashref2str($key).'=';
3985: } elsif (ref($key)) {
1.265 albertel 3986: $result.='=';
1.800 albertel 3987: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3988: } else {
1.800 albertel 3989: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3990: }
3991:
1.800 albertel 3992: if(ref($hashref->{$key}) eq 'ARRAY') {
3993: $result.=&arrayref2str($hashref->{$key}).'&';
3994: } elsif(ref($hashref->{$key}) eq 'HASH') {
3995: $result.=&hashref2str($hashref->{$key}).'&';
3996: } elsif(ref($hashref->{$key})) {
1.265 albertel 3997: $result.='&';
1.800 albertel 3998: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3999: } else {
1.800 albertel 4000: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4001: }
4002: }
1.168 albertel 4003: $result=~s/\&$//;
1.265 albertel 4004: $result .= '__END_HASH_REF__';
1.168 albertel 4005: return $result;
4006: }
4007:
4008: sub str2hash {
1.265 albertel 4009: my ($string)=@_;
4010: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4011: return %$hash;
4012: }
4013:
4014: sub str2hashref {
1.168 albertel 4015: my ($string) = @_;
1.265 albertel 4016:
4017: my %hash;
4018:
4019: if($string !~ /^__HASH_REF__/) {
4020: if (! ($string eq '' || !defined($string))) {
4021: $hash{'error'}='Not hash reference';
4022: }
4023: return (\%hash, $string);
4024: }
4025:
4026: $string =~ s/^__HASH_REF__//;
4027:
4028: while($string !~ /^__END_HASH_REF__/) {
4029: #key
4030: my $key='';
4031: if($string =~ /^__HASH_REF__/) {
4032: ($key, $string)=&str2hashref($string);
4033: if(defined($key->{'error'})) {
4034: $hash{'error'}='Bad data';
4035: return (\%hash, $string);
4036: }
4037: } elsif($string =~ /^__ARRAY_REF__/) {
4038: ($key, $string)=&str2arrayref($string);
4039: if($key->[0] eq 'Array reference error') {
4040: $hash{'error'}='Bad data';
4041: return (\%hash, $string);
4042: }
4043: } else {
4044: $string =~ s/^(.*?)=//;
1.267 albertel 4045: $key=&unescape($1);
1.265 albertel 4046: }
4047: $string =~ s/^=//;
4048:
4049: #value
4050: my $value='';
4051: if($string =~ /^__HASH_REF__/) {
4052: ($value, $string)=&str2hashref($string);
4053: if(defined($value->{'error'})) {
4054: $hash{'error'}='Bad data';
4055: return (\%hash, $string);
4056: }
4057: } elsif($string =~ /^__ARRAY_REF__/) {
4058: ($value, $string)=&str2arrayref($string);
4059: if($value->[0] eq 'Array reference error') {
4060: $hash{'error'}='Bad data';
4061: return (\%hash, $string);
4062: }
4063: } else {
4064: $value=&get_scalar(\$string,'__END_HASH_REF__');
4065: }
4066: $string =~ s/^&//;
4067:
4068: $hash{$key}=$value;
1.204 albertel 4069: }
1.265 albertel 4070:
4071: $string =~ s/^__END_HASH_REF__//;
4072:
4073: return (\%hash, $string);
1.204 albertel 4074: }
4075:
4076: sub str2array {
1.265 albertel 4077: my ($string)=@_;
4078: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4079: return @$array;
4080: }
4081:
4082: sub str2arrayref {
1.204 albertel 4083: my ($string) = @_;
1.265 albertel 4084: my @array;
4085:
4086: if($string !~ /^__ARRAY_REF__/) {
4087: if (! ($string eq '' || !defined($string))) {
4088: $array[0]='Array reference error';
4089: }
4090: return (\@array, $string);
4091: }
4092:
4093: $string =~ s/^__ARRAY_REF__//;
4094:
4095: while($string !~ /^__END_ARRAY_REF__/) {
4096: my $value='';
4097: if($string =~ /^__HASH_REF__/) {
4098: ($value, $string)=&str2hashref($string);
4099: if(defined($value->{'error'})) {
4100: $array[0] ='Array reference error';
4101: return (\@array, $string);
4102: }
4103: } elsif($string =~ /^__ARRAY_REF__/) {
4104: ($value, $string)=&str2arrayref($string);
4105: if($value->[0] eq 'Array reference error') {
4106: $array[0] ='Array reference error';
4107: return (\@array, $string);
4108: }
4109: } else {
4110: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4111: }
4112: $string =~ s/^&//;
4113:
4114: push(@array, $value);
1.191 harris41 4115: }
1.265 albertel 4116:
4117: $string =~ s/^__END_ARRAY_REF__//;
4118:
4119: return (\@array, $string);
1.168 albertel 4120: }
4121:
1.167 albertel 4122: # -------------------------------------------------------------------Temp Store
4123:
1.168 albertel 4124: sub tmpreset {
4125: my ($symb,$namespace,$domain,$stuname) = @_;
4126: if (!$symb) {
4127: $symb=&symbread();
1.620 albertel 4128: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4129: }
4130: $symb=escape($symb);
4131:
1.620 albertel 4132: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4133: $namespace=~s/\//\_/g;
4134: $namespace=~s/\W//g;
4135:
1.620 albertel 4136: if (!$domain) { $domain=$env{'user.domain'}; }
4137: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4138: if ($domain eq 'public' && $stuname eq 'public') {
4139: $stuname=$ENV{'REMOTE_ADDR'};
4140: }
1.1117 foxr 4141: my $path=LONCAPA::tempdir();
1.168 albertel 4142: my %hash;
4143: if (tie(%hash,'GDBM_File',
4144: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4145: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4146: foreach my $key (keys(%hash)) {
1.180 albertel 4147: if ($key=~ /:$symb/) {
1.168 albertel 4148: delete($hash{$key});
4149: }
4150: }
4151: }
4152: }
4153:
1.167 albertel 4154: sub tmpstore {
1.168 albertel 4155: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4156:
4157: if (!$symb) {
4158: $symb=&symbread();
1.620 albertel 4159: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4160: }
4161: $symb=escape($symb);
4162:
4163: if (!$namespace) {
4164: # I don't think we would ever want to store this for a course.
4165: # it seems this will only be used if we don't have a course.
1.620 albertel 4166: #$namespace=$env{'request.course.id'};
1.168 albertel 4167: #if (!$namespace) {
1.620 albertel 4168: $namespace=$env{'request.state'};
1.168 albertel 4169: #}
4170: }
4171: $namespace=~s/\//\_/g;
4172: $namespace=~s/\W//g;
1.620 albertel 4173: if (!$domain) { $domain=$env{'user.domain'}; }
4174: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4175: if ($domain eq 'public' && $stuname eq 'public') {
4176: $stuname=$ENV{'REMOTE_ADDR'};
4177: }
1.168 albertel 4178: my $now=time;
4179: my %hash;
1.1117 foxr 4180: my $path=LONCAPA::tempdir();
1.168 albertel 4181: if (tie(%hash,'GDBM_File',
4182: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4183: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4184: $hash{"version:$symb"}++;
4185: my $version=$hash{"version:$symb"};
4186: my $allkeys='';
4187: foreach my $key (keys(%$storehash)) {
4188: $allkeys.=$key.':';
1.591 albertel 4189: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4190: }
4191: $hash{"$version:$symb:timestamp"}=$now;
4192: $allkeys.='timestamp';
4193: $hash{"$version:keys:$symb"}=$allkeys;
4194: if (untie(%hash)) {
4195: return 'ok';
4196: } else {
4197: return "error:$!";
4198: }
4199: } else {
4200: return "error:$!";
4201: }
4202: }
1.167 albertel 4203:
1.168 albertel 4204: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4205:
1.168 albertel 4206: sub tmprestore {
4207: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4208:
1.168 albertel 4209: if (!$symb) {
4210: $symb=&symbread();
1.620 albertel 4211: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4212: }
4213: $symb=escape($symb);
4214:
1.620 albertel 4215: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4216:
1.620 albertel 4217: if (!$domain) { $domain=$env{'user.domain'}; }
4218: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4219: if ($domain eq 'public' && $stuname eq 'public') {
4220: $stuname=$ENV{'REMOTE_ADDR'};
4221: }
1.168 albertel 4222: my %returnhash;
4223: $namespace=~s/\//\_/g;
4224: $namespace=~s/\W//g;
4225: my %hash;
1.1117 foxr 4226: my $path=LONCAPA::tempdir();
1.168 albertel 4227: if (tie(%hash,'GDBM_File',
4228: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4229: &GDBM_READER(),0640)) {
1.168 albertel 4230: my $version=$hash{"version:$symb"};
4231: $returnhash{'version'}=$version;
4232: my $scope;
4233: for ($scope=1;$scope<=$version;$scope++) {
4234: my $vkeys=$hash{"$scope:keys:$symb"};
4235: my @keys=split(/:/,$vkeys);
4236: my $key;
4237: $returnhash{"$scope:keys"}=$vkeys;
4238: foreach $key (@keys) {
1.591 albertel 4239: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4240: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4241: }
4242: }
1.168 albertel 4243: if (!(untie(%hash))) {
4244: return "error:$!";
4245: }
4246: } else {
4247: return "error:$!";
4248: }
4249: return %returnhash;
1.167 albertel 4250: }
4251:
1.9 www 4252: # ----------------------------------------------------------------------- Store
4253:
4254: sub store {
1.124 www 4255: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4256: my $home='';
4257:
1.168 albertel 4258: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4259:
1.213 www 4260: $symb=&symbclean($symb);
1.122 albertel 4261: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4262:
1.620 albertel 4263: if (!$domain) { $domain=$env{'user.domain'}; }
4264: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4265:
4266: &devalidate($symb,$stuname,$domain);
1.109 www 4267:
4268: $symb=escape($symb);
1.187 www 4269: if (!$namespace) {
1.620 albertel 4270: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4271: return '';
4272: }
4273: }
1.620 albertel 4274: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4275:
4276: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4277: $$storehash{'host'}=$perlvar{'lonHostID'};
4278:
1.12 www 4279: my $namevalue='';
1.800 albertel 4280: foreach my $key (keys(%$storehash)) {
4281: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4282: }
1.12 www 4283: $namevalue=~s/\&$//;
1.187 www 4284: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4285: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4286: }
4287:
1.47 www 4288: # -------------------------------------------------------------- Critical Store
4289:
4290: sub cstore {
1.124 www 4291: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4292: my $home='';
4293:
1.168 albertel 4294: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4295:
1.213 www 4296: $symb=&symbclean($symb);
1.122 albertel 4297: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4298:
1.620 albertel 4299: if (!$domain) { $domain=$env{'user.domain'}; }
4300: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4301:
4302: &devalidate($symb,$stuname,$domain);
1.109 www 4303:
4304: $symb=escape($symb);
1.187 www 4305: if (!$namespace) {
1.620 albertel 4306: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4307: return '';
4308: }
4309: }
1.620 albertel 4310: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4311:
4312: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4313: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4314:
1.47 www 4315: my $namevalue='';
1.800 albertel 4316: foreach my $key (keys(%$storehash)) {
4317: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4318: }
1.47 www 4319: $namevalue=~s/\&$//;
1.187 www 4320: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4321: return critical
4322: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4323: }
4324:
1.9 www 4325: # --------------------------------------------------------------------- Restore
4326:
4327: sub restore {
1.124 www 4328: my ($symb,$namespace,$domain,$stuname) = @_;
4329: my $home='';
4330:
1.168 albertel 4331: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4332:
1.122 albertel 4333: if (!$symb) {
4334: unless ($symb=escape(&symbread())) { return ''; }
4335: } else {
1.213 www 4336: $symb=&escape(&symbclean($symb));
1.122 albertel 4337: }
1.188 www 4338: if (!$namespace) {
1.620 albertel 4339: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4340: return '';
4341: }
4342: }
1.620 albertel 4343: if (!$domain) { $domain=$env{'user.domain'}; }
4344: if (!$stuname) { $stuname=$env{'user.name'}; }
4345: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4346: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4347:
1.12 www 4348: my %returnhash=();
1.800 albertel 4349: foreach my $line (split(/\&/,$answer)) {
4350: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4351: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4352: }
1.75 www 4353: my $version;
4354: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4355: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4356: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4357: }
1.75 www 4358: }
1.13 www 4359: return %returnhash;
1.34 www 4360: }
4361:
4362: # ---------------------------------------------------------- Course Description
1.1118 foxr 4363: #
4364: #
1.34 www 4365:
4366: sub coursedescription {
1.731 albertel 4367: my ($courseid,$args)=@_;
1.34 www 4368: $courseid=~s/^\///;
1.49 www 4369: $courseid=~s/\_/\//g;
1.34 www 4370: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4371: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4372: my $normalid=$cdomain.'_'.$cnum;
4373: # need to always cache even if we get errors otherwise we keep
4374: # trying and trying and trying to get the course description.
4375: my %envhash=();
4376: my %returnhash=();
1.731 albertel 4377:
4378: my $expiretime=600;
4379: if ($env{'request.course.id'} eq $normalid) {
4380: $expiretime=120;
4381: }
4382:
4383: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4384: if (!$args->{'freshen_cache'}
4385: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4386: foreach my $key (keys(%env)) {
4387: next if ($key !~ /^\Q$prefix\E(.*)/);
4388: my ($setting) = $1;
4389: $returnhash{$setting} = $env{$key};
4390: }
4391: return %returnhash;
4392: }
4393:
1.1118 foxr 4394: # get the data again
4395:
1.731 albertel 4396: if (!$args->{'one_time'}) {
4397: $envhash{'course.'.$normalid.'.last_cache'}=time;
4398: }
1.811 albertel 4399:
1.34 www 4400: if ($chome ne 'no_host') {
1.302 albertel 4401: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4402: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4403: my $username = $env{'user.name'}; # Defult username
4404: if(defined $args->{'user'}) {
4405: $username = $args->{'user'};
4406: }
1.129 albertel 4407: $returnhash{'home'}= $chome;
4408: $returnhash{'domain'} = $cdomain;
4409: $returnhash{'num'} = $cnum;
1.741 raeburn 4410: if (!defined($returnhash{'type'})) {
4411: $returnhash{'type'} = 'Course';
4412: }
1.130 albertel 4413: while (my ($name,$value) = each %returnhash) {
1.53 www 4414: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4415: }
1.270 www 4416: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4417: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4418: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4419: $envhash{'course.'.$normalid.'.home'}=$chome;
4420: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4421: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4422: }
4423: }
1.731 albertel 4424: if (!$args->{'one_time'}) {
1.949 raeburn 4425: &appenv(\%envhash);
1.731 albertel 4426: }
1.302 albertel 4427: return %returnhash;
1.461 www 4428: }
4429:
1.1080 raeburn 4430: sub update_released_required {
4431: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4432: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4433: $cid = $env{'request.course.id'};
4434: $cdom = $env{'course.'.$cid.'.domain'};
4435: $cnum = $env{'course.'.$cid.'.num'};
4436: $chome = $env{'course.'.$cid.'.home'};
4437: }
4438: if ($needsrelease) {
4439: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4440: my $needsupdate;
4441: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4442: $needsupdate = 1;
4443: } else {
4444: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4445: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4446: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4447: $needsupdate = 1;
4448: }
4449: }
4450: if ($needsupdate) {
4451: my %needshash = (
4452: 'internal.releaserequired' => $needsrelease,
4453: );
4454: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4455: if ($putresult eq 'ok') {
4456: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4457: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4458: if (ref($crsinfo{$cid}) eq 'HASH') {
4459: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4460: &courseidput($cdom,\%crsinfo,$chome,'notime');
4461: }
4462: }
4463: }
4464: }
4465: return;
4466: }
4467:
1.461 www 4468: # -------------------------------------------------See if a user is privileged
4469:
4470: sub privileged {
4471: my ($username,$domain)=@_;
4472: my $rolesdump=&reply("dump:$domain:$username:roles",
4473: &homeserver($username,$domain));
1.1033 raeburn 4474: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4475: ($rolesdump =~ /^error:/)) {
4476: return 0;
4477: }
1.461 www 4478: my $now=time;
4479: if ($rolesdump ne '') {
1.800 albertel 4480: foreach my $entry (split(/&/,$rolesdump)) {
4481: if ($entry!~/^rolesdef_/) {
4482: my ($area,$role)=split(/=/,$entry);
1.461 www 4483: $area=~s/\_\w\w$//;
4484: my ($trole,$tend,$tstart)=split(/_/,$role);
4485: if (($trole eq 'dc') || ($trole eq 'su')) {
4486: my $active=1;
4487: if ($tend) {
4488: if ($tend<$now) { $active=0; }
4489: }
4490: if ($tstart) {
4491: if ($tstart>$now) { $active=0; }
4492: }
4493: if ($active) { return 1; }
4494: }
4495: }
4496: }
4497: }
4498: return 0;
1.9 www 4499: }
1.1 albertel 4500:
1.103 harris41 4501: # -------------------------------------------------------- Get user privileges
1.11 www 4502:
4503: sub rolesinit {
4504: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4505: my $now=time;
4506: my %userroles = ('user.login.time' => $now);
1.1086 raeburn 4507: my $extra = &freeze_escape({'skipcheck' => 1});
1.1078 raeburn 4508: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4509: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1078 raeburn 4510: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4511: return \%userroles;
4512: }
1.11 www 4513: my %allroles=();
1.678 raeburn 4514: my %allgroups=();
1.11 www 4515:
4516: if ($rolesdump ne '') {
1.800 albertel 4517: foreach my $entry (split(/&/,$rolesdump)) {
4518: if ($entry!~/^rolesdef_/) {
4519: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4520: $area=~s/\_\w\w$//;
1.678 raeburn 4521: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4522: if ($role=~/^cr/) {
1.807 albertel 4523: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4524: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4525: ($tend,$tstart)=split('_',$trest);
4526: } else {
4527: $trole=$role;
4528: }
1.678 raeburn 4529: } elsif ($role =~ m|^gr/|) {
4530: ($trole,$tend,$tstart) = split(/_/,$role);
1.1104 raeburn 4531: next if ($tstart eq '-1');
1.678 raeburn 4532: ($trole,$group_privs) = split(/\//,$trole);
4533: $group_privs = &unescape($group_privs);
1.587 albertel 4534: } else {
4535: ($trole,$tend,$tstart)=split(/_/,$role);
4536: }
1.743 albertel 4537: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4538: $username);
4539: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4540: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4541: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4542: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4543: my $spec=$trole.'.'.$area;
4544: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4545: if ($trole =~ /^cr\//) {
1.567 raeburn 4546: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4547: } elsif ($trole eq 'gr') {
4548: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4549: } else {
1.567 raeburn 4550: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4551: }
1.12 www 4552: }
1.662 raeburn 4553: }
1.191 harris41 4554: }
1.743 albertel 4555: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4556: $userroles{'user.adv'} = $adv;
4557: $userroles{'user.author'} = $author;
1.620 albertel 4558: $env{'user.adv'}=$adv;
1.11 www 4559: }
1.743 albertel 4560: return \%userroles;
1.11 www 4561: }
4562:
1.567 raeburn 4563: sub set_arearole {
4564: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4565: # log the associated role with the area
4566: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4567: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4568: }
4569:
4570: sub custom_roleprivs {
4571: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4572: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4573: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4574: if (&hostname($homsvr) ne '') {
1.567 raeburn 4575: my ($rdummy,$roledef)=
4576: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4577: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4578: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4579: if (defined($syspriv)) {
1.1043 raeburn 4580: if ($trest =~ /^$match_community$/) {
4581: $syspriv =~ s/bre\&S//;
4582: }
1.567 raeburn 4583: $$allroles{'cm./'}.=':'.$syspriv;
4584: $$allroles{$spec.'./'}.=':'.$syspriv;
4585: }
4586: if ($tdomain ne '') {
4587: if (defined($dompriv)) {
4588: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4589: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4590: }
4591: if (($trest ne '') && (defined($coursepriv))) {
4592: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4593: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4594: }
4595: }
4596: }
4597: }
4598: }
4599:
1.678 raeburn 4600: sub group_roleprivs {
4601: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4602: my $access = 1;
4603: my $now = time;
4604: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4605: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4606: if ($access) {
1.811 albertel 4607: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4608: $$allgroups{$course}{$group} .=':'.$group_privs;
4609: }
4610: }
1.567 raeburn 4611:
4612: sub standard_roleprivs {
4613: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4614: if (defined($pr{$trole.':s'})) {
4615: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4616: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4617: }
4618: if ($tdomain ne '') {
4619: if (defined($pr{$trole.':d'})) {
4620: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4621: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4622: }
4623: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4624: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4625: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4626: }
4627: }
4628: }
4629:
4630: sub set_userprivs {
1.1064 raeburn 4631: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4632: my $author=0;
4633: my $adv=0;
1.678 raeburn 4634: my %grouproles = ();
4635: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4636: my @groupkeys;
1.1000 raeburn 4637: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4638: push(@groupkeys,$role);
4639: }
4640: if (ref($groups_roles) eq 'HASH') {
4641: foreach my $key (keys(%{$groups_roles})) {
4642: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4643: push(@groupkeys,$key);
4644: }
4645: }
4646: }
4647: if (@groupkeys > 0) {
4648: foreach my $role (@groupkeys) {
4649: my ($trole,$area,$sec,$extendedarea);
4650: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4651: $trole = $1;
4652: $area = $2;
4653: $sec = $3;
4654: $extendedarea = $area.$sec;
4655: if (exists($$allgroups{$area})) {
4656: foreach my $group (keys(%{$$allgroups{$area}})) {
4657: my $spec = $trole.'.'.$extendedarea;
4658: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4659: $$allgroups{$area}{$group};
1.1064 raeburn 4660: }
1.678 raeburn 4661: }
4662: }
4663: }
4664: }
4665: }
1.800 albertel 4666: foreach my $group (keys(%grouproles)) {
4667: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4668: }
1.800 albertel 4669: foreach my $role (keys(%{$allroles})) {
4670: my %thesepriv;
1.941 raeburn 4671: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4672: foreach my $item (split(/:/,$$allroles{$role})) {
4673: if ($item ne '') {
4674: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4675: if ($restrictions eq '') {
4676: $thesepriv{$privilege}='F';
4677: } elsif ($thesepriv{$privilege} ne 'F') {
4678: $thesepriv{$privilege}.=$restrictions;
4679: }
4680: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4681: }
4682: }
4683: my $thesestr='';
1.1104 raeburn 4684: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 4685: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4686: }
4687: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4688: }
4689: return ($author,$adv);
4690: }
4691:
1.994 raeburn 4692: sub role_status {
1.1104 raeburn 4693: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4694: my @pwhere = ();
4695: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4696: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4697: unless (!defined($$role) || $$role eq '') {
4698: $$where=join('.',@pwhere);
4699: $$trolecode=$$role.'.'.$$where;
4700: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4701: $$tstatus='is';
1.1104 raeburn 4702: if ($$tstart && $$tstart>$update) {
1.994 raeburn 4703: $$tstatus='future';
1.1034 raeburn 4704: if ($$tstart<$now) {
4705: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4706: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4707: my (%allroles,%allgroups,$group_privs,
4708: %groups_roles,@rolecodes);
1.1002 raeburn 4709: my %userroles = (
4710: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4711: );
1.1064 raeburn 4712: @rolecodes = ('cm');
1.1002 raeburn 4713: my $spec=$$role.'.'.$$where;
4714: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4715: if ($$role =~ /^cr\//) {
4716: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4717: push(@rolecodes,'cr');
1.1002 raeburn 4718: } elsif ($$role eq 'gr') {
1.1064 raeburn 4719: push(@rolecodes,$$role);
1.1002 raeburn 4720: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4721: $env{'user.name'});
1.1064 raeburn 4722: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4723: (undef,my $group_privs) = split(/\//,$trole);
4724: $group_privs = &unescape($group_privs);
4725: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4726: 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 4727: &get_groups_roles($tdomain,$trest,
4728: \%course_roles,\@rolecodes,
4729: \%groups_roles);
1.1002 raeburn 4730: } else {
1.1064 raeburn 4731: push(@rolecodes,$$role);
1.1002 raeburn 4732: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4733: }
1.1064 raeburn 4734: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4735: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4736: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4737: }
4738: }
1.1034 raeburn 4739: $$tstatus = 'is';
1.1002 raeburn 4740: }
1.994 raeburn 4741: }
4742: if ($$tend) {
1.1104 raeburn 4743: if ($$tend<$update) {
1.994 raeburn 4744: $$tstatus='expired';
4745: } elsif ($$tend<$now) {
4746: $$tstatus='will_not';
4747: }
4748: }
4749: }
4750: }
4751: }
4752:
1.1104 raeburn 4753: sub get_groups_roles {
4754: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4755: return unless((ref($cdom_courseroles) eq 'HASH') &&
4756: (ref($rolecodes) eq 'ARRAY') &&
4757: (ref($groups_roles) eq 'HASH'));
4758: if (keys(%{$cdom_courseroles}) > 0) {
4759: my ($cnum) = ($rest =~ /^($match_courseid)/);
4760: if ($cdom ne '' && $cnum ne '') {
4761: foreach my $key (keys(%{$cdom_courseroles})) {
4762: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4763: my $crsrole = $1;
4764: my $crssec = $2;
4765: if ($crsrole =~ /^cr/) {
4766: unless (grep(/^cr$/,@{$rolecodes})) {
4767: push(@{$rolecodes},'cr');
4768: }
4769: } else {
4770: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4771: push(@{$rolecodes},$crsrole);
4772: }
4773: }
4774: my $rolekey = "$crsrole./$cdom/$cnum";
4775: if ($crssec ne '') {
4776: $rolekey .= "/$crssec";
4777: }
4778: $rolekey .= './';
4779: $groups_roles->{$rolekey} = $rolecodes;
4780: }
4781: }
4782: }
4783: }
4784: return;
4785: }
4786:
4787: sub delete_env_groupprivs {
4788: my ($where,$courseroles,$possroles) = @_;
4789: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4790: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4791: unless (ref($courseroles->{$udom}) eq 'HASH') {
4792: %{$courseroles->{$udom}} =
4793: &get_my_roles('','','userroles',['active'],
4794: $possroles,[$udom],1);
4795: }
4796: if (ref($courseroles->{$udom}) eq 'HASH') {
4797: foreach my $item (keys(%{$courseroles->{$udom}})) {
4798: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4799: my $area = '/'.$cdom.'/'.$cnum;
4800: my $privkey = "user.priv.$crsrole.$area";
4801: if ($crssec ne '') {
4802: $privkey .= '/'.$crssec;
4803: }
4804: $privkey .= ".$area/$group";
4805: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4806: }
4807: }
4808: return;
4809: }
4810:
1.994 raeburn 4811: sub check_adhoc_privs {
1.1104 raeburn 4812: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4813: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4814: if ($env{$cckey}) {
4815: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 4816: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4817: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 4818: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4819: }
4820: } else {
1.1088 raeburn 4821: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4822: }
4823: }
4824:
4825: sub set_adhoc_privileges {
4826: # role can be cc or ca
1.1088 raeburn 4827: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 4828: my $area = '/'.$dcdom.'/'.$pickedcourse;
4829: my $spec = $role.'.'.$area;
4830: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4831: $env{'user.name'});
4832: my %ccrole = ();
4833: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4834: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4835: &appenv(\%userroles,[$role,'cm']);
4836: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 4837: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4838: &appenv( {'request.role' => $spec,
4839: 'request.role.domain' => $dcdom,
4840: 'request.course.sec' => ''
4841: }
4842: );
4843: my $tadv=0;
4844: if (&allowed('adv') eq 'F') { $tadv=1; }
4845: &appenv({'request.role.adv' => $tadv});
4846: }
1.994 raeburn 4847: }
4848:
1.12 www 4849: # --------------------------------------------------------------- get interface
4850:
4851: sub get {
1.131 albertel 4852: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4853: my $items='';
1.800 albertel 4854: foreach my $item (@$storearr) {
4855: $items.=&escape($item).'&';
1.191 harris41 4856: }
1.12 www 4857: $items=~s/\&$//;
1.620 albertel 4858: if (!$udomain) { $udomain=$env{'user.domain'}; }
4859: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4860: my $uhome=&homeserver($uname,$udomain);
4861:
1.133 albertel 4862: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4863: my @pairs=split(/\&/,$rep);
1.273 albertel 4864: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4865: return @pairs;
4866: }
1.15 www 4867: my %returnhash=();
1.42 www 4868: my $i=0;
1.800 albertel 4869: foreach my $item (@$storearr) {
4870: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4871: $i++;
1.191 harris41 4872: }
1.15 www 4873: return %returnhash;
1.27 www 4874: }
4875:
4876: # --------------------------------------------------------------- del interface
4877:
4878: sub del {
1.133 albertel 4879: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4880: my $items='';
1.800 albertel 4881: foreach my $item (@$storearr) {
4882: $items.=&escape($item).'&';
1.191 harris41 4883: }
1.984 neumanie 4884:
1.27 www 4885: $items=~s/\&$//;
1.620 albertel 4886: if (!$udomain) { $udomain=$env{'user.domain'}; }
4887: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4888: my $uhome=&homeserver($uname,$udomain);
4889: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4890: }
4891:
4892: # -------------------------------------------------------------- dump interface
4893:
4894: sub dump {
1.1086 raeburn 4895: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755 albertel 4896: if (!$udomain) { $udomain=$env{'user.domain'}; }
4897: if (!$uname) { $uname=$env{'user.name'}; }
4898: my $uhome=&homeserver($uname,$udomain);
4899: if ($regexp) {
4900: $regexp=&escape($regexp);
4901: } else {
4902: $regexp='.';
4903: }
1.1086 raeburn 4904: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755 albertel 4905: my @pairs=split(/\&/,$rep);
4906: my %returnhash=();
1.1098 foxr 4907: if (!($rep =~ /^error/ )) {
4908: foreach my $item (@pairs) {
4909: my ($key,$value)=split(/=/,$item,2);
4910: $key = &unescape($key);
4911: next if ($key =~ /^error: 2 /);
4912: $returnhash{$key}=&thaw_unescape($value);
4913: }
1.755 albertel 4914: }
4915: return %returnhash;
1.407 www 4916: }
4917:
1.1098 foxr 4918:
1.717 albertel 4919: # --------------------------------------------------------- dumpstore interface
4920:
4921: sub dumpstore {
4922: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4923: if (!$udomain) { $udomain=$env{'user.domain'}; }
4924: if (!$uname) { $uname=$env{'user.name'}; }
4925: my $uhome=&homeserver($uname,$udomain);
4926: if ($regexp) {
4927: $regexp=&escape($regexp);
4928: } else {
4929: $regexp='.';
4930: }
4931: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4932: my @pairs=split(/\&/,$rep);
4933: my %returnhash=();
4934: foreach my $item (@pairs) {
4935: my ($key,$value)=split(/=/,$item,2);
4936: next if ($key =~ /^error: 2 /);
4937: $returnhash{$key}=&thaw_unescape($value);
4938: }
4939: return %returnhash;
1.717 albertel 4940: }
4941:
1.407 www 4942: # -------------------------------------------------------------- keys interface
4943:
4944: sub getkeys {
4945: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4946: if (!$udomain) { $udomain=$env{'user.domain'}; }
4947: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4948: my $uhome=&homeserver($uname,$udomain);
4949: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4950: my @keyarray=();
1.800 albertel 4951: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4952: next if ($key =~ /^error: 2 /);
1.800 albertel 4953: push(@keyarray,&unescape($key));
1.407 www 4954: }
4955: return @keyarray;
1.318 matthew 4956: }
4957:
1.319 matthew 4958: # --------------------------------------------------------------- currentdump
4959: sub currentdump {
1.328 matthew 4960: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4961: $courseid = $env{'request.course.id'} if (! defined($courseid));
4962: $sdom = $env{'user.domain'} if (! defined($sdom));
4963: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4964: my $uhome = &homeserver($sname,$sdom);
4965: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4966: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4967: #
1.318 matthew 4968: my %returnhash=();
1.319 matthew 4969: #
4970: if ($rep eq "unknown_cmd") {
4971: # an old lond will not know currentdump
4972: # Do a dump and make it look like a currentdump
1.822 albertel 4973: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4974: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4975: my %hash = @tmp;
4976: @tmp=();
1.424 matthew 4977: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4978: } else {
4979: my @pairs=split(/\&/,$rep);
1.800 albertel 4980: foreach my $pair (@pairs) {
4981: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4982: my ($symb,$param) = split(/:/,$key);
4983: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4984: &thaw_unescape($value);
1.319 matthew 4985: }
1.191 harris41 4986: }
1.12 www 4987: return %returnhash;
1.424 matthew 4988: }
4989:
4990: sub convert_dump_to_currentdump{
4991: my %hash = %{shift()};
4992: my %returnhash;
4993: # Code ripped from lond, essentially. The only difference
4994: # here is the unescaping done by lonnet::dump(). Conceivably
4995: # we might run in to problems with parameter names =~ /^v\./
4996: while (my ($key,$value) = each(%hash)) {
4997: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4998: $symb = &unescape($symb);
4999: $param = &unescape($param);
1.424 matthew 5000: next if ($v eq 'version' || $symb eq 'keys');
5001: next if (exists($returnhash{$symb}) &&
5002: exists($returnhash{$symb}->{$param}) &&
5003: $returnhash{$symb}->{'v.'.$param} > $v);
5004: $returnhash{$symb}->{$param}=$value;
5005: $returnhash{$symb}->{'v.'.$param}=$v;
5006: }
5007: #
5008: # Remove all of the keys in the hashes which keep track of
5009: # the version of the parameter.
5010: while (my ($symb,$param_hash) = each(%returnhash)) {
5011: # use a foreach because we are going to delete from the hash.
5012: foreach my $key (keys(%$param_hash)) {
5013: delete($param_hash->{$key}) if ($key =~ /^v\./);
5014: }
5015: }
5016: return \%returnhash;
1.12 www 5017: }
5018:
1.627 albertel 5019: # ------------------------------------------------------ critical inc interface
5020:
5021: sub cinc {
5022: return &inc(@_,'critical');
5023: }
5024:
1.449 matthew 5025: # --------------------------------------------------------------- inc interface
5026:
5027: sub inc {
1.627 albertel 5028: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5029: if (!$udomain) { $udomain=$env{'user.domain'}; }
5030: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5031: my $uhome=&homeserver($uname,$udomain);
5032: my $items='';
5033: if (! ref($store)) {
5034: # got a single value, so use that instead
5035: $items = &escape($store).'=&';
5036: } elsif (ref($store) eq 'SCALAR') {
5037: $items = &escape($$store).'=&';
5038: } elsif (ref($store) eq 'ARRAY') {
5039: $items = join('=&',map {&escape($_);} @{$store});
5040: } elsif (ref($store) eq 'HASH') {
5041: while (my($key,$value) = each(%{$store})) {
5042: $items.= &escape($key).'='.&escape($value).'&';
5043: }
5044: }
5045: $items=~s/\&$//;
1.627 albertel 5046: if ($critical) {
5047: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5048: } else {
5049: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5050: }
1.449 matthew 5051: }
5052:
1.12 www 5053: # --------------------------------------------------------------- put interface
5054:
5055: sub put {
1.134 albertel 5056: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5057: if (!$udomain) { $udomain=$env{'user.domain'}; }
5058: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5059: my $uhome=&homeserver($uname,$udomain);
1.12 www 5060: my $items='';
1.800 albertel 5061: foreach my $item (keys(%$storehash)) {
5062: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5063: }
1.12 www 5064: $items=~s/\&$//;
1.134 albertel 5065: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5066: }
5067:
1.631 albertel 5068: # ------------------------------------------------------------ newput interface
5069:
5070: sub newput {
5071: my ($namespace,$storehash,$udomain,$uname)=@_;
5072: if (!$udomain) { $udomain=$env{'user.domain'}; }
5073: if (!$uname) { $uname=$env{'user.name'}; }
5074: my $uhome=&homeserver($uname,$udomain);
5075: my $items='';
5076: foreach my $key (keys(%$storehash)) {
5077: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5078: }
5079: $items=~s/\&$//;
5080: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5081: }
5082:
5083: # --------------------------------------------------------- putstore interface
5084:
1.524 raeburn 5085: sub putstore {
1.715 albertel 5086: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5087: if (!$udomain) { $udomain=$env{'user.domain'}; }
5088: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5089: my $uhome=&homeserver($uname,$udomain);
5090: my $items='';
1.715 albertel 5091: foreach my $key (keys(%$storehash)) {
5092: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5093: }
1.715 albertel 5094: $items=~s/\&$//;
1.716 albertel 5095: my $esc_symb=&escape($symb);
5096: my $esc_v=&escape($version);
1.715 albertel 5097: my $reply =
1.716 albertel 5098: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5099: $uhome);
5100: if ($reply eq 'unknown_cmd') {
1.716 albertel 5101: # gfall back to way things use to be done
1.715 albertel 5102: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5103: $uname);
1.524 raeburn 5104: }
1.715 albertel 5105: return $reply;
5106: }
5107:
5108: sub old_putstore {
1.716 albertel 5109: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5110: if (!$udomain) { $udomain=$env{'user.domain'}; }
5111: if (!$uname) { $uname=$env{'user.name'}; }
5112: my $uhome=&homeserver($uname,$udomain);
5113: my %newstorehash;
1.800 albertel 5114: foreach my $item (keys(%$storehash)) {
5115: my $key = $version.':'.&escape($symb).':'.$item;
5116: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5117: }
5118: my $items='';
5119: my %allitems = ();
1.800 albertel 5120: foreach my $item (keys(%newstorehash)) {
5121: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5122: my $key = $1.':keys:'.$2;
5123: $allitems{$key} .= $3.':';
5124: }
1.800 albertel 5125: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5126: }
1.800 albertel 5127: foreach my $item (keys(%allitems)) {
5128: $allitems{$item} =~ s/\:$//;
5129: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5130: }
5131: $items=~s/\&$//;
5132: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5133: }
5134:
1.47 www 5135: # ------------------------------------------------------ critical put interface
5136:
5137: sub cput {
1.134 albertel 5138: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5139: if (!$udomain) { $udomain=$env{'user.domain'}; }
5140: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5141: my $uhome=&homeserver($uname,$udomain);
1.47 www 5142: my $items='';
1.800 albertel 5143: foreach my $item (keys(%$storehash)) {
5144: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5145: }
1.47 www 5146: $items=~s/\&$//;
1.134 albertel 5147: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5148: }
5149:
5150: # -------------------------------------------------------------- eget interface
5151:
5152: sub eget {
1.133 albertel 5153: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5154: my $items='';
1.800 albertel 5155: foreach my $item (@$storearr) {
5156: $items.=&escape($item).'&';
1.191 harris41 5157: }
1.12 www 5158: $items=~s/\&$//;
1.620 albertel 5159: if (!$udomain) { $udomain=$env{'user.domain'}; }
5160: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5161: my $uhome=&homeserver($uname,$udomain);
5162: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5163: my @pairs=split(/\&/,$rep);
5164: my %returnhash=();
1.42 www 5165: my $i=0;
1.800 albertel 5166: foreach my $item (@$storearr) {
5167: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5168: $i++;
1.191 harris41 5169: }
1.12 www 5170: return %returnhash;
5171: }
5172:
1.667 albertel 5173: # ------------------------------------------------------------ tmpput interface
5174: sub tmpput {
1.802 raeburn 5175: my ($storehash,$server,$context)=@_;
1.667 albertel 5176: my $items='';
1.800 albertel 5177: foreach my $item (keys(%$storehash)) {
5178: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5179: }
5180: $items=~s/\&$//;
1.802 raeburn 5181: if (defined($context)) {
5182: $items .= ':'.&escape($context);
5183: }
1.667 albertel 5184: return &reply("tmpput:$items",$server);
5185: }
5186:
5187: # ------------------------------------------------------------ tmpget interface
5188: sub tmpget {
1.688 albertel 5189: my ($token,$server)=@_;
5190: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5191: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5192: my %returnhash;
5193: foreach my $item (split(/\&/,$rep)) {
5194: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5195: next if ($key =~ /^error: 2 /);
1.667 albertel 5196: $returnhash{&unescape($key)}=&thaw_unescape($value);
5197: }
5198: return %returnhash;
5199: }
5200:
1.1113 raeburn 5201: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5202: sub tmpdel {
5203: my ($token,$server)=@_;
5204: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5205: return &reply("tmpdel:$token",$server);
5206: }
5207:
1.765 albertel 5208: # -------------------------------------------------- portfolio access checking
5209:
5210: sub portfolio_access {
1.766 albertel 5211: my ($requrl) = @_;
1.765 albertel 5212: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5213: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 5214: if ($result) {
5215: my %setters;
5216: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5217: my ($startblock,$endblock) =
5218: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5219: if ($startblock && $endblock) {
5220: return 'B';
5221: }
5222: } else {
5223: my ($startblock,$endblock) =
5224: &Apache::loncommon::blockcheck(\%setters,'port');
5225: if ($startblock && $endblock) {
5226: return 'B';
5227: }
5228: }
5229: }
1.765 albertel 5230: if ($result eq 'ok') {
1.766 albertel 5231: return 'F';
1.765 albertel 5232: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 5233: return 'A';
1.765 albertel 5234: }
1.766 albertel 5235: return '';
1.765 albertel 5236: }
5237:
5238: sub get_portfolio_access {
1.767 albertel 5239: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5240:
5241: if (!ref($access_hash)) {
5242: my $current_perms = &get_portfile_permissions($udom,$unum);
5243: my %access_controls = &get_access_controls($current_perms,$group,
5244: $file_name);
5245: $access_hash = $access_controls{$file_name};
5246: }
5247:
1.765 albertel 5248: my ($public,$guest,@domains,@users,@courses,@groups);
5249: my $now = time;
5250: if (ref($access_hash) eq 'HASH') {
5251: foreach my $key (keys(%{$access_hash})) {
5252: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5253: if ($start > $now) {
5254: next;
5255: }
5256: if ($end && $end<$now) {
5257: next;
5258: }
5259: if ($scope eq 'public') {
5260: $public = $key;
5261: last;
5262: } elsif ($scope eq 'guest') {
5263: $guest = $key;
5264: } elsif ($scope eq 'domains') {
5265: push(@domains,$key);
5266: } elsif ($scope eq 'users') {
5267: push(@users,$key);
5268: } elsif ($scope eq 'course') {
5269: push(@courses,$key);
5270: } elsif ($scope eq 'group') {
5271: push(@groups,$key);
5272: }
5273: }
5274: if ($public) {
5275: return 'ok';
5276: }
5277: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5278: if ($guest) {
5279: return $guest;
5280: }
5281: } else {
5282: if (@domains > 0) {
5283: foreach my $domkey (@domains) {
5284: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5285: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5286: return 'ok';
5287: }
5288: }
5289: }
5290: }
5291: if (@users > 0) {
5292: foreach my $userkey (@users) {
1.865 raeburn 5293: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5294: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5295: if (ref($item) eq 'HASH') {
5296: if (($item->{'uname'} eq $env{'user.name'}) &&
5297: ($item->{'udom'} eq $env{'user.domain'})) {
5298: return 'ok';
5299: }
5300: }
5301: }
5302: }
1.765 albertel 5303: }
5304: }
5305: my %roleshash;
5306: my @courses_and_groups = @courses;
5307: push(@courses_and_groups,@groups);
5308: if (@courses_and_groups > 0) {
5309: my (%allgroups,%allroles);
5310: my ($start,$end,$role,$sec,$group);
5311: foreach my $envkey (%env) {
1.1060 raeburn 5312: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5313: my $cid = $2.'_'.$3;
5314: if ($1 eq 'gr') {
5315: $group = $4;
5316: $allgroups{$cid}{$group} = $env{$envkey};
5317: } else {
5318: if ($4 eq '') {
5319: $sec = 'none';
5320: } else {
5321: $sec = $4;
5322: }
5323: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5324: }
1.811 albertel 5325: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5326: my $cid = $2.'_'.$3;
5327: if ($4 eq '') {
5328: $sec = 'none';
5329: } else {
5330: $sec = $4;
5331: }
5332: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5333: }
5334: }
5335: if (keys(%allroles) == 0) {
5336: return;
5337: }
5338: foreach my $key (@courses_and_groups) {
5339: my %content = %{$$access_hash{$key}};
5340: my $cnum = $content{'number'};
5341: my $cdom = $content{'domain'};
5342: my $cid = $cdom.'_'.$cnum;
5343: if (!exists($allroles{$cid})) {
5344: next;
5345: }
5346: foreach my $role_id (keys(%{$content{'roles'}})) {
5347: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5348: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5349: my @status = @{$content{'roles'}{$role_id}{'access'}};
5350: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5351: foreach my $role (keys(%{$allroles{$cid}})) {
5352: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5353: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5354: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5355: if (grep/^all$/,@sections) {
5356: return 'ok';
5357: } else {
5358: if (grep/^$sec$/,@sections) {
5359: return 'ok';
5360: }
5361: }
5362: }
5363: }
5364: if (keys(%{$allgroups{$cid}}) == 0) {
5365: if (grep/^none$/,@groups) {
5366: return 'ok';
5367: }
5368: } else {
5369: if (grep/^all$/,@groups) {
5370: return 'ok';
5371: }
5372: foreach my $group (keys(%{$allgroups{$cid}})) {
5373: if (grep/^$group$/,@groups) {
5374: return 'ok';
5375: }
5376: }
5377: }
5378: }
5379: }
5380: }
5381: }
5382: }
5383: if ($guest) {
5384: return $guest;
5385: }
5386: }
5387: }
5388: return;
5389: }
5390:
5391: sub course_group_datechecker {
5392: my ($dates,$now,$status) = @_;
5393: my ($start,$end) = split(/\./,$dates);
5394: if (!$start && !$end) {
5395: return 'ok';
5396: }
5397: if (grep/^active$/,@{$status}) {
5398: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5399: return 'ok';
5400: }
5401: }
5402: if (grep/^previous$/,@{$status}) {
5403: if ($end > $now ) {
5404: return 'ok';
5405: }
5406: }
5407: if (grep/^future$/,@{$status}) {
5408: if ($start > $now) {
5409: return 'ok';
5410: }
5411: }
5412: return;
5413: }
5414:
5415: sub parse_portfolio_url {
5416: my ($url) = @_;
5417:
5418: my ($type,$udom,$unum,$group,$file_name);
5419:
1.823 albertel 5420: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5421: $type = 1;
5422: $udom = $1;
5423: $unum = $2;
5424: $file_name = $3;
1.823 albertel 5425: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5426: $type = 2;
5427: $udom = $1;
5428: $unum = $2;
5429: $group = $3;
5430: $file_name = $3.'/'.$4;
5431: }
5432: if (wantarray) {
5433: return ($type,$udom,$unum,$file_name,$group);
5434: }
5435: return $type;
5436: }
5437:
5438: sub is_portfolio_url {
5439: my ($url) = @_;
5440: return scalar(&parse_portfolio_url($url));
5441: }
5442:
1.798 raeburn 5443: sub is_portfolio_file {
5444: my ($file) = @_;
1.820 raeburn 5445: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5446: return 1;
5447: }
5448: return;
5449: }
5450:
1.976 raeburn 5451: sub usertools_access {
1.1084 raeburn 5452: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 5453: my ($access,%tools);
5454: if ($context eq '') {
5455: $context = 'tools';
5456: }
5457: if ($context eq 'requestcourses') {
5458: %tools = (
5459: official => 1,
5460: unofficial => 1,
1.1006 raeburn 5461: community => 1,
1.985 raeburn 5462: );
5463: } else {
5464: %tools = (
5465: aboutme => 1,
5466: blog => 1,
5467: portfolio => 1,
5468: );
5469: }
1.976 raeburn 5470: return if (!defined($tools{$tool}));
5471:
5472: if ((!defined($udom)) || (!defined($uname))) {
5473: $udom = $env{'user.domain'};
5474: $uname = $env{'user.name'};
5475: }
5476:
1.978 raeburn 5477: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5478: if ($action ne 'reload') {
1.985 raeburn 5479: if ($context eq 'requestcourses') {
5480: return $env{'environment.canrequest.'.$tool};
5481: } else {
5482: return $env{'environment.availabletools.'.$tool};
5483: }
5484: }
1.976 raeburn 5485: }
5486:
5487: my ($toolstatus,$inststatus);
5488:
1.985 raeburn 5489: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5490: ($action ne 'reload')) {
5491: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5492: $inststatus = $env{'environment.inststatus'};
5493: } else {
1.1084 raeburn 5494: if (ref($userenvref) eq 'HASH') {
5495: $toolstatus = $userenvref->{$context.'.'.$tool};
5496: $inststatus = $userenvref->{'inststatus'};
5497: } else {
5498: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5499: $toolstatus = $userenv{$context.'.'.$tool};
5500: $inststatus = $userenv{'inststatus'};
5501: }
1.976 raeburn 5502: }
5503:
5504: if ($toolstatus ne '') {
5505: if ($toolstatus) {
5506: $access = 1;
5507: } else {
5508: $access = 0;
5509: }
5510: return $access;
5511: }
5512:
1.1084 raeburn 5513: my ($is_adv,%domdef);
5514: if (ref($is_advref) eq 'HASH') {
5515: $is_adv = $is_advref->{'is_adv'};
5516: } else {
5517: $is_adv = &is_advanced_user($udom,$uname);
5518: }
5519: if (ref($domdefref) eq 'HASH') {
5520: %domdef = %{$domdefref};
5521: } else {
5522: %domdef = &get_domain_defaults($udom);
5523: }
1.976 raeburn 5524: if (ref($domdef{$tool}) eq 'HASH') {
5525: if ($is_adv) {
5526: if ($domdef{$tool}{'_LC_adv'} ne '') {
5527: if ($domdef{$tool}{'_LC_adv'}) {
5528: $access = 1;
5529: } else {
5530: $access = 0;
5531: }
5532: return $access;
5533: }
5534: }
5535: if ($inststatus ne '') {
5536: my ($hasaccess,$hasnoaccess);
5537: foreach my $affiliation (split(/:/,$inststatus)) {
5538: if ($domdef{$tool}{$affiliation} ne '') {
5539: if ($domdef{$tool}{$affiliation}) {
5540: $hasaccess = 1;
5541: } else {
5542: $hasnoaccess = 1;
5543: }
5544: }
5545: }
5546: if ($hasaccess || $hasnoaccess) {
5547: if ($hasaccess) {
5548: $access = 1;
5549: } elsif ($hasnoaccess) {
5550: $access = 0;
5551: }
5552: return $access;
5553: }
5554: } else {
5555: if ($domdef{$tool}{'default'} ne '') {
5556: if ($domdef{$tool}{'default'}) {
5557: $access = 1;
5558: } elsif ($domdef{$tool}{'default'} == 0) {
5559: $access = 0;
5560: }
5561: return $access;
5562: }
5563: }
5564: } else {
1.985 raeburn 5565: if ($context eq 'tools') {
5566: $access = 1;
5567: } else {
5568: $access = 0;
5569: }
1.976 raeburn 5570: return $access;
5571: }
5572: }
5573:
1.1050 raeburn 5574: sub is_course_owner {
5575: my ($cdom,$cnum,$udom,$uname) = @_;
5576: if (($udom eq '') || ($uname eq '')) {
5577: $udom = $env{'user.domain'};
5578: $uname = $env{'user.name'};
5579: }
5580: unless (($udom eq '') || ($uname eq '')) {
5581: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5582: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5583: return 1;
5584: } else {
5585: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5586: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5587: return 1;
5588: }
5589: }
5590: }
5591: }
5592: return;
5593: }
5594:
1.976 raeburn 5595: sub is_advanced_user {
5596: my ($udom,$uname) = @_;
1.1085 raeburn 5597: if ($udom ne '' && $uname ne '') {
5598: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 5599: if (wantarray) {
5600: return ($env{'user.adv'},$env{'user.author'});
5601: } else {
5602: return $env{'user.adv'};
5603: }
1.1085 raeburn 5604: }
5605: }
1.976 raeburn 5606: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5607: my %allroles;
1.1128 raeburn 5608: my ($is_adv,$is_author);
1.976 raeburn 5609: foreach my $role (keys(%roleshash)) {
5610: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5611: my $area = '/'.$tdomain.'/'.$trest;
5612: if ($sec ne '') {
5613: $area .= '/'.$sec;
5614: }
5615: if (($area ne '') && ($trole ne '')) {
5616: my $spec=$trole.'.'.$area;
5617: if ($trole =~ /^cr\//) {
5618: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5619: } elsif ($trole ne 'gr') {
5620: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5621: }
1.1128 raeburn 5622: if ($trole eq 'au') {
5623: $is_author = 1;
5624: }
1.976 raeburn 5625: }
5626: }
5627: foreach my $role (keys(%allroles)) {
5628: last if ($is_adv);
5629: foreach my $item (split(/:/,$allroles{$role})) {
5630: if ($item ne '') {
5631: my ($privilege,$restrictions)=split(/&/,$item);
5632: if ($privilege eq 'adv') {
5633: $is_adv = 1;
5634: last;
5635: }
5636: }
5637: }
5638: }
1.1128 raeburn 5639: if (wantarray) {
5640: return ($is_adv,$is_author);
5641: }
1.976 raeburn 5642: return $is_adv;
5643: }
1.798 raeburn 5644:
1.1035 raeburn 5645: sub check_can_request {
1.1036 raeburn 5646: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5647: my $canreq = 0;
5648: my ($types,$typename) = &Apache::loncommon::course_types();
5649: my @options = ('approval','validate','autolimit');
5650: my $optregex = join('|',@options);
5651: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5652: foreach my $type (@{$types}) {
5653: if (&usertools_access($env{'user.name'},
5654: $env{'user.domain'},
5655: $type,undef,'requestcourses')) {
5656: $canreq ++;
1.1036 raeburn 5657: if (ref($request_domains) eq 'HASH') {
5658: push(@{$request_domains->{$type}},$env{'user.domain'});
5659: }
1.1035 raeburn 5660: if ($dom eq $env{'user.domain'}) {
5661: $can_request->{$type} = 1;
5662: }
5663: }
5664: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5665: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5666: if (@curr > 0) {
1.1036 raeburn 5667: foreach my $item (@curr) {
5668: if (ref($request_domains) eq 'HASH') {
5669: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5670: if ($otherdom ne '') {
5671: if (ref($request_domains->{$type}) eq 'ARRAY') {
5672: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5673: push(@{$request_domains->{$type}},$otherdom);
5674: }
5675: } else {
5676: push(@{$request_domains->{$type}},$otherdom);
5677: }
5678: }
5679: }
5680: }
5681: unless($dom eq $env{'user.domain'}) {
5682: $canreq ++;
1.1035 raeburn 5683: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5684: $can_request->{$type} = 1;
5685: }
5686: }
5687: }
5688: }
5689: }
5690: }
5691: return $canreq;
5692: }
5693:
1.341 www 5694: # ---------------------------------------------- Custom access rule evaluation
5695:
5696: sub customaccess {
5697: my ($priv,$uri)=@_;
1.807 albertel 5698: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5699: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5700: $udom = &LONCAPA::clean_domain($udom);
5701: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5702: my $access=0;
1.800 albertel 5703: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5704: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5705: if ($type eq 'user') {
5706: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5707: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5708: if ($tdom) {
5709: if ($tdom ne $env{'user.domain'}) { next; }
5710: }
1.896 albertel 5711: if ($tuname) {
5712: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5713: }
5714: $access=($effect eq 'allow');
5715: last;
5716: }
5717: } else {
5718: if ($role) {
5719: if ($role ne $urole) { next; }
5720: }
5721: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5722: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5723: if ($tdom) {
5724: if ($tdom ne $udom) { next; }
5725: }
5726: if ($tcrs) {
5727: if ($tcrs ne $ucrs) { next; }
5728: }
5729: if ($tsec) {
5730: if ($tsec ne $usec) { next; }
5731: }
5732: $access=($effect eq 'allow');
5733: last;
5734: }
5735: if ($realm eq '' && $role eq '') {
5736: $access=($effect eq 'allow');
5737: }
1.402 bowersj2 5738: }
1.341 www 5739: }
5740: return $access;
5741: }
5742:
1.103 harris41 5743: # ------------------------------------------------- Check for a user privilege
1.12 www 5744:
5745: sub allowed {
1.810 raeburn 5746: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5747: my $ver_orguri=$uri;
1.439 www 5748: $uri=&deversion($uri);
1.152 www 5749: my $orguri=$uri;
1.52 www 5750: $uri=&declutter($uri);
1.809 raeburn 5751:
1.810 raeburn 5752: if ($priv eq 'evb') {
5753: # Evade communication block restrictions for specified role in a course
5754: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5755: return $1;
5756: } else {
5757: return;
5758: }
5759: }
5760:
1.620 albertel 5761: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5762: # Free bre access to adm and meta resources
1.775 albertel 5763: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5764: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5765: && ($priv eq 'bre')) {
1.14 www 5766: return 'F';
1.159 www 5767: }
5768:
1.545 banghart 5769: # Free bre access to user's own portfolio contents
1.714 raeburn 5770: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5771: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5772: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5773: my %setters;
5774: my ($startblock,$endblock) =
5775: &Apache::loncommon::blockcheck(\%setters,'port');
5776: if ($startblock && $endblock) {
5777: return 'B';
5778: } else {
5779: return 'F';
5780: }
1.545 banghart 5781: }
5782:
1.762 raeburn 5783: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5784: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5785: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5786: if (exists($env{'request.course.id'})) {
5787: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5788: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5789: if (($domain eq $cdom) && ($name eq $cnum)) {
5790: my $courseprivid=$env{'request.course.id'};
5791: $courseprivid=~s/\_/\//;
5792: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5793: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5794: return $1;
1.762 raeburn 5795: } else {
5796: if ($env{'request.course.sec'}) {
5797: $courseprivid.='/'.$env{'request.course.sec'};
5798: }
5799: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5800: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5801: return $2;
5802: }
1.714 raeburn 5803: }
5804: }
5805: }
5806: }
5807:
1.159 www 5808: # Free bre to public access
5809:
5810: if ($priv eq 'bre') {
1.238 www 5811: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5812: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5813: return 'F';
5814: }
1.238 www 5815: if ($copyright eq 'priv') {
5816: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5817: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5818: return '';
5819: }
5820: }
5821: if ($copyright eq 'domain') {
5822: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5823: unless (($env{'user.domain'} eq $1) ||
5824: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5825: return '';
5826: }
1.262 matthew 5827: }
1.620 albertel 5828: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5829: # Library role, so allow browsing of resources in this domain.
5830: return 'F';
1.238 www 5831: }
1.341 www 5832: if ($copyright eq 'custom') {
5833: unless (&customaccess($priv,$uri)) { return ''; }
5834: }
1.14 www 5835: }
1.264 matthew 5836: # Domain coordinator is trying to create a course
1.620 albertel 5837: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5838: # uri is the requested domain in this case.
5839: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5840: # a role of dc for the domain in question.
1.620 albertel 5841: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5842: }
1.29 www 5843:
1.52 www 5844: my $thisallowed='';
5845: my $statecond=0;
5846: my $courseprivid='';
5847:
1.1039 raeburn 5848: my $ownaccess;
1.1043 raeburn 5849: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5850: if (($priv eq 'bro') && ($env{'user.author'})) {
5851: if ($uri eq '') {
5852: $ownaccess = 1;
5853: } else {
5854: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5855: my $udom = $env{'user.domain'};
5856: my $uname = $env{'user.name'};
5857: if ($uri =~ m{^\Q$udom\E/?$}) {
5858: $ownaccess = 1;
1.1040 raeburn 5859: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5860: unless ($uri =~ m{\.\./}) {
5861: $ownaccess = 1;
5862: }
5863: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5864: my $now = time;
5865: if ($uri =~ m{^([^/]+)/?$}) {
5866: my $adom = $1;
5867: foreach my $key (keys(%env)) {
1.1042 raeburn 5868: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5869: my ($start,$end) = split('.',$env{$key});
5870: if (($now >= $start) && (!$end || $end < $now)) {
5871: $ownaccess = 1;
5872: last;
5873: }
5874: }
5875: }
5876: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5877: my $adom = $1;
5878: my $aname = $2;
1.1042 raeburn 5879: foreach my $role ('ca','aa') {
5880: if ($env{"user.role.$role./$adom/$aname"}) {
5881: my ($start,$end) =
5882: split('.',$env{"user.role.$role./$adom/$aname"});
5883: if (($now >= $start) && (!$end || $end < $now)) {
5884: $ownaccess = 1;
5885: last;
5886: }
1.1039 raeburn 5887: }
5888: }
5889: }
5890: }
5891: }
5892: }
5893: }
5894:
1.52 www 5895: # Course
5896:
1.620 albertel 5897: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5898: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5899: $thisallowed.=$1;
5900: }
1.52 www 5901: }
1.29 www 5902:
1.52 www 5903: # Domain
5904:
1.620 albertel 5905: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5906: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5907: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5908: $thisallowed.=$1;
5909: }
1.12 www 5910: }
1.52 www 5911:
5912: # Course: uri itself is a course
1.66 www 5913: my $courseuri=$uri;
5914: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5915: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5916:
1.620 albertel 5917: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5918: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5919: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5920: $thisallowed.=$1;
5921: }
1.12 www 5922: }
1.29 www 5923:
1.665 albertel 5924: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5925: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5926: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5927: $thisallowed='';
1.671 raeburn 5928: my ($match)=&is_on_map($uri);
5929: if ($match) {
5930: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5931: =~/\Q$priv\E\&([^\:]*)/) {
5932: $thisallowed.=$1;
5933: }
5934: } else {
1.705 albertel 5935: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5936: if ($refuri) {
5937: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5938: $thisallowed='F';
1.671 raeburn 5939: } else {
5940: $refuri=&declutter($refuri);
5941: my ($match) = &is_on_map($refuri);
5942: if ($match) {
5943: $thisallowed='F';
5944: }
1.669 raeburn 5945: }
1.671 raeburn 5946: }
5947: }
1.314 www 5948: }
1.492 albertel 5949:
1.766 albertel 5950: if ($priv eq 'bre'
5951: && $thisallowed ne 'F'
5952: && $thisallowed ne '2'
5953: && &is_portfolio_url($uri)) {
5954: $thisallowed = &portfolio_access($uri);
5955: }
5956:
1.52 www 5957: # Full access at system, domain or course-wide level? Exit.
1.29 www 5958: if ($thisallowed=~/F/) {
5959: return 'F';
5960: }
5961:
1.52 www 5962: # If this is generating or modifying users, exit with special codes
1.29 www 5963:
1.643 www 5964: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5965: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5966: my ($audom,$auname)=split('/',$uri);
1.643 www 5967: # no author name given, so this just checks on the general right to make a co-author in this domain
5968: unless ($auname) { return $thisallowed; }
5969: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5970: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5971: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5972: ($audom ne $env{'request.role.domain'}))) { return ''; }
5973: }
1.52 www 5974: return $thisallowed;
5975: }
5976: #
1.103 harris41 5977: # Gathered so far: system, domain and course wide privileges
1.52 www 5978: #
5979: # Course: See if uri or referer is an individual resource that is part of
5980: # the course
5981:
1.620 albertel 5982: if ($env{'request.course.id'}) {
1.232 www 5983:
1.620 albertel 5984: $courseprivid=$env{'request.course.id'};
5985: if ($env{'request.course.sec'}) {
5986: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5987: }
5988: $courseprivid=~s/\_/\//;
5989: my $checkreferer=1;
1.232 www 5990: my ($match,$cond)=&is_on_map($uri);
5991: if ($match) {
5992: $statecond=$cond;
1.620 albertel 5993: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5994: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5995: $thisallowed.=$1;
5996: $checkreferer=0;
5997: }
1.29 www 5998: }
1.83 www 5999:
1.148 www 6000: if ($checkreferer) {
1.620 albertel 6001: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6002: unless ($refuri) {
1.800 albertel 6003: foreach my $key (keys(%env)) {
6004: if ($key=~/^httpref\..*\*/) {
6005: my $pattern=$key;
1.156 www 6006: $pattern=~s/^httpref\.\/res\///;
1.148 www 6007: $pattern=~s/\*/\[\^\/\]\+/g;
6008: $pattern=~s/\//\\\//g;
1.152 www 6009: if ($orguri=~/$pattern/) {
1.800 albertel 6010: $refuri=$env{$key};
1.148 www 6011: }
6012: }
1.191 harris41 6013: }
1.148 www 6014: }
1.232 www 6015:
1.148 www 6016: if ($refuri) {
1.152 www 6017: $refuri=&declutter($refuri);
1.232 www 6018: my ($match,$cond)=&is_on_map($refuri);
6019: if ($match) {
6020: my $refstatecond=$cond;
1.620 albertel 6021: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6022: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 6023: $thisallowed.=$1;
1.53 www 6024: $uri=$refuri;
6025: $statecond=$refstatecond;
1.52 www 6026: }
6027: }
1.148 www 6028: }
1.29 www 6029: }
1.52 www 6030: }
1.29 www 6031:
1.52 www 6032: #
1.103 harris41 6033: # Gathered now: all privileges that could apply, and condition number
1.52 www 6034: #
6035: #
6036: # Full or no access?
6037: #
1.29 www 6038:
1.52 www 6039: if ($thisallowed=~/F/) {
6040: return 'F';
6041: }
1.29 www 6042:
1.52 www 6043: unless ($thisallowed) {
6044: return '';
6045: }
1.29 www 6046:
1.52 www 6047: # Restrictions exist, deal with them
6048: #
6049: # C:according to course preferences
6050: # R:according to resource settings
6051: # L:unless locked
6052: # X:according to user session state
6053: #
6054:
6055: # Possibly locked functionality, check all courses
1.54 www 6056: # Locks might take effect only after 10 minutes cache expiration for other
6057: # courses, and 2 minutes for current course
1.52 www 6058:
6059: my $envkey;
6060: if ($thisallowed=~/L/) {
1.1000 raeburn 6061: foreach $envkey (keys(%env)) {
1.54 www 6062: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6063: my $courseid=$2;
6064: my $roleid=$1.'.'.$2;
1.92 www 6065: $courseid=~s/^\///;
1.54 www 6066: my $expiretime=600;
1.620 albertel 6067: if ($env{'request.role'} eq $roleid) {
1.54 www 6068: $expiretime=120;
6069: }
6070: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6071: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6072: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6073: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6074: }
1.620 albertel 6075: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6076: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6077: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6078: &log($env{'user.domain'},$env{'user.name'},
6079: $env{'user.home'},
1.57 www 6080: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6081: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6082: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6083: return '';
6084: }
6085: }
1.620 albertel 6086: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6087: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6088: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6089: &log($env{'user.domain'},$env{'user.name'},
6090: $env{'user.home'},
1.57 www 6091: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6092: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6093: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6094: return '';
6095: }
6096: }
6097: }
1.29 www 6098: }
1.52 www 6099: }
6100:
6101: #
6102: # Rest of the restrictions depend on selected course
6103: #
6104:
1.620 albertel 6105: unless ($env{'request.course.id'}) {
1.766 albertel 6106: if ($thisallowed eq 'A') {
6107: return 'A';
1.814 raeburn 6108: } elsif ($thisallowed eq 'B') {
6109: return 'B';
1.766 albertel 6110: } else {
6111: return '1';
6112: }
1.52 www 6113: }
1.29 www 6114:
1.52 www 6115: #
6116: # Now user is definitely in a course
6117: #
1.53 www 6118:
6119:
6120: # Course preferences
6121:
6122: if ($thisallowed=~/C/) {
1.620 albertel 6123: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6124: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6125: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6126: =~/\Q$rolecode\E/) {
1.1103 raeburn 6127: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6128: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6129: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6130: $env{'request.course.id'});
6131: }
1.237 www 6132: return '';
6133: }
6134:
1.620 albertel 6135: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6136: =~/\Q$unamedom\E/) {
1.1103 raeburn 6137: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6138: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6139: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6140: $env{'request.course.id'});
6141: }
1.54 www 6142: return '';
6143: }
1.53 www 6144: }
6145:
6146: # Resource preferences
6147:
6148: if ($thisallowed=~/R/) {
1.620 albertel 6149: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6150: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6151: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6152: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6153: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6154: }
6155: return '';
1.54 www 6156: }
1.53 www 6157: }
1.30 www 6158:
1.246 www 6159: # Restricted by state or randomout?
1.30 www 6160:
1.52 www 6161: if ($thisallowed=~/X/) {
1.620 albertel 6162: if ($env{'acc.randomout'}) {
1.579 albertel 6163: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 6164: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 6165: return '';
6166: }
1.247 www 6167: }
6168: if (&condval($statecond)) {
1.52 www 6169: return '2';
6170: } else {
6171: return '';
6172: }
6173: }
1.30 www 6174:
1.766 albertel 6175: if ($thisallowed eq 'A') {
6176: return 'A';
1.814 raeburn 6177: } elsif ($thisallowed eq 'B') {
6178: return 'B';
1.766 albertel 6179: }
1.52 www 6180: return 'F';
1.232 www 6181: }
6182:
1.710 albertel 6183: sub split_uri_for_cond {
6184: my $uri=&deversion(&declutter(shift));
6185: my @uriparts=split(/\//,$uri);
6186: my $filename=pop(@uriparts);
6187: my $pathname=join('/',@uriparts);
6188: return ($pathname,$filename);
6189: }
1.232 www 6190: # --------------------------------------------------- Is a resource on the map?
6191:
6192: sub is_on_map {
1.710 albertel 6193: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 6194: #Trying to find the conditional for the file
1.620 albertel 6195: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 6196: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 6197: if ($match) {
1.289 bowersj2 6198: return (1,$1);
6199: } else {
1.434 www 6200: return (0,0);
1.289 bowersj2 6201: }
1.12 www 6202: }
6203:
1.427 www 6204: # --------------------------------------------------------- Get symb from alias
6205:
6206: sub get_symb_from_alias {
6207: my $symb=shift;
6208: my ($map,$resid,$url)=&decode_symb($symb);
6209: # Already is a symb
6210: if ($url) { return $symb; }
6211: # Must be an alias
6212: my $aliassymb='';
6213: my %bighash;
1.620 albertel 6214: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 6215: &GDBM_READER(),0640)) {
6216: my $rid=$bighash{'mapalias_'.$symb};
6217: if ($rid) {
6218: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 6219: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6220: $resid,$bighash{'src_'.$rid});
1.427 www 6221: }
6222: untie %bighash;
6223: }
6224: return $aliassymb;
6225: }
6226:
1.12 www 6227: # ----------------------------------------------------------------- Define Role
6228:
6229: sub definerole {
6230: if (allowed('mcr','/')) {
6231: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 6232: foreach my $role (split(':',$sysrole)) {
6233: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6234: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6235: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6236: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6237: return "refused:s:$crole&$cqual";
6238: }
6239: }
1.191 harris41 6240: }
1.800 albertel 6241: foreach my $role (split(':',$domrole)) {
6242: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6243: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6244: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6245: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 6246: return "refused:d:$crole&$cqual";
6247: }
6248: }
1.191 harris41 6249: }
1.800 albertel 6250: foreach my $role (split(':',$courole)) {
6251: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6252: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6253: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6254: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6255: return "refused:c:$crole&$cqual";
6256: }
6257: }
1.191 harris41 6258: }
1.620 albertel 6259: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6260: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6261: "rolesdef_$rolename=".
6262: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 6263: return reply($command,$env{'user.home'});
1.12 www 6264: } else {
6265: return 'refused';
6266: }
1.105 harris41 6267: }
6268:
6269: # ---------------- Make a metadata query against the network of library servers
6270:
6271: sub metadata_query {
1.244 matthew 6272: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 6273: my %rhash;
1.845 albertel 6274: my %libserv = &all_library();
1.244 matthew 6275: my @server_list = (defined($server_array) ? @$server_array
6276: : keys(%libserv) );
6277: for my $server (@server_list) {
1.118 harris41 6278: unless ($custom or $customshow) {
6279: my $reply=&reply("querysend:".&escape($query),$server);
6280: $rhash{$server}=$reply;
6281: }
6282: else {
6283: my $reply=&reply("querysend:".&escape($query).':'.
6284: &escape($custom).':'.&escape($customshow),
6285: $server);
6286: $rhash{$server}=$reply;
6287: }
1.112 harris41 6288: }
1.118 harris41 6289: return \%rhash;
1.240 www 6290: }
6291:
6292: # ----------------------------------------- Send log queries and wait for reply
6293:
6294: sub log_query {
6295: my ($uname,$udom,$query,%filters)=@_;
6296: my $uhome=&homeserver($uname,$udom);
6297: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 6298: my $uhost=&hostname($uhome);
1.800 albertel 6299: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 6300: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6301: $uhome);
1.479 albertel 6302: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 6303: return get_query_reply($queryid);
6304: }
6305:
1.818 raeburn 6306: # -------------------------- Update MySQL table for portfolio file
6307:
6308: sub update_portfolio_table {
1.821 raeburn 6309: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 6310: if ($group ne '') {
6311: $file_name =~s /^\Q$group\E//;
6312: }
1.818 raeburn 6313: my $homeserver = &homeserver($uname,$udom);
6314: my $queryid=
1.821 raeburn 6315: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6316: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 6317: my $reply = &get_query_reply($queryid);
6318: return $reply;
6319: }
6320:
1.899 raeburn 6321: # -------------------------- Update MySQL allusers table
6322:
6323: sub update_allusers_table {
6324: my ($uname,$udom,$names) = @_;
6325: my $homeserver = &homeserver($uname,$udom);
6326: my $queryid=
6327: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6328: 'lastname='.&escape($names->{'lastname'}).'%%'.
6329: 'firstname='.&escape($names->{'firstname'}).'%%'.
6330: 'middlename='.&escape($names->{'middlename'}).'%%'.
6331: 'generation='.&escape($names->{'generation'}).'%%'.
6332: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6333: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 6334: return;
1.899 raeburn 6335: }
6336:
1.508 raeburn 6337: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 6338:
6339: sub fetch_enrollment_query {
1.511 raeburn 6340: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 6341: my $homeserver;
1.547 raeburn 6342: my $maxtries = 1;
1.508 raeburn 6343: if ($context eq 'automated') {
6344: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 6345: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 6346: } else {
6347: $homeserver = &homeserver($cnum,$dom);
6348: }
1.838 albertel 6349: my $host=&hostname($homeserver);
1.506 raeburn 6350: my $cmd = '';
1.1000 raeburn 6351: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 6352: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 6353: }
6354: $cmd =~ s/%%$//;
6355: $cmd = &escape($cmd);
6356: my $query = 'fetchenrollment';
1.620 albertel 6357: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 6358: unless ($queryid=~/^\Q$host\E\_/) {
6359: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6360: return 'error: '.$queryid;
6361: }
1.506 raeburn 6362: my $reply = &get_query_reply($queryid);
1.547 raeburn 6363: my $tries = 1;
6364: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6365: $reply = &get_query_reply($queryid);
6366: $tries ++;
6367: }
1.526 raeburn 6368: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 6369: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 6370: } else {
1.901 albertel 6371: my @responses = split(/:/,$reply);
1.515 raeburn 6372: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 6373: foreach my $line (@responses) {
6374: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 6375: $$replyref{$key} = $value;
6376: }
6377: } else {
1.1117 foxr 6378: my $pathname = LONCAPA::tempdir();
1.800 albertel 6379: foreach my $line (@responses) {
6380: my ($key,$value) = split(/=/,$line);
1.506 raeburn 6381: $$replyref{$key} = $value;
6382: if ($value > 0) {
1.800 albertel 6383: foreach my $item (@{$$affiliatesref{$key}}) {
6384: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 6385: my $destname = $pathname.'/'.$filename;
6386: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 6387: if ($xml_classlist =~ /^error/) {
6388: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6389: } else {
1.506 raeburn 6390: if ( open(FILE,">$destname") ) {
6391: print FILE &unescape($xml_classlist);
6392: close(FILE);
1.526 raeburn 6393: } else {
6394: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6395: }
6396: }
6397: }
6398: }
6399: }
6400: }
6401: return 'ok';
6402: }
6403: return 'error';
6404: }
6405:
1.242 www 6406: sub get_query_reply {
6407: my $queryid=shift;
1.1117 foxr 6408: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 6409: my $reply='';
6410: for (1..100) {
6411: sleep 2;
6412: if (-e $replyfile.'.end') {
1.448 albertel 6413: if (open(my $fh,$replyfile)) {
1.904 albertel 6414: $reply = join('',<$fh>);
6415: close($fh);
1.240 www 6416: } else { return 'error: reply_file_error'; }
1.242 www 6417: return &unescape($reply);
6418: }
1.240 www 6419: }
1.242 www 6420: return 'timeout:'.$queryid;
1.240 www 6421: }
6422:
6423: sub courselog_query {
1.241 www 6424: #
6425: # possible filters:
6426: # url: url or symb
6427: # username
6428: # domain
6429: # action: view, submit, grade
6430: # start: timestamp
6431: # end: timestamp
6432: #
1.240 www 6433: my (%filters)=@_;
1.620 albertel 6434: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6435: if ($filters{'url'}) {
6436: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6437: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6438: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6439: }
1.620 albertel 6440: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6441: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6442: return &log_query($cname,$cdom,'courselog',%filters);
6443: }
6444:
6445: sub userlog_query {
1.858 raeburn 6446: #
6447: # possible filters:
6448: # action: log check role
6449: # start: timestamp
6450: # end: timestamp
6451: #
1.240 www 6452: my ($uname,$udom,%filters)=@_;
6453: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6454: }
6455:
1.506 raeburn 6456: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6457:
6458: sub auto_run {
1.508 raeburn 6459: my ($cnum,$cdom) = @_;
1.876 raeburn 6460: my $response = 0;
6461: my $settings;
6462: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6463: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6464: $settings = $domconfig{'autoenroll'};
6465: if ($settings->{'run'} eq '1') {
6466: $response = 1;
6467: }
6468: } else {
1.934 raeburn 6469: my $homeserver;
6470: if (&is_course($cdom,$cnum)) {
6471: $homeserver = &homeserver($cnum,$cdom);
6472: } else {
6473: $homeserver = &domain($cdom,'primary');
6474: }
6475: if ($homeserver ne 'no_host') {
6476: $response = &reply('autorun:'.$cdom,$homeserver);
6477: }
1.876 raeburn 6478: }
1.506 raeburn 6479: return $response;
6480: }
1.776 albertel 6481:
1.506 raeburn 6482: sub auto_get_sections {
1.508 raeburn 6483: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6484: my $homeserver;
6485: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6486: $homeserver = &homeserver($cnum,$cdom);
6487: }
6488: if (!defined($homeserver)) {
6489: if ($cdom =~ /^$match_domain$/) {
6490: $homeserver = &domain($cdom,'primary');
6491: }
6492: }
6493: my @secs;
6494: if (defined($homeserver)) {
6495: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6496: unless ($response eq 'refused') {
6497: @secs = split(/:/,$response);
6498: }
1.506 raeburn 6499: }
6500: return @secs;
6501: }
1.776 albertel 6502:
1.506 raeburn 6503: sub auto_new_course {
1.1099 raeburn 6504: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6505: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 6506: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6507: return $response;
6508: }
1.776 albertel 6509:
1.506 raeburn 6510: sub auto_validate_courseID {
1.508 raeburn 6511: my ($cnum,$cdom,$inst_course_id) = @_;
6512: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6513: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6514: return $response;
6515: }
1.776 albertel 6516:
1.1007 raeburn 6517: sub auto_validate_instcode {
1.1020 raeburn 6518: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6519: my ($homeserver,$response);
6520: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6521: $homeserver = &homeserver($cnum,$cdom);
6522: }
6523: if (!defined($homeserver)) {
6524: if ($cdom =~ /^$match_domain$/) {
6525: $homeserver = &domain($cdom,'primary');
6526: }
6527: }
1.1065 raeburn 6528: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6529: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6530: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6531: return ($outcome,$description);
1.1007 raeburn 6532: }
6533:
1.506 raeburn 6534: sub auto_create_password {
1.873 raeburn 6535: my ($cnum,$cdom,$authparam,$udom) = @_;
6536: my ($homeserver,$response);
1.506 raeburn 6537: my $create_passwd = 0;
6538: my $authchk = '';
1.873 raeburn 6539: if ($udom =~ /^$match_domain$/) {
6540: $homeserver = &domain($udom,'primary');
6541: }
6542: if ($homeserver eq '') {
6543: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6544: $homeserver = &homeserver($cnum,$cdom);
6545: }
6546: }
6547: if ($homeserver eq '') {
6548: $authchk = 'nodomain';
1.506 raeburn 6549: } else {
1.873 raeburn 6550: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6551: if ($response eq 'refused') {
6552: $authchk = 'refused';
6553: } else {
1.901 albertel 6554: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6555: }
1.506 raeburn 6556: }
6557: return ($authparam,$create_passwd,$authchk);
6558: }
6559:
1.706 raeburn 6560: sub auto_photo_permission {
6561: my ($cnum,$cdom,$students) = @_;
6562: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6563: my ($outcome,$perm_reqd,$conditions) =
6564: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6565: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6566: return (undef,undef);
6567: }
1.706 raeburn 6568: return ($outcome,$perm_reqd,$conditions);
6569: }
6570:
6571: sub auto_checkphotos {
6572: my ($uname,$udom,$pid) = @_;
6573: my $homeserver = &homeserver($uname,$udom);
6574: my ($result,$resulttype);
6575: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6576: &escape($uname).':'.&escape($pid),
6577: $homeserver));
1.709 albertel 6578: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6579: return (undef,undef);
6580: }
1.706 raeburn 6581: if ($outcome) {
6582: ($result,$resulttype) = split(/:/,$outcome);
6583: }
6584: return ($result,$resulttype);
6585: }
6586:
6587: sub auto_photochoice {
6588: my ($cnum,$cdom) = @_;
6589: my $homeserver = &homeserver($cnum,$cdom);
6590: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6591: &escape($cdom),
6592: $homeserver)));
1.709 albertel 6593: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6594: return (undef,undef);
6595: }
1.706 raeburn 6596: return ($update,$comment);
6597: }
6598:
6599: sub auto_photoupdate {
6600: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6601: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6602: my $host=&hostname($homeserver);
1.706 raeburn 6603: my $cmd = '';
6604: my $maxtries = 1;
1.800 albertel 6605: foreach my $affiliate (keys(%{$affiliatesref})) {
6606: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6607: }
6608: $cmd =~ s/%%$//;
6609: $cmd = &escape($cmd);
6610: my $query = 'institutionalphotos';
6611: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6612: unless ($queryid=~/^\Q$host\E\_/) {
6613: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6614: return 'error: '.$queryid;
6615: }
6616: my $reply = &get_query_reply($queryid);
6617: my $tries = 1;
6618: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6619: $reply = &get_query_reply($queryid);
6620: $tries ++;
6621: }
6622: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6623: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6624: } else {
6625: my @responses = split(/:/,$reply);
6626: my $outcome = shift(@responses);
6627: foreach my $item (@responses) {
6628: my ($key,$value) = split(/=/,$item);
6629: $$photo{$key} = $value;
6630: }
6631: return $outcome;
6632: }
6633: return 'error';
6634: }
6635:
1.521 raeburn 6636: sub auto_instcode_format {
1.793 albertel 6637: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6638: $cat_order) = @_;
1.521 raeburn 6639: my $courses = '';
1.772 raeburn 6640: my @homeservers;
1.521 raeburn 6641: if ($caller eq 'global') {
1.841 albertel 6642: my %servers = &get_servers($codedom,'library');
6643: foreach my $tryserver (keys(%servers)) {
6644: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6645: push(@homeservers,$tryserver);
6646: }
1.584 raeburn 6647: }
1.1022 raeburn 6648: } elsif ($caller eq 'requests') {
6649: if ($codedom =~ /^$match_domain$/) {
6650: my $chome = &domain($codedom,'primary');
6651: unless ($chome eq 'no_host') {
6652: push(@homeservers,$chome);
6653: }
6654: }
1.521 raeburn 6655: } else {
1.772 raeburn 6656: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6657: }
1.793 albertel 6658: foreach my $code (keys(%{$instcodes})) {
6659: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6660: }
6661: chop($courses);
1.772 raeburn 6662: my $ok_response = 0;
6663: my $response;
6664: while (@homeservers > 0 && $ok_response == 0) {
6665: my $server = shift(@homeservers);
6666: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6667: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6668: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6669: split(/:/,$response);
1.772 raeburn 6670: %{$codes} = (%{$codes},&str2hash($codes_str));
6671: push(@{$codetitles},&str2array($codetitles_str));
6672: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6673: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6674: $ok_response = 1;
6675: }
6676: }
6677: if ($ok_response) {
1.521 raeburn 6678: return 'ok';
1.772 raeburn 6679: } else {
6680: return $response;
1.521 raeburn 6681: }
6682: }
6683:
1.792 raeburn 6684: sub auto_instcode_defaults {
6685: my ($domain,$returnhash,$code_order) = @_;
6686: my @homeservers;
1.841 albertel 6687:
6688: my %servers = &get_servers($domain,'library');
6689: foreach my $tryserver (keys(%servers)) {
6690: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6691: push(@homeservers,$tryserver);
6692: }
1.792 raeburn 6693: }
1.841 albertel 6694:
1.792 raeburn 6695: my $response;
1.841 albertel 6696: foreach my $server (@homeservers) {
1.792 raeburn 6697: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6698: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6699:
6700: foreach my $pair (split(/\&/,$response)) {
6701: my ($name,$value)=split(/\=/,$pair);
6702: if ($name eq 'code_order') {
6703: @{$code_order} = split(/\&/,&unescape($value));
6704: } else {
6705: $returnhash->{&unescape($name)}=&unescape($value);
6706: }
6707: }
6708: return 'ok';
1.792 raeburn 6709: }
1.841 albertel 6710:
6711: return $response;
1.1003 raeburn 6712: }
6713:
6714: sub auto_possible_instcodes {
1.1007 raeburn 6715: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6716: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6717: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6718: return;
6719: }
1.1003 raeburn 6720: my (@homeservers,$uhome);
6721: if (defined(&domain($domain,'primary'))) {
6722: $uhome=&domain($domain,'primary');
6723: push(@homeservers,&domain($domain,'primary'));
6724: } else {
6725: my %servers = &get_servers($domain,'library');
6726: foreach my $tryserver (keys(%servers)) {
6727: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6728: push(@homeservers,$tryserver);
6729: }
6730: }
6731: }
6732: my $response;
6733: foreach my $server (@homeservers) {
6734: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6735: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6736: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6737: split(':',$response);
6738: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6739: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6740: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6741: my ($name,$value)=split('=',$item);
6742: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6743: }
6744: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6745: my ($name,$value)=split('=',$item);
6746: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6747: }
6748: return 'ok';
6749: }
6750: return $response;
6751: }
1.792 raeburn 6752:
1.1010 raeburn 6753: sub auto_courserequest_checks {
6754: my ($dom) = @_;
1.1020 raeburn 6755: my ($homeserver,%validations);
6756: if ($dom =~ /^$match_domain$/) {
6757: $homeserver = &domain($dom,'primary');
6758: }
6759: unless ($homeserver eq 'no_host') {
6760: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6761: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6762: my @items = split(/&/,$response);
6763: foreach my $item (@items) {
6764: my ($key,$value) = split('=',$item);
6765: $validations{&unescape($key)} = &thaw_unescape($value);
6766: }
6767: }
6768: }
1.1010 raeburn 6769: return %validations;
6770: }
6771:
1.1020 raeburn 6772: sub auto_courserequest_validation {
6773: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6774: my ($homeserver,$response);
6775: if ($dom =~ /^$match_domain$/) {
6776: $homeserver = &domain($dom,'primary');
6777: }
6778: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6779:
1.1020 raeburn 6780: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6781: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6782: ':'.&escape($instcode).':'.&escape($instseclist),
6783: $homeserver));
6784: }
6785: return $response;
6786: }
6787:
1.777 albertel 6788: sub auto_validate_class_sec {
1.918 raeburn 6789: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6790: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6791: my $ownerlist;
6792: if (ref($owners) eq 'ARRAY') {
6793: $ownerlist = join(',',@{$owners});
6794: } else {
6795: $ownerlist = $owners;
6796: }
1.773 raeburn 6797: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6798: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6799: return $response;
6800: }
6801:
1.679 raeburn 6802: # ------------------------------------------------------- Course Group routines
6803:
6804: sub get_coursegroups {
1.809 raeburn 6805: my ($cdom,$cnum,$group,$namespace) = @_;
6806: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6807: }
6808:
1.679 raeburn 6809: sub modify_coursegroup {
6810: my ($cdom,$cnum,$groupsettings) = @_;
6811: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6812: }
6813:
1.809 raeburn 6814: sub toggle_coursegroup_status {
6815: my ($cdom,$cnum,$group,$action) = @_;
6816: my ($from_namespace,$to_namespace);
6817: if ($action eq 'delete') {
6818: $from_namespace = 'coursegroups';
6819: $to_namespace = 'deleted_groups';
6820: } else {
6821: $from_namespace = 'deleted_groups';
6822: $to_namespace = 'coursegroups';
6823: }
6824: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6825: if (my $tmp = &error(%curr_group)) {
6826: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6827: return ('read error',$tmp);
6828: } else {
6829: my %savedsettings = %curr_group;
1.809 raeburn 6830: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6831: my $deloutcome;
6832: if ($result eq 'ok') {
1.809 raeburn 6833: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6834: } else {
6835: return ('write error',$result);
6836: }
6837: if ($deloutcome eq 'ok') {
6838: return 'ok';
6839: } else {
6840: return ('delete error',$deloutcome);
6841: }
6842: }
6843: }
6844:
1.679 raeburn 6845: sub modify_group_roles {
1.957 raeburn 6846: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6847: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6848: my $role = 'gr/'.&escape($userprivs);
6849: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6850: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6851: if ($result eq 'ok') {
6852: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6853: }
1.679 raeburn 6854: return $result;
6855: }
6856:
6857: sub modify_coursegroup_membership {
6858: my ($cdom,$cnum,$membership) = @_;
6859: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6860: return $result;
6861: }
6862:
1.682 raeburn 6863: sub get_active_groups {
6864: my ($udom,$uname,$cdom,$cnum) = @_;
6865: my $now = time;
6866: my %groups = ();
6867: foreach my $key (keys(%env)) {
1.811 albertel 6868: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6869: my ($start,$end) = split(/\./,$env{$key});
6870: if (($end!=0) && ($end<$now)) { next; }
6871: if (($start!=0) && ($start>$now)) { next; }
6872: if ($1 eq $cdom && $2 eq $cnum) {
6873: $groups{$3} = $env{$key} ;
6874: }
6875: }
6876: }
6877: return %groups;
6878: }
6879:
1.683 raeburn 6880: sub get_group_membership {
6881: my ($cdom,$cnum,$group) = @_;
6882: return(&dump('groupmembership',$cdom,$cnum,$group));
6883: }
6884:
6885: sub get_users_groups {
6886: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6887: my @usersgroups;
1.683 raeburn 6888: my $cachetime=1800;
6889:
6890: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6891: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6892: if (defined($cached)) {
1.734 albertel 6893: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6894: } else {
6895: $grouplist = '';
1.816 raeburn 6896: my $courseurl = &courseid_to_courseurl($courseid);
1.1086 raeburn 6897: my $extra = &freeze_escape({'skipcheck' => 1});
6898: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817 raeburn 6899: my $access_end = $env{'course.'.$courseid.
6900: '.default_enrollment_end_date'};
6901: my $now = time;
6902: foreach my $key (keys(%roleshash)) {
6903: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6904: my $group = $1;
6905: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6906: my $start = $2;
6907: my $end = $1;
6908: if ($start == -1) { next; } # deleted from group
6909: if (($start!=0) && ($start>$now)) { next; }
6910: if (($end!=0) && ($end<$now)) {
6911: if ($access_end && $access_end < $now) {
6912: if ($access_end - $end < 86400) {
6913: push(@usersgroups,$group);
1.733 raeburn 6914: }
6915: }
1.817 raeburn 6916: next;
1.733 raeburn 6917: }
1.817 raeburn 6918: push(@usersgroups,$group);
1.683 raeburn 6919: }
6920: }
6921: }
1.817 raeburn 6922: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6923: $grouplist = join(':',@usersgroups);
6924: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6925: }
1.733 raeburn 6926: return @usersgroups;
1.683 raeburn 6927: }
6928:
6929: sub devalidate_getgroups_cache {
6930: my ($udom,$uname,$cdom,$cnum)=@_;
6931: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6932:
1.683 raeburn 6933: my $hashid="$udom:$uname:$courseid";
6934: &devalidate_cache_new('getgroups',$hashid);
6935: }
6936:
1.12 www 6937: # ------------------------------------------------------------------ Plain Text
6938:
6939: sub plaintext {
1.988 raeburn 6940: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6941: if ($short =~ m{^cr/}) {
1.758 albertel 6942: return (split('/',$short))[-1];
6943: }
1.742 raeburn 6944: if (!defined($cid)) {
6945: $cid = $env{'request.course.id'};
6946: }
6947: my %rolenames = (
1.1008 raeburn 6948: Course => 'std',
6949: Community => 'alt1',
1.742 raeburn 6950: );
1.1037 raeburn 6951: if ($cid ne '') {
6952: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6953: unless ($forcedefault) {
6954: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6955: &Apache::lonlocal::mt_escape(\$roletext);
6956: return &Apache::lonlocal::mt($roletext);
6957: }
6958: }
6959: }
6960: if ((defined($type)) && (defined($rolenames{$type})) &&
6961: (defined($rolenames{$type})) &&
6962: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6963: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6964: } elsif ($cid ne '') {
6965: my $crstype = $env{'course.'.$cid.'.type'};
6966: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6967: (defined($prp{$short}{$rolenames{$crstype}}))) {
6968: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6969: }
1.742 raeburn 6970: }
1.1037 raeburn 6971: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6972: }
6973:
6974: # ----------------------------------------------------------------- Assign Role
6975:
6976: sub assignrole {
1.957 raeburn 6977: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6978: $context)=@_;
1.21 www 6979: my $mrole;
6980: if ($role =~ /^cr\//) {
1.393 www 6981: my $cwosec=$url;
1.811 albertel 6982: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6983: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6984: my $refused = 1;
6985: if ($context eq 'requestcourses') {
6986: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6987: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6988: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6989: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6990: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6991: if ($crsenv{'internal.courseowner'} eq
6992: $env{'user.name'}.':'.$env{'user.domain'}) {
6993: $refused = '';
6994: }
6995: }
6996: }
6997: }
6998: }
6999: if ($refused) {
7000: &logthis('Refused custom assignrole: '.
7001: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7002: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7003: return 'refused';
7004: }
1.104 www 7005: }
1.21 www 7006: $mrole='cr';
1.678 raeburn 7007: } elsif ($role =~ /^gr\//) {
7008: my $cwogrp=$url;
1.811 albertel 7009: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 7010: unless (&allowed('mdg',$cwogrp)) {
7011: &logthis('Refused group assignrole: '.
7012: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7013: $env{'user.name'}.' at '.$env{'user.domain'});
7014: return 'refused';
7015: }
7016: $mrole='gr';
1.21 www 7017: } else {
1.82 www 7018: my $cwosec=$url;
1.811 albertel 7019: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 7020: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7021: my $refused;
7022: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7023: if (!(&allowed('c'.$role,$url))) {
7024: $refused = 1;
7025: }
7026: } else {
7027: $refused = 1;
7028: }
1.947 raeburn 7029: if ($refused) {
1.1045 raeburn 7030: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7031: if (!$selfenroll && $context eq 'course') {
7032: my %crsenv;
7033: if ($role eq 'cc' || $role eq 'co') {
7034: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7035: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7036: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7037: if ($crsenv{'internal.courseowner'} eq
7038: $env{'user.name'}.':'.$env{'user.domain'}) {
7039: $refused = '';
7040: }
7041: }
7042: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7043: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7044: if ($crsenv{'internal.courseowner'} eq
7045: $env{'user.name'}.':'.$env{'user.domain'}) {
7046: $refused = '';
7047: }
7048: }
7049: }
7050: }
7051: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 7052: $refused = '';
1.1017 raeburn 7053: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 7054: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 7055: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 7056: my $wrongcc;
7057: if ($cnum =~ /^$match_community$/) {
7058: $wrongcc = 1 if ($role eq 'cc');
7059: } else {
7060: $wrongcc = 1 if ($role eq 'co');
7061: }
7062: unless ($wrongcc) {
7063: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7064: if ($crsenv{'internal.courseowner'} eq
7065: $env{'user.name'}.':'.$env{'user.domain'}) {
7066: $refused = '';
7067: }
1.1017 raeburn 7068: }
7069: }
7070: }
7071: if ($refused) {
1.947 raeburn 7072: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7073: ' '.$role.' '.$end.' '.$start.' by '.
7074: $env{'user.name'}.' at '.$env{'user.domain'});
7075: return 'refused';
7076: }
1.932 raeburn 7077: }
1.104 www 7078: }
1.21 www 7079: $mrole=$role;
7080: }
1.620 albertel 7081: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7082: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 7083: if ($end) { $command.='_'.$end; }
1.21 www 7084: if ($start) {
7085: if ($end) {
1.81 www 7086: $command.='_'.$start;
1.21 www 7087: } else {
1.81 www 7088: $command.='_0_'.$start;
1.21 www 7089: }
7090: }
1.739 raeburn 7091: my $origstart = $start;
7092: my $origend = $end;
1.957 raeburn 7093: my $delflag;
1.357 www 7094: # actually delete
7095: if ($deleteflag) {
1.373 www 7096: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 7097: # modify command to delete the role
1.620 albertel 7098: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 7099: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 7100: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 7101: # set start and finish to negative values for userrolelog
7102: $start=-1;
7103: $end=-1;
1.957 raeburn 7104: $delflag = 1;
1.357 www 7105: }
7106: }
7107: # send command
1.349 www 7108: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 7109: # log new user role if status is ok
1.349 www 7110: if ($answer eq 'ok') {
1.663 raeburn 7111: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 7112: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 7113: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 7114: unless ($role =~ /^gr/) {
7115: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 7116: $origstart,$selfenroll,$context);
1.739 raeburn 7117: }
1.1053 raeburn 7118: if ($role eq 'cc') {
7119: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7120: }
1.349 www 7121: }
7122: return $answer;
1.169 harris41 7123: }
7124:
1.1053 raeburn 7125: sub autoupdate_coowners {
7126: my ($url,$end,$start,$uname,$udom) = @_;
7127: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7128: if (($cdom ne '') && ($cnum ne '')) {
7129: my $now = time;
7130: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7131: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7132: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7133: my $instcode = $coursehash{'internal.coursecode'};
7134: if ($instcode ne '') {
1.1056 raeburn 7135: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7136: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 7137: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 7138: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7139: if ($result eq 'valid') {
7140: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 7141: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7142: push(@newcoowners,$coowner);
7143: }
7144: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7145: push(@newcoowners,$uname.':'.$udom);
7146: }
7147: @newcoowners = sort(@newcoowners);
7148: } else {
7149: push(@newcoowners,$uname.':'.$udom);
7150: }
7151: } else {
7152: if ($coursehash{'internal.co-owners'}) {
7153: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7154: unless ($coowner eq $uname.':'.$udom) {
7155: push(@newcoowners,$coowner);
7156: }
7157: }
7158: unless (@newcoowners > 0) {
7159: $delcoowners = 1;
7160: $coowners = '';
7161: }
7162: }
7163: }
7164: if (@newcoowners || $delcoowners) {
7165: &store_coowners($cdom,$cnum,$coursehash{'home'},
7166: $delcoowners,@newcoowners);
7167: }
7168: }
7169: }
7170: }
7171: }
7172: }
7173: }
7174:
7175: sub store_coowners {
7176: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7177: my $cid = $cdom.'_'.$cnum;
7178: my ($coowners,$delresult,$putresult);
7179: if (@newcoowners) {
7180: $coowners = join(',',@newcoowners);
7181: my %coownershash = (
7182: 'internal.co-owners' => $coowners,
7183: );
7184: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7185: if ($putresult eq 'ok') {
7186: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7187: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7188: }
7189: }
7190: }
7191: if ($delcoowners) {
7192: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7193: if ($delresult eq 'ok') {
7194: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7195: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7196: }
7197: }
7198: }
7199: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7200: my %crsinfo =
7201: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7202: if (ref($crsinfo{$cid}) eq 'HASH') {
7203: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7204: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7205: }
7206: }
7207: }
7208:
1.169 harris41 7209: # -------------------------------------------------- Modify user authentication
1.197 www 7210: # Overrides without validation
7211:
1.169 harris41 7212: sub modifyuserauth {
7213: my ($udom,$uname,$umode,$upass)=@_;
7214: my $uhome=&homeserver($uname,$udom);
1.197 www 7215: unless (&allowed('mau',$udom)) { return 'refused'; }
7216: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 7217: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7218: ' in domain '.$env{'request.role.domain'});
1.169 harris41 7219: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7220: &escape($upass),$uhome);
1.620 albertel 7221: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 7222: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7223: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7224: &log($udom,,$uname,$uhome,
1.620 albertel 7225: 'Authentication changed by '.$env{'user.domain'}.', '.
7226: $env{'user.name'}.', '.$umode.
1.197 www 7227: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 7228: unless ($reply eq 'ok') {
1.197 www 7229: &logthis('Authentication mode error: '.$reply);
1.169 harris41 7230: return 'error: '.$reply;
7231: }
1.170 harris41 7232: return 'ok';
1.80 www 7233: }
7234:
1.81 www 7235: # --------------------------------------------------------------- Modify a user
1.80 www 7236:
1.81 www 7237: sub modifyuser {
1.206 matthew 7238: my ($udom, $uname, $uid,
7239: $umode, $upass, $first,
7240: $middle, $last, $gene,
1.1058 raeburn 7241: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 7242: $udom= &LONCAPA::clean_domain($udom);
7243: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 7244: my $showcandelete = 'none';
7245: if (ref($candelete) eq 'ARRAY') {
7246: if (@{$candelete} > 0) {
7247: $showcandelete = join(', ',@{$candelete});
7248: }
7249: }
1.81 www 7250: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 7251: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 7252: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 7253: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7254: ' desiredhome not specified').
1.620 albertel 7255: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7256: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 7257: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 7258: my $newuser;
7259: if ($uhome eq 'no_host') {
7260: $newuser = 1;
7261: }
1.80 www 7262: # ----------------------------------------------------------------- Create User
1.406 albertel 7263: if (($uhome eq 'no_host') &&
7264: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 7265: my $unhome='';
1.844 albertel 7266: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 7267: $unhome = $desiredhome;
1.620 albertel 7268: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7269: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 7270: } else { # load balancing routine for determining $unhome
1.81 www 7271: my $loadm=10000000;
1.841 albertel 7272: my %servers = &get_servers($udom,'library');
7273: foreach my $tryserver (keys(%servers)) {
7274: my $answer=reply('load',$tryserver);
7275: if (($answer=~/\d+/) && ($answer<$loadm)) {
7276: $loadm=$answer;
7277: $unhome=$tryserver;
7278: }
1.80 www 7279: }
7280: }
7281: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 7282: return 'error: unable to find a home server for '.$uname.
7283: ' in domain '.$udom;
1.80 www 7284: }
7285: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7286: &escape($upass),$unhome);
7287: unless ($reply eq 'ok') {
7288: return 'error: '.$reply;
7289: }
1.230 stredwic 7290: $uhome=&homeserver($uname,$udom,'true');
1.80 www 7291: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 7292: return 'error: unable verify users home machine.';
1.80 www 7293: }
1.209 matthew 7294: } # End of creation of new user
1.80 www 7295: # ---------------------------------------------------------------------- Add ID
7296: if ($uid) {
7297: $uid=~tr/A-Z/a-z/;
7298: my %uidhash=&idrget($udom,$uname);
1.196 www 7299: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7300: && (!$forceid)) {
1.80 www 7301: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 7302: return 'error: user id "'.$uid.'" does not match '.
7303: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 7304: }
7305: } else {
7306: &idput($udom,($uname => $uid));
7307: }
7308: }
7309: # -------------------------------------------------------------- Add names, etc
1.313 matthew 7310: my @tmp=&get('environment',
1.899 raeburn 7311: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 7312: 'permanentemail','inststatus'],
1.134 albertel 7313: $udom,$uname);
1.1075 raeburn 7314: my (%names,%oldnames);
1.313 matthew 7315: if ($tmp[0] =~ m/^error:.*/) {
7316: %names=();
7317: } else {
7318: %names = @tmp;
1.1075 raeburn 7319: %oldnames = %names;
1.313 matthew 7320: }
1.388 www 7321: #
1.1058 raeburn 7322: # If name, email and/or uid are blank (e.g., because an uploaded file
7323: # of users did not contain them), do not overwrite existing values
7324: # unless field is in $candelete array ref.
7325: #
7326:
7327: my @fields = ('firstname','middlename','lastname','generation',
7328: 'permanentemail','id');
7329: my %newvalues;
7330: if (ref($candelete) eq 'ARRAY') {
7331: foreach my $field (@fields) {
7332: if (grep(/^\Q$field\E$/,@{$candelete})) {
7333: if ($field eq 'firstname') {
7334: $names{$field} = $first;
7335: } elsif ($field eq 'middlename') {
7336: $names{$field} = $middle;
7337: } elsif ($field eq 'lastname') {
7338: $names{$field} = $last;
7339: } elsif ($field eq 'generation') {
7340: $names{$field} = $gene;
7341: } elsif ($field eq 'permanentemail') {
7342: $names{$field} = $email;
7343: } elsif ($field eq 'id') {
7344: $names{$field} = $uid;
7345: }
7346: }
7347: }
7348: }
1.388 www 7349: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 7350: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 7351: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 7352: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 7353: if ($email) {
7354: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 7355: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 7356: }
1.899 raeburn 7357: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 7358: if (defined($inststatus)) {
7359: $names{'inststatus'} = '';
7360: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7361: if (ref($usertypes) eq 'HASH') {
7362: my @okstatuses;
7363: foreach my $item (split(/:/,$inststatus)) {
7364: if (defined($usertypes->{$item})) {
7365: push(@okstatuses,$item);
7366: }
7367: }
7368: if (@okstatuses) {
7369: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7370: }
7371: }
7372: }
1.1075 raeburn 7373: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 7374: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 7375: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 7376: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7377: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7378: } else {
7379: $logmsg .= ' during self creation';
7380: }
1.1075 raeburn 7381: my $changed;
7382: if ($newuser) {
7383: $changed = 1;
7384: } else {
7385: foreach my $field (@fields) {
7386: if ($names{$field} ne $oldnames{$field}) {
7387: $changed = 1;
7388: last;
7389: }
7390: }
7391: }
7392: unless ($changed) {
7393: $logmsg = 'No changes in user information needed for: '.$logmsg;
7394: &logthis($logmsg);
7395: return 'ok';
7396: }
7397: my $reply = &put('environment', \%names, $udom,$uname);
7398: if ($reply ne 'ok') {
7399: return 'error: '.$reply;
7400: }
1.1087 raeburn 7401: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7402: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7403: }
1.1075 raeburn 7404: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7405: &devalidate_cache_new('namescache',$uname.':'.$udom);
7406: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7407: &logthis($logmsg);
1.134 albertel 7408: return 'ok';
1.80 www 7409: }
7410:
1.81 www 7411: # -------------------------------------------------------------- Modify student
1.80 www 7412:
1.81 www 7413: sub modifystudent {
7414: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7415: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7416: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7417: if (!$cid) {
1.620 albertel 7418: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7419: return 'not_in_class';
7420: }
1.80 www 7421: }
7422: # --------------------------------------------------------------- Make the user
1.81 www 7423: my $reply=&modifyuser
1.209 matthew 7424: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7425: $desiredhome,$email,$inststatus);
1.80 www 7426: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7427: # This will cause &modify_student_enrollment to get the uid from the
7428: # students environment
7429: $uid = undef if (!$forceid);
1.455 albertel 7430: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7431: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7432: return $reply;
7433: }
7434:
7435: sub modify_student_enrollment {
1.957 raeburn 7436: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7437: my ($cdom,$cnum,$chome);
7438: if (!$cid) {
1.620 albertel 7439: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7440: return 'not_in_class';
7441: }
1.620 albertel 7442: $cdom=$env{'course.'.$cid.'.domain'};
7443: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7444: } else {
7445: ($cdom,$cnum)=split(/_/,$cid);
7446: }
1.620 albertel 7447: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7448: if (!$chome) {
1.457 raeburn 7449: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7450: }
1.455 albertel 7451: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7452: # Make sure the user exists
1.81 www 7453: my $uhome=&homeserver($uname,$udom);
7454: if (($uhome eq '') || ($uhome eq 'no_host')) {
7455: return 'error: no such user';
7456: }
1.297 matthew 7457: # Get student data if we were not given enough information
7458: if (!defined($first) || $first eq '' ||
7459: !defined($last) || $last eq '' ||
7460: !defined($uid) || $uid eq '' ||
7461: !defined($middle) || $middle eq '' ||
7462: !defined($gene) || $gene eq '') {
1.294 matthew 7463: # They did not supply us with enough data to enroll the student, so
7464: # we need to pick up more information.
1.297 matthew 7465: my %tmp = &get('environment',
1.294 matthew 7466: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7467: ,$udom,$uname);
7468:
1.800 albertel 7469: #foreach my $key (keys(%tmp)) {
7470: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7471: #}
1.294 matthew 7472: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7473: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7474: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7475: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7476: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7477: }
1.556 albertel 7478: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 7479: my $reply=cput('classlist',
7480: {"$uname:$udom" =>
1.515 raeburn 7481: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7482: $cdom,$cnum);
1.81 www 7483: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
7484: return 'error: '.$reply;
1.652 albertel 7485: } else {
7486: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 7487: }
1.297 matthew 7488: # Add student role to user
1.83 www 7489: my $uurl='/'.$cid;
1.81 www 7490: $uurl=~s/\_/\//g;
7491: if ($usec) {
7492: $uurl.='/'.$usec;
7493: }
1.957 raeburn 7494: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 7495: }
7496:
1.556 albertel 7497: sub format_name {
7498: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7499: my $name;
7500: if ($first ne 'lastname') {
7501: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7502: } else {
7503: if ($lastname=~/\S/) {
7504: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7505: $name=~s/\s+,/,/;
7506: } else {
7507: $name.= $firstname.' '.$middlename.' '.$generation;
7508: }
7509: }
7510: $name=~s/^\s+//;
7511: $name=~s/\s+$//;
7512: $name=~s/\s+/ /g;
7513: return $name;
7514: }
7515:
1.84 www 7516: # ------------------------------------------------- Write to course preferences
7517:
7518: sub writecoursepref {
7519: my ($courseid,%prefs)=@_;
7520: $courseid=~s/^\///;
7521: $courseid=~s/\_/\//g;
7522: my ($cdomain,$cnum)=split(/\//,$courseid);
7523: my $chome=homeserver($cnum,$cdomain);
7524: if (($chome eq '') || ($chome eq 'no_host')) {
7525: return 'error: no such course';
7526: }
7527: my $cstring='';
1.800 albertel 7528: foreach my $pref (keys(%prefs)) {
7529: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7530: }
1.84 www 7531: $cstring=~s/\&$//;
7532: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7533: }
7534:
7535: # ---------------------------------------------------------- Make/modify course
7536:
7537: sub createcourse {
1.741 raeburn 7538: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7539: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7540: $url=&declutter($url);
7541: my $cid='';
1.1028 raeburn 7542: if ($context eq 'requestcourses') {
7543: my $can_create = 0;
7544: my ($ownername,$ownerdom) = split(':',$course_owner);
7545: if ($udom eq $ownerdom) {
7546: if (&usertools_access($ownername,$ownerdom,$category,undef,
7547: $context)) {
7548: $can_create = 1;
7549: }
7550: } else {
7551: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7552: $category);
7553: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7554: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7555: if (@curr > 0) {
7556: my @options = qw(approval validate autolimit);
7557: my $optregex = join('|',@options);
7558: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7559: $can_create = 1;
7560: }
7561: }
7562: }
7563: }
7564: if ($can_create) {
7565: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7566: unless (&allowed('ccc',$udom)) {
7567: return 'refused';
7568: }
1.1017 raeburn 7569: }
7570: } else {
7571: return 'refused';
7572: }
1.1028 raeburn 7573: } elsif (!&allowed('ccc',$udom)) {
7574: return 'refused';
1.84 www 7575: }
1.1011 raeburn 7576: # --------------------------------------------------------------- Get Unique ID
7577: my $uname;
7578: if ($cnum =~ /^$match_courseid$/) {
7579: my $chome=&homeserver($cnum,$udom,'true');
7580: if (($chome eq '') || ($chome eq 'no_host')) {
7581: $uname = $cnum;
7582: } else {
1.1038 raeburn 7583: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7584: }
7585: } else {
1.1038 raeburn 7586: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7587: }
7588: return $uname if ($uname =~ /^error/);
7589: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7590: if (!defined($course_server)) {
7591: if (defined(&domain($udom,'primary'))) {
7592: $course_server = &domain($udom,'primary');
7593: } else {
7594: $course_server = $env{'user.home'};
7595: }
7596: }
7597: my %host_servers =
7598: &Apache::lonnet::get_servers($udom,'library');
7599: unless ($host_servers{$course_server}) {
7600: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7601: }
1.84 www 7602: # ------------------------------------------------------------- Make the course
7603: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7604: $course_server);
1.84 www 7605: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7606: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7607: if (($uhome eq '') || ($uhome eq 'no_host')) {
7608: return 'error: no such course';
7609: }
1.271 www 7610: # ----------------------------------------------------------------- Course made
1.516 raeburn 7611: # log existence
1.1029 raeburn 7612: my $now = time;
1.918 raeburn 7613: my $newcourse = {
7614: $udom.'_'.$uname => {
1.921 raeburn 7615: description => $description,
7616: inst_code => $inst_code,
7617: owner => $course_owner,
7618: type => $crstype,
1.1029 raeburn 7619: creator => $env{'user.name'}.':'.
7620: $env{'user.domain'},
7621: created => $now,
7622: context => $context,
1.918 raeburn 7623: },
7624: };
1.921 raeburn 7625: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7626: # set toplevel url
1.271 www 7627: my $topurl=$url;
7628: unless ($nonstandard) {
7629: # ------------------------------------------ For standard courses, make top url
7630: my $mapurl=&clutter($url);
1.278 www 7631: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7632: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7633: <map>
7634: <resource id="1" type="start"></resource>
7635: <resource id="2" src="$mapurl"></resource>
7636: <resource id="3" type="finish"></resource>
7637: <link index="1" from="1" to="2"></link>
7638: <link index="2" from="2" to="3"></link>
7639: </map>
7640: ENDINITMAP
7641: $topurl=&declutter(
1.638 albertel 7642: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7643: );
7644: }
7645: # ----------------------------------------------------------- Write preferences
1.84 www 7646: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7647: ('description' => $description,
7648: 'url' => $topurl,
7649: 'internal.creator' => $env{'user.name'}.':'.
7650: $env{'user.domain'},
7651: 'internal.created' => $now,
7652: 'internal.creationcontext' => $context)
7653: );
1.84 www 7654: return '/'.$udom.'/'.$uname;
7655: }
7656:
1.1011 raeburn 7657: # ------------------------------------------------------------------- Create ID
7658: sub generate_coursenum {
1.1038 raeburn 7659: my ($udom,$crstype) = @_;
1.1011 raeburn 7660: my $domdesc = &domain($udom);
7661: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7662: my $first;
7663: if ($crstype eq 'Community') {
7664: $first = '0';
7665: } else {
7666: $first = int(1+rand(9));
7667: }
7668: my $uname=$first.
1.1011 raeburn 7669: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7670: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7671: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7672: # ----------------------------------------------- Make sure that does not exist
7673: my $uhome=&homeserver($uname,$udom,'true');
7674: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7675: if ($crstype eq 'Community') {
7676: $first = '0';
7677: } else {
7678: $first = int(1+rand(9));
7679: }
7680: $uname=$first.
1.1011 raeburn 7681: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7682: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7683: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7684: $uhome=&homeserver($uname,$udom,'true');
7685: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7686: return 'error: unable to generate unique course-ID';
7687: }
7688: }
7689: return $uname;
7690: }
7691:
1.813 albertel 7692: sub is_course {
7693: my ($cdom,$cnum) = @_;
7694: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7695: undef,'.');
1.813 albertel 7696: if (exists($courses{$cdom.'_'.$cnum})) {
7697: return 1;
7698: }
7699: return 0;
7700: }
7701:
1.1015 raeburn 7702: sub store_userdata {
7703: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7704: my $result;
1.1016 raeburn 7705: if ($datakey ne '') {
1.1013 raeburn 7706: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7707: if ($udom eq '' || $uname eq '') {
7708: $udom = $env{'user.domain'};
7709: $uname = $env{'user.name'};
7710: }
7711: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7712: if (($uhome eq '') || ($uhome eq 'no_host')) {
7713: $result = 'error: no_host';
7714: } else {
7715: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7716: $storehash->{'host'} = $perlvar{'lonHostID'};
7717:
7718: my $namevalue='';
7719: foreach my $key (keys(%{$storehash})) {
7720: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7721: }
7722: $namevalue=~s/\&$//;
1.1105 raeburn 7723: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
7724: $namevalue,$uhome);
1.1013 raeburn 7725: }
7726: } else {
7727: $result = 'error: data to store was not a hash reference';
7728: }
7729: } else {
7730: $result= 'error: invalid requestkey';
7731: }
7732: return $result;
7733: }
7734:
1.21 www 7735: # ---------------------------------------------------------- Assign Custom Role
7736:
7737: sub assigncustomrole {
1.957 raeburn 7738: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7739: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7740: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7741: }
7742:
7743: # ----------------------------------------------------------------- Revoke Role
7744:
7745: sub revokerole {
1.957 raeburn 7746: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7747: my $now=time;
1.965 raeburn 7748: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7749: }
7750:
7751: # ---------------------------------------------------------- Revoke Custom Role
7752:
7753: sub revokecustomrole {
1.957 raeburn 7754: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7755: my $now=time;
1.357 www 7756: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7757: $deleteflag,$selfenroll,$context);
1.17 www 7758: }
7759:
1.533 banghart 7760: # ------------------------------------------------------------ Disk usage
1.535 albertel 7761: sub diskusage {
1.955 raeburn 7762: my ($udom,$uname,$directorypath,$getpropath)=@_;
7763: $directorypath =~ s/\/$//;
7764: my $listing=&reply('du2:'.&escape($directorypath).':'
7765: .&escape($getpropath).':'.&escape($uname).':'
7766: .&escape($udom),homeserver($uname,$udom));
7767: if ($listing eq 'unknown_cmd') {
7768: if ($getpropath) {
7769: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7770: }
7771: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7772: }
1.514 albertel 7773: return $listing;
1.512 banghart 7774: }
7775:
1.566 banghart 7776: sub is_locked {
1.1096 raeburn 7777: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 7778: my @check;
7779: my $is_locked;
1.1093 raeburn 7780: push (@check,$file_name);
1.613 albertel 7781: my %locked = &get('file_permissions',\@check,
1.620 albertel 7782: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7783: my ($tmp)=keys(%locked);
7784: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7785:
1.566 banghart 7786: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7787: $is_locked = 'false';
7788: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 7789: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7790: $is_locked = 'true';
1.1096 raeburn 7791: if (ref($which) eq 'ARRAY') {
7792: push(@{$which},$entry);
7793: } else {
7794: last;
7795: }
1.745 raeburn 7796: }
7797: }
1.566 banghart 7798: } else {
7799: $is_locked = 'false';
7800: }
1.1093 raeburn 7801: return $is_locked;
1.566 banghart 7802: }
7803:
1.759 albertel 7804: sub declutter_portfile {
7805: my ($file) = @_;
1.833 albertel 7806: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7807: return $file;
7808: }
7809:
1.559 banghart 7810: # ------------------------------------------------------------- Mark as Read Only
7811:
7812: sub mark_as_readonly {
7813: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7814: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7815: my ($tmp)=keys(%current_permissions);
7816: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7817: foreach my $file (@{$files}) {
1.759 albertel 7818: $file = &declutter_portfile($file);
1.561 banghart 7819: push(@{$current_permissions{$file}},$what);
1.559 banghart 7820: }
1.613 albertel 7821: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7822: return;
7823: }
7824:
1.572 banghart 7825: # ------------------------------------------------------------Save Selected Files
7826:
7827: sub save_selected_files {
7828: my ($user, $path, @files) = @_;
7829: my $filename = $user."savedfiles";
1.573 banghart 7830: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7831: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7832: foreach my $file (@files) {
1.620 albertel 7833: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7834: }
7835: foreach my $file (@other_files) {
1.574 banghart 7836: print (OUT $file."\n");
1.572 banghart 7837: }
1.574 banghart 7838: close (OUT);
1.572 banghart 7839: return 'ok';
7840: }
7841:
1.574 banghart 7842: sub clear_selected_files {
7843: my ($user) = @_;
7844: my $filename = $user."savedfiles";
1.1117 foxr 7845: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 7846: print (OUT undef);
7847: close (OUT);
7848: return ("ok");
7849: }
7850:
1.572 banghart 7851: sub files_in_path {
7852: my ($user, $path) = @_;
7853: my $filename = $user."savedfiles";
7854: my %return_files;
1.1117 foxr 7855: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 7856: while (my $line_in = <IN>) {
1.574 banghart 7857: chomp ($line_in);
7858: my @paths_and_file = split (m!/!, $line_in);
7859: my $file_part = pop (@paths_and_file);
7860: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7861: $path_part.='/';
7862: my $path_and_file = $path_part.$file_part;
7863: if ($path_part eq $path) {
7864: $return_files{$file_part}= 'selected';
7865: }
7866: }
1.574 banghart 7867: close (IN);
7868: return (\%return_files);
1.572 banghart 7869: }
7870:
7871: # called in portfolio select mode, to show files selected NOT in current directory
7872: sub files_not_in_path {
7873: my ($user, $path) = @_;
7874: my $filename = $user."savedfiles";
7875: my @return_files;
7876: my $path_part;
1.1117 foxr 7877: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 7878: while (my $line = <IN>) {
1.572 banghart 7879: #ok, I know it's clunky, but I want it to work
1.800 albertel 7880: my @paths_and_file = split(m|/|, $line);
7881: my $file_part = pop(@paths_and_file);
7882: chomp($file_part);
7883: my $path_part = join('/', @paths_and_file);
1.572 banghart 7884: $path_part .= '/';
7885: my $path_and_file = $path_part.$file_part;
7886: if ($path_part ne $path) {
1.800 albertel 7887: push(@return_files, ($path_and_file));
1.572 banghart 7888: }
7889: }
1.800 albertel 7890: close(OUT);
1.574 banghart 7891: return (@return_files);
1.572 banghart 7892: }
7893:
1.745 raeburn 7894: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7895:
1.745 raeburn 7896: sub get_portfile_permissions {
7897: my ($domain,$user) = @_;
1.613 albertel 7898: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7899: my ($tmp)=keys(%current_permissions);
7900: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7901: return \%current_permissions;
7902: }
7903:
7904: #---------------------------------------------Get portfolio file access controls
7905:
1.749 raeburn 7906: sub get_access_controls {
1.745 raeburn 7907: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7908: my %access;
7909: my $real_file = $file;
7910: $file =~ s/\.meta$//;
1.745 raeburn 7911: if (defined($file)) {
1.749 raeburn 7912: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7913: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7914: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7915: }
7916: }
1.745 raeburn 7917: } else {
1.749 raeburn 7918: foreach my $key (keys(%{$current_permissions})) {
7919: if ($key =~ /\0accesscontrol$/) {
7920: if (defined($group)) {
7921: if ($key !~ m-^\Q$group\E/-) {
7922: next;
7923: }
7924: }
7925: my ($fullpath) = split(/\0/,$key);
7926: if (ref($$current_permissions{$key}) eq 'HASH') {
7927: foreach my $control (keys(%{$$current_permissions{$key}})) {
7928: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7929: }
7930: }
7931: }
7932: }
7933: }
7934: return %access;
7935: }
7936:
7937: sub modify_access_controls {
7938: my ($file_name,$changes,$domain,$user)=@_;
7939: my ($outcome,$deloutcome);
7940: my %store_permissions;
7941: my %new_values;
7942: my %new_control;
7943: my %translation;
7944: my @deletions = ();
7945: my $now = time;
7946: if (exists($$changes{'activate'})) {
7947: if (ref($$changes{'activate'}) eq 'HASH') {
7948: my @newitems = sort(keys(%{$$changes{'activate'}}));
7949: my $numnew = scalar(@newitems);
7950: for (my $i=0; $i<$numnew; $i++) {
7951: my $newkey = $newitems[$i];
7952: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7953: if ($newkey =~ /^\d+:/) {
7954: $newkey =~ s/^(\d+)/$newid/;
7955: $translation{$1} = $newid;
7956: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7957: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7958: $translation{$1} = $newid;
7959: }
1.749 raeburn 7960: $new_values{$file_name."\0".$newkey} =
7961: $$changes{'activate'}{$newitems[$i]};
7962: $new_control{$newkey} = $now;
7963: }
7964: }
7965: }
7966: my %todelete;
7967: my %changed_items;
7968: foreach my $action ('delete','update') {
7969: if (exists($$changes{$action})) {
7970: if (ref($$changes{$action}) eq 'HASH') {
7971: foreach my $key (keys(%{$$changes{$action}})) {
7972: my ($itemnum) = ($key =~ /^([^:]+):/);
7973: if ($action eq 'delete') {
7974: $todelete{$itemnum} = 1;
7975: } else {
7976: $changed_items{$itemnum} = $key;
7977: }
7978: }
1.745 raeburn 7979: }
7980: }
1.749 raeburn 7981: }
7982: # get lock on access controls for file.
7983: my $lockhash = {
7984: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7985: ':'.$env{'user.domain'},
7986: };
7987: my $tries = 0;
7988: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7989:
7990: while (($gotlock ne 'ok') && $tries <3) {
7991: $tries ++;
7992: sleep 1;
7993: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7994: }
7995: if ($gotlock eq 'ok') {
7996: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7997: my ($tmp)=keys(%curr_permissions);
7998: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7999: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8000: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8001: if (ref($curr_controls) eq 'HASH') {
8002: foreach my $control_item (keys(%{$curr_controls})) {
8003: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8004: if (defined($todelete{$itemnum})) {
8005: push(@deletions,$file_name."\0".$control_item);
8006: } else {
8007: if (defined($changed_items{$itemnum})) {
8008: $new_control{$changed_items{$itemnum}} = $now;
8009: push(@deletions,$file_name."\0".$control_item);
8010: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8011: } else {
8012: $new_control{$control_item} = $$curr_controls{$control_item};
8013: }
8014: }
1.745 raeburn 8015: }
8016: }
8017: }
1.970 raeburn 8018: my ($group);
8019: if (&is_course($domain,$user)) {
8020: ($group,my $file) = split(/\//,$file_name,2);
8021: }
1.749 raeburn 8022: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8023: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8024: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8025: # remove lock
8026: my @del_lock = ($file_name."\0".'locked_access_records');
8027: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 8028: my $sqlresult =
1.970 raeburn 8029: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 8030: $group);
1.749 raeburn 8031: } else {
8032: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 8033: }
1.749 raeburn 8034: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 8035: }
8036:
1.827 raeburn 8037: sub make_public_indefinitely {
8038: my ($requrl) = @_;
8039: my $now = time;
8040: my $action = 'activate';
8041: my $aclnum = 0;
8042: if (&is_portfolio_url($requrl)) {
8043: my (undef,$udom,$unum,$file_name,$group) =
8044: &parse_portfolio_url($requrl);
8045: my $current_perms = &get_portfile_permissions($udom,$unum);
8046: my %access_controls = &get_access_controls($current_perms,
8047: $group,$file_name);
8048: foreach my $key (keys(%{$access_controls{$file_name}})) {
8049: my ($num,$scope,$end,$start) =
8050: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8051: if ($scope eq 'public') {
8052: if ($start <= $now && $end == 0) {
8053: $action = 'none';
8054: } else {
8055: $action = 'update';
8056: $aclnum = $num;
8057: }
8058: last;
8059: }
8060: }
8061: if ($action eq 'none') {
8062: return 'ok';
8063: } else {
8064: my %changes;
8065: my $newend = 0;
8066: my $newstart = $now;
8067: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8068: $changes{$action}{$newkey} = {
8069: type => 'public',
8070: time => {
8071: start => $newstart,
8072: end => $newend,
8073: },
8074: };
8075: my ($outcome,$deloutcome,$new_values,$translation) =
8076: &modify_access_controls($file_name,\%changes,$udom,$unum);
8077: return $outcome;
8078: }
8079: } else {
8080: return 'invalid';
8081: }
8082: }
8083:
1.745 raeburn 8084: #------------------------------------------------------Get Marked as Read Only
8085:
8086: sub get_marked_as_readonly {
8087: my ($domain,$user,$what,$group) = @_;
8088: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 8089: my @readonly_files;
1.629 banghart 8090: my $cmp1=$what;
8091: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 8092: while (my ($file_name,$value) = each(%{$current_permissions})) {
8093: if (defined($group)) {
8094: if ($file_name !~ m-^\Q$group\E/-) {
8095: next;
8096: }
8097: }
1.561 banghart 8098: if (ref($value) eq "ARRAY"){
8099: foreach my $stored_what (@{$value}) {
1.629 banghart 8100: my $cmp2=$stored_what;
1.759 albertel 8101: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 8102: $cmp2=join('',@{$stored_what});
1.745 raeburn 8103: }
1.629 banghart 8104: if ($cmp1 eq $cmp2) {
1.561 banghart 8105: push(@readonly_files, $file_name);
1.745 raeburn 8106: last;
1.563 banghart 8107: } elsif (!defined($what)) {
8108: push(@readonly_files, $file_name);
1.745 raeburn 8109: last;
1.561 banghart 8110: }
8111: }
1.745 raeburn 8112: }
1.561 banghart 8113: }
8114: return @readonly_files;
8115: }
1.577 banghart 8116: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 8117:
1.577 banghart 8118: sub get_marked_as_readonly_hash {
1.745 raeburn 8119: my ($current_permissions,$group,$what) = @_;
1.577 banghart 8120: my %readonly_files;
1.745 raeburn 8121: while (my ($file_name,$value) = each(%{$current_permissions})) {
8122: if (defined($group)) {
8123: if ($file_name !~ m-^\Q$group\E/-) {
8124: next;
8125: }
8126: }
1.577 banghart 8127: if (ref($value) eq "ARRAY"){
8128: foreach my $stored_what (@{$value}) {
1.745 raeburn 8129: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 8130: foreach my $lock_descriptor(@{$stored_what}) {
8131: if ($lock_descriptor eq 'graded') {
8132: $readonly_files{$file_name} = 'graded';
8133: } elsif ($lock_descriptor eq 'handback') {
8134: $readonly_files{$file_name} = 'handback';
8135: } else {
8136: if (!exists($readonly_files{$file_name})) {
8137: $readonly_files{$file_name} = 'locked';
8138: }
8139: }
1.745 raeburn 8140: }
1.750 banghart 8141: }
1.577 banghart 8142: }
8143: }
8144: }
8145: return %readonly_files;
8146: }
1.559 banghart 8147: # ------------------------------------------------------------ Unmark as Read Only
8148:
8149: sub unmark_as_readonly {
1.629 banghart 8150: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8151: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 8152: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 8153: $file_name = &declutter_portfile($file_name);
1.634 albertel 8154: my $symb_crs = $what;
8155: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 8156: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 8157: my ($tmp)=keys(%current_permissions);
8158: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8159: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 8160: foreach my $file (@readonly_files) {
1.759 albertel 8161: my $clean_file = &declutter_portfile($file);
8162: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 8163: my $current_locks = $current_permissions{$file};
1.563 banghart 8164: my @new_locks;
8165: my @del_keys;
8166: if (ref($current_locks) eq "ARRAY"){
8167: foreach my $locker (@{$current_locks}) {
1.632 albertel 8168: my $compare=$locker;
1.749 raeburn 8169: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 8170: $compare=join('',@{$locker});
1.746 raeburn 8171: if ($compare ne $symb_crs) {
8172: push(@new_locks, $locker);
8173: }
1.563 banghart 8174: }
8175: }
1.650 albertel 8176: if (scalar(@new_locks) > 0) {
1.563 banghart 8177: $current_permissions{$file} = \@new_locks;
8178: } else {
8179: push(@del_keys, $file);
1.613 albertel 8180: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 8181: delete($current_permissions{$file});
1.563 banghart 8182: }
8183: }
1.561 banghart 8184: }
1.613 albertel 8185: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8186: return;
8187: }
1.512 banghart 8188:
1.17 www 8189: # ------------------------------------------------------------ Directory lister
8190:
8191: sub dirlist {
1.955 raeburn 8192: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 8193: $uri=~s/^\///;
8194: $uri=~s/\/$//;
1.253 stredwic 8195: my ($udom, $uname);
1.955 raeburn 8196: if ($getuserdir) {
1.253 stredwic 8197: $udom = $userdomain;
8198: $uname = $username;
1.955 raeburn 8199: } else {
8200: (undef,$udom,$uname)=split(/\//,$uri);
8201: if(defined($userdomain)) {
8202: $udom = $userdomain;
8203: }
8204: if(defined($username)) {
8205: $uname = $username;
8206: }
1.253 stredwic 8207: }
1.955 raeburn 8208: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 8209:
1.955 raeburn 8210: $dirRoot = $perlvar{'lonDocRoot'};
8211: if (defined($getpropath)) {
8212: $dirRoot = &propath($udom,$uname);
1.253 stredwic 8213: $dirRoot =~ s/\/$//;
1.955 raeburn 8214: } elsif (defined($getuserdir)) {
8215: my $subdir=$uname.'__';
8216: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8217: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8218: ."/$udom/$subdir/$uname";
8219: } elsif (defined($alternateRoot)) {
8220: $dirRoot = $alternateRoot;
1.751 banghart 8221: }
1.253 stredwic 8222:
8223: if($udom) {
8224: if($uname) {
1.955 raeburn 8225: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 8226: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 8227: .':'.&escape($uname).':'.&escape($udom),
8228: &homeserver($uname,$udom));
8229: if ($listing eq 'unknown_cmd') {
8230: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
8231: &homeserver($uname,$udom));
8232: } else {
8233: @listing_results = map { &unescape($_); } split(/:/,$listing);
8234: }
1.605 matthew 8235: if ($listing eq 'unknown_cmd') {
1.800 albertel 8236: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
8237: &homeserver($uname,$udom));
1.605 matthew 8238: @listing_results = split(/:/,$listing);
8239: } else {
8240: @listing_results = map { &unescape($_); } split(/:/,$listing);
8241: }
8242: return @listing_results;
1.955 raeburn 8243: } elsif(!$alternateRoot) {
1.800 albertel 8244: my %allusers;
1.841 albertel 8245: my %servers = &get_servers($udom,'library');
1.955 raeburn 8246: foreach my $tryserver (keys(%servers)) {
8247: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8248: &escape($udom),$tryserver);
8249: if ($listing eq 'unknown_cmd') {
8250: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8251: $udom, $tryserver);
8252: } else {
8253: @listing_results = map { &unescape($_); } split(/:/,$listing);
8254: }
1.841 albertel 8255: if ($listing eq 'unknown_cmd') {
8256: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8257: $udom, $tryserver);
8258: @listing_results = split(/:/,$listing);
8259: } else {
8260: @listing_results =
8261: map { &unescape($_); } split(/:/,$listing);
8262: }
8263: if ($listing_results[0] ne 'no_such_dir' &&
8264: $listing_results[0] ne 'empty' &&
8265: $listing_results[0] ne 'con_lost') {
8266: foreach my $line (@listing_results) {
8267: my ($entry) = split(/&/,$line,2);
8268: $allusers{$entry} = 1;
8269: }
8270: }
1.253 stredwic 8271: }
8272: my $alluserstr='';
1.800 albertel 8273: foreach my $user (sort(keys(%allusers))) {
8274: $alluserstr.=$user.'&user:';
1.253 stredwic 8275: }
8276: $alluserstr=~s/:$//;
8277: return split(/:/,$alluserstr);
8278: } else {
1.800 albertel 8279: return ('missing user name');
1.253 stredwic 8280: }
1.955 raeburn 8281: } elsif(!defined($getpropath)) {
1.841 albertel 8282: my @all_domains = sort(&all_domains());
1.955 raeburn 8283: foreach my $domain (@all_domains) {
8284: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
8285: }
8286: return @all_domains;
8287: } else {
1.800 albertel 8288: return ('missing domain');
1.275 stredwic 8289: }
8290: }
8291:
8292: # --------------------------------------------- GetFileTimestamp
8293: # This function utilizes dirlist and returns the date stamp for
8294: # when it was last modified. It will also return an error of -1
8295: # if an error occurs
8296:
8297: sub GetFileTimestamp {
1.955 raeburn 8298: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 8299: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8300: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 8301: my ($fileStat) =
8302: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
8303: undef,$getuserdir);
1.275 stredwic 8304: my @stats = split('&', $fileStat);
8305: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 8306: # @stats contains first the filename, then the stat output
8307: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 8308: } else {
8309: return -1;
1.253 stredwic 8310: }
1.26 www 8311: }
8312:
1.712 albertel 8313: sub stat_file {
8314: my ($uri) = @_;
1.787 albertel 8315: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 8316:
1.955 raeburn 8317: my ($udom,$uname,$file);
1.712 albertel 8318: if ($uri =~ m-^/(uploaded|editupload)/-) {
8319: ($udom,$uname,$file) =
1.811 albertel 8320: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 8321: $file = 'userfiles/'.$file;
8322: }
8323: if ($uri =~ m-^/res/-) {
8324: ($udom,$uname) =
1.807 albertel 8325: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 8326: $file = $uri;
8327: }
8328:
8329: if (!$udom || !$uname || !$file) {
8330: # unable to handle the uri
8331: return ();
8332: }
1.956 raeburn 8333: my $getpropath;
8334: if ($file =~ /^userfiles\//) {
8335: $getpropath = 1;
8336: }
1.955 raeburn 8337: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 8338: my @stats = split('&', $result);
1.721 banghart 8339:
1.712 albertel 8340: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
8341: shift(@stats); #filename is first
8342: return @stats;
8343: }
8344: return ();
8345: }
8346:
1.26 www 8347: # -------------------------------------------------------- Value of a Condition
8348:
1.713 albertel 8349: # gets the value of a specific preevaluated condition
8350: # stored in the string $env{user.state.<cid>}
8351: # or looks up a condition reference in the bighash and if if hasn't
8352: # already been evaluated recurses into docondval to get the value of
8353: # the condition, then memoizing it to
8354: # $env{user.state.<cid>.<condition>}
1.40 www 8355: sub directcondval {
8356: my $number=shift;
1.620 albertel 8357: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 8358: &Apache::lonuserstate::evalstate();
8359: }
1.713 albertel 8360: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8361: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8362: } elsif ($number =~ /^_/) {
8363: my $sub_condition;
8364: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8365: &GDBM_READER(),0640)) {
8366: $sub_condition=$bighash{'conditions'.$number};
8367: untie(%bighash);
8368: }
8369: my $value = &docondval($sub_condition);
1.949 raeburn 8370: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 8371: return $value;
8372: }
1.620 albertel 8373: if ($env{'user.state.'.$env{'request.course.id'}}) {
8374: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 8375: } else {
8376: return 2;
8377: }
8378: }
8379:
1.713 albertel 8380: # get the collection of conditions for this resource
1.26 www 8381: sub condval {
8382: my $condidx=shift;
1.54 www 8383: my $allpathcond='';
1.713 albertel 8384: foreach my $cond (split(/\|/,$condidx)) {
8385: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8386: $allpathcond.=
8387: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8388: }
1.191 harris41 8389: }
1.54 www 8390: $allpathcond=~s/\|$//;
1.713 albertel 8391: return &docondval($allpathcond);
8392: }
8393:
8394: #evaluates an expression of conditions
8395: sub docondval {
8396: my ($allpathcond) = @_;
8397: my $result=0;
8398: if ($env{'request.course.id'}
8399: && defined($allpathcond)) {
8400: my $operand='|';
8401: my @stack;
8402: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8403: if ($chunk eq '(') {
8404: push @stack,($operand,$result);
8405: } elsif ($chunk eq ')') {
8406: my $before=pop @stack;
8407: if (pop @stack eq '&') {
8408: $result=$result>$before?$before:$result;
8409: } else {
8410: $result=$result>$before?$result:$before;
8411: }
8412: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8413: $operand=$chunk;
8414: } else {
8415: my $new=directcondval($chunk);
8416: if ($operand eq '&') {
8417: $result=$result>$new?$new:$result;
8418: } else {
8419: $result=$result>$new?$result:$new;
8420: }
8421: }
8422: }
1.26 www 8423: }
8424: return $result;
1.421 albertel 8425: }
8426:
8427: # ---------------------------------------------------- Devalidate courseresdata
8428:
8429: sub devalidatecourseresdata {
8430: my ($coursenum,$coursedomain)=@_;
8431: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8432: &devalidate_cache_new('courseres',$hashid);
1.28 www 8433: }
8434:
1.763 www 8435:
1.200 www 8436: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8437: #
8438: # Parameters:
8439: # $coursenum - Number of the course.
8440: # $coursedomain - Domain at which the course was created.
8441: # Returns:
8442: # A hash of the course parameters along (I think) with timestamps
8443: # and version info.
1.877 foxr 8444:
1.624 albertel 8445: sub get_courseresdata {
8446: my ($coursenum,$coursedomain)=@_;
1.200 www 8447: my $coursehom=&homeserver($coursenum,$coursedomain);
8448: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8449: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8450: my %dumpreply;
1.417 albertel 8451: unless (defined($cached)) {
1.624 albertel 8452: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 8453: $result=\%dumpreply;
1.251 albertel 8454: my ($tmp) = keys(%dumpreply);
8455: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 8456: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 8457: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8458: return $tmp;
1.416 albertel 8459: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8460: $result=undef;
1.599 albertel 8461: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8462: }
8463: }
1.624 albertel 8464: return $result;
8465: }
8466:
1.633 albertel 8467: sub devalidateuserresdata {
8468: my ($uname,$udom)=@_;
8469: my $hashid="$udom:$uname";
8470: &devalidate_cache_new('userres',$hashid);
8471: }
8472:
1.624 albertel 8473: sub get_userresdata {
8474: my ($uname,$udom)=@_;
8475: #most student don\'t have any data set, check if there is some data
8476: if (&EXT_cache_status($udom,$uname)) { return undef; }
8477:
8478: my $hashid="$udom:$uname";
8479: my ($result,$cached)=&is_cached_new('userres',$hashid);
8480: if (!defined($cached)) {
8481: my %resourcedata=&dump('resourcedata',$udom,$uname);
8482: $result=\%resourcedata;
8483: &do_cache_new('userres',$hashid,$result,600);
8484: }
8485: my ($tmp)=keys(%$result);
8486: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8487: return $result;
8488: }
8489: #error 2 occurs when the .db doesn't exist
8490: if ($tmp!~/error: 2 /) {
1.672 albertel 8491: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8492: " Trying to get resource data for ".
8493: $uname." at ".$udom.": ".
8494: $tmp."</font>");
8495: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8496: #&EXT_cache_set($udom,$uname);
8497: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8498: undef($tmp); # not really an error so don't send it back
1.624 albertel 8499: }
8500: return $tmp;
8501: }
1.879 foxr 8502: #----------------------------------------------- resdata - return resource data
8503: # Purpose:
8504: # Return resource data for either users or for a course.
8505: # Parameters:
8506: # $name - Course/user name.
8507: # $domain - Name of the domain the user/course is registered on.
8508: # $type - Type of thing $name is (must be 'course' or 'user'
8509: # @which - Array of names of resources desired.
8510: # Returns:
8511: # The value of the first reasource in @which that is found in the
8512: # resource hash.
8513: # Exceptional Conditions:
8514: # If the $type passed in is not valid (not the string 'course' or
8515: # 'user', an undefined reference is returned.
8516: # If none of the resources are found, an undef is returned
1.624 albertel 8517: sub resdata {
8518: my ($name,$domain,$type,@which)=@_;
8519: my $result;
8520: if ($type eq 'course') {
8521: $result=&get_courseresdata($name,$domain);
8522: } elsif ($type eq 'user') {
8523: $result=&get_userresdata($name,$domain);
8524: }
8525: if (!ref($result)) { return $result; }
1.251 albertel 8526: foreach my $item (@which) {
1.927 albertel 8527: if (defined($result->{$item->[0]})) {
8528: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8529: }
1.250 albertel 8530: }
1.291 albertel 8531: return undef;
1.200 www 8532: }
8533:
1.379 matthew 8534: #
8535: # EXT resource caching routines
8536: #
8537:
8538: sub clear_EXT_cache_status {
1.383 albertel 8539: &delenv('cache.EXT.');
1.379 matthew 8540: }
8541:
8542: sub EXT_cache_status {
8543: my ($target_domain,$target_user) = @_;
1.383 albertel 8544: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8545: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8546: # We know already the user has no data
8547: return 1;
8548: } else {
8549: return 0;
8550: }
8551: }
8552:
8553: sub EXT_cache_set {
8554: my ($target_domain,$target_user) = @_;
1.383 albertel 8555: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8556: #&appenv({$cachename => time});
1.379 matthew 8557: }
8558:
1.28 www 8559: # --------------------------------------------------------- Value of a Variable
1.58 www 8560: sub EXT {
1.715 albertel 8561:
1.395 albertel 8562: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8563: unless ($varname) { return ''; }
1.218 albertel 8564: #get real user name/domain, courseid and symb
8565: my $courseid;
1.359 albertel 8566: my $publicuser;
1.427 www 8567: if ($symbparm) {
8568: $symbparm=&get_symb_from_alias($symbparm);
8569: }
1.218 albertel 8570: if (!($uname && $udom)) {
1.790 albertel 8571: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8572: if (!$symbparm) { $symbparm=$cursymb; }
8573: } else {
1.620 albertel 8574: $courseid=$env{'request.course.id'};
1.218 albertel 8575: }
1.48 www 8576: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8577: my $rest;
1.320 albertel 8578: if (defined($therest[0])) {
1.48 www 8579: $rest=join('.',@therest);
8580: } else {
8581: $rest='';
8582: }
1.320 albertel 8583:
1.57 www 8584: my $qualifierrest=$qualifier;
8585: if ($rest) { $qualifierrest.='.'.$rest; }
8586: my $spacequalifierrest=$space;
8587: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8588: if ($realm eq 'user') {
1.48 www 8589: # --------------------------------------------------------------- user.resource
8590: if ($space eq 'resource') {
1.651 albertel 8591: if ( (defined($Apache::lonhomework::parsing_a_problem)
8592: || defined($Apache::lonhomework::parsing_a_task))
8593: &&
1.744 albertel 8594: ($symbparm eq &symbread()) ) {
8595: # if we are in the middle of processing the resource the
8596: # get the value we are planning on committing
8597: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8598: return $Apache::lonhomework::results{$qualifierrest};
8599: } else {
8600: return $Apache::lonhomework::history{$qualifierrest};
8601: }
1.335 albertel 8602: } else {
1.359 albertel 8603: my %restored;
1.620 albertel 8604: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8605: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8606: } else {
8607: %restored=&restore($symbparm,$courseid,$udom,$uname);
8608: }
1.335 albertel 8609: return $restored{$qualifierrest};
8610: }
1.48 www 8611: # ----------------------------------------------------------------- user.access
8612: } elsif ($space eq 'access') {
1.218 albertel 8613: # FIXME - not supporting calls for a specific user
1.48 www 8614: return &allowed($qualifier,$rest);
8615: # ------------------------------------------ user.preferences, user.environment
8616: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8617: if (($uname eq $env{'user.name'}) &&
8618: ($udom eq $env{'user.domain'})) {
8619: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8620: } else {
1.359 albertel 8621: my %returnhash;
8622: if (!$publicuser) {
8623: %returnhash=&userenvironment($udom,$uname,
8624: $qualifierrest);
8625: }
1.218 albertel 8626: return $returnhash{$qualifierrest};
8627: }
1.48 www 8628: # ----------------------------------------------------------------- user.course
8629: } elsif ($space eq 'course') {
1.218 albertel 8630: # FIXME - not supporting calls for a specific user
1.620 albertel 8631: return $env{join('.',('request.course',$qualifier))};
1.48 www 8632: # ------------------------------------------------------------------- user.role
8633: } elsif ($space eq 'role') {
1.218 albertel 8634: # FIXME - not supporting calls for a specific user
1.620 albertel 8635: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8636: if ($qualifier eq 'value') {
8637: return $role;
8638: } elsif ($qualifier eq 'extent') {
8639: return $where;
8640: }
8641: # ----------------------------------------------------------------- user.domain
8642: } elsif ($space eq 'domain') {
1.218 albertel 8643: return $udom;
1.48 www 8644: # ------------------------------------------------------------------- user.name
8645: } elsif ($space eq 'name') {
1.218 albertel 8646: return $uname;
1.48 www 8647: # ---------------------------------------------------- Any other user namespace
1.29 www 8648: } else {
1.359 albertel 8649: my %reply;
8650: if (!$publicuser) {
8651: %reply=&get($space,[$qualifierrest],$udom,$uname);
8652: }
8653: return $reply{$qualifierrest};
1.48 www 8654: }
1.236 www 8655: } elsif ($realm eq 'query') {
8656: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8657: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8658: [$spacequalifierrest]);
1.620 albertel 8659: return $env{'form.'.$spacequalifierrest};
1.236 www 8660: } elsif ($realm eq 'request') {
1.48 www 8661: # ------------------------------------------------------------- request.browser
8662: if ($space eq 'browser') {
1.430 www 8663: if ($qualifier eq 'textremote') {
1.676 albertel 8664: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8665: return 1;
8666: } else {
8667: return 0;
8668: }
8669: } else {
1.620 albertel 8670: return $env{'browser.'.$qualifier};
1.430 www 8671: }
1.57 www 8672: # ------------------------------------------------------------ request.filename
8673: } else {
1.620 albertel 8674: return $env{'request.'.$spacequalifierrest};
1.29 www 8675: }
1.28 www 8676: } elsif ($realm eq 'course') {
1.48 www 8677: # ---------------------------------------------------------- course.description
1.620 albertel 8678: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8679: } elsif ($realm eq 'resource') {
1.165 www 8680:
1.620 albertel 8681: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8682: if (!$symbparm) { $symbparm=&symbread(); }
8683: }
1.693 albertel 8684:
8685: if ($space eq 'title') {
8686: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8687: return &gettitle($symbparm);
8688: }
8689:
8690: if ($space eq 'map') {
8691: my ($map) = &decode_symb($symbparm);
8692: return &symbread($map);
8693: }
1.905 albertel 8694: if ($space eq 'filename') {
8695: if ($symbparm) {
8696: return &clutter((&decode_symb($symbparm))[2]);
8697: }
8698: return &hreflocation('',$env{'request.filename'});
8699: }
1.693 albertel 8700:
8701: my ($section, $group, @groups);
1.593 albertel 8702: my ($courselevelm,$courselevel);
1.539 albertel 8703: if ($symbparm && defined($courseid) &&
1.620 albertel 8704: $courseid eq $env{'request.course.id'}) {
1.165 www 8705:
1.218 albertel 8706: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8707:
1.60 www 8708: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8709: my $symbp=$symbparm;
1.735 albertel 8710: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8711:
8712: my $symbparm=$symbp.'.'.$spacequalifierrest;
8713: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8714:
1.620 albertel 8715: if (($env{'user.name'} eq $uname) &&
8716: ($env{'user.domain'} eq $udom)) {
8717: $section=$env{'request.course.sec'};
1.733 raeburn 8718: @groups = split(/:/,$env{'request.course.groups'});
8719: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8720: } else {
1.539 albertel 8721: if (! defined($usection)) {
1.551 albertel 8722: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8723: } else {
8724: $section = $usection;
8725: }
1.733 raeburn 8726: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8727: }
8728:
8729: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8730: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8731: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8732:
1.593 albertel 8733: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8734: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8735: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8736:
1.60 www 8737: # ----------------------------------------------------------- first, check user
1.624 albertel 8738:
8739: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8740: ([$courselevelr,'resource'],
8741: [$courselevelm,'map' ],
8742: [$courselevel, 'course' ]));
1.931 albertel 8743: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8744:
1.594 albertel 8745: # ------------------------------------------------ second, check some of course
1.684 raeburn 8746: my $coursereply;
1.691 raeburn 8747: if (@groups > 0) {
8748: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8749: $mapparm,$spacequalifierrest);
1.927 albertel 8750: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8751: }
1.96 www 8752:
1.684 raeburn 8753: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8754: $env{'course.'.$courseid.'.domain'},
8755: 'course',
8756: ([$seclevelr, 'resource'],
8757: [$seclevelm, 'map' ],
8758: [$seclevel, 'course' ],
8759: [$courselevelr,'resource']));
8760: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8761:
1.60 www 8762: # ------------------------------------------------------ third, check map parms
1.218 albertel 8763: my %parmhash=();
8764: my $thisparm='';
8765: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8766: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8767: &GDBM_READER(),0640)) {
1.218 albertel 8768: $thisparm=$parmhash{$symbparm};
8769: untie(%parmhash);
8770: }
1.927 albertel 8771: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8772: }
1.594 albertel 8773: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8774:
1.218 albertel 8775: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8776: my $filename;
8777: if (!$symbparm) { $symbparm=&symbread(); }
8778: if ($symbparm) {
1.409 www 8779: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8780: } else {
1.620 albertel 8781: $filename=$env{'request.filename'};
1.282 albertel 8782: }
8783: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8784: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8785: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8786: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8787:
1.927 albertel 8788: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8789: if ($symbparm && defined($courseid) &&
1.620 albertel 8790: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8791: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8792: $env{'course.'.$courseid.'.domain'},
8793: 'course',
1.927 albertel 8794: ([$courselevelm,'map' ],
8795: [$courselevel, 'course']));
8796: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8797: }
1.145 www 8798: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8799: unless ($space eq '0') {
1.336 albertel 8800: my @parts=split(/_/,$space);
8801: my $id=pop(@parts);
8802: my $part=join('_',@parts);
8803: if ($part eq '') { $part='0'; }
1.927 albertel 8804: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8805: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8806: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8807: }
1.395 albertel 8808: if ($recurse) { return undef; }
8809: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8810: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8811: # ---------------------------------------------------- Any other user namespace
8812: } elsif ($realm eq 'environment') {
8813: # ----------------------------------------------------------------- environment
1.620 albertel 8814: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8815: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8816: } else {
1.770 albertel 8817: if ($uname eq 'anonymous' && $udom eq '') {
8818: return '';
8819: }
1.219 albertel 8820: my %returnhash=&userenvironment($udom,$uname,
8821: $spacequalifierrest);
8822: return $returnhash{$spacequalifierrest};
8823: }
1.28 www 8824: } elsif ($realm eq 'system') {
1.48 www 8825: # ----------------------------------------------------------------- system.time
8826: if ($space eq 'time') {
8827: return time;
8828: }
1.696 albertel 8829: } elsif ($realm eq 'server') {
8830: # ----------------------------------------------------------------- system.time
8831: if ($space eq 'name') {
8832: return $ENV{'SERVER_NAME'};
8833: }
1.28 www 8834: }
1.48 www 8835: return '';
1.61 www 8836: }
8837:
1.927 albertel 8838: sub get_reply {
8839: my ($reply_value) = @_;
1.940 raeburn 8840: if (ref($reply_value) eq 'ARRAY') {
8841: if (wantarray) {
8842: return @$reply_value;
8843: }
8844: return $reply_value->[0];
8845: } else {
8846: return $reply_value;
1.927 albertel 8847: }
8848: }
8849:
1.691 raeburn 8850: sub check_group_parms {
8851: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8852: my @groupitems = ();
8853: my $resultitem;
1.927 albertel 8854: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8855: foreach my $group (@{$groups}) {
8856: foreach my $level (@levels) {
1.927 albertel 8857: my $item = $courseid.'.['.$group.'].'.$level->[0];
8858: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8859: }
8860: }
8861: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8862: $env{'course.'.$courseid.'.domain'},
8863: 'course',@groupitems);
8864: return $coursereply;
8865: }
8866:
8867: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8868: my ($courseid,@groups) = @_;
8869: @groups = sort(@groups);
1.691 raeburn 8870: return @groups;
8871: }
8872:
1.395 albertel 8873: sub packages_tab_default {
8874: my ($uri,$varname)=@_;
8875: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8876:
8877: my (@extension,@specifics,$do_default);
8878: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8879: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8880: if ($pack_type eq 'default') {
8881: $do_default=1;
8882: } elsif ($pack_type eq 'extension') {
8883: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8884: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8885: # only look at packages defaults for packages that this id is
1.738 albertel 8886: push(@specifics,[$package,$pack_type,$pack_part]);
8887: }
8888: }
8889: # first look for a package that matches the requested part id
8890: foreach my $package (@specifics) {
8891: my (undef,$pack_type,$pack_part)=@{$package};
8892: next if ($pack_part ne $part);
8893: if (defined($packagetab{"$pack_type&$name&default"})) {
8894: return $packagetab{"$pack_type&$name&default"};
8895: }
8896: }
8897: # look for any possible matching non extension_ package
8898: foreach my $package (@specifics) {
8899: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8900: if (defined($packagetab{"$pack_type&$name&default"})) {
8901: return $packagetab{"$pack_type&$name&default"};
8902: }
1.585 albertel 8903: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8904: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8905: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8906: }
8907: }
1.738 albertel 8908: # look for any posible extension_ match
8909: foreach my $package (@extension) {
8910: my ($package,$pack_type)=@{$package};
8911: if (defined($packagetab{"$pack_type&$name&default"})) {
8912: return $packagetab{"$pack_type&$name&default"};
8913: }
8914: if (defined($packagetab{$package."&$name&default"})) {
8915: return $packagetab{$package."&$name&default"};
8916: }
8917: }
8918: # look for a global default setting
8919: if ($do_default && defined($packagetab{"default&$name&default"})) {
8920: return $packagetab{"default&$name&default"};
8921: }
1.395 albertel 8922: return undef;
8923: }
8924:
1.334 albertel 8925: sub add_prefix_and_part {
8926: my ($prefix,$part)=@_;
8927: my $keyroot;
8928: if (defined($prefix) && $prefix !~ /^__/) {
8929: # prefix that has a part already
8930: $keyroot=$prefix;
8931: } elsif (defined($prefix)) {
8932: # prefix that is missing a part
8933: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8934: } else {
8935: # no prefix at all
8936: if (defined($part)) { $keyroot='_'.$part; }
8937: }
8938: return $keyroot;
8939: }
8940:
1.71 www 8941: # ---------------------------------------------------------------- Get metadata
8942:
1.599 albertel 8943: my %metaentry;
1.1070 www 8944: my %importedpartids;
1.71 www 8945: sub metadata {
1.176 www 8946: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8947: $uri=&declutter($uri);
1.288 albertel 8948: # if it is a non metadata possible uri return quickly
1.529 albertel 8949: if (($uri eq '') ||
8950: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8951: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108 raeburn 8952: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 8953: return undef;
8954: }
8955: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8956: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8957: return undef;
1.288 albertel 8958: }
1.73 www 8959: my $filename=$uri;
8960: $uri=~s/\.meta$//;
1.172 www 8961: #
8962: # Is the metadata already cached?
1.177 www 8963: # Look at timestamp of caching
1.172 www 8964: # Everything is cached by the main uri, libraries are never directly cached
8965: #
1.428 albertel 8966: if (!defined($liburi)) {
1.599 albertel 8967: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8968: if (defined($cached)) { return $result->{':'.$what}; }
8969: }
8970: {
1.1069 www 8971: # Imported parts would go here
1.1070 www 8972: my %importedids=();
8973: my @origfileimportpartids=();
1.1069 www 8974: my $importedparts=0;
1.172 www 8975: #
8976: # Is this a recursive call for a library?
8977: #
1.599 albertel 8978: # if (! exists($metacache{$uri})) {
8979: # $metacache{$uri}={};
8980: # }
1.924 albertel 8981: my $cachetime = 60*60;
1.171 www 8982: if ($liburi) {
8983: $liburi=&declutter($liburi);
8984: $filename=$liburi;
1.401 bowersj2 8985: } else {
1.599 albertel 8986: &devalidate_cache_new('meta',$uri);
8987: undef(%metaentry);
1.401 bowersj2 8988: }
1.140 www 8989: my %metathesekeys=();
1.73 www 8990: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8991: my $metastring;
1.924 albertel 8992: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8993: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8994: $metastring =
1.929 albertel 8995: &Apache::lonnet::ssi_body($which,
1.924 albertel 8996: ('grade_target' => 'meta'));
8997: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 8998: } elsif (($uri !~ m -^(editupload)/-) &&
8999: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 9000: my $file=&filelocation('',&clutter($filename));
1.599 albertel 9001: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 9002: $metastring=&getfile($file);
1.489 albertel 9003: }
1.208 albertel 9004: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 9005: my $token;
1.140 www 9006: undef %metathesekeys;
1.71 www 9007: while ($token=$parser->get_token) {
1.339 albertel 9008: if ($token->[0] eq 'S') {
9009: if (defined($token->[2]->{'package'})) {
1.172 www 9010: #
9011: # This is a package - get package info
9012: #
1.339 albertel 9013: my $package=$token->[2]->{'package'};
9014: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9015: if (defined($token->[2]->{'id'})) {
9016: $keyroot.='_'.$token->[2]->{'id'};
9017: }
1.599 albertel 9018: if ($metaentry{':packages'}) {
9019: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 9020: } else {
1.599 albertel 9021: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 9022: }
1.736 albertel 9023: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 9024: my $part=$keyroot;
9025: $part=~s/^\_//;
1.736 albertel 9026: if ($pack_entry=~/^\Q$package\E\&/ ||
9027: $pack_entry=~/^\Q$package\E_0\&/) {
9028: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 9029: # ignore package.tab specified default values
9030: # here &package_tab_default() will fetch those
9031: if ($subp eq 'default') { next; }
1.736 albertel 9032: my $value=$packagetab{$pack_entry};
1.432 albertel 9033: my $unikey;
9034: if ($pack =~ /_0$/) {
9035: $unikey='parameter_0_'.$name;
9036: $part=0;
9037: } else {
9038: $unikey='parameter'.$keyroot.'_'.$name;
9039: }
1.339 albertel 9040: if ($subp eq 'display') {
9041: $value.=' [Part: '.$part.']';
9042: }
1.599 albertel 9043: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 9044: $metathesekeys{$unikey}=1;
1.599 albertel 9045: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9046: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 9047: }
1.599 albertel 9048: if (defined($metaentry{':'.$unikey.'.default'})) {
9049: $metaentry{':'.$unikey}=
9050: $metaentry{':'.$unikey.'.default'};
1.356 albertel 9051: }
1.339 albertel 9052: }
9053: }
9054: } else {
1.172 www 9055: #
9056: # This is not a package - some other kind of start tag
1.339 albertel 9057: #
9058: my $entry=$token->[1];
1.1068 www 9059: my $unikey='';
1.175 www 9060:
1.339 albertel 9061: if ($entry eq 'import') {
1.175 www 9062: #
9063: # Importing a library here
1.339 albertel 9064: #
1.1067 www 9065: my $location=$parser->get_text('/import');
9066: my $dir=$filename;
9067: $dir=~s|[^/]*$||;
9068: $location=&filelocation($dir,$location);
1.1069 www 9069:
1.1068 www 9070: my $importmode=$token->[2]->{'importmode'};
9071: if ($importmode eq 'problem') {
1.1069 www 9072: # Import as problem/response
1.1068 www 9073: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9074: } elsif ($importmode eq 'part') {
9075: # Import as part(s)
1.1069 www 9076: $importedparts=1;
9077: # We need to get the original file and the imported file to get the part order correct
9078: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9079: # Load and inspect original file
1.1070 www 9080: if ($#origfileimportpartids<0) {
9081: undef(%importedpartids);
9082: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9083: my $origfile=&getfile($origfilelocation);
9084: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9085: }
9086:
1.1069 www 9087: # Load and inspect imported file
9088: my $impfile=&getfile($location);
9089: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9090: if ($#impfilepartids>=0) {
9091: # This problem had parts
1.1070 www 9092: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 9093: } else {
9094: # Importing by turning a single problem into a problem part
9095: # It gets the import-tags ID as part-ID
9096: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 9097: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 9098: }
1.1068 www 9099: } else {
9100: # Normal import
9101: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9102: if (defined($token->[2]->{'id'})) {
9103: $unikey.='_'.$token->[2]->{'id'};
9104: }
1.1067 www 9105: }
9106:
1.339 albertel 9107: if ($depthcount<20) {
1.736 albertel 9108: my $metadata =
9109: &metadata($uri,'keys', $location,$unikey,
9110: $depthcount+1);
9111: foreach my $meta (split(',',$metadata)) {
9112: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9113: $metathesekeys{$meta}=1;
1.339 albertel 9114: }
1.1068 www 9115:
9116: }
1.1067 www 9117: } else {
9118: #
9119: # Not importing, some other kind of non-package, non-library start tag
9120: #
9121: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9122: if (defined($token->[2]->{'id'})) {
9123: $unikey.='_'.$token->[2]->{'id'};
9124: }
1.339 albertel 9125: if (defined($token->[2]->{'name'})) {
9126: $unikey.='_'.$token->[2]->{'name'};
9127: }
9128: $metathesekeys{$unikey}=1;
1.736 albertel 9129: foreach my $param (@{$token->[3]}) {
9130: $metaentry{':'.$unikey.'.'.$param} =
9131: $token->[2]->{$param};
1.339 albertel 9132: }
9133: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 9134: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 9135: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9136: # only ws inside the tag, and not in default, so use default
9137: # as value
1.599 albertel 9138: $metaentry{':'.$unikey}=$default;
1.908 albertel 9139: } elsif ( $internaltext =~ /\S/ ) {
9140: # something interesting inside the tag
9141: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 9142: } else {
1.908 albertel 9143: # no interesting values, don't set a default
1.339 albertel 9144: }
1.172 www 9145: # end of not-a-package not-a-library import
1.339 albertel 9146: }
1.172 www 9147: # end of not-a-package start tag
1.339 albertel 9148: }
1.172 www 9149: # the next is the end of "start tag"
1.339 albertel 9150: }
9151: }
1.483 albertel 9152: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 9153: $extension = lc($extension);
9154: if ($extension eq 'htm') { $extension='html'; }
9155:
1.737 albertel 9156: foreach my $key (keys(%packagetab)) {
1.483 albertel 9157: #no specific packages #how's our extension
9158: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 9159: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 9160: \%metathesekeys);
9161: }
1.883 albertel 9162:
9163: if (!exists($metaentry{':packages'})
9164: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 9165: foreach my $key (keys(%packagetab)) {
1.483 albertel 9166: #no specific packages well let's get default then
9167: if ($key!~/^default&/) { next; }
1.488 albertel 9168: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 9169: \%metathesekeys);
9170: }
9171: }
1.338 www 9172: # are there custom rights to evaluate
1.599 albertel 9173: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 9174:
1.338 www 9175: #
9176: # Importing a rights file here
1.339 albertel 9177: #
9178: unless ($depthcount) {
1.599 albertel 9179: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 9180: my $dir=$filename;
9181: $dir=~s|[^/]*$||;
9182: $location=&filelocation($dir,$location);
1.736 albertel 9183: my $rights_metadata =
9184: &metadata($uri,'keys',$location,'_rights',
9185: $depthcount+1);
9186: foreach my $rights (split(',',$rights_metadata)) {
9187: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9188: $metathesekeys{$rights}=1;
1.339 albertel 9189: }
9190: }
9191: }
1.737 albertel 9192: # uniqifiy package listing
9193: my %seen;
9194: my @uniq_packages =
9195: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9196: $metaentry{':packages'} = join(',',@uniq_packages);
9197:
1.1070 www 9198: if ($importedparts) {
9199: # We had imported parts and need to rebuild partorder
9200: $metaentry{':partorder'}='';
9201: $metathesekeys{'partorder'}=1;
9202: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9203: if ($origfileimportpartids[$index] eq 'part') {
9204: # original part, part of the problem
9205: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9206: } else {
9207: # we have imported parts at this position
9208: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9209: }
9210: }
9211: $metaentry{':partorder'}=~s/^\,//;
9212: }
9213:
1.737 albertel 9214: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 9215: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9216: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 9217: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 9218: # this is the end of "was not already recently cached
1.71 www 9219: }
1.599 albertel 9220: return $metaentry{':'.$what};
1.261 albertel 9221: }
9222:
1.488 albertel 9223: sub metadata_create_package_def {
1.483 albertel 9224: my ($uri,$key,$package,$metathesekeys)=@_;
9225: my ($pack,$name,$subp)=split(/\&/,$key);
9226: if ($subp eq 'default') { next; }
9227:
1.599 albertel 9228: if (defined($metaentry{':packages'})) {
9229: $metaentry{':packages'}.=','.$package;
1.483 albertel 9230: } else {
1.599 albertel 9231: $metaentry{':packages'}=$package;
1.483 albertel 9232: }
9233: my $value=$packagetab{$key};
9234: my $unikey;
9235: $unikey='parameter_0_'.$name;
1.599 albertel 9236: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 9237: $$metathesekeys{$unikey}=1;
1.599 albertel 9238: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9239: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 9240: }
1.599 albertel 9241: if (defined($metaentry{':'.$unikey.'.default'})) {
9242: $metaentry{':'.$unikey}=
9243: $metaentry{':'.$unikey.'.default'};
1.483 albertel 9244: }
9245: }
9246:
1.261 albertel 9247: sub metadata_generate_part0 {
9248: my ($metadata,$metacache,$uri) = @_;
9249: my %allnames;
1.737 albertel 9250: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 9251: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 9252: my $part=$$metacache{':'.$metakey.'.part'};
9253: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 9254: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 9255: $allnames{$name}=$part;
9256: }
9257: }
9258: }
9259: foreach my $name (keys(%allnames)) {
9260: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 9261: my $key=":parameter_0_$name";
1.261 albertel 9262: $$metacache{"$key.part"}='0';
9263: $$metacache{"$key.name"}=$name;
1.428 albertel 9264: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 9265: $allnames{$name}.'_'.$name.
9266: '.type'};
1.428 albertel 9267: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 9268: '.display'};
1.644 www 9269: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 9270: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 9271: $$metacache{"$key.display"}=$olddis;
9272: }
1.71 www 9273: }
9274:
1.764 albertel 9275: # ------------------------------------------------------ Devalidate title cache
9276:
9277: sub devalidate_title_cache {
9278: my ($url)=@_;
9279: if (!$env{'request.course.id'}) { return; }
9280: my $symb=&symbread($url);
9281: if (!$symb) { return; }
9282: my $key=$env{'request.course.id'}."\0".$symb;
9283: &devalidate_cache_new('title',$key);
9284: }
9285:
1.1014 droeschl 9286: # ------------------------------------------------- Get the title of a course
9287:
9288: sub current_course_title {
9289: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9290: }
1.301 www 9291: # ------------------------------------------------- Get the title of a resource
9292:
9293: sub gettitle {
9294: my $urlsymb=shift;
9295: my $symb=&symbread($urlsymb);
1.534 albertel 9296: if ($symb) {
1.620 albertel 9297: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 9298: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 9299: if (defined($cached)) {
9300: return $result;
9301: }
1.534 albertel 9302: my ($map,$resid,$url)=&decode_symb($symb);
9303: my $title='';
1.907 albertel 9304: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9305: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9306: } else {
9307: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9308: &GDBM_READER(),0640)) {
9309: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9310: $title=$bighash{'title_'.$mapid.'.'.$resid};
9311: untie(%bighash);
9312: }
1.534 albertel 9313: }
9314: $title=~s/\&colon\;/\:/gs;
9315: if ($title) {
1.599 albertel 9316: return &do_cache_new('title',$key,$title,600);
1.534 albertel 9317: }
9318: $urlsymb=$url;
9319: }
9320: my $title=&metadata($urlsymb,'title');
9321: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9322: return $title;
1.301 www 9323: }
1.613 albertel 9324:
1.614 albertel 9325: sub get_slot {
9326: my ($which,$cnum,$cdom)=@_;
9327: if (!$cnum || !$cdom) {
1.790 albertel 9328: (undef,my $courseid)=&whichuser();
1.620 albertel 9329: $cdom=$env{'course.'.$courseid.'.domain'};
9330: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 9331: }
1.703 albertel 9332: my $key=join("\0",'slots',$cdom,$cnum,$which);
9333: my %slotinfo;
9334: if (exists($remembered{$key})) {
9335: $slotinfo{$which} = $remembered{$key};
9336: } else {
9337: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9338: &Apache::lonhomework::showhash(%slotinfo);
9339: my ($tmp)=keys(%slotinfo);
9340: if ($tmp=~/^error:/) { return (); }
9341: $remembered{$key} = $slotinfo{$which};
9342: }
1.616 albertel 9343: if (ref($slotinfo{$which}) eq 'HASH') {
9344: return %{$slotinfo{$which}};
9345: }
9346: return $slotinfo{$which};
1.614 albertel 9347: }
1.31 www 9348: # ------------------------------------------------- Update symbolic store links
9349:
9350: sub symblist {
9351: my ($mapname,%newhash)=@_;
1.438 www 9352: $mapname=&deversion(&declutter($mapname));
1.31 www 9353: my %hash;
1.620 albertel 9354: if (($env{'request.course.fn'}) && (%newhash)) {
9355: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9356: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 9357: foreach my $url (keys(%newhash)) {
1.711 albertel 9358: next if ($url eq 'last_known'
9359: && $env{'form.no_update_last_known'});
9360: $hash{declutter($url)}=&encode_symb($mapname,
9361: $newhash{$url}->[1],
9362: $newhash{$url}->[0]);
1.191 harris41 9363: }
1.31 www 9364: if (untie(%hash)) {
9365: return 'ok';
9366: }
9367: }
9368: }
9369: return 'error';
1.212 www 9370: }
9371:
9372: # --------------------------------------------------------------- Verify a symb
9373:
9374: sub symbverify {
1.510 www 9375: my ($symb,$thisurl)=@_;
9376: my $thisfn=$thisurl;
1.439 www 9377: $thisfn=&declutter($thisfn);
1.215 www 9378: # direct jump to resource in page or to a sequence - will construct own symbs
9379: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9380: # check URL part
1.409 www 9381: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 9382:
1.431 www 9383: unless ($url eq $thisfn) { return 0; }
1.213 www 9384:
1.216 www 9385: $symb=&symbclean($symb);
1.510 www 9386: $thisurl=&deversion($thisurl);
1.439 www 9387: $thisfn=&deversion($thisfn);
1.213 www 9388:
9389: my %bighash;
9390: my $okay=0;
1.431 www 9391:
1.620 albertel 9392: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9393: &GDBM_READER(),0640)) {
1.1032 raeburn 9394: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9395: $thisurl =~ s/\?.+$//;
9396: }
1.510 www 9397: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102 raeburn 9398: unless ($ids) {
9399: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9400: $ids=$bighash{$idkey};
1.216 www 9401: }
9402: if ($ids) {
9403: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 9404: foreach my $id (split(/\,/,$ids)) {
9405: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 9406: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9407: $symb =~ s/\?.+$//;
9408: }
1.216 www 9409: if (
9410: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9411: eq $symb) {
1.620 albertel 9412: if (($env{'request.role.adv'}) ||
1.1101 raeburn 9413: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9414: ($thisurl eq '/adm/navmaps')) {
1.582 albertel 9415: $okay=1;
9416: }
9417: }
1.216 www 9418: }
9419: }
1.213 www 9420: untie(%bighash);
9421: }
9422: return $okay;
1.31 www 9423: }
9424:
1.210 www 9425: # --------------------------------------------------------------- Clean-up symb
9426:
9427: sub symbclean {
9428: my $symb=shift;
1.568 albertel 9429: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 9430: # remove version from map
9431: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 9432:
1.210 www 9433: # remove version from URL
9434: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 9435:
1.507 www 9436: # remove wrapper
9437:
1.510 www 9438: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 9439: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 9440: return $symb;
1.409 www 9441: }
9442:
9443: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 9444:
9445: sub encode_symb {
9446: my ($map,$resid,$url)=@_;
9447: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9448: }
1.409 www 9449:
9450: sub decode_symb {
1.568 albertel 9451: my $symb=shift;
9452: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9453: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 9454: return (&fixversion($map),$resid,&fixversion($url));
9455: }
9456:
9457: sub fixversion {
9458: my $fn=shift;
1.609 banghart 9459: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 9460: my %bighash;
9461: my $uri=&clutter($fn);
1.620 albertel 9462: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 9463: # is this cached?
1.599 albertel 9464: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 9465: if (defined($cached)) { return $result; }
9466: # unfortunately not cached, or expired
1.620 albertel 9467: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 9468: &GDBM_READER(),0640)) {
9469: if ($bighash{'version_'.$uri}) {
9470: my $version=$bighash{'version_'.$uri};
1.444 www 9471: unless (($version eq 'mostrecent') ||
9472: ($version==&getversion($uri))) {
1.440 www 9473: $uri=~s/\.(\w+)$/\.$version\.$1/;
9474: }
9475: }
9476: untie %bighash;
1.413 www 9477: }
1.599 albertel 9478: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 9479: }
9480:
9481: sub deversion {
9482: my $url=shift;
9483: $url=~s/\.\d+\.(\w+)$/\.$1/;
9484: return $url;
1.210 www 9485: }
9486:
1.31 www 9487: # ------------------------------------------------------ Return symb list entry
9488:
9489: sub symbread {
1.249 www 9490: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 9491: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 9492: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 9493: # no filename provided? try from environment
1.44 www 9494: unless ($thisfn) {
1.620 albertel 9495: if ($env{'request.symb'}) {
9496: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 9497: }
1.620 albertel 9498: $thisfn=$env{'request.filename'};
1.44 www 9499: }
1.569 albertel 9500: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 9501: # is that filename actually a symb? Verify, clean, and return
9502: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 9503: if (&symbverify($thisfn,$1)) {
1.620 albertel 9504: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 9505: }
1.242 www 9506: }
1.44 www 9507: $thisfn=declutter($thisfn);
1.31 www 9508: my %hash;
1.37 www 9509: my %bighash;
9510: my $syval='';
1.620 albertel 9511: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 9512: my $targetfn = $thisfn;
1.609 banghart 9513: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 9514: $targetfn = 'adm/wrapper/'.$thisfn;
9515: }
1.687 albertel 9516: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9517: $targetfn=$1;
9518: }
1.620 albertel 9519: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9520: &GDBM_READER(),0640)) {
1.481 raeburn 9521: $syval=$hash{$targetfn};
1.37 www 9522: untie(%hash);
9523: }
9524: # ---------------------------------------------------------- There was an entry
9525: if ($syval) {
1.601 albertel 9526: #unless ($syval=~/\_\d+$/) {
1.620 albertel 9527: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 9528: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9529: #return $env{$cache_str}='';
1.601 albertel 9530: #}
9531: #$syval.=$1;
9532: #}
1.37 www 9533: } else {
9534: # ------------------------------------------------------- Was not in symb table
1.620 albertel 9535: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9536: &GDBM_READER(),0640)) {
1.37 www 9537: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 9538: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 9539: unless ($ids) {
9540: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 9541: }
9542: unless ($ids) {
9543: # alias?
9544: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 9545: }
1.37 www 9546: if ($ids) {
9547: # ------------------------------------------------------------------- Has ID(s)
9548: my @possibilities=split(/\,/,$ids);
1.39 www 9549: if ($#possibilities==0) {
9550: # ----------------------------------------------- There is only one possibility
1.37 www 9551: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 9552: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9553: $resid,$thisfn);
1.249 www 9554: } elsif (!$donotrecurse) {
1.39 www 9555: # ------------------------------------------ There is more than one possibility
9556: my $realpossible=0;
1.800 albertel 9557: foreach my $id (@possibilities) {
9558: my $file=$bighash{'src_'.$id};
1.39 www 9559: if (&allowed('bre',$file)) {
1.800 albertel 9560: my ($mapid,$resid)=split(/\./,$id);
1.39 www 9561: if ($bighash{'map_type_'.$mapid} ne 'page') {
9562: $realpossible++;
1.626 albertel 9563: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9564: $resid,$thisfn);
1.39 www 9565: }
9566: }
1.191 harris41 9567: }
1.39 www 9568: if ($realpossible!=1) { $syval=''; }
1.249 www 9569: } else {
9570: $syval='';
1.37 www 9571: }
9572: }
9573: untie(%bighash)
1.481 raeburn 9574: }
1.31 www 9575: }
1.62 www 9576: if ($syval) {
1.620 albertel 9577: return $env{$cache_str}=$syval;
1.62 www 9578: }
1.31 www 9579: }
1.949 raeburn 9580: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9581: return $env{$cache_str}='';
1.31 www 9582: }
9583:
9584: # ---------------------------------------------------------- Return random seed
9585:
1.32 www 9586: sub numval {
9587: my $txt=shift;
9588: $txt=~tr/A-J/0-9/;
9589: $txt=~tr/a-j/0-9/;
9590: $txt=~tr/K-T/0-9/;
9591: $txt=~tr/k-t/0-9/;
9592: $txt=~tr/U-Z/0-5/;
9593: $txt=~tr/u-z/0-5/;
9594: $txt=~s/\D//g;
1.564 albertel 9595: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 9596: return int($txt);
1.368 albertel 9597: }
9598:
1.484 albertel 9599: sub numval2 {
9600: my $txt=shift;
9601: $txt=~tr/A-J/0-9/;
9602: $txt=~tr/a-j/0-9/;
9603: $txt=~tr/K-T/0-9/;
9604: $txt=~tr/k-t/0-9/;
9605: $txt=~tr/U-Z/0-5/;
9606: $txt=~tr/u-z/0-5/;
9607: $txt=~s/\D//g;
9608: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9609: my $total;
9610: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9611: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9612: return int($total);
9613: }
9614:
1.575 albertel 9615: sub numval3 {
9616: use integer;
9617: my $txt=shift;
9618: $txt=~tr/A-J/0-9/;
9619: $txt=~tr/a-j/0-9/;
9620: $txt=~tr/K-T/0-9/;
9621: $txt=~tr/k-t/0-9/;
9622: $txt=~tr/U-Z/0-5/;
9623: $txt=~tr/u-z/0-5/;
9624: $txt=~s/\D//g;
9625: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9626: my $total;
9627: foreach my $val (@txts) { $total+=$val; }
9628: if ($_64bit) { $total=(($total<<32)>>32); }
9629: return $total;
9630: }
9631:
1.675 albertel 9632: sub digest {
9633: my ($data)=@_;
9634: my $digest=&Digest::MD5::md5($data);
9635: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9636: my ($e,$f);
9637: {
9638: use integer;
9639: $e=($a+$b);
9640: $f=($c+$d);
9641: if ($_64bit) {
9642: $e=(($e<<32)>>32);
9643: $f=(($f<<32)>>32);
9644: }
9645: }
9646: if (wantarray) {
9647: return ($e,$f);
9648: } else {
9649: my $g;
9650: {
9651: use integer;
9652: $g=($e+$f);
9653: if ($_64bit) {
9654: $g=(($g<<32)>>32);
9655: }
9656: }
9657: return $g;
9658: }
9659: }
9660:
1.368 albertel 9661: sub latest_rnd_algorithm_id {
1.675 albertel 9662: return '64bit5';
1.366 albertel 9663: }
1.32 www 9664:
1.503 albertel 9665: sub get_rand_alg {
9666: my ($courseid)=@_;
1.790 albertel 9667: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9668: if ($courseid) {
1.620 albertel 9669: return $env{"course.$courseid.rndseed"};
1.503 albertel 9670: }
9671: return &latest_rnd_algorithm_id();
9672: }
9673:
1.562 albertel 9674: sub validCODE {
9675: my ($CODE)=@_;
9676: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9677: return 0;
9678: }
9679:
1.491 albertel 9680: sub getCODE {
1.620 albertel 9681: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9682: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9683: defined($Apache::lonhomework::parsing_a_task) ) &&
9684: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9685: return $Apache::lonhomework::history{'resource.CODE'};
9686: }
9687: return undef;
9688: }
9689:
1.31 www 9690: sub rndseed {
1.155 albertel 9691: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 9692: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9693: if (!defined($symb)) {
1.366 albertel 9694: unless ($symb=$wsymb) { return time; }
9695: }
9696: if (!$courseid) { $courseid=$wcourseid; }
9697: if (!$domain) { $domain=$wdomain; }
9698: if (!$username) { $username=$wusername }
1.503 albertel 9699: my $which=&get_rand_alg();
1.1110 www 9700:
1.491 albertel 9701: if (defined(&getCODE())) {
1.675 albertel 9702: if ($which eq '64bit5') {
9703: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9704: } elsif ($which eq '64bit4') {
1.575 albertel 9705: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9706: } else {
9707: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9708: }
1.675 albertel 9709: } elsif ($which eq '64bit5') {
9710: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9711: } elsif ($which eq '64bit4') {
9712: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9713: } elsif ($which eq '64bit3') {
9714: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9715: } elsif ($which eq '64bit2') {
9716: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9717: } elsif ($which eq '64bit') {
9718: return &rndseed_64bit($symb,$courseid,$domain,$username);
9719: }
9720: return &rndseed_32bit($symb,$courseid,$domain,$username);
9721: }
9722:
9723: sub rndseed_32bit {
9724: my ($symb,$courseid,$domain,$username)=@_;
9725: {
9726: use integer;
9727: my $symbchck=unpack("%32C*",$symb) << 27;
9728: my $symbseed=numval($symb) << 22;
9729: my $namechck=unpack("%32C*",$username) << 17;
9730: my $nameseed=numval($username) << 12;
9731: my $domainseed=unpack("%32C*",$domain) << 7;
9732: my $courseseed=unpack("%32C*",$courseid);
9733: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9734: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9735: #&logthis("rndseed :$num:$symb");
1.564 albertel 9736: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9737: return $num;
9738: }
9739: }
9740:
9741: sub rndseed_64bit {
9742: my ($symb,$courseid,$domain,$username)=@_;
9743: {
9744: use integer;
9745: my $symbchck=unpack("%32S*",$symb) << 21;
9746: my $symbseed=numval($symb) << 10;
9747: my $namechck=unpack("%32S*",$username);
9748:
9749: my $nameseed=numval($username) << 21;
9750: my $domainseed=unpack("%32S*",$domain) << 10;
9751: my $courseseed=unpack("%32S*",$courseid);
9752:
9753: my $num1=$symbchck+$symbseed+$namechck;
9754: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9755: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9756: #&logthis("rndseed :$num:$symb");
1.564 albertel 9757: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9758: return "$num1,$num2";
1.155 albertel 9759: }
1.366 albertel 9760: }
9761:
1.443 albertel 9762: sub rndseed_64bit2 {
9763: my ($symb,$courseid,$domain,$username)=@_;
9764: {
9765: use integer;
9766: # strings need to be an even # of cahracters long, it it is odd the
9767: # last characters gets thrown away
9768: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9769: my $symbseed=numval($symb) << 10;
9770: my $namechck=unpack("%32S*",$username.' ');
9771:
9772: my $nameseed=numval($username) << 21;
1.501 albertel 9773: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9774: my $courseseed=unpack("%32S*",$courseid.' ');
9775:
9776: my $num1=$symbchck+$symbseed+$namechck;
9777: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9778: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9779: #&logthis("rndseed :$num:$symb");
1.803 albertel 9780: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9781: return "$num1,$num2";
9782: }
9783: }
9784:
9785: sub rndseed_64bit3 {
9786: my ($symb,$courseid,$domain,$username)=@_;
9787: {
9788: use integer;
9789: # strings need to be an even # of cahracters long, it it is odd the
9790: # last characters gets thrown away
9791: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9792: my $symbseed=numval2($symb) << 10;
9793: my $namechck=unpack("%32S*",$username.' ');
9794:
9795: my $nameseed=numval2($username) << 21;
1.443 albertel 9796: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9797: my $courseseed=unpack("%32S*",$courseid.' ');
9798:
9799: my $num1=$symbchck+$symbseed+$namechck;
9800: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9801: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9802: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9803: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 9804:
1.503 albertel 9805: return "$num1:$num2";
1.443 albertel 9806: }
9807: }
9808:
1.575 albertel 9809: sub rndseed_64bit4 {
9810: my ($symb,$courseid,$domain,$username)=@_;
9811: {
9812: use integer;
9813: # strings need to be an even # of cahracters long, it it is odd the
9814: # last characters gets thrown away
9815: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9816: my $symbseed=numval3($symb) << 10;
9817: my $namechck=unpack("%32S*",$username.' ');
9818:
9819: my $nameseed=numval3($username) << 21;
9820: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9821: my $courseseed=unpack("%32S*",$courseid.' ');
9822:
9823: my $num1=$symbchck+$symbseed+$namechck;
9824: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9825: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9826: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9827: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 9828:
1.575 albertel 9829: return "$num1:$num2";
9830: }
9831: }
9832:
1.675 albertel 9833: sub rndseed_64bit5 {
9834: my ($symb,$courseid,$domain,$username)=@_;
9835: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9836: return "$num1:$num2";
9837: }
9838:
1.366 albertel 9839: sub rndseed_CODE_64bit {
9840: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9841: {
1.366 albertel 9842: use integer;
1.443 albertel 9843: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9844: my $symbseed=numval2($symb);
1.491 albertel 9845: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9846: my $CODEseed=numval(&getCODE());
1.443 albertel 9847: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9848: my $num1=$symbseed+$CODEchck;
9849: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9850: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9851: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9852: if ($_64bit) { $num1=(($num1<<32)>>32); }
9853: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9854: return "$num1:$num2";
1.366 albertel 9855: }
9856: }
9857:
1.575 albertel 9858: sub rndseed_CODE_64bit4 {
9859: my ($symb,$courseid,$domain,$username)=@_;
9860: {
9861: use integer;
9862: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9863: my $symbseed=numval3($symb);
9864: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9865: my $CODEseed=numval3(&getCODE());
9866: my $courseseed=unpack("%32S*",$courseid.' ');
9867: my $num1=$symbseed+$CODEchck;
9868: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9869: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9870: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9871: if ($_64bit) { $num1=(($num1<<32)>>32); }
9872: if ($_64bit) { $num2=(($num2<<32)>>32); }
9873: return "$num1:$num2";
9874: }
9875: }
9876:
1.675 albertel 9877: sub rndseed_CODE_64bit5 {
9878: my ($symb,$courseid,$domain,$username)=@_;
9879: my $code = &getCODE();
9880: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9881: return "$num1:$num2";
9882: }
9883:
1.366 albertel 9884: sub setup_random_from_rndseed {
9885: my ($rndseed)=@_;
1.503 albertel 9886: if ($rndseed =~/([,:])/) {
9887: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9888: &Math::Random::random_set_seed(abs($num1),abs($num2));
9889: } else {
9890: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9891: }
1.36 albertel 9892: }
9893:
1.474 albertel 9894: sub latest_receipt_algorithm_id {
1.835 albertel 9895: return 'receipt3';
1.474 albertel 9896: }
9897:
1.480 www 9898: sub recunique {
9899: my $fucourseid=shift;
9900: my $unique;
1.835 albertel 9901: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9902: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9903: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9904: } else {
9905: $unique=$perlvar{'lonReceipt'};
9906: }
9907: return unpack("%32C*",$unique);
9908: }
9909:
9910: sub recprefix {
9911: my $fucourseid=shift;
9912: my $prefix;
1.835 albertel 9913: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9914: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9915: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9916: } else {
9917: $prefix=$perlvar{'lonHostID'};
9918: }
9919: return unpack("%32C*",$prefix);
9920: }
9921:
1.76 www 9922: sub ireceipt {
1.474 albertel 9923: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9924:
9925: my $return =&recprefix($fucourseid).'-';
9926:
9927: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9928: $env{'request.state'} eq 'construct') {
9929: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9930: return $return;
9931: }
9932:
1.76 www 9933: my $cuname=unpack("%32C*",$funame);
9934: my $cudom=unpack("%32C*",$fudom);
9935: my $cucourseid=unpack("%32C*",$fucourseid);
9936: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9937: my $cunique=&recunique($fucourseid);
1.474 albertel 9938: my $cpart=unpack("%32S*",$part);
1.835 albertel 9939: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9940:
1.790 albertel 9941: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9942:
9943: $return.= ($cunique%$cuname+
9944: $cunique%$cudom+
9945: $cusymb%$cuname+
9946: $cusymb%$cudom+
9947: $cucourseid%$cuname+
9948: $cucourseid%$cudom+
9949: $cpart%$cuname+
9950: $cpart%$cudom);
9951: } else {
9952: $return.= ($cunique%$cuname+
9953: $cunique%$cudom+
9954: $cusymb%$cuname+
9955: $cusymb%$cudom+
9956: $cucourseid%$cuname+
9957: $cucourseid%$cudom);
9958: }
9959: return $return;
1.76 www 9960: }
9961:
9962: sub receipt {
1.474 albertel 9963: my ($part)=@_;
1.790 albertel 9964: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9965: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9966: }
1.260 ng 9967:
1.790 albertel 9968: sub whichuser {
9969: my ($passedsymb)=@_;
9970: my ($symb,$courseid,$domain,$name,$publicuser);
9971: if (defined($env{'form.grade_symb'})) {
9972: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9973: my $allowed=&allowed('vgr',$tmp_courseid);
9974: if (!$allowed &&
9975: exists($env{'request.course.sec'}) &&
9976: $env{'request.course.sec'} !~ /^\s*$/) {
9977: $allowed=&allowed('vgr',$tmp_courseid.
9978: '/'.$env{'request.course.sec'});
9979: }
9980: if ($allowed) {
9981: ($symb)=&get_env_multiple('form.grade_symb');
9982: $courseid=$tmp_courseid;
9983: ($domain)=&get_env_multiple('form.grade_domain');
9984: ($name)=&get_env_multiple('form.grade_username');
9985: return ($symb,$courseid,$domain,$name,$publicuser);
9986: }
9987: }
9988: if (!$passedsymb) {
9989: $symb=&symbread();
9990: } else {
9991: $symb=$passedsymb;
9992: }
9993: $courseid=$env{'request.course.id'};
9994: $domain=$env{'user.domain'};
9995: $name=$env{'user.name'};
9996: if ($name eq 'public' && $domain eq 'public') {
9997: if (!defined($env{'form.username'})) {
9998: $env{'form.username'}.=time.rand(10000000);
9999: }
10000: $name.=$env{'form.username'};
10001: }
10002: return ($symb,$courseid,$domain,$name,$publicuser);
10003:
10004: }
10005:
1.36 albertel 10006: # ------------------------------------------------------------ Serves up a file
1.472 albertel 10007: # returns either the contents of the file or
10008: # -1 if the file doesn't exist
1.481 raeburn 10009: #
10010: # if the target is a file that was uploaded via DOCS,
10011: # a check will be made to see if a current copy exists on the local server,
10012: # if it does this will be served, otherwise a copy will be retrieved from
10013: # the home server for the course and stored in /home/httpd/html/userfiles on
10014: # the local server.
1.472 albertel 10015:
1.36 albertel 10016: sub getfile {
1.538 albertel 10017: my ($file) = @_;
1.609 banghart 10018: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 10019: &repcopy($file);
10020: return &readfile($file);
10021: }
10022:
10023: sub repcopy_userfile {
10024: my ($file)=@_;
1.609 banghart 10025: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 10026: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 10027: my ($cdom,$cnum,$filename) =
1.811 albertel 10028: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 10029: my $uri="/uploaded/$cdom/$cnum/$filename";
10030: if (-e "$file") {
1.828 www 10031: # we already have a local copy, check it out
1.538 albertel 10032: my @fileinfo = stat($file);
1.828 www 10033: my $rtncode;
10034: my $info;
1.538 albertel 10035: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 10036: if ($lwpresp ne 'ok') {
1.828 www 10037: # there is no such file anymore, even though we had a local copy
1.482 albertel 10038: if ($rtncode eq '404') {
1.538 albertel 10039: unlink($file);
1.482 albertel 10040: }
10041: return -1;
10042: }
10043: if ($info < $fileinfo[9]) {
1.828 www 10044: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 10045: return 'ok';
1.828 www 10046: } else {
10047: # the file is outdated, get rid of it
10048: unlink($file);
1.482 albertel 10049: }
1.828 www 10050: }
10051: # one way or the other, at this point, we don't have the file
10052: # construct the correct path for the file
10053: my @parts = ($cdom,$cnum);
10054: if ($filename =~ m|^(.+)/[^/]+$|) {
10055: push @parts, split(/\//,$1);
10056: }
10057: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10058: foreach my $part (@parts) {
10059: $path .= '/'.$part;
10060: if (!-e $path) {
10061: mkdir($path,0770);
1.482 albertel 10062: }
10063: }
1.828 www 10064: # now the path exists for sure
10065: # get a user agent
10066: my $ua=new LWP::UserAgent;
10067: my $transferfile=$file.'.in.transfer';
10068: # FIXME: this should flock
10069: if (-e $transferfile) { return 'ok'; }
10070: my $request;
10071: $uri=~s/^\///;
1.980 raeburn 10072: my $homeserver = &homeserver($cnum,$cdom);
10073: my $protocol = $protocol{$homeserver};
10074: $protocol = 'http' if ($protocol ne 'https');
10075: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 10076: my $response=$ua->request($request,$transferfile);
10077: # did it work?
10078: if ($response->is_error()) {
10079: unlink($transferfile);
10080: &logthis("Userfile repcopy failed for $uri");
10081: return -1;
10082: }
10083: # worked, rename the transfer file
10084: rename($transferfile,$file);
1.607 raeburn 10085: return 'ok';
1.481 raeburn 10086: }
10087:
1.517 albertel 10088: sub tokenwrapper {
10089: my $uri=shift;
1.980 raeburn 10090: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 10091: $uri=~s|^/||;
1.620 albertel 10092: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 10093: my $token=$1;
1.552 albertel 10094: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10095: if ($udom && $uname && $file) {
10096: $file=~s|(\?\.*)*$||;
1.949 raeburn 10097: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 10098: my $homeserver = &homeserver($uname,$udom);
10099: my $protocol = $protocol{$homeserver};
10100: $protocol = 'http' if ($protocol ne 'https');
10101: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 10102: (($uri=~/\?/)?'&':'?').'token='.$token.
10103: '&tokenissued='.$perlvar{'lonHostID'};
10104: } else {
10105: return '/adm/notfound.html';
10106: }
10107: }
10108:
1.828 www 10109: # call with reqtype HEAD: get last modification time
10110: # call with reqtype GET: get the file contents
10111: # Do not call this with reqtype GET for large files! It loads everything into memory
10112: #
1.481 raeburn 10113: sub getuploaded {
10114: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10115: $uri=~s/^\///;
1.980 raeburn 10116: my $homeserver = &homeserver($cnum,$cdom);
10117: my $protocol = $protocol{$homeserver};
10118: $protocol = 'http' if ($protocol ne 'https');
10119: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 10120: my $ua=new LWP::UserAgent;
10121: my $request=new HTTP::Request($reqtype,$uri);
10122: my $response=$ua->request($request);
10123: $$rtncode = $response->code;
1.482 albertel 10124: if (! $response->is_success()) {
10125: return 'failed';
10126: }
10127: if ($reqtype eq 'HEAD') {
1.486 www 10128: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 10129: } elsif ($reqtype eq 'GET') {
10130: $$info = $response->content;
1.472 albertel 10131: }
1.482 albertel 10132: return 'ok';
1.36 albertel 10133: }
10134:
1.481 raeburn 10135: sub readfile {
10136: my $file = shift;
10137: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10138: my $fh;
10139: open($fh,"<$file");
10140: my $a='';
1.800 albertel 10141: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 10142: return $a;
10143: }
10144:
1.36 albertel 10145: sub filelocation {
1.590 banghart 10146: my ($dir,$file) = @_;
10147: my $location;
10148: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 10149:
10150: if ($file =~ m-^/adm/-) {
10151: $file=~s-^/adm/wrapper/-/-;
10152: $file=~s-^/adm/coursedocs/showdoc/-/-;
10153: }
1.882 albertel 10154:
1.590 banghart 10155: if ($file=~m:^/~:) { # is a contruction space reference
10156: $location = $file;
10157: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 10158: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 10159: # is a correct contruction space reference
10160: $location = $file;
1.956 raeburn 10161: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10162: $location = $file;
1.609 banghart 10163: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 10164: my ($udom,$uname,$filename)=
1.811 albertel 10165: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 10166: my $home=&homeserver($uname,$udom);
10167: my $is_me=0;
10168: my @ids=¤t_machine_ids();
10169: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10170: if ($is_me) {
1.1117 foxr 10171: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 10172: } else {
10173: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10174: $udom.'/'.$uname.'/'.$filename;
10175: }
1.882 albertel 10176: } elsif ($file =~ m-^/adm/-) {
10177: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 10178: } else {
10179: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10180: $file=~s:^/res/:/:;
10181: if ( !( $file =~ m:^/:) ) {
10182: $location = $dir. '/'.$file;
10183: } else {
10184: $location = '/home/httpd/html/res'.$file;
10185: }
1.59 albertel 10186: }
1.590 banghart 10187: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 10188: while ($location=~m{/\.\./}) {
10189: if ($location =~ m{/[^/]+/\.\./}) {
10190: $location=~ s{/[^/]+/\.\./}{/}g;
10191: } else {
10192: $location=~ s{/\.\./}{/}g;
10193: }
10194: } #remove dir/..
1.590 banghart 10195: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10196: return $location;
1.46 www 10197: }
1.36 albertel 10198:
1.46 www 10199: sub hreflocation {
10200: my ($dir,$file)=@_;
1.980 raeburn 10201: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 10202: $file=filelocation($dir,$file);
1.700 albertel 10203: } elsif ($file=~m-^/adm/-) {
10204: $file=~s-^/adm/wrapper/-/-;
10205: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 10206: }
10207: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10208: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 10209: } elsif ($file=~m-/home/($match_username)/public_html/-) {
10210: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 10211: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 10212: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 10213: -/uploaded/$1/$2/-x;
1.46 www 10214: }
1.913 albertel 10215: if ($file=~ m{^/userfiles/}) {
10216: $file =~ s{^/userfiles/}{/uploaded/};
10217: }
1.462 albertel 10218: return $file;
1.465 albertel 10219: }
10220:
10221: sub current_machine_domains {
1.853 albertel 10222: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10223: }
10224:
10225: sub machine_domains {
10226: my ($hostname) = @_;
1.465 albertel 10227: my @domains;
1.838 albertel 10228: my %hostname = &all_hostnames();
1.465 albertel 10229: while( my($id, $name) = each(%hostname)) {
1.467 matthew 10230: # &logthis("-$id-$name-$hostname-");
1.465 albertel 10231: if ($hostname eq $name) {
1.844 albertel 10232: push(@domains,&host_domain($id));
1.465 albertel 10233: }
10234: }
10235: return @domains;
10236: }
10237:
10238: sub current_machine_ids {
1.853 albertel 10239: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10240: }
10241:
10242: sub machine_ids {
10243: my ($hostname) = @_;
10244: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 10245: my @ids;
1.888 albertel 10246: my %name_to_host = &all_names();
1.889 albertel 10247: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10248: return @{ $name_to_host{$hostname} };
10249: }
10250: return;
1.31 www 10251: }
10252:
1.824 raeburn 10253: sub additional_machine_domains {
10254: my @domains;
10255: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10256: while( my $line = <$fh>) {
10257: $line =~ s/\s//g;
10258: push(@domains,$line);
10259: }
10260: return @domains;
10261: }
10262:
10263: sub default_login_domain {
10264: my $domain = $perlvar{'lonDefDomain'};
10265: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10266: foreach my $posdom (¤t_machine_domains(),
10267: &additional_machine_domains()) {
10268: if (lc($posdom) eq lc($testdomain)) {
10269: $domain=$posdom;
10270: last;
10271: }
10272: }
10273: return $domain;
10274: }
10275:
1.31 www 10276: # ------------------------------------------------------------- Declutters URLs
10277:
10278: sub declutter {
10279: my $thisfn=shift;
1.569 albertel 10280: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 10281: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 10282: $thisfn=~s/^\///;
1.697 albertel 10283: $thisfn=~s|^adm/wrapper/||;
10284: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 10285: $thisfn=~s/^res\///;
1.1032 raeburn 10286: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10287: $thisfn=~s/\?.+$//;
10288: }
1.268 www 10289: return $thisfn;
10290: }
10291:
10292: # ------------------------------------------------------------- Clutter up URLs
10293:
10294: sub clutter {
10295: my $thisfn='/'.&declutter(shift);
1.887 albertel 10296: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 10297: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 10298: $thisfn='/res'.$thisfn;
10299: }
1.1031 raeburn 10300: if ($thisfn !~m|^/adm|) {
10301: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 10302: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 10303: } else {
10304: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10305: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 10306: if ($embstyle eq 'ssi'
10307: || ($embstyle eq 'hdn')
10308: || ($embstyle eq 'rat')
10309: || ($embstyle eq 'prv')
10310: || ($embstyle eq 'ign')) {
10311: #do nothing with these
10312: } elsif (($embstyle eq 'img')
1.695 albertel 10313: || ($embstyle eq 'emb')
10314: || ($embstyle eq 'wrp')) {
10315: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 10316: } elsif ($embstyle eq 'unk'
10317: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 10318: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 10319: } else {
1.718 www 10320: # &logthis("Got a blank emb style");
1.695 albertel 10321: }
1.694 albertel 10322: }
10323: }
1.31 www 10324: return $thisfn;
1.12 www 10325: }
10326:
1.787 albertel 10327: sub clutter_with_no_wrapper {
10328: my $uri = &clutter(shift);
10329: if ($uri =~ m-^/adm/-) {
10330: $uri =~ s-^/adm/wrapper/-/-;
10331: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
10332: }
10333: return $uri;
10334: }
10335:
1.557 albertel 10336: sub freeze_escape {
10337: my ($value)=@_;
10338: if (ref($value)) {
10339: $value=&nfreeze($value);
10340: return '__FROZEN__'.&escape($value);
10341: }
10342: return &escape($value);
10343: }
10344:
1.11 www 10345:
1.557 albertel 10346: sub thaw_unescape {
10347: my ($value)=@_;
10348: if ($value =~ /^__FROZEN__/) {
10349: substr($value,0,10,undef);
10350: $value=&unescape($value);
10351: return &thaw($value);
10352: }
10353: return &unescape($value);
10354: }
10355:
1.436 albertel 10356: sub correct_line_ends {
10357: my ($result)=@_;
10358: $$result =~s/\r\n/\n/mg;
10359: $$result =~s/\r/\n/mg;
1.415 albertel 10360: }
1.1 albertel 10361: # ================================================================ Main Program
10362:
1.184 www 10363: sub goodbye {
1.204 albertel 10364: &logthis("Starting Shut down");
1.443 albertel 10365: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 10366: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 10367: #converted
1.599 albertel 10368: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 10369: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10370: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10371: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 10372: #1.1 only
1.870 albertel 10373: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10374: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10375: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10376: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10377: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 10378: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10379: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 10380: &flushcourselogs();
10381: &logthis("Shutting down");
10382: }
10383:
1.852 albertel 10384: sub get_dns {
1.869 albertel 10385: my ($url,$func,$ignore_cache) = @_;
10386: if (!$ignore_cache) {
10387: my ($content,$cached)=
10388: &Apache::lonnet::is_cached_new('dns',$url);
10389: if ($cached) {
10390: &$func($content);
10391: return;
10392: }
10393: }
10394:
10395: my %alldns;
1.852 albertel 10396: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10397: foreach my $dns (<$config>) {
10398: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 10399: my $line = $1;
10400: my ($host,$protocol) = split(/:/,$line);
10401: if ($protocol ne 'https') {
10402: $protocol = 'http';
10403: }
10404: $alldns{$host} = $protocol;
1.869 albertel 10405: }
10406: while (%alldns) {
10407: my ($dns) = keys(%alldns);
1.852 albertel 10408: my $ua=new LWP::UserAgent;
1.979 raeburn 10409: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 10410: my $response=$ua->request($request);
1.979 raeburn 10411: delete($alldns{$dns});
1.852 albertel 10412: next if ($response->is_error());
10413: my @content = split("\n",$response->content);
1.869 albertel 10414: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 10415: &$func(\@content);
1.869 albertel 10416: return;
1.852 albertel 10417: }
10418: close($config);
1.871 albertel 10419: my $which = (split('/',$url))[3];
10420: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10421: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 10422: my @content = <$config>;
10423: &$func(\@content);
10424: return;
1.852 albertel 10425: }
1.327 albertel 10426: # ------------------------------------------------------------ Read domain file
10427: {
1.852 albertel 10428: my $loaded;
1.846 albertel 10429: my %domain;
10430:
1.852 albertel 10431: sub parse_domain_tab {
10432: my ($lines) = @_;
10433: foreach my $line (@$lines) {
10434: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 10435:
1.846 albertel 10436: chomp($line);
1.852 albertel 10437: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 10438: my %this_domain;
10439: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10440: 'lang_def', 'city', 'longi', 'lati',
10441: 'primary') {
10442: $this_domain{$field} = shift(@elements);
10443: }
10444: $domain{$name} = \%this_domain;
1.852 albertel 10445: }
10446: }
1.864 albertel 10447:
10448: sub reset_domain_info {
10449: undef($loaded);
10450: undef(%domain);
10451: }
10452:
1.852 albertel 10453: sub load_domain_tab {
1.869 albertel 10454: my ($ignore_cache) = @_;
10455: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 10456: my $fh;
10457: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10458: my @lines = <$fh>;
10459: &parse_domain_tab(\@lines);
1.448 albertel 10460: }
1.852 albertel 10461: close($fh);
10462: $loaded = 1;
1.327 albertel 10463: }
1.846 albertel 10464:
10465: sub domain {
1.852 albertel 10466: &load_domain_tab() if (!$loaded);
10467:
1.846 albertel 10468: my ($name,$what) = @_;
10469: return if ( !exists($domain{$name}) );
10470:
10471: if (!$what) {
10472: return $domain{$name}{'description'};
10473: }
10474: return $domain{$name}{$what};
10475: }
1.974 raeburn 10476:
10477: sub domain_info {
10478: &load_domain_tab() if (!$loaded);
10479: return %domain;
10480: }
10481:
1.327 albertel 10482: }
10483:
10484:
1.1 albertel 10485: # ------------------------------------------------------------- Read hosts file
10486: {
1.838 albertel 10487: my %hostname;
1.844 albertel 10488: my %hostdom;
1.845 albertel 10489: my %libserv;
1.852 albertel 10490: my $loaded;
1.888 albertel 10491: my %name_to_host;
1.1074 raeburn 10492: my %internetdom;
1.1107 raeburn 10493: my %LC_dns_serv;
1.852 albertel 10494:
10495: sub parse_hosts_tab {
10496: my ($file) = @_;
10497: foreach my $configline (@$file) {
10498: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 10499: chomp($configline);
10500: if ($configline =~ /^\^/) {
10501: if ($configline =~ /^\^([\w.\-]+)/) {
10502: $LC_dns_serv{$1} = 1;
10503: }
10504: next;
10505: }
1.1074 raeburn 10506: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 10507: $name=~s/\s//g;
10508: if ($id && $domain && $role && $name) {
10509: $hostname{$id}=$name;
1.888 albertel 10510: push(@{$name_to_host{$name}}, $id);
1.852 albertel 10511: $hostdom{$id}=$domain;
10512: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 10513: if (defined($protocol)) {
10514: if ($protocol eq 'https') {
10515: $protocol{$id} = $protocol;
10516: } else {
10517: $protocol{$id} = 'http';
10518: }
1.968 raeburn 10519: } else {
1.969 raeburn 10520: $protocol{$id} = 'http';
1.968 raeburn 10521: }
1.1074 raeburn 10522: if (defined($intdom)) {
10523: $internetdom{$id} = $intdom;
10524: }
1.852 albertel 10525: }
10526: }
10527: }
1.864 albertel 10528:
10529: sub reset_hosts_info {
1.897 albertel 10530: &purge_remembered();
1.864 albertel 10531: &reset_domain_info();
10532: &reset_hosts_ip_info();
1.892 albertel 10533: undef(%name_to_host);
1.864 albertel 10534: undef(%hostname);
10535: undef(%hostdom);
10536: undef(%libserv);
10537: undef($loaded);
10538: }
1.1 albertel 10539:
1.852 albertel 10540: sub load_hosts_tab {
1.869 albertel 10541: my ($ignore_cache) = @_;
10542: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 10543: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10544: my @config = <$config>;
10545: &parse_hosts_tab(\@config);
10546: close($config);
10547: $loaded=1;
1.1 albertel 10548: }
1.852 albertel 10549:
1.838 albertel 10550: sub hostname {
1.852 albertel 10551: &load_hosts_tab() if (!$loaded);
10552:
1.838 albertel 10553: my ($lonid) = @_;
10554: return $hostname{$lonid};
10555: }
1.845 albertel 10556:
1.838 albertel 10557: sub all_hostnames {
1.852 albertel 10558: &load_hosts_tab() if (!$loaded);
10559:
1.838 albertel 10560: return %hostname;
10561: }
1.845 albertel 10562:
1.888 albertel 10563: sub all_names {
10564: &load_hosts_tab() if (!$loaded);
10565:
10566: return %name_to_host;
10567: }
10568:
1.974 raeburn 10569: sub all_host_domain {
10570: &load_hosts_tab() if (!$loaded);
10571: return %hostdom;
10572: }
10573:
1.845 albertel 10574: sub is_library {
1.852 albertel 10575: &load_hosts_tab() if (!$loaded);
10576:
1.845 albertel 10577: return exists($libserv{$_[0]});
10578: }
10579:
10580: sub all_library {
1.852 albertel 10581: &load_hosts_tab() if (!$loaded);
10582:
1.845 albertel 10583: return %libserv;
10584: }
10585:
1.1062 droeschl 10586: sub unique_library {
10587: #2x reverse removes all hostnames that appear more than once
10588: my %unique = reverse &all_library();
10589: return reverse %unique;
10590: }
10591:
1.841 albertel 10592: sub get_servers {
1.852 albertel 10593: &load_hosts_tab() if (!$loaded);
10594:
1.841 albertel 10595: my ($domain,$type) = @_;
10596: my %possible_hosts = ($type eq 'library') ? %libserv
10597: : %hostname;
10598: my %result;
1.842 albertel 10599: if (ref($domain) eq 'ARRAY') {
10600: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 10601: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 10602: $result{$host} = $hostname;
10603: }
10604: }
10605: } else {
10606: while ( my ($host,$hostname) = each(%possible_hosts)) {
10607: if ($hostdom{$host} eq $domain) {
10608: $result{$host} = $hostname;
10609: }
1.841 albertel 10610: }
10611: }
10612: return %result;
10613: }
1.845 albertel 10614:
1.1062 droeschl 10615: sub get_unique_servers {
10616: my %unique = reverse &get_servers(@_);
10617: return reverse %unique;
10618: }
10619:
1.844 albertel 10620: sub host_domain {
1.852 albertel 10621: &load_hosts_tab() if (!$loaded);
10622:
1.844 albertel 10623: my ($lonid) = @_;
10624: return $hostdom{$lonid};
10625: }
10626:
1.841 albertel 10627: sub all_domains {
1.852 albertel 10628: &load_hosts_tab() if (!$loaded);
10629:
1.841 albertel 10630: my %seen;
10631: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10632: return @uniq;
10633: }
1.1074 raeburn 10634:
10635: sub internet_dom {
10636: &load_hosts_tab() if (!$loaded);
10637:
10638: my ($lonid) = @_;
10639: return $internetdom{$lonid};
10640: }
1.1107 raeburn 10641:
10642: sub is_LC_dns {
10643: &load_hosts_tab() if (!$loaded);
10644:
10645: my ($hostname) = @_;
10646: return exists($LC_dns_serv{$hostname});
10647: }
10648:
1.1 albertel 10649: }
10650:
1.847 albertel 10651: {
10652: my %iphost;
1.856 albertel 10653: my %name_to_ip;
10654: my %lonid_to_ip;
1.869 albertel 10655:
1.847 albertel 10656: sub get_hosts_from_ip {
10657: my ($ip) = @_;
10658: my %iphosts = &get_iphost();
10659: if (ref($iphosts{$ip})) {
10660: return @{$iphosts{$ip}};
10661: }
10662: return;
1.839 albertel 10663: }
1.864 albertel 10664:
10665: sub reset_hosts_ip_info {
10666: undef(%iphost);
10667: undef(%name_to_ip);
10668: undef(%lonid_to_ip);
10669: }
1.856 albertel 10670:
10671: sub get_host_ip {
10672: my ($lonid) = @_;
10673: if (exists($lonid_to_ip{$lonid})) {
10674: return $lonid_to_ip{$lonid};
10675: }
10676: my $name=&hostname($lonid);
10677: my $ip = gethostbyname($name);
10678: return if (!$ip || length($ip) ne 4);
10679: $ip=inet_ntoa($ip);
10680: $name_to_ip{$name} = $ip;
10681: $lonid_to_ip{$lonid} = $ip;
10682: return $ip;
10683: }
1.847 albertel 10684:
10685: sub get_iphost {
1.869 albertel 10686: my ($ignore_cache) = @_;
1.894 albertel 10687:
1.869 albertel 10688: if (!$ignore_cache) {
10689: if (%iphost) {
10690: return %iphost;
10691: }
10692: my ($ip_info,$cached)=
10693: &Apache::lonnet::is_cached_new('iphost','iphost');
10694: if ($cached) {
10695: %iphost = %{$ip_info->[0]};
10696: %name_to_ip = %{$ip_info->[1]};
10697: %lonid_to_ip = %{$ip_info->[2]};
10698: return %iphost;
10699: }
10700: }
1.894 albertel 10701:
10702: # get yesterday's info for fallback
10703: my %old_name_to_ip;
10704: my ($ip_info,$cached)=
10705: &Apache::lonnet::is_cached_new('iphost','iphost');
10706: if ($cached) {
10707: %old_name_to_ip = %{$ip_info->[1]};
10708: }
10709:
1.888 albertel 10710: my %name_to_host = &all_names();
10711: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10712: my $ip;
10713: if (!exists($name_to_ip{$name})) {
10714: $ip = gethostbyname($name);
10715: if (!$ip || length($ip) ne 4) {
1.894 albertel 10716: if (defined($old_name_to_ip{$name})) {
10717: $ip = $old_name_to_ip{$name};
10718: &logthis("Can't find $name defaulting to old $ip");
10719: } else {
10720: &logthis("Name $name no IP found");
10721: next;
10722: }
10723: } else {
10724: $ip=inet_ntoa($ip);
1.847 albertel 10725: }
10726: $name_to_ip{$name} = $ip;
10727: } else {
10728: $ip = $name_to_ip{$name};
1.653 albertel 10729: }
1.888 albertel 10730: foreach my $id (@{ $name_to_host{$name} }) {
10731: $lonid_to_ip{$id} = $ip;
10732: }
10733: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10734: }
1.869 albertel 10735: &Apache::lonnet::do_cache_new('iphost','iphost',
10736: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10737: 48*60*60);
1.869 albertel 10738:
1.847 albertel 10739: return %iphost;
1.598 albertel 10740: }
10741:
1.992 raeburn 10742: #
10743: # Given a DNS returns the loncapa host name for that DNS
10744: #
10745: sub host_from_dns {
10746: my ($dns) = @_;
10747: my @hosts;
10748: my $ip;
10749:
1.993 raeburn 10750: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10751: $ip = $name_to_ip{$dns};
10752: }
10753: if (!$ip) {
10754: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10755: if (length($ip) == 4) {
10756: $ip = &IO::Socket::inet_ntoa($ip);
10757: }
10758: }
10759: if ($ip) {
10760: @hosts = get_hosts_from_ip($ip);
10761: return $hosts[0];
10762: }
10763: return undef;
1.986 foxr 10764: }
1.992 raeburn 10765:
1.1074 raeburn 10766: sub get_internet_names {
10767: my ($lonid) = @_;
10768: return if ($lonid eq '');
10769: my ($idnref,$cached)=
10770: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10771: if ($cached) {
10772: return $idnref;
10773: }
10774: my $ip = &get_host_ip($lonid);
10775: my @hosts = &get_hosts_from_ip($ip);
10776: my %iphost = &get_iphost();
10777: my (@idns,%seen);
10778: foreach my $id (@hosts) {
10779: my $dom = &host_domain($id);
10780: my $prim_id = &domain($dom,'primary');
10781: my $prim_ip = &get_host_ip($prim_id);
10782: next if ($seen{$prim_ip});
10783: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10784: foreach my $id (@{$iphost{$prim_ip}}) {
10785: my $intdom = &internet_dom($id);
10786: unless (grep(/^\Q$intdom\E$/,@idns)) {
10787: push(@idns,$intdom);
10788: }
10789: }
10790: }
10791: $seen{$prim_ip} = 1;
10792: }
10793: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10794: }
10795:
1.986 foxr 10796: }
10797:
1.1079 raeburn 10798: sub all_loncaparevs {
10799: 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);
10800: }
10801:
1.862 albertel 10802: BEGIN {
10803:
10804: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10805: unless ($readit) {
10806: {
10807: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10808: %perlvar = (%perlvar,%{$configvars});
10809: }
10810:
10811:
1.1 albertel 10812: # ------------------------------------------------------ Read spare server file
10813: {
1.448 albertel 10814: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10815:
10816: while (my $configline=<$config>) {
10817: chomp($configline);
1.284 matthew 10818: if ($configline) {
1.784 albertel 10819: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10820: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10821: push(@{ $spareid{$type} }, $host);
1.1 albertel 10822: }
10823: }
1.448 albertel 10824: close($config);
1.1 albertel 10825: }
1.11 www 10826: # ------------------------------------------------------------ Read permissions
10827: {
1.448 albertel 10828: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10829:
10830: while (my $configline=<$config>) {
1.448 albertel 10831: chomp($configline);
10832: if ($configline) {
10833: my ($role,$perm)=split(/ /,$configline);
10834: if ($perm ne '') { $pr{$role}=$perm; }
10835: }
1.11 www 10836: }
1.448 albertel 10837: close($config);
1.11 www 10838: }
10839:
10840: # -------------------------------------------- Read plain texts for permissions
10841: {
1.448 albertel 10842: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10843:
10844: while (my $configline=<$config>) {
1.448 albertel 10845: chomp($configline);
10846: if ($configline) {
1.742 raeburn 10847: my ($short,@plain)=split(/:/,$configline);
10848: %{$prp{$short}} = ();
10849: if (@plain > 0) {
10850: $prp{$short}{'std'} = $plain[0];
10851: for (my $i=1; $i<@plain; $i++) {
10852: $prp{$short}{'alt'.$i} = $plain[$i];
10853: }
10854: }
1.448 albertel 10855: }
1.135 www 10856: }
1.448 albertel 10857: close($config);
1.135 www 10858: }
10859:
10860: # ---------------------------------------------------------- Read package table
10861: {
1.448 albertel 10862: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10863:
10864: while (my $configline=<$config>) {
1.483 albertel 10865: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10866: chomp($configline);
10867: my ($short,$plain)=split(/:/,$configline);
10868: my ($pack,$name)=split(/\&/,$short);
10869: if ($plain ne '') {
10870: $packagetab{$pack.'&'.$name.'&name'}=$name;
10871: $packagetab{$short}=$plain;
10872: }
1.11 www 10873: }
1.448 albertel 10874: close($config);
1.329 matthew 10875: }
10876:
1.1073 raeburn 10877: # ---------------------------------------------------------- Read loncaparev table
10878: {
10879: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10880: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10881: while (my $configline=<$config>) {
10882: chomp($configline);
10883: my ($hostid,$loncaparev)=split(/:/,$configline);
10884: $loncaparevs{$hostid}=$loncaparev;
10885: }
10886: close($config);
10887: }
10888: }
10889: }
10890:
1.1074 raeburn 10891: # ---------------------------------------------------------- Read serverhostID table
10892: {
10893: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10894: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10895: while (my $configline=<$config>) {
10896: chomp($configline);
10897: my ($name,$id)=split(/:/,$configline);
10898: $serverhomeIDs{$name}=$id;
10899: }
10900: close($config);
10901: }
10902: }
10903: }
10904:
1.1079 raeburn 10905: {
10906: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10907: if (-e $file) {
10908: my $parser = HTML::LCParser->new($file);
10909: while (my $token = $parser->get_token()) {
10910: if ($token->[0] eq 'S') {
10911: my $item = $token->[1];
10912: my $name = $token->[2]{'name'};
10913: my $value = $token->[2]{'value'};
10914: if ($item ne '' && $name ne '' && $value ne '') {
10915: my $release = $parser->get_text();
10916: $release =~ s/(^\s*|\s*$ )//gx;
10917: $needsrelease{$item.':'.$name.':'.$value} = $release;
10918: }
10919: }
10920: }
10921: }
1.1073 raeburn 10922: }
10923:
1.329 matthew 10924: # ------------- set up temporary directory
10925: {
1.1117 foxr 10926: $tmpdir = LONCAPA::tempdir();
1.329 matthew 10927:
1.11 www 10928: }
10929:
1.794 albertel 10930: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10931: 'compress_threshold'=> 20_000,
10932: });
1.185 www 10933:
1.281 www 10934: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10935: $dumpcount=0;
1.958 www 10936: $locknum=0;
1.22 www 10937:
1.163 harris41 10938: &logtouch();
1.672 albertel 10939: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10940: $readit=1;
1.564 albertel 10941: {
10942: use integer;
10943: my $test=(2**32)+1;
1.568 albertel 10944: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10945: &logthis(" Detected 64bit platform ($_64bit)");
10946: }
1.195 www 10947: }
1.1 albertel 10948: }
1.179 www 10949:
1.1 albertel 10950: 1;
1.191 harris41 10951: __END__
10952:
1.243 albertel 10953: =pod
10954:
1.191 harris41 10955: =head1 NAME
10956:
1.243 albertel 10957: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10958:
10959: =head1 SYNOPSIS
10960:
1.243 albertel 10961: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10962:
10963: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10964:
1.243 albertel 10965: Common parameters:
10966:
10967: =over 4
10968:
10969: =item *
10970:
10971: $uname : an internal username (if $cname expecting a course Id specifically)
10972:
10973: =item *
10974:
10975: $udom : a domain (if $cdom expecting a course's domain specifically)
10976:
10977: =item *
10978:
10979: $symb : a resource instance identifier
10980:
10981: =item *
10982:
10983: $namespace : the name of a .db file that contains the data needed or
10984: being set.
10985:
10986: =back
10987:
1.394 bowersj2 10988: =head1 OVERVIEW
1.191 harris41 10989:
1.394 bowersj2 10990: lonnet provides subroutines which interact with the
10991: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10992: about classes, users, and resources.
1.243 albertel 10993:
10994: For many of these objects you can also use this to store data about
10995: them or modify them in various ways.
1.191 harris41 10996:
1.394 bowersj2 10997: =head2 Symbs
1.191 harris41 10998:
1.394 bowersj2 10999: To identify a specific instance of a resource, LON-CAPA uses symbols
11000: or "symbs"X<symb>. These identifiers are built from the URL of the
11001: map, the resource number of the resource in the map, and the URL of
11002: the resource itself. The latter is somewhat redundant, but might help
11003: if maps change.
11004:
11005: An example is
11006:
11007: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11008:
11009: The respective map entry is
11010:
11011: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11012: title="Problem 2">
11013: </resource>
11014:
11015: Symbs are used by the random number generator, as well as to store and
11016: restore data specific to a certain instance of for example a problem.
11017:
11018: =head2 Storing And Retrieving Data
11019:
11020: X<store()>X<cstore()>X<restore()>Three of the most important functions
11021: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11022: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11023: is is the non-critical message twin of cstore. These functions are for
11024: handlers to store a perl hash to a user's permanent data space in an
11025: easy manner, and to retrieve it again on another call. It is expected
11026: that a handler would use this once at the beginning to retrieve data,
11027: and then again once at the end to send only the new data back.
11028:
11029: The data is stored in the user's data directory on the user's
11030: homeserver under the ID of the course.
11031:
11032: The hash that is returned by restore will have all of the previous
11033: value for all of the elements of the hash.
11034:
11035: Example:
11036:
11037: #creating a hash
11038: my %hash;
11039: $hash{'foo'}='bar';
11040:
11041: #storing it
11042: &Apache::lonnet::cstore(\%hash);
11043:
11044: #changing a value
11045: $hash{'foo'}='notbar';
11046:
11047: #adding a new value
11048: $hash{'bar'}='foo';
11049: &Apache::lonnet::cstore(\%hash);
11050:
11051: #retrieving the hash
11052: my %history=&Apache::lonnet::restore();
11053:
11054: #print the hash
11055: foreach my $key (sort(keys(%history))) {
11056: print("\%history{$key} = $history{$key}");
11057: }
11058:
11059: Will print out:
1.191 harris41 11060:
1.394 bowersj2 11061: %history{1:foo} = bar
11062: %history{1:keys} = foo:timestamp
11063: %history{1:timestamp} = 990455579
11064: %history{2:bar} = foo
11065: %history{2:foo} = notbar
11066: %history{2:keys} = foo:bar:timestamp
11067: %history{2:timestamp} = 990455580
11068: %history{bar} = foo
11069: %history{foo} = notbar
11070: %history{timestamp} = 990455580
11071: %history{version} = 2
11072:
11073: Note that the special hash entries C<keys>, C<version> and
11074: C<timestamp> were added to the hash. C<version> will be equal to the
11075: total number of versions of the data that have been stored. The
11076: C<timestamp> attribute will be the UNIX time the hash was
11077: stored. C<keys> is available in every historical section to list which
11078: keys were added or changed at a specific historical revision of a
11079: hash.
11080:
11081: B<Warning>: do not store the hash that restore returns directly. This
11082: will cause a mess since it will restore the historical keys as if the
11083: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 11084:
1.394 bowersj2 11085: Calling convention:
1.191 harris41 11086:
1.394 bowersj2 11087: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11088: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 11089:
1.394 bowersj2 11090: For more detailed information, see lonnet specific documentation.
1.191 harris41 11091:
1.394 bowersj2 11092: =head1 RETURN MESSAGES
1.191 harris41 11093:
1.394 bowersj2 11094: =over 4
1.191 harris41 11095:
1.394 bowersj2 11096: =item * B<con_lost>: unable to contact remote host
1.191 harris41 11097:
1.394 bowersj2 11098: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11099: when the connection is brought back up
1.191 harris41 11100:
1.394 bowersj2 11101: =item * B<con_failed>: unable to contact remote host and unable to save message
11102: for later delivery
1.191 harris41 11103:
1.967 bisitz 11104: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 11105:
1.394 bowersj2 11106: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 11107: that was requested
1.191 harris41 11108:
1.243 albertel 11109: =back
1.191 harris41 11110:
1.243 albertel 11111: =head1 PUBLIC SUBROUTINES
1.191 harris41 11112:
1.243 albertel 11113: =head2 Session Environment Functions
1.191 harris41 11114:
1.243 albertel 11115: =over 4
1.191 harris41 11116:
1.394 bowersj2 11117: =item *
11118: X<appenv()>
1.949 raeburn 11119: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 11120: the user envirnoment file, and will be restored for each access this
1.620 albertel 11121: user makes during this session, also modifies the %env for the current
1.949 raeburn 11122: process. Optional rolesarrayref - if defined contains a reference to an array
11123: of roles which are exempt from the restriction on modifying user.role entries
11124: in the user's environment.db and in %env.
1.191 harris41 11125:
11126: =item *
1.394 bowersj2 11127: X<delenv()>
1.987 raeburn 11128: B<delenv($delthis,$regexp)>: removes all items from the session
11129: environment file that begin with $delthis. If the
11130: optional second arg - $regexp - is true, $delthis is treated as a
11131: regular expression, otherwise \Q$delthis\E is used.
11132: The values are also deleted from the current processes %env.
1.191 harris41 11133:
1.795 albertel 11134: =item * get_env_multiple($name)
11135:
11136: gets $name from the %env hash, it seemlessly handles the cases where multiple
11137: values may be defined and end up as an array ref.
11138:
11139: returns an array of values
11140:
1.243 albertel 11141: =back
11142:
11143: =head2 User Information
1.191 harris41 11144:
1.243 albertel 11145: =over 4
1.191 harris41 11146:
11147: =item *
1.394 bowersj2 11148: X<queryauthenticate()>
11149: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 11150: authentication scheme
11151:
11152: =item *
1.394 bowersj2 11153: X<authenticate()>
1.1073 raeburn 11154: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 11155: authenticate user from domain's lib servers (first use the current
11156: one). C<$upass> should be the users password.
1.1073 raeburn 11157: $checkdefauth is optional (value is 1 if a check should be made to
11158: authenticate user using default authentication method, and allow
11159: account creation if username does not have account in the domain).
11160: $clientcancheckhost is optional (value is 1 if checking whether the
11161: server can host will occur on the client side in lonauth.pm).
1.191 harris41 11162:
11163: =item *
1.394 bowersj2 11164: X<homeserver()>
11165: B<homeserver($uname,$udom)>: find the server which has
11166: the user's directory and files (there must be only one), this caches
11167: the answer, and also caches if there is a borken connection.
1.191 harris41 11168:
11169: =item *
1.394 bowersj2 11170: X<idget()>
11171: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11172: (IDs are a unique resource in a domain, there must be only 1 ID per
11173: username, and only 1 username per ID in a specific domain) (returns
11174: hash: id=>name,id=>name)
1.191 harris41 11175:
11176: =item *
1.394 bowersj2 11177: X<idrget()>
11178: B<idrget($udom,@unames)>: find the IDs behind a list of
11179: usernames (returns hash: name=>id,name=>id)
1.191 harris41 11180:
11181: =item *
1.394 bowersj2 11182: X<idput()>
11183: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 11184:
11185: =item *
1.394 bowersj2 11186: X<rolesinit()>
11187: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 11188:
11189: =item *
1.551 albertel 11190: X<getsection()>
11191: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 11192: course $cname, return section name/number or '' for "not in course"
11193: and '-1' for "no section"
11194:
11195: =item *
1.394 bowersj2 11196: X<userenvironment()>
11197: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 11198: passed in @what from the requested user's environment, returns a hash
11199:
1.858 raeburn 11200: =item *
11201: X<userlog_query()>
1.859 albertel 11202: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11203: activity.log file. %filters defines filters applied when parsing the
11204: log file. These can be start or end timestamps, or the type of action
11205: - log to look for Login or Logout events, check for Checkin or
11206: Checkout, role for role selection. The response is in the form
11207: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11208: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 11209:
1.243 albertel 11210: =back
11211:
11212: =head2 User Roles
11213:
11214: =over 4
11215:
11216: =item *
11217:
1.810 raeburn 11218: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 11219: F: full access
11220: U,I,K: authentication modes (cxx only)
11221: '': forbidden
11222: 1: user needs to choose course
11223: 2: browse allowed
1.766 albertel 11224: A: passphrase authentication needed
1.243 albertel 11225:
11226: =item *
11227:
11228: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11229: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11230: and course level
11231:
11232: =item *
11233:
1.988 raeburn 11234: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11235: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 11236: $type is Course (default) or Community.
1.988 raeburn 11237: If $forcedefault evaluates to true, text returned will be default
11238: text for $type. Otherwise, if this is a course, the text returned
11239: will be a custom name for the role (if defined in the course's
11240: environment). If no custom name is defined the default is returned.
11241:
1.832 raeburn 11242: =item *
11243:
1.935 raeburn 11244: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 11245: All arguments are optional. Returns a hash of a roles, either for
11246: co-author/assistant author roles for a user's Construction Space
1.906 albertel 11247: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 11248: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11249: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11250: For each key, value is set to colon-separated start and end times for
11251: the role. If no username and domain are specified, will default to
1.934 raeburn 11252: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 11253: of role statuses (active, future or previous), roles
11254: (e.g., cc,in, st etc.) and domains of the roles which can be used
11255: to restrict the list of roles reported. If no array ref is
11256: provided for types, will default to return only active roles.
1.834 albertel 11257:
1.243 albertel 11258: =back
11259:
11260: =head2 User Modification
11261:
11262: =over 4
11263:
11264: =item *
11265:
1.957 raeburn 11266: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 11267: user for the level given by URL. Optional start and end dates (leave empty
11268: string or zero for "no date")
1.191 harris41 11269:
11270: =item *
11271:
1.243 albertel 11272: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11273: change a users, password, possible return values are: ok,
11274: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11275: refused
1.191 harris41 11276:
11277: =item *
11278:
1.243 albertel 11279: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 11280:
11281: =item *
11282:
1.1058 raeburn 11283: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11284: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11285:
11286: will update user information (firstname,middlename,lastname,generation,
11287: permanentemail), and if forceid is true, student/employee ID also.
11288: A user's institutional affiliation(s) can also be updated.
11289: User information fields will not be overwritten with empty entries
11290: unless the field is included in the $candelete array reference.
11291: This array is included when a single user is modified via "Manage Users",
11292: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 11293:
11294: =item *
11295:
1.286 matthew 11296: modifystudent
11297:
1.957 raeburn 11298: modify a student's enrollment and identification information.
1.286 matthew 11299: The course id is resolved based on the current users environment.
11300: This means the envoking user must be a course coordinator or otherwise
11301: associated with a course.
11302:
1.297 matthew 11303: This call is essentially a wrapper for lonnet::modifyuser and
11304: lonnet::modify_student_enrollment
1.286 matthew 11305:
11306: Inputs:
11307:
11308: =over 4
11309:
1.957 raeburn 11310: =item B<$udom> Student's loncapa domain
1.286 matthew 11311:
1.957 raeburn 11312: =item B<$uname> Student's loncapa login name
1.286 matthew 11313:
1.964 bisitz 11314: =item B<$uid> Student/Employee ID
1.286 matthew 11315:
1.957 raeburn 11316: =item B<$umode> Student's authentication mode
1.286 matthew 11317:
1.957 raeburn 11318: =item B<$upass> Student's password
1.286 matthew 11319:
1.957 raeburn 11320: =item B<$first> Student's first name
1.286 matthew 11321:
1.957 raeburn 11322: =item B<$middle> Student's middle name
1.286 matthew 11323:
1.957 raeburn 11324: =item B<$last> Student's last name
1.286 matthew 11325:
1.957 raeburn 11326: =item B<$gene> Student's generation
1.286 matthew 11327:
1.957 raeburn 11328: =item B<$usec> Student's section in course
1.286 matthew 11329:
11330: =item B<$end> Unix time of the roles expiration
11331:
11332: =item B<$start> Unix time of the roles start date
11333:
11334: =item B<$forceid> If defined, allow $uid to be changed
11335:
11336: =item B<$desiredhome> server to use as home server for student
11337:
1.957 raeburn 11338: =item B<$email> Student's permanent e-mail address
11339:
11340: =item B<$type> Type of enrollment (auto or manual)
11341:
1.963 raeburn 11342: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
11343:
11344: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 11345:
1.963 raeburn 11346: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 11347:
1.963 raeburn 11348: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 11349:
1.963 raeburn 11350: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 11351:
1.286 matthew 11352: =back
1.297 matthew 11353:
11354: =item *
11355:
11356: modify_student_enrollment
11357:
11358: Change a students enrollment status in a class. The environment variable
11359: 'role.request.course' must be defined for this function to proceed.
11360:
11361: Inputs:
11362:
11363: =over 4
11364:
11365: =item $udom, students domain
11366:
11367: =item $uname, students name
11368:
11369: =item $uid, students user id
11370:
11371: =item $first, students first name
11372:
11373: =item $middle
11374:
11375: =item $last
11376:
11377: =item $gene
11378:
11379: =item $usec
11380:
11381: =item $end
11382:
11383: =item $start
11384:
1.957 raeburn 11385: =item $type
11386:
11387: =item $locktype
11388:
11389: =item $cid
11390:
11391: =item $selfenroll
11392:
11393: =item $context
11394:
1.297 matthew 11395: =back
11396:
1.191 harris41 11397:
11398: =item *
11399:
1.243 albertel 11400: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11401: custom role; give a custom role to a user for the level given by URL. Specify
11402: name and domain of role author, and role name
1.191 harris41 11403:
11404: =item *
11405:
1.243 albertel 11406: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 11407:
11408: =item *
11409:
1.243 albertel 11410: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11411:
11412: =back
11413:
11414: =head2 Course Infomation
11415:
11416: =over 4
1.191 harris41 11417:
11418: =item *
11419:
1.1118 foxr 11420: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 11421: specified course id, including all environment settings for the
11422: course, the description of the course will be in the hash under the
11423: key 'description'
1.191 harris41 11424:
1.1118 foxr 11425: $options is an optional parameter that if supplied is a hash reference that controls
11426: what how this function works. It has the following key/values:
11427:
11428: =over 4
11429:
11430: =item freshen_cache
11431:
11432: If defined, and the environment cache for the course is valid, it is
11433: returned in the returned hash.
11434:
11435: =item one_time
11436:
11437: If defined, the last cache time is set to _now_
11438:
11439: =item user
11440:
11441: If defined, the supplied username is used instead of the current user.
11442:
11443:
11444: =back
11445:
1.191 harris41 11446: =item *
11447:
1.624 albertel 11448: resdata($name,$domain,$type,@which) : request for current parameter
11449: setting for a specific $type, where $type is either 'course' or 'user',
11450: @what should be a list of parameters to ask about. This routine caches
11451: answers for 5 minutes.
1.243 albertel 11452:
1.877 foxr 11453: =item *
11454:
11455: get_courseresdata($courseid, $domain) : dump the entire course resource
11456: data base, returning a hash that is keyed by the resource name and has
11457: values that are the resource value. I believe that the timestamps and
11458: versions are also returned.
11459:
11460:
1.243 albertel 11461: =back
11462:
11463: =head2 Course Modification
11464:
11465: =over 4
1.191 harris41 11466:
11467: =item *
11468:
1.243 albertel 11469: writecoursepref($courseid,%prefs) : write preferences (environment
11470: database) for a course
1.191 harris41 11471:
11472: =item *
11473:
1.1011 raeburn 11474: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11475:
11476: =item *
11477:
1.1038 raeburn 11478: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 11479:
11480: =back
11481:
11482: =head2 Resource Subroutines
11483:
11484: =over 4
1.191 harris41 11485:
11486: =item *
11487:
1.243 albertel 11488: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 11489:
11490: =item *
11491:
1.243 albertel 11492: repcopy($filename) : subscribes to the requested file, and attempts to
11493: replicate from the owning library server, Might return
1.607 raeburn 11494: 'unavailable', 'not_found', 'forbidden', 'ok', or
11495: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 11496: resource. Expects the local filesystem pathname
11497: (/home/httpd/html/res/....)
11498:
11499: =back
11500:
11501: =head2 Resource Information
11502:
11503: =over 4
1.191 harris41 11504:
11505: =item *
11506:
1.243 albertel 11507: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11508: a vairety of different possible values, $varname should be a request
11509: string, and the other parameters can be used to specify who and what
11510: one is asking about.
11511:
11512: Possible values for $varname are environment.lastname (or other item
11513: from the envirnment hash), user.name (or someother aspect about the
11514: user), resource.0.maxtries (or some other part and parameter of a
11515: resource)
1.204 albertel 11516:
11517: =item *
11518:
1.243 albertel 11519: directcondval($number) : get current value of a condition; reads from a state
11520: string
1.204 albertel 11521:
11522: =item *
11523:
1.243 albertel 11524: condval($condidx) : value of condition index based on state
1.204 albertel 11525:
11526: =item *
11527:
1.243 albertel 11528: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11529: resource's metadata, $what should be either a specific key, or either
11530: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11531: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11532:
11533: this function automatically caches all requests
1.191 harris41 11534:
11535: =item *
11536:
1.243 albertel 11537: metadata_query($query,$custom,$customshow) : make a metadata query against the
11538: network of library servers; returns file handle of where SQL and regex results
11539: will be stored for query
1.191 harris41 11540:
11541: =item *
11542:
1.243 albertel 11543: symbread($filename) : return symbolic list entry (filename argument optional);
11544: returns the data handle
1.191 harris41 11545:
11546: =item *
11547:
1.243 albertel 11548: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 11549: a possible symb for the URL in $thisfn, and if is an encryypted
11550: resource that the user accessed using /enc/ returns a 1 on success, 0
11551: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 11552: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 11553:
1.191 harris41 11554:
11555: =item *
11556:
1.243 albertel 11557: symbclean($symb) : removes versions numbers from a symb, returns the
11558: cleaned symb
1.191 harris41 11559:
11560: =item *
11561:
1.243 albertel 11562: is_on_map($uri) : checks if the $uri is somewhere on the current
11563: course map, user must be in a course for it to work.
1.191 harris41 11564:
11565: =item *
11566:
1.243 albertel 11567: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 11568:
11569: =item *
11570:
1.243 albertel 11571: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11572: a random seed, all arguments are optional, if they aren't sent it uses the
11573: environment to derive them. Note: if symb isn't sent and it can't get one
11574: from &symbread it will use the current time as its return value
1.191 harris41 11575:
11576: =item *
11577:
1.243 albertel 11578: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11579: unfakeable, receipt
1.191 harris41 11580:
11581: =item *
11582:
1.620 albertel 11583: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 11584:
11585: =item *
11586:
1.243 albertel 11587: countacc($url) : count the number of accesses to a given URL
1.191 harris41 11588:
11589: =item *
11590:
1.243 albertel 11591: 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 11592:
11593: =item *
11594:
1.243 albertel 11595: 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 11596:
11597: =item *
11598:
1.243 albertel 11599: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 11600:
11601: =item *
11602:
1.243 albertel 11603: devalidate($symb) : devalidate temporary spreadsheet calculations,
11604: forcing spreadsheet to reevaluate the resource scores next time.
11605:
11606: =back
11607:
11608: =head2 Storing/Retreiving Data
11609:
11610: =over 4
1.191 harris41 11611:
11612: =item *
11613:
1.243 albertel 11614: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11615: for this url; hashref needs to be given and should be a \%hashname; the
11616: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 11617: be derived from the env
1.191 harris41 11618:
11619: =item *
11620:
1.243 albertel 11621: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11622: uses critical subroutine
1.191 harris41 11623:
11624: =item *
11625:
1.243 albertel 11626: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11627: all args are optional
1.191 harris41 11628:
11629: =item *
11630:
1.717 albertel 11631: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11632: dumps the complete (or key matching regexp) namespace into a hash
11633: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11634: normally &store()ed into
11635:
11636: $range should be either an integer '100' (give me the first 100
11637: matching records)
11638: or be two integers sperated by a - with no spaces
11639: '30-50' (give me the 30th through the 50th matching
11640: records)
11641:
11642:
11643: =item *
11644:
11645: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11646: replaces a &store() version of data with a replacement set of data
11647: for a particular resource in a namespace passed in the $storehash hash
11648: reference
11649:
11650: =item *
11651:
1.243 albertel 11652: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11653: works very similar to store/cstore, but all data is stored in a
11654: temporary location and can be reset using tmpreset, $storehash should
11655: be a hash reference, returns nothing on success
1.191 harris41 11656:
11657: =item *
11658:
1.243 albertel 11659: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11660: similar to restore, but all data is stored in a temporary location and
11661: can be reset using tmpreset. Returns a hash of values on success,
11662: error string otherwise.
1.191 harris41 11663:
11664: =item *
11665:
1.243 albertel 11666: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11667: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 11668:
11669: =item *
11670:
1.243 albertel 11671: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11672: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11673:
11674: =item *
11675:
1.243 albertel 11676: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11677: namesp ($udom and $uname are optional)
1.191 harris41 11678:
11679: =item *
11680:
1.702 albertel 11681: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11682: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11683: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11684:
1.702 albertel 11685: $range should be either an integer '100' (give me the first 100
11686: matching records)
11687: or be two integers sperated by a - with no spaces
11688: '30-50' (give me the 30th through the 50th matching
11689: records)
1.449 matthew 11690: =item *
11691:
11692: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11693: $store can be a scalar, an array reference, or if the amount to be
11694: incremented is > 1, a hash reference.
11695:
11696: ($udom and $uname are optional)
1.191 harris41 11697:
11698: =item *
11699:
1.243 albertel 11700: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11701: ($udom and $uname are optional)
1.191 harris41 11702:
11703: =item *
11704:
1.243 albertel 11705: cput($namespace,$storehash,$udom,$uname) : critical put
11706: ($udom and $uname are optional)
1.191 harris41 11707:
11708: =item *
11709:
1.748 albertel 11710: newput($namespace,$storehash,$udom,$uname) :
11711:
11712: Attempts to store the items in the $storehash, but only if they don't
11713: currently exist, if this succeeds you can be certain that you have
11714: successfully created a new key value pair in the $namespace db.
11715:
11716:
11717: Args:
11718: $namespace: name of database to store values to
11719: $storehash: hashref to store to the db
11720: $udom: (optional) domain of user containing the db
11721: $uname: (optional) name of user caontaining the db
11722:
11723: Returns:
11724: 'ok' -> succeeded in storing all keys of $storehash
11725: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11726: least <key> already existed in the db (other
11727: requested keys may also already exist)
1.967 bisitz 11728: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11729: 'con_lost' -> unable to contact request server
11730: 'refused' -> action was not allowed by remote machine
11731:
11732:
11733: =item *
11734:
1.243 albertel 11735: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11736: reference filled in from namesp (encrypts the return communication)
11737: ($udom and $uname are optional)
1.191 harris41 11738:
11739: =item *
11740:
1.243 albertel 11741: log($udom,$name,$home,$message) : write to permanent log for user; use
11742: critical subroutine
11743:
1.806 raeburn 11744: =item *
11745:
1.860 raeburn 11746: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11747: array reference filled in from namespace found in domain level on either
11748: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11749:
11750: =item *
11751:
1.860 raeburn 11752: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11753: domain level either on specified domain server ($uhome) or primary domain
11754: server ($udom and $uhome are optional)
1.806 raeburn 11755:
1.943 raeburn 11756: =item *
11757:
11758: get_domain_defaults($target_domain) : returns hash with defaults for
11759: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11760: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11761: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11762: Values are retrieved from cache (if current), or from domain's configuration.db
11763: (if available), or lastly from values in lonTabs/dns_domain,tab,
11764: or lonTabs/domain.tab.
11765:
11766: %domdefaults = &get_auth_defaults($target_domain);
11767:
1.243 albertel 11768: =back
11769:
11770: =head2 Network Status Functions
11771:
11772: =over 4
1.191 harris41 11773:
11774: =item *
11775:
11776: dirlist($uri) : return directory list based on URI
11777:
11778: =item *
11779:
1.243 albertel 11780: spareserver() : find server with least workload from spare.tab
11781:
1.986 foxr 11782:
11783: =item *
11784:
11785: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11786: if there is no corresponding loncapa host.
11787:
1.243 albertel 11788: =back
11789:
1.986 foxr 11790:
1.243 albertel 11791: =head2 Apache Request
11792:
11793: =over 4
1.191 harris41 11794:
11795: =item *
11796:
1.243 albertel 11797: ssi($url,%hash) : server side include, does a complete request cycle on url to
11798: localhost, posts hash
11799:
11800: =back
11801:
11802: =head2 Data to String to Data
11803:
11804: =over 4
1.191 harris41 11805:
11806: =item *
11807:
1.243 albertel 11808: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11809: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11810:
11811: =item *
11812:
1.243 albertel 11813: hashref2str($hashref) : convert a hashref into a string complete with
11814: escaping and '=' and '&' separators, supports elements that are
11815: arrayrefs and hashrefs
1.191 harris41 11816:
11817: =item *
11818:
1.243 albertel 11819: arrayref2str($arrayref) : convert an arrayref into a string complete
11820: with escaping and '&' separators, supports elements that are arrayrefs
11821: and hashrefs
1.191 harris41 11822:
11823: =item *
11824:
1.243 albertel 11825: str2hash($string) : convert string to hash using unescaping and
11826: splitting on '=' and '&', supports elements that are arrayrefs and
11827: hashrefs
1.191 harris41 11828:
11829: =item *
11830:
1.243 albertel 11831: str2array($string) : convert string to hash using unescaping and
11832: splitting on '&', supports elements that are arrayrefs and hashrefs
11833:
11834: =back
11835:
11836: =head2 Logging Routines
11837:
11838:
11839: These routines allow one to make log messages in the lonnet.log and
11840: lonnet.perm logfiles.
1.191 harris41 11841:
1.1119 foxr 11842: =over 4
11843:
1.191 harris41 11844: =item *
11845:
1.243 albertel 11846: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 11847:
11848: =item *
11849:
1.243 albertel 11850: logthis() : append message to the normal lonnet.log file, it gets
11851: preiodically rolled over and deleted.
1.191 harris41 11852:
11853: =item *
11854:
1.243 albertel 11855: logperm() : append a permanent message to lonnet.perm.log, this log
11856: file never gets deleted by any automated portion of the system, only
11857: messages of critical importance should go in here.
11858:
1.1119 foxr 11859:
1.243 albertel 11860: =back
11861:
11862: =head2 General File Helper Routines
11863:
11864: =over 4
1.191 harris41 11865:
11866: =item *
11867:
1.481 raeburn 11868: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11869: (a) files in /uploaded
11870: (i) If a local copy of the file exists -
11871: compares modification date of local copy with last-modified date for
11872: definitive version stored on home server for course. If local copy is
11873: stale, requests a new version from the home server and stores it.
11874: If the original has been removed from the home server, then local copy
11875: is unlinked.
11876: (ii) If local copy does not exist -
11877: requests the file from the home server and stores it.
11878:
11879: If $caller is 'uploadrep':
11880: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11881: for request for files originally uploaded via DOCS.
11882: - returns 'ok' if fresh local copy now available, -1 otherwise.
11883:
11884: Otherwise:
11885: This indicates a call from the content generation phase of the request.
11886: - returns the entire contents of the file or -1.
11887:
11888: (b) files in /res
11889: - returns the entire contents of a file or -1;
11890: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11891:
1.712 albertel 11892:
11893: =item *
11894:
11895: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11896: reference
11897:
11898: returns either a stat() list of data about the file or an empty list
11899: if the file doesn't exist or couldn't find out about it (connection
11900: problems or user unknown)
11901:
1.191 harris41 11902: =item *
11903:
1.243 albertel 11904: filelocation($dir,$file) : returns file system location of a file
11905: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11906: directory that relative $file lookups are to looked in ($dir of /a/dir
11907: and a file of ../bob will become /a/bob)
1.191 harris41 11908:
11909: =item *
11910:
11911: hreflocation($dir,$file) : returns file system location or a URL; same as
11912: filelocation except for hrefs
11913:
11914: =item *
11915:
11916: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11917:
1.243 albertel 11918: =back
11919:
1.608 albertel 11920: =head2 Usererfile file routines (/uploaded*)
11921:
11922: =over 4
11923:
11924: =item *
11925:
11926: userfileupload(): main rotine for putting a file in a user or course's
11927: filespace, arguments are,
11928:
1.620 albertel 11929: formname - required - this is the name of the element in $env where the
1.608 albertel 11930: filename, and the contents of the file to create/modifed exist
1.620 albertel 11931: the filename is in $env{'form.'.$formname.'.filename'} and the
11932: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 11933: context - if coursedoc, store the file in the course of the active role
11934: of the current user;
11935: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
11936: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 11937: subdir - required - subdirectory to put the file in under ../userfiles/
11938: if undefined, it will be placed in "unknown"
11939:
11940: (This routine calls clean_filename() to remove any dangerous
11941: characters from the filename, and then calls finuserfileupload() to
11942: complete the transaction)
11943:
11944: returns either the url of the uploaded file (/uploaded/....) if successful
11945: and /adm/notfound.html if unsuccessful
11946:
11947: =item *
11948:
11949: clean_filename(): routine for cleaing a filename up for storage in
11950: userfile space, argument is:
11951:
11952: filename - proposed filename
11953:
11954: returns: the new clean filename
11955:
11956: =item *
11957:
1.1090 raeburn 11958: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 11959: userspace, probably shouldn't be called directly
11960:
11961: docuname: username or courseid of destination for the file
11962: docudom: domain of user/course of destination for the file
11963: formname: same as for userfileupload()
1.1090 raeburn 11964: fname: filename (including subdirectories) for the file
11965: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
11966: allfiles: reference to hash used to store objects found by parser
11967: codebase: reference to hash used for codebases of java objects found by parser
11968: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
11969: thumbheight: height (pixels) of thumbnail to be created for uploaded image
11970: resizewidth: width to be used to resize image using resizeImage from ImageMagick
11971: resizeheight: height to be used to resize image using resizeImage from ImageMagick
11972: context: if 'overwrite', will move the uploaded file from its temporary location to
11973: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 11974: mimetype: reference to scalar to accommodate mime type determined
11975: from File::MMagic if $parser = parse.
1.608 albertel 11976:
11977: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 11978: and /adm/notfound.html if unsuccessful (or an error message if context
11979: was 'overwrite').
11980:
1.608 albertel 11981:
11982: =item *
11983:
11984: renameuserfile(): renames an existing userfile to a new name
11985:
11986: Args:
11987: docuname: username or courseid of destination for the file
11988: docudom: domain of user/course of destination for the file
11989: old: current file name (including any subdirs under userfiles)
11990: new: desired file name (including any subdirs under userfiles)
11991:
11992: =item *
11993:
11994: mkdiruserfile(): creates a directory is a userfiles dir
11995:
11996: Args:
11997: docuname: username or courseid of destination for the file
11998: docudom: domain of user/course of destination for the file
11999: dir: dir to create (including any subdirs under userfiles)
12000:
12001: =item *
12002:
12003: removeuserfile(): removes a file that exists in userfiles
12004:
12005: Args:
12006: docuname: username or courseid of destination for the file
12007: docudom: domain of user/course of destination for the file
12008: fname: filname to delete (including any subdirs under userfiles)
12009:
12010: =item *
12011:
12012: removeuploadedurl(): convience function for removeuserfile()
12013:
12014: Args:
12015: url: a full /uploaded/... url to delete
12016:
1.747 albertel 12017: =item *
12018:
12019: get_portfile_permissions():
12020: Args:
12021: domain: domain of user or course contain the portfolio files
12022: user: name of user or num of course contain the portfolio files
12023: Returns:
12024: hashref of a dump of the proper file_permissions.db
12025:
12026:
12027: =item *
12028:
12029: get_access_controls():
12030:
12031: Args:
12032: current_permissions: the hash ref returned from get_portfile_permissions()
12033: group: (optional) the group you want the files associated with
12034: file: (optional) the file you want access info on
12035:
12036: Returns:
1.749 raeburn 12037: a hash (keys are file names) of hashes containing
12038: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12039: values are XML containing access control settings (see below)
1.747 albertel 12040:
12041: Internal notes:
12042:
1.749 raeburn 12043: access controls are stored in file_permissions.db as key=value pairs.
12044: key -> path to file/file_name\0uniqueID:scope_end_start
12045: where scope -> public,guest,course,group,domains or users.
12046: end -> UNIX time for end of access (0 -> no end date)
12047: start -> UNIX time for start of access
12048:
12049: value -> XML description of access control
12050: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12051: <start></start>
12052: <end></end>
12053:
12054: <password></password> for scope type = guest
12055:
12056: <domain></domain> for scope type = course or group
12057: <number></number>
12058: <roles id="">
12059: <role></role>
12060: <access></access>
12061: <section></section>
12062: <group></group>
12063: </roles>
12064:
12065: <dom></dom> for scope type = domains
12066:
12067: <users> for scope type = users
12068: <user>
12069: <uname></uname>
12070: <udom></udom>
12071: </user>
12072: </users>
12073: </scope>
12074:
12075: Access data is also aggregated for each file in an additional key=value pair:
12076: key -> path to file/file_name\0accesscontrol
12077: value -> reference to hash
12078: hash contains key = value pairs
12079: where key = uniqueID:scope_end_start
12080: value = UNIX time record was last updated
12081:
12082: Used to improve speed of look-ups of access controls for each file.
12083:
12084: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12085:
12086: modify_access_controls():
12087:
12088: Modifies access controls for a portfolio file
12089: Args
12090: 1. file name
12091: 2. reference to hash of required changes,
12092: 3. domain
12093: 4. username
12094: where domain,username are the domain of the portfolio owner
12095: (either a user or a course)
12096:
12097: Returns:
12098: 1. result of additions or updates ('ok' or 'error', with error message).
12099: 2. result of deletions ('ok' or 'error', with error message).
12100: 3. reference to hash of any new or updated access controls.
12101: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12102: key = integer (inbound ID)
12103: value = uniqueID
1.747 albertel 12104:
1.608 albertel 12105: =back
12106:
1.243 albertel 12107: =head2 HTTP Helper Routines
12108:
12109: =over 4
12110:
1.191 harris41 12111: =item *
12112:
12113: escape() : unpack non-word characters into CGI-compatible hex codes
12114:
12115: =item *
12116:
12117: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12118:
1.243 albertel 12119: =back
12120:
12121: =head1 PRIVATE SUBROUTINES
12122:
12123: =head2 Underlying communication routines (Shouldn't call)
12124:
12125: =over 4
12126:
12127: =item *
12128:
12129: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12130:
12131: =item *
12132:
12133: reply() : uses subreply to send a message to remote machine, logs all failures
12134:
12135: =item *
12136:
12137: critical() : passes a critical message to another server; if cannot
12138: get through then place message in connection buffer directory and
12139: returns con_delayed, if incapable of saving message, returns
12140: con_failed
12141:
12142: =item *
12143:
12144: reconlonc() : tries to reconnect lonc client processes.
12145:
12146: =back
12147:
12148: =head2 Resource Access Logging
12149:
12150: =over 4
12151:
12152: =item *
12153:
12154: flushcourselogs() : flush (save) buffer logs and access logs
12155:
12156: =item *
12157:
12158: courselog($what) : save message for course in hash
12159:
12160: =item *
12161:
12162: courseacclog($what) : save message for course using &courselog(). Perform
12163: special processing for specific resource types (problems, exams, quizzes, etc).
12164:
1.191 harris41 12165: =item *
12166:
12167: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12168: as a PerlChildExitHandler
1.243 albertel 12169:
12170: =back
12171:
12172: =head2 Other
12173:
12174: =over 4
12175:
12176: =item *
12177:
12178: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 12179:
12180: =back
12181:
12182: =cut
1.877 foxr 12183:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>