Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1189
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1189 ! raeburn 4: # $Id: lonnet.pm,v 1.1188 2012/08/27 14:33:24 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.1182 foxr 78:
1.1173 foxr 79: use Encode;
80:
1.871 albertel 81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 82: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
83: %managerstab);
1.871 albertel 84:
85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
86: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
87: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 88: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 89:
1.1 albertel 90: use IO::Socket;
1.31 www 91: use GDBM_File;
1.208 albertel 92: use HTML::LCParser;
1.88 www 93: use Fcntl qw(:flock);
1.870 albertel 94: use Storable qw(thaw nfreeze);
1.539 albertel 95: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 96: use Cache::Memcached;
1.676 albertel 97: use Digest::MD5;
1.790 albertel 98: use Math::Random;
1.1024 raeburn 99: use File::MMagic;
1.807 albertel 100: use LONCAPA qw(:DEFAULT :match);
1.740 www 101: use LONCAPA::Configuration;
1.1160 www 102: use LONCAPA::lonmetadata;
1.1167 droeschl 103: use LONCAPA::Lond;
1.1117 foxr 104:
1.1090 raeburn 105: use File::Copy;
1.676 albertel 106:
1.195 www 107: my $readit;
1.550 foxr 108: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 109:
1.619 albertel 110: require Exporter;
111:
112: our @ISA = qw (Exporter);
113: our @EXPORT = qw(%env);
114:
1.449 matthew 115:
1.1187 raeburn 116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729 www 117: {
118: my $logid;
1.1187 raeburn 119: sub write_log {
1.1188 raeburn 120: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184 raeburn 121: if ($context eq 'course') {
122: if (($cnum eq '') || ($cdom eq '')) {
123: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
124: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
125: }
1.957 raeburn 126: }
1.1184 raeburn 127: $logid ++;
1.957 raeburn 128: my $now = time();
129: my $id=$now.'00000'.$$.'00000'.$logid;
1.1184 raeburn 130: my $logentry = {
131: $id => {
132: 'exe_uname' => $env{'user.name'},
133: 'exe_udom' => $env{'user.domain'},
134: 'exe_time' => $now,
135: 'exe_ip' => $ENV{'REMOTE_ADDR'},
136: 'delflag' => $delflag,
137: 'logentry' => $storehash,
138: 'uname' => $uname,
139: 'udom' => $udom,
140: }
141: };
142: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729 www 143: }
144: }
1.1 albertel 145:
1.163 harris41 146: sub logtouch {
147: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 148: unless (-e "$execdir/logs/lonnet.log") {
149: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 150: close $fh;
151: }
152: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
153: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
154: }
155:
1.1 albertel 156: sub logthis {
157: my $message=shift;
158: my $execdir=$perlvar{'lonDaemons'};
159: my $now=time;
160: my $local=localtime($now);
1.448 albertel 161: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 162: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
163: print $fh $logstring;
1.448 albertel 164: close($fh);
165: }
1.1 albertel 166: return 1;
167: }
168:
169: sub logperm {
170: my $message=shift;
171: my $execdir=$perlvar{'lonDaemons'};
172: my $now=time;
173: my $local=localtime($now);
1.448 albertel 174: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
175: print $fh "$now:$message:$local\n";
176: close($fh);
177: }
1.1 albertel 178: return 1;
179: }
180:
1.850 albertel 181: sub create_connection {
1.853 albertel 182: my ($hostname,$lonid) = @_;
1.851 albertel 183: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 184: Type => SOCK_STREAM,
185: Timeout => 10);
186: return 0 if (!$client);
1.890 albertel 187: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 188: my $result = <$client>;
189: chomp($result);
190: return 1 if ($result eq 'done');
191: return 0;
192: }
193:
1.983 raeburn 194: sub get_server_timezone {
195: my ($cnum,$cdom) = @_;
196: my $home=&homeserver($cnum,$cdom);
197: if ($home ne 'no_host') {
198: my $cachetime = 24*3600;
199: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
200: if (defined($cached)) {
201: return $timezone;
202: } else {
203: my $timezone = &reply('servertimezone',$home);
204: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
205: }
206: }
207: }
1.850 albertel 208:
1.1106 raeburn 209: sub get_server_distarch {
210: my ($lonhost,$ignore_cache) = @_;
211: if (defined($lonhost)) {
212: if (!defined(&hostname($lonhost))) {
213: return;
214: }
215: my $cachetime = 12*3600;
216: if (!$ignore_cache) {
217: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
218: if (defined($cached)) {
219: return $distarch;
220: }
221: }
222: my $rep = &reply('serverdistarch',$lonhost);
223: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
224: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
225: $rep eq '') {
226: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
227: }
228: }
229: return;
230: }
231:
1.993 raeburn 232: sub get_server_loncaparev {
1.1073 raeburn 233: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 234: if (defined($lonhost)) {
235: if (!defined(&hostname($lonhost))) {
236: undef($lonhost);
237: }
238: }
239: if (!defined($lonhost)) {
240: if (defined(&domain($dom,'primary'))) {
241: $lonhost=&domain($dom,'primary');
242: if ($lonhost eq 'no_host') {
243: undef($lonhost);
244: }
245: }
246: }
247: if (defined($lonhost)) {
1.1073 raeburn 248: my $cachetime = 12*3600;
249: if (!$ignore_cache) {
250: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
251: if (defined($cached)) {
252: return $loncaparev;
253: }
254: }
255: my ($answer,$loncaparev);
256: my @ids=¤t_machine_ids();
257: if (grep(/^\Q$lonhost\E$/,@ids)) {
258: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 259: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 260: $loncaparev = $1;
261: }
262: } else {
263: $answer = &reply('serverloncaparev',$lonhost);
264: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
265: if ($caller eq 'loncron') {
266: my $ua=new LWP::UserAgent;
1.1082 raeburn 267: $ua->timeout(4);
1.1073 raeburn 268: my $protocol = $protocol{$lonhost};
269: $protocol = 'http' if ($protocol ne 'https');
270: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
271: my $request=new HTTP::Request('GET',$url);
272: my $response=$ua->request($request);
273: unless ($response->is_error()) {
274: my $content = $response->content;
1.1081 raeburn 275: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 276: $loncaparev = $1;
277: }
278: }
279: } else {
280: $loncaparev = $loncaparevs{$lonhost};
281: }
1.1081 raeburn 282: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 283: $loncaparev = $1;
284: }
1.993 raeburn 285: }
1.1073 raeburn 286: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 287: }
288: }
289:
1.1074 raeburn 290: sub get_server_homeID {
291: my ($hostname,$ignore_cache,$caller) = @_;
292: unless ($ignore_cache) {
293: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
294: if (defined($cached)) {
295: return $serverhomeID;
296: }
297: }
298: my $cachetime = 12*3600;
299: my $serverhomeID;
300: if ($caller eq 'loncron') {
301: my @machine_ids = &machine_ids($hostname);
302: foreach my $id (@machine_ids) {
303: my $response = &reply('serverhomeID',$id);
304: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
305: $serverhomeID = $response;
306: last;
307: }
308: }
309: if ($serverhomeID eq '') {
310: $serverhomeID = $machine_ids[-1];
311: }
312: } else {
313: $serverhomeID = $serverhomeIDs{$hostname};
314: }
315: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
316: }
317:
1.1121 raeburn 318: sub get_remote_globals {
319: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 320: my ($result,%returnhash,%whatneeded);
321: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 322: foreach my $what (sort(keys(%{$whathash}))) {
323: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 324: my ($response,$cached);
1.1121 raeburn 325: unless ($ignore_cache) {
1.1125 raeburn 326: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 327: }
328: if (defined($cached)) {
1.1125 raeburn 329: $returnhash{$what} = $response;
1.1121 raeburn 330: } else {
1.1125 raeburn 331: $whatneeded{$what} = 1;
1.1121 raeburn 332: }
333: }
1.1125 raeburn 334: if (keys(%whatneeded) == 0) {
335: $result = 'ok';
336: } else {
1.1121 raeburn 337: my $requested = &freeze_escape(\%whatneeded);
338: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 339: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
340: ($rep eq 'unknown_cmd')) {
341: $result = $rep;
342: } else {
343: $result = 'ok';
1.1121 raeburn 344: my @pairs=split(/\&/,$rep);
1.1125 raeburn 345: foreach my $item (@pairs) {
346: my ($key,$value)=split(/=/,$item,2);
347: my $what = &unescape($key);
348: my $hashid = $lonhost.'-'.$what;
349: $returnhash{$what}=&thaw_unescape($value);
350: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 351: }
352: }
353: }
354: }
1.1125 raeburn 355: return ($result,\%returnhash);
1.1121 raeburn 356: }
357:
1.1124 raeburn 358: sub remote_devalidate_cache {
359: my ($lonhost,$name,$id) = @_;
1.1130 raeburn 360: my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124 raeburn 361: return $response;
362: }
363:
1.1 albertel 364: # -------------------------------------------------- Non-critical communication
365: sub subreply {
366: my ($cmd,$server)=@_;
1.838 albertel 367: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 368: #
369: # With loncnew process trimming, there's a timing hole between lonc server
370: # process exit and the master server picking up the listen on the AF_UNIX
371: # socket. In that time interval, a lock file will exist:
372:
373: my $lockfile=$peerfile.".lock";
374: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
375: sleep(1);
376: }
377: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 378: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 379: #
1.550 foxr 380: # We'll give the connection a few tries before abandoning it. If
381: # connection is not possible, we'll con_lost back to the client.
382: #
383: my $client;
384: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
385: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
386: Type => SOCK_STREAM,
387: Timeout => 10);
1.869 albertel 388: if ($client) {
1.550 foxr 389: last; # Connected!
1.850 albertel 390: } else {
1.853 albertel 391: &create_connection(&hostname($server),$server);
1.550 foxr 392: }
1.850 albertel 393: sleep(1); # Try again later if failed connection.
1.550 foxr 394: }
395: my $answer;
396: if ($client) {
1.704 albertel 397: print $client "sethost:$server:$cmd\n";
1.550 foxr 398: $answer=<$client>;
399: if (!$answer) { $answer="con_lost"; }
400: chomp($answer);
401: } else {
402: $answer = 'con_lost'; # Failed connection.
403: }
1.1 albertel 404: return $answer;
405: }
406:
407: sub reply {
408: my ($cmd,$server)=@_;
1.838 albertel 409: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 410: my $answer=subreply($cmd,$server);
1.65 www 411: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 412: &logthis("<font color=\"blue\">WARNING:".
1.12 www 413: " $cmd to $server returned $answer</font>");
414: }
1.1 albertel 415: return $answer;
416: }
417:
418: # ----------------------------------------------------------- Send USR1 to lonc
419:
420: sub reconlonc {
1.891 albertel 421: my ($lonid) = @_;
422: my $hostname = &hostname($lonid);
423: if ($lonid) {
424: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
425: if ($hostname && -e $peerfile) {
426: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
427: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
428: Type => SOCK_STREAM,
429: Timeout => 10);
430: if ($client) {
431: print $client ("reset_retries\n");
432: my $answer=<$client>;
433: #reset just this one.
434: }
435: }
436: return;
437: }
438:
1.836 www 439: &logthis("Trying to reconnect lonc");
1.1 albertel 440: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 441: if (open(my $fh,"<$loncfile")) {
1.1 albertel 442: my $loncpid=<$fh>;
443: chomp($loncpid);
444: if (kill 0 => $loncpid) {
445: &logthis("lonc at pid $loncpid responding, sending USR1");
446: kill USR1 => $loncpid;
447: sleep 1;
1.836 www 448: } else {
1.12 www 449: &logthis(
1.672 albertel 450: "<font color=\"blue\">WARNING:".
1.12 www 451: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 452: }
453: } else {
1.836 www 454: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 455: }
456: }
457:
458: # ------------------------------------------------------ Critical communication
1.12 www 459:
1.1 albertel 460: sub critical {
461: my ($cmd,$server)=@_;
1.838 albertel 462: unless (&hostname($server)) {
1.672 albertel 463: &logthis("<font color=\"blue\">WARNING:".
1.89 www 464: " Critical message to unknown server ($server)</font>");
465: return 'no_such_host';
466: }
1.1 albertel 467: my $answer=reply($cmd,$server);
468: if ($answer eq 'con_lost') {
469: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 470: my $answer=reply($cmd,$server);
1.1 albertel 471: if ($answer eq 'con_lost') {
472: my $now=time;
473: my $middlename=$cmd;
1.5 www 474: $middlename=substr($middlename,0,16);
1.1 albertel 475: $middlename=~s/\W//g;
476: my $dfilename=
1.305 www 477: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
478: $dumpcount++;
1.1 albertel 479: {
1.448 albertel 480: my $dfh;
481: if (open($dfh,">$dfilename")) {
482: print $dfh "$cmd\n";
483: close($dfh);
484: }
1.1 albertel 485: }
486: sleep 2;
487: my $wcmd='';
488: {
1.448 albertel 489: my $dfh;
490: if (open($dfh,"<$dfilename")) {
491: $wcmd=<$dfh>;
492: close($dfh);
493: }
1.1 albertel 494: }
495: chomp($wcmd);
1.7 www 496: if ($wcmd eq $cmd) {
1.672 albertel 497: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 498: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 499: &logperm("D:$server:$cmd");
500: return 'con_delayed';
501: } else {
1.672 albertel 502: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 503: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 504: &logperm("F:$server:$cmd");
505: return 'con_failed';
506: }
507: }
508: }
509: return $answer;
1.405 albertel 510: }
511:
1.755 albertel 512: # ------------------------------------------- check if return value is an error
513:
514: sub error {
515: my ($result) = @_;
1.756 albertel 516: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 517: if ($2 == 2) { return undef; }
518: return $1;
519: }
520: return undef;
521: }
522:
1.783 albertel 523: sub convert_and_load_session_env {
524: my ($lonidsdir,$handle)=@_;
525: my @profile;
526: {
1.917 albertel 527: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
528: if (!$opened) {
1.915 albertel 529: return 0;
530: }
1.783 albertel 531: flock($idf,LOCK_SH);
532: @profile=<$idf>;
533: close($idf);
534: }
535: my %temp_env;
536: foreach my $line (@profile) {
1.786 albertel 537: if ($line !~ m/=/) {
538: return 0;
539: }
1.783 albertel 540: chomp($line);
541: my ($envname,$envvalue)=split(/=/,$line,2);
542: $temp_env{&unescape($envname)} = &unescape($envvalue);
543: }
544: unlink("$lonidsdir/$handle.id");
545: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
546: 0640)) {
547: %disk_env = %temp_env;
548: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
549: untie(%disk_env);
550: }
1.786 albertel 551: return 1;
1.783 albertel 552: }
553:
1.374 www 554: # ------------------------------------------- Transfer profile into environment
1.780 albertel 555: my $env_loaded;
556: sub transfer_profile_to_env {
1.788 albertel 557: my ($lonidsdir,$handle,$force_transfer) = @_;
558: if (!$force_transfer && $env_loaded) { return; }
1.374 www 559:
1.720 albertel 560: if (!defined($lonidsdir)) {
561: $lonidsdir = $perlvar{'lonIDsDir'};
562: }
563: if (!defined($handle)) {
564: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
565: }
566:
1.786 albertel 567: my $convert;
568: {
1.917 albertel 569: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
570: if (!$opened) {
1.915 albertel 571: return;
572: }
1.786 albertel 573: flock($idf,LOCK_SH);
574: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
575: &GDBM_READER(),0640)) {
576: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
577: untie(%disk_env);
578: } else {
579: $convert = 1;
580: }
581: }
582: if ($convert) {
583: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
584: &logthis("Failed to load session, or convert session.");
585: }
1.374 www 586: }
1.783 albertel 587:
1.786 albertel 588: my %remove;
1.783 albertel 589: while ( my $envname = each(%env) ) {
1.433 matthew 590: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
591: if ($time < time-300) {
1.783 albertel 592: $remove{$key}++;
1.433 matthew 593: }
594: }
595: }
1.783 albertel 596:
1.619 albertel 597: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 598: $env_loaded=1;
1.783 albertel 599: foreach my $expired_key (keys(%remove)) {
1.433 matthew 600: &delenv($expired_key);
1.374 www 601: }
1.1 albertel 602: }
603:
1.916 albertel 604: # ---------------------------------------------------- Check for valid session
605: sub check_for_valid_session {
1.1155 raeburn 606: my ($r,$name) = @_;
1.916 albertel 607: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 608: if ($name eq '') {
609: $name = 'lonID';
610: }
611: my $lonid=$cookies{$name};
1.916 albertel 612: return undef if (!$lonid);
613:
614: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 615: my $lonidsdir;
616: if ($name eq 'lonDAV') {
617: $lonidsdir=$r->dir_config('lonDAVsessDir');
618: } else {
619: $lonidsdir=$r->dir_config('lonIDsDir');
620: }
1.916 albertel 621: return undef if (!-e "$lonidsdir/$handle.id");
622:
1.917 albertel 623: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
624: return undef if (!$opened);
1.916 albertel 625:
626: flock($idf,LOCK_SH);
627: my %disk_env;
628: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
629: &GDBM_READER(),0640)) {
630: return undef;
631: }
632:
633: if (!defined($disk_env{'user.name'})
634: || !defined($disk_env{'user.domain'})) {
635: return undef;
636: }
637: return $handle;
638: }
639:
1.830 albertel 640: sub timed_flock {
641: my ($file,$lock_type) = @_;
642: my $failed=0;
643: eval {
644: local $SIG{__DIE__}='DEFAULT';
645: local $SIG{ALRM}=sub {
646: $failed=1;
647: die("failed lock");
648: };
649: alarm(13);
650: flock($file,$lock_type);
651: alarm(0);
652: };
653: if ($failed) {
654: return undef;
655: } else {
656: return 1;
657: }
658: }
659:
1.5 www 660: # ---------------------------------------------------------- Append Environment
661:
662: sub appenv {
1.949 raeburn 663: my ($newenv,$roles) = @_;
664: if (ref($newenv) eq 'HASH') {
665: foreach my $key (keys(%{$newenv})) {
666: my $refused = 0;
667: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
668: $refused = 1;
669: if (ref($roles) eq 'ARRAY') {
670: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
671: if (grep(/^\Q$role\E$/,@{$roles})) {
672: $refused = 0;
673: }
674: }
675: }
676: if ($refused) {
677: &logthis("<font color=\"blue\">WARNING: ".
678: "Attempt to modify environment ".$key." to ".$newenv->{$key}
679: .'</font>');
680: delete($newenv->{$key});
681: } else {
682: $env{$key}=$newenv->{$key};
683: }
684: }
685: my $opened = open(my $env_file,'+<',$env{'user.environment'});
686: if ($opened
687: && &timed_flock($env_file,LOCK_EX)
688: &&
689: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
690: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
691: while (my ($key,$value) = each(%{$newenv})) {
692: $disk_env{$key} = $value;
693: }
694: untie(%disk_env);
1.35 www 695: }
1.191 harris41 696: }
1.56 www 697: return 'ok';
698: }
699: # ----------------------------------------------------- Delete from Environment
700:
701: sub delenv {
1.1104 raeburn 702: my ($delthis,$regexp,$roles) = @_;
703: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
704: my $refused = 1;
705: if (ref($roles) eq 'ARRAY') {
706: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
707: if (grep(/^\Q$role\E$/,@{$roles})) {
708: $refused = 0;
709: }
710: }
711: if ($refused) {
712: &logthis("<font color=\"blue\">WARNING: ".
713: "Attempt to delete from environment ".$delthis);
714: return 'error';
715: }
1.56 www 716: }
1.917 albertel 717: my $opened = open(my $env_file,'+<',$env{'user.environment'});
718: if ($opened
1.915 albertel 719: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 720: &&
721: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
722: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 723: foreach my $key (keys(%disk_env)) {
1.987 raeburn 724: if ($regexp) {
725: if ($key=~/^$delthis/) {
726: delete($env{$key});
727: delete($disk_env{$key});
728: }
729: } else {
730: if ($key=~/^\Q$delthis\E/) {
731: delete($env{$key});
732: delete($disk_env{$key});
733: }
734: }
1.448 albertel 735: }
1.783 albertel 736: untie(%disk_env);
1.5 www 737: }
738: return 'ok';
1.369 albertel 739: }
740:
1.790 albertel 741: sub get_env_multiple {
742: my ($name) = @_;
743: my @values;
744: if (defined($env{$name})) {
745: # exists is it an array
746: if (ref($env{$name})) {
747: @values=@{ $env{$name} };
748: } else {
749: $values[0]=$env{$name};
750: }
751: }
752: return(@values);
753: }
754:
1.958 www 755: # ------------------------------------------------------------------- Locking
756:
757: sub set_lock {
758: my ($text)=@_;
759: $locknum++;
760: my $id=$$.'-'.$locknum;
761: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
762: 'session.lock.'.$id => $text});
763: return $id;
764: }
765:
766: sub get_locks {
767: my $num=0;
768: my %texts=();
769: foreach my $lock (split(/\,/,$env{'session.locks'})) {
770: if ($lock=~/\w/) {
771: $num++;
772: $texts{$lock}=$env{'session.lock.'.$lock};
773: }
774: }
775: return ($num,%texts);
776: }
777:
778: sub remove_lock {
779: my ($id)=@_;
780: my $newlocks='';
781: foreach my $lock (split(/\,/,$env{'session.locks'})) {
782: if (($lock=~/\w/) && ($lock ne $id)) {
783: $newlocks.=','.$lock;
784: }
785: }
786: &appenv({'session.locks' => $newlocks});
787: &delenv('session.lock.'.$id);
788: }
789:
790: sub remove_all_locks {
791: my $activelocks=$env{'session.locks'};
792: foreach my $lock (split(/\,/,$env{'session.locks'})) {
793: if ($lock=~/\w/) {
794: &remove_lock($lock);
795: }
796: }
797: }
798:
799:
1.369 albertel 800: # ------------------------------------------ Find out current server userload
801: sub userload {
802: my $numusers=0;
803: {
804: opendir(LONIDS,$perlvar{'lonIDsDir'});
805: my $filename;
806: my $curtime=time;
807: while ($filename=readdir(LONIDS)) {
1.925 albertel 808: next if ($filename eq '.' || $filename eq '..');
809: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 810: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 811: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 812: }
813: closedir(LONIDS);
814: }
815: my $userloadpercent=0;
816: my $maxuserload=$perlvar{'lonUserLoadLim'};
817: if ($maxuserload) {
1.371 albertel 818: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 819: }
1.372 albertel 820: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 821: return $userloadpercent;
1.283 www 822: }
823:
1.1 albertel 824: # ------------------------------ Find server with least workload from spare.tab
1.11 www 825:
1.1 albertel 826: sub spareserver {
1.1083 raeburn 827: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 828: my $spare_server;
1.370 albertel 829: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 830: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
831: : $userloadpercent;
1.1083 raeburn 832: my ($uint_dom,$remotesessions);
833: if (($udom ne '') && (&domain($udom) ne '')) {
834: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
835: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
836: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
837: $remotesessions = $udomdefaults{'remotesessions'};
838: }
1.1123 raeburn 839: my $spareshash = &this_host_spares($udom);
840: if (ref($spareshash) eq 'HASH') {
841: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
842: foreach my $try_server (@{ $spareshash->{'primary'} }) {
843: if ($uint_dom) {
844: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
845: $try_server));
846: }
847: ($spare_server, $lowest_load) =
848: &compare_server_load($try_server, $spare_server, $lowest_load);
849: }
1.1083 raeburn 850: }
1.784 albertel 851:
1.1123 raeburn 852: my $found_server = ($spare_server ne '' && $lowest_load < 100);
853:
854: if (!$found_server) {
855: if (ref($spareshash->{'default'}) eq 'ARRAY') {
856: foreach my $try_server (@{ $spareshash->{'default'} }) {
857: if ($uint_dom) {
858: next unless (&spare_can_host($udom,$uint_dom,
859: $remotesessions,$try_server));
860: }
861: ($spare_server, $lowest_load) =
862: &compare_server_load($try_server, $spare_server, $lowest_load);
863: }
864: }
865: }
1.784 albertel 866: }
867:
868: if (!$want_server_name) {
1.968 raeburn 869: my $protocol = 'http';
870: if ($protocol{$spare_server} eq 'https') {
871: $protocol = $protocol{$spare_server};
872: }
1.1001 raeburn 873: if (defined($spare_server)) {
874: my $hostname = &hostname($spare_server);
1.1083 raeburn 875: if (defined($hostname)) {
1.1001 raeburn 876: $spare_server = $protocol.'://'.$hostname;
877: }
878: }
1.784 albertel 879: }
880: return $spare_server;
881: }
882:
883: sub compare_server_load {
884: my ($try_server, $spare_server, $lowest_load) = @_;
885:
886: my $loadans = &reply('load', $try_server);
887: my $userloadans = &reply('userload',$try_server);
888:
889: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 890: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 891: }
892:
893: my $load;
894: if ($loadans =~ /\d/) {
895: if ($userloadans =~ /\d/) {
896: #both are numbers, pick the bigger one
897: $load = ($loadans > $userloadans) ? $loadans
898: : $userloadans;
1.411 albertel 899: } else {
1.784 albertel 900: $load = $loadans;
1.411 albertel 901: }
1.784 albertel 902: } else {
903: $load = $userloadans;
904: }
905:
906: if (($load =~ /\d/) && ($load < $lowest_load)) {
907: $spare_server = $try_server;
908: $lowest_load = $load;
1.370 albertel 909: }
1.784 albertel 910: return ($spare_server,$lowest_load);
1.202 matthew 911: }
1.914 albertel 912:
913: # --------------------------- ask offload servers if user already has a session
914: sub find_existing_session {
915: my ($udom,$uname) = @_;
1.1123 raeburn 916: my $spareshash = &this_host_spares($udom);
917: if (ref($spareshash) eq 'HASH') {
918: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
919: foreach my $try_server (@{ $spareshash->{'primary'} }) {
920: return $try_server if (&has_user_session($try_server, $udom, $uname));
921: }
922: }
923: if (ref($spareshash->{'default'}) eq 'ARRAY') {
924: foreach my $try_server (@{ $spareshash->{'default'} }) {
925: return $try_server if (&has_user_session($try_server, $udom, $uname));
926: }
927: }
1.914 albertel 928: }
929: return;
930: }
931:
932: # -------------------------------- ask if server already has a session for user
933: sub has_user_session {
934: my ($lonid,$udom,$uname) = @_;
935: my $result = &reply(join(':','userhassession',
936: map {&escape($_)} ($udom,$uname)),$lonid);
937: return 1 if ($result eq 'ok');
938:
939: return 0;
940: }
941:
1.1076 raeburn 942: # --------- determine least loaded server in a user's domain which allows login
943:
944: sub choose_server {
1.1115 raeburn 945: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 946: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 947: my %servers = &get_servers($udom);
1.1076 raeburn 948: my $lowest_load = 30000;
1.1151 raeburn 949: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 950: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 951: my $loginvia;
952: if ($checkloginvia) {
953: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 954: if ($loginvia) {
955: my ($server,$path) = split(/:/,$loginvia);
956: ($login_host, $lowest_load) =
957: &compare_server_load($server, $login_host, $lowest_load);
958: if ($login_host eq $server) {
959: $portal_path = $path;
1.1151 raeburn 960: $isredirect = 1;
1.1116 raeburn 961: }
962: } else {
963: ($login_host, $lowest_load) =
964: &compare_server_load($lonhost, $login_host, $lowest_load);
965: if ($login_host eq $lonhost) {
966: $portal_path = '';
1.1151 raeburn 967: $isredirect = '';
1.1116 raeburn 968: }
969: }
970: } else {
1.1076 raeburn 971: ($login_host, $lowest_load) =
1.1116 raeburn 972: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 973: }
974: }
975: if ($login_host ne '') {
1.1116 raeburn 976: $hostname = &hostname($login_host);
1.1076 raeburn 977: }
1.1151 raeburn 978: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 979: }
980:
1.202 matthew 981: # --------------------------------------------- Try to change a user's password
982:
983: sub changepass {
1.799 raeburn 984: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 985: $currentpass = &escape($currentpass);
986: $newpass = &escape($newpass);
1.1030 raeburn 987: my $lonhost = $perlvar{'lonHostID'};
988: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 989: $server);
990: if (! $answer) {
991: &logthis("No reply on password change request to $server ".
992: "by $uname in domain $udom.");
993: } elsif ($answer =~ "^ok") {
994: &logthis("$uname in $udom successfully changed their password ".
995: "on $server.");
996: } elsif ($answer =~ "^pwchange_failure") {
997: &logthis("$uname in $udom was unable to change their password ".
998: "on $server. The action was blocked by either lcpasswd ".
999: "or pwchange");
1000: } elsif ($answer =~ "^non_authorized") {
1001: &logthis("$uname in $udom did not get their password correct when ".
1002: "attempting to change it on $server.");
1003: } elsif ($answer =~ "^auth_mode_error") {
1004: &logthis("$uname in $udom attempted to change their password despite ".
1005: "not being locally or internally authenticated on $server.");
1006: } elsif ($answer =~ "^unknown_user") {
1007: &logthis("$uname in $udom attempted to change their password ".
1008: "on $server but were unable to because $server is not ".
1009: "their home server.");
1010: } elsif ($answer =~ "^refused") {
1011: &logthis("$server refused to change $uname in $udom password because ".
1012: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1013: } elsif ($answer =~ "invalid_client") {
1014: &logthis("$server refused to change $uname in $udom password because ".
1015: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1016: }
1017: return $answer;
1.1 albertel 1018: }
1019:
1.169 harris41 1020: # ----------------------- Try to determine user's current authentication scheme
1021:
1022: sub queryauthenticate {
1023: my ($uname,$udom)=@_;
1.456 albertel 1024: my $uhome=&homeserver($uname,$udom);
1025: if (!$uhome) {
1026: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1027: return 'no_host';
1028: }
1029: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1030: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1031: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1032: }
1.456 albertel 1033: return $answer;
1.169 harris41 1034: }
1035:
1.1 albertel 1036: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1037:
1.1 albertel 1038: sub authenticate {
1.1073 raeburn 1039: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1040: $upass=&escape($upass);
1041: $uname= &LONCAPA::clean_username($uname);
1.836 www 1042: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1043: my $newhome;
1.836 www 1044: if ((!$uhome) || ($uhome eq 'no_host')) {
1045: # Maybe the machine was offline and only re-appeared again recently?
1046: &reconlonc();
1047: # One more
1.952 raeburn 1048: $uhome=&homeserver($uname,$udom,1);
1049: if (($uhome eq 'no_host') && $checkdefauth) {
1050: if (defined(&domain($udom,'primary'))) {
1051: $newhome=&domain($udom,'primary');
1052: }
1053: if ($newhome ne '') {
1054: $uhome = $newhome;
1055: }
1056: }
1.836 www 1057: if ((!$uhome) || ($uhome eq 'no_host')) {
1058: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1059: return 'no_host';
1060: }
1.1 albertel 1061: }
1.1073 raeburn 1062: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1063: if ($answer eq 'authorized') {
1.952 raeburn 1064: if ($newhome) {
1065: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1066: return 'no_account_on_host';
1067: } else {
1068: &logthis("User $uname at $udom authorized by $uhome");
1069: return $uhome;
1070: }
1.471 albertel 1071: }
1072: if ($answer eq 'non_authorized') {
1073: &logthis("User $uname at $udom rejected by $uhome");
1074: return 'no_host';
1.9 www 1075: }
1.471 albertel 1076: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1077: return 'no_host';
1078: }
1079:
1.1073 raeburn 1080: sub can_host_session {
1.1074 raeburn 1081: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1082: my $canhost = 1;
1.1074 raeburn 1083: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1084: if (ref($remotesessions) eq 'HASH') {
1085: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1086: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1087: $canhost = 0;
1088: } else {
1089: $canhost = 1;
1090: }
1091: }
1092: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1093: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1094: $canhost = 1;
1095: } else {
1096: $canhost = 0;
1097: }
1098: }
1099: if ($canhost) {
1100: if ($remotesessions->{'version'} ne '') {
1101: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1102: if ($reqmajor ne '' && $reqminor ne '') {
1103: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1104: my $major = $1;
1105: my $minor = $2;
1106: if (($major < $reqmajor ) ||
1107: (($major == $reqmajor) && ($minor < $reqminor))) {
1108: $canhost = 0;
1109: }
1110: } else {
1111: $canhost = 0;
1112: }
1113: }
1114: }
1115: }
1116: }
1117: if ($canhost) {
1118: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1119: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1120: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1121: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1122: if (($uint_dom ne '') &&
1123: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1124: $canhost = 0;
1125: } else {
1126: $canhost = 1;
1127: }
1128: }
1129: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1130: if (($uint_dom ne '') &&
1131: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1132: $canhost = 1;
1133: } else {
1134: $canhost = 0;
1135: }
1136: }
1137: }
1138: }
1139: return $canhost;
1140: }
1141:
1.1083 raeburn 1142: sub spare_can_host {
1143: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1144: my $canhost=1;
1145: my @intdoms;
1146: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1147: if (ref($internet_names) eq 'ARRAY') {
1148: @intdoms = @{$internet_names};
1149: }
1150: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1151: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1152: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1153: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1154: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1155: $canhost = &can_host_session($udom,$try_server,$remoterev,
1156: $remotesessions,
1157: $defdomdefaults{'hostedsessions'});
1158: }
1159: return $canhost;
1160: }
1161:
1.1123 raeburn 1162: sub this_host_spares {
1163: my ($dom) = @_;
1.1126 raeburn 1164: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1165: my @hosts = ¤t_machine_ids();
1166: foreach my $lonhost (@hosts) {
1167: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1168: $dom_in_use = $dom;
1169: $lonhost_in_use = $lonhost;
1.1123 raeburn 1170: last;
1171: }
1172: }
1.1126 raeburn 1173: if ($dom_in_use ne '') {
1174: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1175: }
1176: if (ref($result) ne 'HASH') {
1177: $lonhost_in_use = $perlvar{'lonHostID'};
1178: $dom_in_use = &host_domain($lonhost_in_use);
1179: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1180: if (ref($result) ne 'HASH') {
1181: $result = \%spareid;
1182: }
1183: }
1184: return $result;
1185: }
1186:
1187: sub spares_for_offload {
1188: my ($dom_in_use,$lonhost_in_use) = @_;
1189: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1190: if (defined($cached)) {
1191: return $result;
1192: } else {
1.1126 raeburn 1193: my $cachetime = 60*60*24;
1194: my %domconfig =
1195: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1196: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1197: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1198: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1199: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1200: }
1201: }
1202: }
1203: }
1.1126 raeburn 1204: return;
1.1123 raeburn 1205: }
1206:
1.1129 raeburn 1207: sub get_lonbalancer_config {
1208: my ($servers) = @_;
1209: my ($currbalancer,$currtargets);
1210: if (ref($servers) eq 'HASH') {
1211: foreach my $server (keys(%{$servers})) {
1212: my %what = (
1213: spareid => 1,
1214: perlvar => 1,
1215: );
1216: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1217: if ($result eq 'ok') {
1218: if (ref($returnhash) eq 'HASH') {
1219: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1220: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1221: $currbalancer = $server;
1222: $currtargets = {};
1223: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1224: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1225: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1226: }
1227: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1228: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1229: }
1230: }
1231: last;
1232: }
1233: }
1234: }
1235: }
1236: }
1237: }
1238: return ($currbalancer,$currtargets);
1239: }
1240:
1241: sub check_loadbalancing {
1242: my ($uname,$udom) = @_;
1243: my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
1244: $offloadto,$otherserver);
1245: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1246: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1247: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1248: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1249: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1250: my $serverhomedom = &host_domain($lonhost);
1251:
1252: my $cachetime = 60*60*24;
1253:
1254: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1255: $dom_in_use = $udom;
1256: $homeintdom = 1;
1257: } else {
1258: $dom_in_use = $serverhomedom;
1259: }
1260: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1261: unless (defined($cached)) {
1262: my %domconfig =
1263: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1264: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1265: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1266: }
1267: }
1268: if (ref($result) eq 'HASH') {
1269: my $currbalancer = $result->{'lonhost'};
1270: my $currtargets = $result->{'targets'};
1271: my $currrules = $result->{'rules'};
1272: if ($currbalancer ne '') {
1273: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1274: $is_balancer = 1;
1275: }
1276: }
1277: if ($is_balancer) {
1278: if (ref($currrules) eq 'HASH') {
1279: if ($homeintdom) {
1280: if ($uname ne '') {
1281: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1282: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1283: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1284: $rule_in_effect = $currrules->{'_LC_author'};
1285: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1286: $rule_in_effect = $currrules->{'_LC_adv'}
1287: }
1288: }
1289: if ($rule_in_effect eq '') {
1290: my %userenv = &userenvironment($udom,$uname,'inststatus');
1291: if ($userenv{'inststatus'} ne '') {
1292: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1293: my ($othertitle,$usertypes,$types) =
1294: &Apache::loncommon::sorted_inst_types($udom);
1295: if (ref($types) eq 'ARRAY') {
1296: foreach my $type (@{$types}) {
1297: if (grep(/^\Q$type\E$/,@statuses)) {
1298: if (exists($currrules->{$type})) {
1299: $rule_in_effect = $currrules->{$type};
1300: }
1301: }
1302: }
1303: }
1304: } else {
1305: if (exists($currrules->{'default'})) {
1306: $rule_in_effect = $currrules->{'default'};
1307: }
1308: }
1309: }
1310: } else {
1311: if (exists($currrules->{'default'})) {
1312: $rule_in_effect = $currrules->{'default'};
1313: }
1314: }
1315: } else {
1316: if ($currrules->{'_LC_external'} ne '') {
1317: $rule_in_effect = $currrules->{'_LC_external'};
1318: }
1319: }
1320: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1321: $uname,$udom);
1322: }
1323: }
1324: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1325: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1326: unless (defined($cached)) {
1327: my %domconfig =
1328: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1329: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1330: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1331: }
1332: }
1333: if (ref($result) eq 'HASH') {
1334: my $currbalancer = $result->{'lonhost'};
1335: my $currtargets = $result->{'targets'};
1336: my $currrules = $result->{'rules'};
1337:
1338: if ($currbalancer eq $lonhost) {
1339: $is_balancer = 1;
1340: if (ref($currrules) eq 'HASH') {
1341: if ($currrules->{'_LC_internetdom'} ne '') {
1342: $rule_in_effect = $currrules->{'_LC_internetdom'};
1343: }
1344: }
1345: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1346: $uname,$udom);
1347: }
1348: } else {
1349: if ($perlvar{'lonBalancer'} eq 'yes') {
1350: $is_balancer = 1;
1351: $offloadto = &this_host_spares($dom_in_use);
1352: }
1353: }
1354: } else {
1355: if ($perlvar{'lonBalancer'} eq 'yes') {
1356: $is_balancer = 1;
1357: $offloadto = &this_host_spares($dom_in_use);
1358: }
1359: }
1.1176 raeburn 1360: if ($is_balancer) {
1361: my $lowest_load = 30000;
1362: if (ref($offloadto) eq 'HASH') {
1363: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1364: foreach my $try_server (@{$offloadto->{'primary'}}) {
1365: ($otherserver,$lowest_load) =
1366: &compare_server_load($try_server,$otherserver,$lowest_load);
1367: }
1.1129 raeburn 1368: }
1.1176 raeburn 1369: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1370:
1.1176 raeburn 1371: if (!$found_server) {
1372: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1373: foreach my $try_server (@{$offloadto->{'default'}}) {
1374: ($otherserver,$lowest_load) =
1375: &compare_server_load($try_server,$otherserver,$lowest_load);
1376: }
1377: }
1378: }
1379: } elsif (ref($offloadto) eq 'ARRAY') {
1380: if (@{$offloadto} == 1) {
1381: $otherserver = $offloadto->[0];
1382: } elsif (@{$offloadto} > 1) {
1383: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1384: ($otherserver,$lowest_load) =
1385: &compare_server_load($try_server,$otherserver,$lowest_load);
1386: }
1387: }
1388: }
1.1176 raeburn 1389: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1390: $is_balancer = 0;
1391: if ($uname ne '' && $udom ne '') {
1392: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1393:
1394: &appenv({'user.loadbalexempt' => $lonhost,
1395: 'user.loadbalcheck.time' => time});
1396: }
1.1129 raeburn 1397: }
1398: }
1399: }
1400: return ($is_balancer,$otherserver);
1401: }
1402:
1403: sub get_loadbalancer_targets {
1404: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1405: my $offloadto;
1.1175 raeburn 1406: if ($rule_in_effect eq 'none') {
1407: return [$perlvar{'lonHostID'}];
1408: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1409: $offloadto = $currtargets;
1410: } else {
1411: if ($rule_in_effect eq 'homeserver') {
1412: my $homeserver = &homeserver($uname,$udom);
1413: if ($homeserver ne 'no_host') {
1414: $offloadto = [$homeserver];
1415: }
1416: } elsif ($rule_in_effect eq 'externalbalancer') {
1417: my %domconfig =
1418: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1419: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1420: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1421: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1422: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1423: }
1424: }
1425: } else {
1.1178 raeburn 1426: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1427: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1428: if (&hostname($remotebalancer) ne '') {
1429: $offloadto = [$remotebalancer];
1430: }
1431: }
1432: } elsif (&hostname($rule_in_effect) ne '') {
1433: $offloadto = [$rule_in_effect];
1434: }
1435: }
1436: return $offloadto;
1437: }
1438:
1.1127 raeburn 1439: sub internet_dom_servers {
1440: my ($dom) = @_;
1441: my (%uniqservers,%servers);
1442: my $primaryserver = &hostname(&domain($dom,'primary'));
1443: my @machinedoms = &machine_domains($primaryserver);
1444: foreach my $mdom (@machinedoms) {
1445: my %currservers = %servers;
1446: my %server = &get_servers($mdom);
1447: %servers = (%currservers,%server);
1448: }
1449: my %by_hostname;
1450: foreach my $id (keys(%servers)) {
1451: push(@{$by_hostname{$servers{$id}}},$id);
1452: }
1453: foreach my $hostname (sort(keys(%by_hostname))) {
1454: if (@{$by_hostname{$hostname}} > 1) {
1455: my $match = 0;
1456: foreach my $id (@{$by_hostname{$hostname}}) {
1457: if (&host_domain($id) eq $dom) {
1458: $uniqservers{$id} = $hostname;
1459: $match = 1;
1460: }
1461: }
1462: unless ($match) {
1463: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1464: }
1465: } else {
1466: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1467: }
1468: }
1469: return %uniqservers;
1470: }
1471:
1.1 albertel 1472: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1473:
1.599 albertel 1474: my %homecache;
1.1 albertel 1475: sub homeserver {
1.230 stredwic 1476: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1477: my $index="$uname:$udom";
1.426 albertel 1478:
1.599 albertel 1479: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1480:
1481: my %servers = &get_servers($udom,'library');
1482: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1483: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1484: exists($badServerCache{$tryserver}));
1.841 albertel 1485:
1486: my $answer=reply("home:$udom:$uname",$tryserver);
1487: if ($answer eq 'found') {
1488: delete($badServerCache{$tryserver});
1489: return $homecache{$index}=$tryserver;
1490: } elsif ($answer eq 'no_host') {
1491: $badServerCache{$tryserver}=1;
1492: }
1.1 albertel 1493: }
1494: return 'no_host';
1.70 www 1495: }
1496:
1497: # ------------------------------------- Find the usernames behind a list of IDs
1498:
1499: sub idget {
1500: my ($udom,@ids)=@_;
1501: my %returnhash=();
1502:
1.841 albertel 1503: my %servers = &get_servers($udom,'library');
1504: foreach my $tryserver (keys(%servers)) {
1505: my $idlist=join('&',@ids);
1506: $idlist=~tr/A-Z/a-z/;
1507: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1508: my @answer=();
1509: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1510: @answer=split(/\&/,$reply);
1511: } ;
1512: my $i;
1513: for ($i=0;$i<=$#ids;$i++) {
1514: if ($answer[$i]) {
1515: $returnhash{$ids[$i]}=$answer[$i];
1516: }
1517: }
1518: }
1.70 www 1519: return %returnhash;
1520: }
1521:
1522: # ------------------------------------- Find the IDs behind a list of usernames
1523:
1524: sub idrget {
1525: my ($udom,@unames)=@_;
1526: my %returnhash=();
1.800 albertel 1527: foreach my $uname (@unames) {
1528: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1529: }
1.70 www 1530: return %returnhash;
1531: }
1532:
1533: # ------------------------------- Store away a list of names and associated IDs
1534:
1535: sub idput {
1536: my ($udom,%ids)=@_;
1537: my %servers=();
1.800 albertel 1538: foreach my $uname (keys(%ids)) {
1539: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1540: my $uhom=&homeserver($uname,$udom);
1.70 www 1541: if ($uhom ne 'no_host') {
1.800 albertel 1542: my $id=&escape($ids{$uname});
1.70 www 1543: $id=~tr/A-Z/a-z/;
1.800 albertel 1544: my $esc_unam=&escape($uname);
1.70 www 1545: if ($servers{$uhom}) {
1.800 albertel 1546: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1547: } else {
1.800 albertel 1548: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1549: }
1550: }
1.191 harris41 1551: }
1.800 albertel 1552: foreach my $server (keys(%servers)) {
1553: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1554: }
1.344 www 1555: }
1556:
1.1023 raeburn 1557: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1558: sub dump_dom {
1.1165 droeschl 1559: my ($namespace, $udom, $regexp) = @_;
1560:
1561: $udom ||= $env{'user.domain'};
1562:
1563: return () unless $udom;
1564:
1565: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1566: }
1567:
1.1023 raeburn 1568: # ------------------------------------------ get items from domain db files
1.806 raeburn 1569:
1570: sub get_dom {
1.860 raeburn 1571: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1572: my $items='';
1573: foreach my $item (@$storearr) {
1574: $items.=&escape($item).'&';
1575: }
1576: $items=~s/\&$//;
1.860 raeburn 1577: if (!$udom) {
1578: $udom=$env{'user.domain'};
1579: if (defined(&domain($udom,'primary'))) {
1580: $uhome=&domain($udom,'primary');
1581: } else {
1.874 albertel 1582: undef($uhome);
1.860 raeburn 1583: }
1584: } else {
1585: if (!$uhome) {
1586: if (defined(&domain($udom,'primary'))) {
1587: $uhome=&domain($udom,'primary');
1588: }
1589: }
1590: }
1591: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1592: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1593: my %returnhash;
1.875 albertel 1594: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1595: return %returnhash;
1596: }
1.806 raeburn 1597: my @pairs=split(/\&/,$rep);
1598: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1599: return @pairs;
1600: }
1601: my $i=0;
1602: foreach my $item (@$storearr) {
1603: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1604: $i++;
1605: }
1606: return %returnhash;
1607: } else {
1.880 banghart 1608: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1609: }
1610: }
1611:
1612: # -------------------------------------------- put items in domain db files
1613:
1614: sub put_dom {
1.860 raeburn 1615: my ($namespace,$storehash,$udom,$uhome)=@_;
1616: if (!$udom) {
1617: $udom=$env{'user.domain'};
1618: if (defined(&domain($udom,'primary'))) {
1619: $uhome=&domain($udom,'primary');
1620: } else {
1.874 albertel 1621: undef($uhome);
1.860 raeburn 1622: }
1623: } else {
1624: if (!$uhome) {
1625: if (defined(&domain($udom,'primary'))) {
1626: $uhome=&domain($udom,'primary');
1627: }
1628: }
1629: }
1630: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1631: my $items='';
1632: foreach my $item (keys(%$storehash)) {
1633: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1634: }
1635: $items=~s/\&$//;
1636: return &reply("putdom:$udom:$namespace:$items",$uhome);
1637: } else {
1.860 raeburn 1638: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1639: }
1640: }
1641:
1.1023 raeburn 1642: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1643: sub newput_dom {
1.1023 raeburn 1644: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1645: my $result;
1646: if (!$udom) {
1647: $udom=$env{'user.domain'};
1648: }
1.1023 raeburn 1649: if ($udom) {
1650: my $uname = &get_domainconfiguser($udom);
1651: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1652: }
1653: return $result;
1654: }
1655:
1.1023 raeburn 1656: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1657: sub del_dom {
1.1023 raeburn 1658: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1659: if (ref($storearr) eq 'ARRAY') {
1660: if (!$udom) {
1661: $udom=$env{'user.domain'};
1662: }
1.1023 raeburn 1663: if ($udom) {
1664: my $uname = &get_domainconfiguser($udom);
1665: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1666: }
1667: }
1668: }
1669:
1.1023 raeburn 1670: # ----------------------------------construct domainconfig user for a domain
1671: sub get_domainconfiguser {
1672: my ($udom) = @_;
1673: return $udom.'-domainconfig';
1674: }
1675:
1.837 raeburn 1676: sub retrieve_inst_usertypes {
1677: my ($udom) = @_;
1678: my (%returnhash,@order);
1.989 raeburn 1679: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1680: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1681: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1682: %returnhash = %{$domdefs{'inststatustypes'}};
1683: @order = @{$domdefs{'inststatusorder'}};
1684: } else {
1685: if (defined(&domain($udom,'primary'))) {
1686: my $uhome=&domain($udom,'primary');
1687: my $rep=&reply("inst_usertypes:$udom",$uhome);
1688: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1689: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1690: return (\%returnhash,\@order);
1691: }
1692: my ($hashitems,$orderitems) = split(/:/,$rep);
1693: my @pairs=split(/\&/,$hashitems);
1694: foreach my $item (@pairs) {
1695: my ($key,$value)=split(/=/,$item,2);
1696: $key = &unescape($key);
1697: next if ($key =~ /^error: 2 /);
1698: $returnhash{$key}=&thaw_unescape($value);
1699: }
1700: my @esc_order = split(/\&/,$orderitems);
1701: foreach my $item (@esc_order) {
1702: push(@order,&unescape($item));
1703: }
1704: } else {
1705: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1706: }
1707: }
1708: return (\%returnhash,\@order);
1709: }
1710:
1.868 raeburn 1711: sub is_domainimage {
1712: my ($url) = @_;
1713: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1714: if (&domain($1) ne '') {
1715: return '1';
1716: }
1717: }
1718: return;
1719: }
1720:
1.899 raeburn 1721: sub inst_directory_query {
1722: my ($srch) = @_;
1723: my $udom = $srch->{'srchdomain'};
1724: my %results;
1725: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1726: my $outcome;
1.899 raeburn 1727: if ($homeserver ne '') {
1.904 albertel 1728: my $queryid=&reply("querysend:instdirsearch:".
1729: &escape($srch->{'srchby'}).':'.
1730: &escape($srch->{'srchterm'}).':'.
1731: &escape($srch->{'srchtype'}),$homeserver);
1732: my $host=&hostname($homeserver);
1733: if ($queryid !~/^\Q$host\E\_/) {
1734: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1735: return;
1736: }
1737: my $response = &get_query_reply($queryid);
1738: my $maxtries = 5;
1739: my $tries = 1;
1740: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1741: $response = &get_query_reply($queryid);
1742: $tries ++;
1743: }
1744:
1745: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1746: if ($response eq 'unavailable') {
1747: $outcome = $response;
1748: } else {
1749: $outcome = 'ok';
1750: my @matches = split(/\n/,$response);
1751: foreach my $match (@matches) {
1752: my ($key,$value) = split(/=/,$match);
1753: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1754: }
1.899 raeburn 1755: }
1756: }
1757: }
1.909 raeburn 1758: return ($outcome,%results);
1.899 raeburn 1759: }
1760:
1761: sub usersearch {
1762: my ($srch) = @_;
1763: my $dom = $srch->{'srchdomain'};
1764: my %results;
1765: my %libserv = &all_library();
1766: my $query = 'usersearch';
1767: foreach my $tryserver (keys(%libserv)) {
1768: if (&host_domain($tryserver) eq $dom) {
1769: my $host=&hostname($tryserver);
1770: my $queryid=
1.911 raeburn 1771: &reply("querysend:".&escape($query).':'.
1772: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1773: &escape($srch->{'srchtype'}).':'.
1774: &escape($srch->{'srchterm'}),$tryserver);
1775: if ($queryid !~/^\Q$host\E\_/) {
1776: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1777: next;
1.899 raeburn 1778: }
1779: my $reply = &get_query_reply($queryid);
1780: my $maxtries = 1;
1781: my $tries = 1;
1782: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1783: $reply = &get_query_reply($queryid);
1784: $tries ++;
1785: }
1786: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1787: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1788: } else {
1.911 raeburn 1789: my @matches;
1790: if ($reply =~ /\n/) {
1791: @matches = split(/\n/,$reply);
1792: } else {
1793: @matches = split(/\&/,$reply);
1794: }
1.899 raeburn 1795: foreach my $match (@matches) {
1796: my ($uname,$udom,%userhash);
1.911 raeburn 1797: foreach my $entry (split(/:/,$match)) {
1798: my ($key,$value) =
1799: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1800: $userhash{$key} = $value;
1801: if ($key eq 'username') {
1802: $uname = $value;
1803: } elsif ($key eq 'domain') {
1804: $udom = $value;
1.911 raeburn 1805: }
1.899 raeburn 1806: }
1807: $results{$uname.':'.$udom} = \%userhash;
1808: }
1809: }
1810: }
1811: }
1812: return %results;
1813: }
1814:
1.912 raeburn 1815: sub get_instuser {
1816: my ($udom,$uname,$id) = @_;
1817: my $homeserver = &domain($udom,'primary');
1818: my ($outcome,%results);
1819: if ($homeserver ne '') {
1820: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1821: &escape($id).':'.&escape($udom),$homeserver);
1822: my $host=&hostname($homeserver);
1823: if ($queryid !~/^\Q$host\E\_/) {
1824: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1825: return;
1826: }
1827: my $response = &get_query_reply($queryid);
1828: my $maxtries = 5;
1829: my $tries = 1;
1830: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1831: $response = &get_query_reply($queryid);
1832: $tries ++;
1833: }
1834: if (!&error($response) && $response ne 'refused') {
1835: if ($response eq 'unavailable') {
1836: $outcome = $response;
1837: } else {
1838: $outcome = 'ok';
1839: my @matches = split(/\n/,$response);
1840: foreach my $match (@matches) {
1841: my ($key,$value) = split(/=/,$match);
1842: $results{&unescape($key)} = &thaw_unescape($value);
1843: }
1844: }
1845: }
1846: }
1847: my %userinfo;
1848: if (ref($results{$uname}) eq 'HASH') {
1849: %userinfo = %{$results{$uname}};
1850: }
1851: return ($outcome,%userinfo);
1852: }
1853:
1854: sub inst_rulecheck {
1.923 raeburn 1855: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1856: my %returnhash;
1857: if ($udom ne '') {
1858: if (ref($rules) eq 'ARRAY') {
1859: @{$rules} = map {&escape($_);} (@{$rules});
1860: my $rulestr = join(':',@{$rules});
1861: my $homeserver=&domain($udom,'primary');
1862: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1863: my $response;
1864: if ($item eq 'username') {
1865: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1866: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1867: $homeserver));
1.923 raeburn 1868: } elsif ($item eq 'id') {
1869: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1870: ':'.&escape($id).':'.$rulestr,
1871: $homeserver));
1.945 raeburn 1872: } elsif ($item eq 'selfcreate') {
1873: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1874: &escape($udom).':'.&escape($uname).
1875: ':'.$rulestr,$homeserver));
1.923 raeburn 1876: }
1.912 raeburn 1877: if ($response ne 'refused') {
1878: my @pairs=split(/\&/,$response);
1879: foreach my $item (@pairs) {
1880: my ($key,$value)=split(/=/,$item,2);
1881: $key = &unescape($key);
1882: next if ($key =~ /^error: 2 /);
1883: $returnhash{$key}=&thaw_unescape($value);
1884: }
1885: }
1886: }
1887: }
1888: }
1889: return %returnhash;
1890: }
1891:
1892: sub inst_userrules {
1.923 raeburn 1893: my ($udom,$check) = @_;
1.912 raeburn 1894: my (%ruleshash,@ruleorder);
1895: if ($udom ne '') {
1896: my $homeserver=&domain($udom,'primary');
1897: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1898: my $response;
1899: if ($check eq 'id') {
1900: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1901: $homeserver);
1.943 raeburn 1902: } elsif ($check eq 'email') {
1903: $response=&reply('instemailrules:'.&escape($udom),
1904: $homeserver);
1.923 raeburn 1905: } else {
1906: $response=&reply('instuserrules:'.&escape($udom),
1907: $homeserver);
1908: }
1.912 raeburn 1909: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1910: ($response ne 'unknown_cmd') &&
1.912 raeburn 1911: ($response ne 'no_such_host')) {
1912: my ($hashitems,$orderitems) = split(/:/,$response);
1913: my @pairs=split(/\&/,$hashitems);
1914: foreach my $item (@pairs) {
1915: my ($key,$value)=split(/=/,$item,2);
1916: $key = &unescape($key);
1917: next if ($key =~ /^error: 2 /);
1918: $ruleshash{$key}=&thaw_unescape($value);
1919: }
1920: my @esc_order = split(/\&/,$orderitems);
1921: foreach my $item (@esc_order) {
1922: push(@ruleorder,&unescape($item));
1923: }
1924: }
1925: }
1926: }
1927: return (\%ruleshash,\@ruleorder);
1928: }
1929:
1.976 raeburn 1930: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1931:
1932: sub get_domain_defaults {
1933: my ($domain) = @_;
1934: my $cachetime = 60*60*24;
1935: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1936: if (defined($cached)) {
1937: if (ref($result) eq 'HASH') {
1938: return %{$result};
1939: }
1940: }
1941: my %domdefaults;
1942: my %domconfig =
1.989 raeburn 1943: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1944: 'requestcourses','inststatus',
1.1183 raeburn 1945: 'coursedefaults','usersessions',
1946: 'requestauthor'],$domain);
1.943 raeburn 1947: if (ref($domconfig{'defaults'}) eq 'HASH') {
1948: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1949: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1950: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1951: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1952: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 1953: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 1954: } else {
1955: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1956: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1957: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1958: }
1.976 raeburn 1959: if (ref($domconfig{'quotas'}) eq 'HASH') {
1960: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1961: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1962: } else {
1963: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1964: }
1.1177 raeburn 1965: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 1966: foreach my $item (@usertools) {
1967: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1968: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1969: }
1970: }
1971: }
1.985 raeburn 1972: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1973: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1974: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1975: }
1976: }
1.1183 raeburn 1977: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
1978: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
1979: }
1.989 raeburn 1980: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1981: foreach my $item ('inststatustypes','inststatusorder') {
1982: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1983: }
1984: }
1.1047 raeburn 1985: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1986: foreach my $item ('canuse_pdfforms') {
1987: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1988: }
1989: }
1.1073 raeburn 1990: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1991: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1992: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1993: }
1994: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1995: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1996: }
1997: }
1.943 raeburn 1998: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1999: $cachetime);
2000: return %domdefaults;
2001: }
2002:
1.344 www 2003: # --------------------------------------------------- Assign a key to a student
2004:
2005: sub assign_access_key {
1.364 www 2006: #
2007: # a valid key looks like uname:udom#comments
2008: # comments are being appended
2009: #
1.498 www 2010: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2011: $kdom=
1.620 albertel 2012: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2013: $knum=
1.620 albertel 2014: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2015: $cdom=
1.620 albertel 2016: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2017: $cnum=
1.620 albertel 2018: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2019: $udom=$env{'user.name'} unless (defined($udom));
2020: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2021: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2022: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2023: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2024: # assigned to this person
2025: # - this should not happen,
1.345 www 2026: # unless something went wrong
2027: # the first time around
2028: # ready to assign
1.364 www 2029: $logentry=$1.'; '.$logentry;
1.496 www 2030: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2031: $kdom,$knum) eq 'ok') {
1.345 www 2032: # key now belongs to user
1.346 www 2033: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2034: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2035: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2036: return 'ok';
2037: } else {
2038: return
2039: 'error: Count not permanently assign key, will need to be re-entered later.';
2040: }
2041: } else {
2042: return 'error: Could not assign key, try again later.';
2043: }
1.364 www 2044: } elsif (!$existing{$ckey}) {
1.345 www 2045: # the key does not exist
2046: return 'error: The key does not exist';
2047: } else {
2048: # the key is somebody else's
2049: return 'error: The key is already in use';
2050: }
1.344 www 2051: }
2052:
1.364 www 2053: # ------------------------------------------ put an additional comment on a key
2054:
2055: sub comment_access_key {
2056: #
2057: # a valid key looks like uname:udom#comments
2058: # comments are being appended
2059: #
2060: my ($ckey,$cdom,$cnum,$logentry)=@_;
2061: $cdom=
1.620 albertel 2062: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2063: $cnum=
1.620 albertel 2064: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2065: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2066: if ($existing{$ckey}) {
2067: $existing{$ckey}.='; '.$logentry;
2068: # ready to assign
1.367 www 2069: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2070: $cdom,$cnum) eq 'ok') {
2071: return 'ok';
2072: } else {
2073: return 'error: Count not store comment.';
2074: }
2075: } else {
2076: # the key does not exist
2077: return 'error: The key does not exist';
2078: }
2079: }
2080:
1.344 www 2081: # ------------------------------------------------------ Generate a set of keys
2082:
2083: sub generate_access_keys {
1.364 www 2084: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2085: $cdom=
1.620 albertel 2086: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2087: $cnum=
1.620 albertel 2088: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2089: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2090: unless (($cdom) && ($cnum)) { return 0; }
2091: if ($number>10000) { return 0; }
2092: sleep(2); # make sure don't get same seed twice
2093: srand(time()^($$+($$<<15))); # from "Programming Perl"
2094: my $total=0;
2095: for (my $i=1;$i<=$number;$i++) {
2096: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2097: sprintf("%lx",int(100000*rand)).'-'.
2098: sprintf("%lx",int(100000*rand));
2099: $newkey=~s/1/g/g; # folks mix up 1 and l
2100: $newkey=~s/0/h/g; # and also 0 and O
2101: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2102: if ($existing{$newkey}) {
2103: $i--;
2104: } else {
1.364 www 2105: if (&put('accesskeys',
2106: { $newkey => '# generated '.localtime().
1.620 albertel 2107: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2108: '; '.$logentry },
2109: $cdom,$cnum) eq 'ok') {
1.344 www 2110: $total++;
2111: }
2112: }
2113: }
1.620 albertel 2114: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2115: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2116: return $total;
2117: }
2118:
2119: # ------------------------------------------------------- Validate an accesskey
2120:
2121: sub validate_access_key {
2122: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2123: $cdom=
1.620 albertel 2124: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2125: $cnum=
1.620 albertel 2126: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2127: $udom=$env{'user.domain'} unless (defined($udom));
2128: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2129: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2130: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2131: }
2132:
2133: # ------------------------------------- Find the section of student in a course
1.652 albertel 2134: sub devalidate_getsection_cache {
2135: my ($udom,$unam,$courseid)=@_;
2136: my $hashid="$udom:$unam:$courseid";
2137: &devalidate_cache_new('getsection',$hashid);
2138: }
1.298 matthew 2139:
1.815 albertel 2140: sub courseid_to_courseurl {
2141: my ($courseid) = @_;
2142: #already url style courseid
2143: return $courseid if ($courseid =~ m{^/});
2144:
2145: if (exists($env{'course.'.$courseid.'.num'})) {
2146: my $cnum = $env{'course.'.$courseid.'.num'};
2147: my $cdom = $env{'course.'.$courseid.'.domain'};
2148: return "/$cdom/$cnum";
2149: }
2150:
2151: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2152: if (exists($courseinfo{'num'})) {
2153: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2154: }
2155:
2156: return undef;
2157: }
2158:
1.298 matthew 2159: sub getsection {
2160: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2161: my $cachetime=1800;
1.551 albertel 2162:
2163: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2164: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2165: if (defined($cached)) { return $result; }
2166:
1.298 matthew 2167: my %Pending;
2168: my %Expired;
2169: #
2170: # Each role can either have not started yet (pending), be active,
2171: # or have expired.
2172: #
2173: # If there is an active role, we are done.
2174: #
2175: # If there is more than one role which has not started yet,
2176: # choose the one which will start sooner
2177: # If there is one role which has not started yet, return it.
2178: #
2179: # If there is more than one expired role, choose the one which ended last.
2180: # If there is a role which has expired, return it.
2181: #
1.815 albertel 2182: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2183: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2184: foreach my $key (keys(%roleshash)) {
1.479 albertel 2185: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2186: my $section=$1;
2187: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2188: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2189: my $now=time;
1.548 albertel 2190: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2191: $Expired{$end}=$section;
2192: next;
2193: }
1.548 albertel 2194: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2195: $Pending{$start}=$section;
2196: next;
2197: }
1.599 albertel 2198: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2199: }
2200: #
2201: # Presumedly there will be few matching roles from the above
2202: # loop and the sorting time will be negligible.
2203: if (scalar(keys(%Pending))) {
2204: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2205: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2206: }
2207: if (scalar(keys(%Expired))) {
2208: my @sorted = sort {$a <=> $b} keys(%Expired);
2209: my $time = pop(@sorted);
1.599 albertel 2210: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2211: }
1.599 albertel 2212: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2213: }
1.70 www 2214:
1.599 albertel 2215: sub save_cache {
2216: &purge_remembered();
1.722 albertel 2217: #&Apache::loncommon::validate_page();
1.620 albertel 2218: undef(%env);
1.780 albertel 2219: undef($env_loaded);
1.599 albertel 2220: }
1.452 albertel 2221:
1.599 albertel 2222: my $to_remember=-1;
2223: my %remembered;
2224: my %accessed;
2225: my $kicks=0;
2226: my $hits=0;
1.849 albertel 2227: sub make_key {
2228: my ($name,$id) = @_;
1.872 albertel 2229: if (length($id) > 65
2230: && length(&escape($id)) > 200) {
2231: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2232: }
1.849 albertel 2233: return &escape($name.':'.$id);
2234: }
2235:
1.599 albertel 2236: sub devalidate_cache_new {
2237: my ($name,$id,$debug) = @_;
2238: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2239: $id=&make_key($name,$id);
1.599 albertel 2240: $memcache->delete($id);
2241: delete($remembered{$id});
2242: delete($accessed{$id});
2243: }
2244:
2245: sub is_cached_new {
2246: my ($name,$id,$debug) = @_;
1.849 albertel 2247: $id=&make_key($name,$id);
1.599 albertel 2248: if (exists($remembered{$id})) {
1.1133 foxr 2249: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2250: $accessed{$id}=[&gettimeofday()];
2251: $hits++;
2252: return ($remembered{$id},1);
2253: }
2254: my $value = $memcache->get($id);
2255: if (!(defined($value))) {
2256: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2257: return (undef,undef);
1.416 albertel 2258: }
1.599 albertel 2259: if ($value eq '__undef__') {
2260: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2261: $value=undef;
2262: }
2263: &make_room($id,$value,$debug);
2264: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2265: return ($value,1);
2266: }
2267:
2268: sub do_cache_new {
2269: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2270: $id=&make_key($name,$id);
1.599 albertel 2271: my $setvalue=$value;
2272: if (!defined($setvalue)) {
2273: $setvalue='__undef__';
2274: }
1.623 albertel 2275: if (!defined($time) ) {
2276: $time=600;
2277: }
1.599 albertel 2278: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2279: my $result = $memcache->set($id,$setvalue,$time);
2280: if (! $result) {
1.872 albertel 2281: &logthis("caching of id -> $id failed");
1.910 albertel 2282: $memcache->disconnect_all();
1.872 albertel 2283: }
1.600 albertel 2284: # need to make a copy of $value
1.919 albertel 2285: &make_room($id,$value,$debug);
1.599 albertel 2286: return $value;
2287: }
2288:
2289: sub make_room {
2290: my ($id,$value,$debug)=@_;
1.919 albertel 2291:
2292: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2293: : $value;
1.599 albertel 2294: if ($to_remember<0) { return; }
2295: $accessed{$id}=[&gettimeofday()];
2296: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2297: my $to_kick;
2298: my $max_time=0;
2299: foreach my $other (keys(%accessed)) {
2300: if (&tv_interval($accessed{$other}) > $max_time) {
2301: $to_kick=$other;
2302: $max_time=&tv_interval($accessed{$other});
2303: }
2304: }
2305: delete($remembered{$to_kick});
2306: delete($accessed{$to_kick});
2307: $kicks++;
2308: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2309: return;
2310: }
2311:
1.599 albertel 2312: sub purge_remembered {
1.604 albertel 2313: #&logthis("Tossing ".scalar(keys(%remembered)));
2314: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2315: undef(%remembered);
2316: undef(%accessed);
1.428 albertel 2317: }
1.70 www 2318: # ------------------------------------- Read an entry from a user's environment
2319:
2320: sub userenvironment {
2321: my ($udom,$unam,@what)=@_;
1.976 raeburn 2322: my $items;
2323: foreach my $item (@what) {
2324: $items.=&escape($item).'&';
2325: }
2326: $items=~s/\&$//;
1.70 www 2327: my %returnhash=();
1.1009 raeburn 2328: my $uhome = &homeserver($unam,$udom);
2329: unless ($uhome eq 'no_host') {
2330: my @answer=split(/\&/,
2331: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2332: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2333: return %returnhash;
2334: }
1.1009 raeburn 2335: my $i;
2336: for ($i=0;$i<=$#what;$i++) {
2337: $returnhash{$what[$i]}=&unescape($answer[$i]);
2338: }
1.70 www 2339: }
2340: return %returnhash;
1.1 albertel 2341: }
2342:
1.617 albertel 2343: # ---------------------------------------------------------- Get a studentphoto
2344: sub studentphoto {
2345: my ($udom,$unam,$ext) = @_;
2346: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2347: if (defined($env{'request.course.id'})) {
1.708 raeburn 2348: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2349: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2350: return(&retrievestudentphoto($udom,$unam,$ext));
2351: } else {
2352: my ($result,$perm_reqd)=
1.707 albertel 2353: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2354: if ($result eq 'ok') {
2355: if (!($perm_reqd eq 'yes')) {
2356: return(&retrievestudentphoto($udom,$unam,$ext));
2357: }
2358: }
2359: }
2360: }
2361: } else {
2362: my ($result,$perm_reqd) =
1.707 albertel 2363: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2364: if ($result eq 'ok') {
2365: if (!($perm_reqd eq 'yes')) {
2366: return(&retrievestudentphoto($udom,$unam,$ext));
2367: }
2368: }
2369: }
2370: return '/adm/lonKaputt/lonlogo_broken.gif';
2371: }
2372:
2373: sub retrievestudentphoto {
2374: my ($udom,$unam,$ext,$type) = @_;
2375: my $home=&Apache::lonnet::homeserver($unam,$udom);
2376: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2377: if ($ret eq 'ok') {
2378: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2379: if ($type eq 'thumbnail') {
2380: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2381: }
2382: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2383: return $tokenurl;
2384: } else {
2385: if ($type eq 'thumbnail') {
2386: return '/adm/lonKaputt/genericstudent_tn.gif';
2387: } else {
2388: return '/adm/lonKaputt/lonlogo_broken.gif';
2389: }
1.617 albertel 2390: }
2391: }
2392:
1.263 www 2393: # -------------------------------------------------------------------- New chat
2394:
2395: sub chatsend {
1.724 raeburn 2396: my ($newentry,$anon,$group)=@_;
1.620 albertel 2397: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2398: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2399: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2400: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2401: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2402: &escape($newentry)).':'.$group,$chome);
1.292 www 2403: }
2404:
2405: # ------------------------------------------ Find current version of a resource
2406:
2407: sub getversion {
2408: my $fname=&clutter(shift);
1.1189 ! raeburn 2409: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292 www 2410: return ¤tversion(&filelocation('',$fname));
2411: }
2412:
2413: sub currentversion {
2414: my $fname=shift;
2415: my $author=$fname;
2416: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2417: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2418: my $home=&homeserver($uname,$udom);
1.292 www 2419: if ($home eq 'no_host') {
2420: return -1;
2421: }
1.1112 www 2422: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2423: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2424: return -1;
2425: }
1.1112 www 2426: return $answer;
1.263 www 2427: }
2428:
1.1111 www 2429: #
2430: # Return special version number of resource if set by override, empty otherwise
2431: #
2432: sub usedversion {
2433: my $fname=shift;
2434: unless ($fname) { $fname=$env{'request.uri'}; }
2435: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2436: if ($urlversion) { return $urlversion; }
2437: return '';
2438: }
2439:
1.1 albertel 2440: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2441:
1.1 albertel 2442: sub subscribe {
2443: my $fname=shift;
1.761 raeburn 2444: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2445: $fname=~s/[\n\r]//g;
1.1 albertel 2446: my $author=$fname;
2447: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2448: my ($udom,$uname)=split(/\//,$author);
2449: my $home=homeserver($uname,$udom);
1.335 albertel 2450: if ($home eq 'no_host') {
2451: return 'not_found';
1.1 albertel 2452: }
2453: my $answer=reply("sub:$fname",$home);
1.64 www 2454: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2455: $answer.=' by '.$home;
2456: }
1.1 albertel 2457: return $answer;
2458: }
2459:
1.8 www 2460: # -------------------------------------------------------------- Replicate file
2461:
2462: sub repcopy {
2463: my $filename=shift;
1.23 www 2464: $filename=~s/\/+/\//g;
1.1142 raeburn 2465: my $londocroot = $perlvar{'lonDocRoot'};
2466: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2467: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2468: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2469: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2470: return &repcopy_userfile($filename);
2471: }
1.532 albertel 2472: $filename=~s/[\n\r]//g;
1.8 www 2473: my $transname="$filename.in.transfer";
1.828 www 2474: # FIXME: this should flock
1.607 raeburn 2475: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2476: my $remoteurl=subscribe($filename);
1.64 www 2477: if ($remoteurl =~ /^con_lost by/) {
2478: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2479: return 'unavailable';
1.8 www 2480: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2481: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2482: return 'not_found';
1.64 www 2483: } elsif ($remoteurl =~ /^rejected by/) {
2484: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2485: return 'forbidden';
1.20 www 2486: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2487: return 'ok';
1.8 www 2488: } else {
1.290 www 2489: my $author=$filename;
2490: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2491: my ($udom,$uname)=split(/\//,$author);
2492: my $home=homeserver($uname,$udom);
2493: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2494: my @parts=split(/\//,$filename);
2495: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2496: if ($path ne "$londocroot/res") {
1.8 www 2497: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2498: return 'bad_request';
1.8 www 2499: }
2500: my $count;
2501: for ($count=5;$count<$#parts;$count++) {
2502: $path.="/$parts[$count]";
2503: if ((-e $path)!=1) {
2504: mkdir($path,0777);
2505: }
2506: }
2507: my $ua=new LWP::UserAgent;
2508: my $request=new HTTP::Request('GET',"$remoteurl");
2509: my $response=$ua->request($request,$transname);
2510: if ($response->is_error()) {
2511: unlink($transname);
2512: my $message=$response->status_line;
1.672 albertel 2513: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2514: ." LWP get: $message: $filename</font>");
1.607 raeburn 2515: return 'unavailable';
1.8 www 2516: } else {
1.16 www 2517: if ($remoteurl!~/\.meta$/) {
2518: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2519: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2520: if ($mresponse->is_error()) {
2521: unlink($filename.'.meta');
2522: &logthis(
1.672 albertel 2523: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2524: }
2525: }
1.8 www 2526: rename($transname,$filename);
1.607 raeburn 2527: return 'ok';
1.8 www 2528: }
1.290 www 2529: }
1.8 www 2530: }
1.330 www 2531: }
2532:
2533: # ------------------------------------------------ Get server side include body
2534: sub ssi_body {
1.381 albertel 2535: my ($filelink,%form)=@_;
1.606 matthew 2536: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2537: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2538: }
1.953 www 2539: my $output='';
2540: my $response;
1.980 raeburn 2541: if ($filelink=~/^https?\:/) {
1.954 raeburn 2542: ($output,$response)=&externalssi($filelink);
1.953 www 2543: } else {
1.1004 droeschl 2544: $filelink .= $filelink=~/\?/ ? '&' : '?';
2545: $filelink .= 'inhibitmenu=yes';
1.953 www 2546: ($output,$response)=&ssi($filelink,%form);
2547: }
1.778 albertel 2548: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2549: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2550: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2551: if (wantarray) {
2552: return ($output, $response);
2553: } else {
2554: return $output;
2555: }
1.8 www 2556: }
2557:
1.15 www 2558: # --------------------------------------------------------- Server Side Include
2559:
1.782 albertel 2560: sub absolute_url {
2561: my ($host_name) = @_;
2562: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2563: if ($host_name eq '') {
2564: $host_name = $ENV{'SERVER_NAME'};
2565: }
2566: return $protocol.$host_name;
2567: }
2568:
1.942 foxr 2569: #
2570: # Server side include.
2571: # Parameters:
2572: # fn Possibly encrypted resource name/id.
2573: # form Hash that describes how the rendering should be done
2574: # and other things.
1.944 foxr 2575: # Returns:
1.950 raeburn 2576: # Scalar context: The content of the response.
2577: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2578: #
1.15 www 2579: sub ssi {
2580:
1.944 foxr 2581: my ($fn,%form)=@_;
1.15 www 2582: my $ua=new LWP::UserAgent;
1.23 www 2583: my $request;
1.711 albertel 2584:
2585: $form{'no_update_last_known'}=1;
1.895 albertel 2586: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2587: if (%form) {
1.782 albertel 2588: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2589: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2590: } else {
1.782 albertel 2591: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2592: }
2593:
1.15 www 2594: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2595: my $response= $ua->request($request);
1.1182 foxr 2596: my $content = $response->content;
2597:
2598:
1.944 foxr 2599: if (wantarray) {
1.1173 foxr 2600: return ($content, $response);
1.944 foxr 2601: } else {
1.1173 foxr 2602: return $content;
1.942 foxr 2603: }
1.324 www 2604: }
2605:
2606: sub externalssi {
2607: my ($url)=@_;
2608: my $ua=new LWP::UserAgent;
2609: my $request=new HTTP::Request('GET',$url);
2610: my $response=$ua->request($request);
1.954 raeburn 2611: if (wantarray) {
2612: return ($response->content, $response);
2613: } else {
2614: return $response->content;
2615: }
1.15 www 2616: }
1.254 www 2617:
1.492 albertel 2618: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2619:
2620: sub allowuploaded {
2621: my ($srcurl,$url)=@_;
2622: $url=&clutter(&declutter($url));
2623: my $dir=$url;
2624: $dir=~s/\/[^\/]+$//;
2625: my %httpref=();
2626: my $httpurl=&hreflocation('',$url);
2627: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2628: &Apache::lonnet::appenv(\%httpref);
1.254 www 2629: }
1.477 raeburn 2630:
1.478 albertel 2631: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2632: # input: action, courseID, current domain, intended
1.637 raeburn 2633: # path to file, source of file, instruction to parse file for objects,
2634: # ref to hash for embedded objects,
2635: # ref to hash for codebase of java objects.
1.1095 raeburn 2636: # reference to scalar to accommodate mime type determined
2637: # from File::MMagic if $parser = parse.
1.637 raeburn 2638: #
1.485 raeburn 2639: # output: url to file (if action was uploaddoc),
2640: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2641: #
1.478 albertel 2642: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2643: # course.
1.477 raeburn 2644: #
1.478 albertel 2645: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2646: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2647: # course's home server.
1.477 raeburn 2648: #
1.478 albertel 2649: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2650: # be copied from $source (current location) to
2651: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2652: # and will then be copied to
2653: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2654: # course's home server.
1.485 raeburn 2655: #
1.481 raeburn 2656: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2657: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2658: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2659: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2660: # in course's home server.
1.637 raeburn 2661: #
1.477 raeburn 2662:
2663: sub process_coursefile {
1.1095 raeburn 2664: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2665: $mimetype)=@_;
1.477 raeburn 2666: my $fetchresult;
1.638 albertel 2667: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2668: if ($action eq 'propagate') {
1.638 albertel 2669: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2670: $home);
1.481 raeburn 2671: } else {
1.477 raeburn 2672: my $fpath = '';
2673: my $fname = $file;
1.478 albertel 2674: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2675: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2676: my $filepath = &build_filepath($fpath);
1.481 raeburn 2677: if ($action eq 'copy') {
2678: if ($source eq '') {
2679: $fetchresult = 'no source file';
2680: return $fetchresult;
2681: } else {
2682: my $destination = $filepath.'/'.$fname;
2683: rename($source,$destination);
2684: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2685: $home);
1.481 raeburn 2686: }
2687: } elsif ($action eq 'uploaddoc') {
2688: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2689: print $fh $env{'form.'.$source};
1.481 raeburn 2690: close($fh);
1.637 raeburn 2691: if ($parser eq 'parse') {
1.1024 raeburn 2692: my $mm = new File::MMagic;
1.1095 raeburn 2693: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2694: if ($type eq 'text/html') {
1.1024 raeburn 2695: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2696: unless ($parse_result eq 'ok') {
2697: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2698: }
1.637 raeburn 2699: }
1.1095 raeburn 2700: if (ref($mimetype)) {
2701: $$mimetype = $type;
2702: }
1.637 raeburn 2703: }
1.477 raeburn 2704: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2705: $home);
1.481 raeburn 2706: if ($fetchresult eq 'ok') {
2707: return '/uploaded/'.$fpath.'/'.$fname;
2708: } else {
2709: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2710: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2711: return '/adm/notfound.html';
2712: }
1.477 raeburn 2713: }
2714: }
1.485 raeburn 2715: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2716: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2717: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2718: }
2719: return $fetchresult;
2720: }
2721:
1.637 raeburn 2722: sub build_filepath {
2723: my ($fpath) = @_;
2724: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2725: unless ($fpath eq '') {
2726: my @parts=split('/',$fpath);
2727: foreach my $part (@parts) {
2728: $filepath.= '/'.$part;
2729: if ((-e $filepath)!=1) {
2730: mkdir($filepath,0777);
2731: }
2732: }
2733: }
2734: return $filepath;
2735: }
2736:
2737: sub store_edited_file {
1.638 albertel 2738: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2739: my $file = $primary_url;
2740: $file =~ s#^/uploaded/$docudom/$docuname/##;
2741: my $fpath = '';
2742: my $fname = $file;
2743: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2744: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2745: my $filepath = &build_filepath($fpath);
2746: open(my $fh,'>'.$filepath.'/'.$fname);
2747: print $fh $content;
2748: close($fh);
1.638 albertel 2749: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2750: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2751: $home);
1.637 raeburn 2752: if ($$fetchresult eq 'ok') {
2753: return '/uploaded/'.$fpath.'/'.$fname;
2754: } else {
1.638 albertel 2755: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2756: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2757: return '/adm/notfound.html';
2758: }
2759: }
2760:
1.531 albertel 2761: sub clean_filename {
1.831 albertel 2762: my ($fname,$args)=@_;
1.315 www 2763: # Replace Windows backslashes by forward slashes
1.257 www 2764: $fname=~s/\\/\//g;
1.831 albertel 2765: if (!$args->{'keep_path'}) {
2766: # Get rid of everything but the actual filename
2767: $fname=~s/^.*\/([^\/]+)$/$1/;
2768: }
1.315 www 2769: # Replace spaces by underscores
2770: $fname=~s/\s+/\_/g;
2771: # Replace all other weird characters by nothing
1.831 albertel 2772: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2773: # Replace all .\d. sequences with _\d. so they no longer look like version
2774: # numbers
2775: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2776: return $fname;
2777: }
1.1051 raeburn 2778: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2779: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2780: # image with the same aspect ratio as the original, but with dimensions which do
2781: # not exceed $resizewidth and $resizeheight.
2782:
1.984 neumanie 2783: sub resizeImage {
1.1051 raeburn 2784: my ($img_path,$resizewidth,$resizeheight) = @_;
2785: my $ima = Image::Magick->new;
2786: my $resized;
2787: if (-e $img_path) {
2788: $ima->Read($img_path);
2789: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2790: my $width = $ima->Get('width');
2791: my $height = $ima->Get('height');
2792: if ($width > $resizewidth) {
2793: my $factor = $width/$resizewidth;
2794: my $newheight = $height/$factor;
2795: $ima->Scale(width=>$resizewidth,height=>$newheight);
2796: $resized = 1;
2797: }
2798: }
2799: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2800: my $width = $ima->Get('width');
2801: my $height = $ima->Get('height');
2802: if ($height > $resizeheight) {
2803: my $factor = $height/$resizeheight;
2804: my $newwidth = $width/$factor;
2805: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2806: $resized = 1;
2807: }
2808: }
2809: if ($resized) {
2810: $ima->Write($img_path);
2811: }
2812: }
2813: return;
1.977 amueller 2814: }
2815:
1.608 albertel 2816: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2817: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 2818: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 2819: # $context - possible values: coursedoc, existingfile, overwrite,
2820: # canceloverwrite, or ''.
2821: # if 'coursedoc': upload to the current course
2822: # if 'existingfile': write file to tmp/overwrites directory
2823: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2824: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2825: # $subdir - directory in userfile to store the file into
1.858 raeburn 2826: # $parser - instruction to parse file for objects ($parser = parse)
2827: # $allfiles - reference to hash for embedded objects
2828: # $codebase - reference to hash for codebase of java objects
2829: # $desuname - username for permanent storage of uploaded file
2830: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2831: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2832: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2833: # $resizewidth - width (pixels) to which to resize uploaded image
2834: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 2835: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 2836: # from File::MMagic.
1.858 raeburn 2837: #
1.686 albertel 2838: # output: url of file in userspace, or error: <message>
2839: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2840:
1.531 albertel 2841: sub userfileupload {
1.1090 raeburn 2842: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 2843: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2844: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2845: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2846: $fname=&clean_filename($fname);
1.1090 raeburn 2847: # See if there is anything left
1.257 www 2848: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 2849: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2850: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2851: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2852: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2853: my $now = time;
1.1090 raeburn 2854: my $filepath;
1.1095 raeburn 2855: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 2856: $filepath = 'tmp/helprequests/'.$now;
2857: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2858: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2859: '_'.$env{'user.domain'}.'/pending';
2860: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2861: my ($docuname,$docudom);
2862: if ($destudom) {
2863: $docudom = $destudom;
2864: } else {
2865: $docudom = $env{'user.domain'};
2866: }
2867: if ($destuname) {
2868: $docuname = $destuname;
2869: } else {
2870: $docuname = $env{'user.name'};
2871: }
2872: if (exists($env{'form.group'})) {
2873: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2874: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2875: }
2876: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2877: if ($context eq 'canceloverwrite') {
2878: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2879: if (-e $tempfile) {
2880: my @info = stat($tempfile);
2881: if ($info[9] eq $env{'form.timestamp'}) {
2882: unlink($tempfile);
2883: }
2884: }
2885: return;
1.523 raeburn 2886: }
2887: }
1.1090 raeburn 2888: # Create the directory if not present
1.741 raeburn 2889: my @parts=split(/\//,$filepath);
2890: my $fullpath = $perlvar{'lonDaemons'};
2891: for (my $i=0;$i<@parts;$i++) {
2892: $fullpath .= '/'.$parts[$i];
2893: if ((-e $fullpath)!=1) {
2894: mkdir($fullpath,0777);
2895: }
2896: }
2897: open(my $fh,'>'.$fullpath.'/'.$fname);
2898: print $fh $env{'form.'.$formname};
2899: close($fh);
1.1090 raeburn 2900: if ($context eq 'existingfile') {
2901: my @info = stat($fullpath.'/'.$fname);
2902: return ($fullpath.'/'.$fname,$info[9]);
2903: } else {
2904: return $fullpath.'/'.$fname;
2905: }
1.523 raeburn 2906: }
1.995 raeburn 2907: if ($subdir eq 'scantron') {
2908: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 2909: } else {
1.995 raeburn 2910: $fname="$subdir/$fname";
2911: }
1.1090 raeburn 2912: if ($context eq 'coursedoc') {
1.638 albertel 2913: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2914: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2915: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2916: return &finishuserfileupload($docuname,$docudom,
2917: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2918: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 2919: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2920: } else {
1.620 albertel 2921: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2922: return &process_coursefile('uploaddoc',$docuname,$docudom,
2923: $fname,$formname,$parser,
1.1095 raeburn 2924: $allfiles,$codebase,$mimetype);
1.481 raeburn 2925: }
1.719 banghart 2926: } elsif (defined($destuname)) {
2927: my $docuname=$destuname;
2928: my $docudom=$destudom;
1.860 raeburn 2929: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2930: $parser,$allfiles,$codebase,
1.1051 raeburn 2931: $thumbwidth,$thumbheight,
1.1095 raeburn 2932: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2933: } else {
1.638 albertel 2934: my $docuname=$env{'user.name'};
2935: my $docudom=$env{'user.domain'};
1.714 raeburn 2936: if (exists($env{'form.group'})) {
2937: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2938: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2939: }
1.860 raeburn 2940: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2941: $parser,$allfiles,$codebase,
1.1051 raeburn 2942: $thumbwidth,$thumbheight,
1.1095 raeburn 2943: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2944: }
1.271 www 2945: }
2946:
2947: sub finishuserfileupload {
1.860 raeburn 2948: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 2949: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2950: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2951: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2952:
1.860 raeburn 2953: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2954: $file=$fname;
2955: if ($fname=~m|/|) {
2956: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2957: $path.=$fnamepath.'/';
2958: }
1.259 www 2959: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2960: my $count;
2961: for ($count=4;$count<=$#parts;$count++) {
2962: $filepath.="/$parts[$count]";
2963: if ((-e $filepath)!=1) {
2964: mkdir($filepath,0777);
2965: }
2966: }
1.984 neumanie 2967:
1.258 www 2968: # Save the file
2969: {
1.701 albertel 2970: if (!open(FH,'>'.$filepath.'/'.$file)) {
2971: &logthis('Failed to create '.$filepath.'/'.$file);
2972: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2973: return '/adm/notfound.html';
2974: }
1.1090 raeburn 2975: if ($context eq 'overwrite') {
1.1117 foxr 2976: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 2977: my $target = $filepath.'/'.$file;
2978: if (-e $source) {
2979: my @info = stat($source);
2980: if ($info[9] eq $env{'form.timestamp'}) {
2981: unless (&File::Copy::move($source,$target)) {
2982: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2983: return "Moving from $source failed";
2984: }
2985: } else {
2986: return "Temporary file: $source had unexpected date/time for last modification";
2987: }
2988: } else {
2989: return "Temporary file: $source missing";
2990: }
2991: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2992: &logthis('Failed to write to '.$filepath.'/'.$file);
2993: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2994: return '/adm/notfound.html';
2995: }
1.570 albertel 2996: close(FH);
1.1051 raeburn 2997: if ($resizewidth && $resizeheight) {
2998: my $mm = new File::MMagic;
2999: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3000: if ($mime_type =~ m{^image/}) {
3001: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3002: }
1.977 amueller 3003: }
1.258 www 3004: }
1.1152 raeburn 3005: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3006: if (ref($mimetype)) {
3007: if ($$mimetype eq '') {
3008: my $mm = new File::MMagic;
3009: my $type = $mm->checktype_filename($filepath.'/'.$file);
3010: $$mimetype = $type;
3011: }
3012: }
3013: }
1.637 raeburn 3014: if ($parser eq 'parse') {
1.1152 raeburn 3015: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3016: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3017: $allfiles,$codebase);
3018: unless ($parse_result eq 'ok') {
3019: &logthis('Failed to parse '.$filepath.$file.
3020: ' for embedded media: '.$parse_result);
3021: }
1.637 raeburn 3022: }
3023: }
1.860 raeburn 3024: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3025: my $input = $filepath.'/'.$file;
3026: my $output = $filepath.'/'.'tn-'.$file;
3027: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3028: system("convert -sample $thumbsize $input $output");
3029: if (-e $filepath.'/'.'tn-'.$file) {
3030: $fetchthumb = 1;
3031: }
3032: }
1.858 raeburn 3033:
1.259 www 3034: # Notify homeserver to grep it
3035: #
1.984 neumanie 3036: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3037: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3038: if ($fetchresult eq 'ok') {
1.860 raeburn 3039: if ($fetchthumb) {
3040: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3041: if ($thumbresult ne 'ok') {
3042: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3043: $docuhome.': '.$thumbresult);
3044: }
3045: }
1.259 www 3046: #
1.258 www 3047: # Return the URL to it
1.494 albertel 3048: return '/uploaded/'.$path.$file;
1.263 www 3049: } else {
1.494 albertel 3050: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3051: ': '.$fetchresult);
1.263 www 3052: return '/adm/notfound.html';
1.858 raeburn 3053: }
1.493 albertel 3054: }
3055:
1.637 raeburn 3056: sub extract_embedded_items {
1.961 raeburn 3057: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3058: my @state = ();
1.1164 raeburn 3059: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3060: my %javafiles = (
3061: codebase => '',
3062: code => '',
3063: archive => ''
3064: );
3065: my %mediafiles = (
3066: src => '',
3067: movie => '',
3068: );
1.648 raeburn 3069: my $p;
3070: if ($content) {
3071: $p = HTML::LCParser->new($content);
3072: } else {
1.961 raeburn 3073: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3074: }
1.641 albertel 3075: while (my $t=$p->get_token()) {
1.640 albertel 3076: if ($t->[0] eq 'S') {
3077: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3078: push(@state, $tagname);
1.648 raeburn 3079: if (lc($tagname) eq 'allow') {
3080: &add_filetype($allfiles,$attr->{'src'},'src');
3081: }
1.640 albertel 3082: if (lc($tagname) eq 'img') {
3083: &add_filetype($allfiles,$attr->{'src'},'src');
3084: }
1.886 albertel 3085: if (lc($tagname) eq 'a') {
3086: &add_filetype($allfiles,$attr->{'href'},'href');
3087: }
1.645 raeburn 3088: if (lc($tagname) eq 'script') {
1.1164 raeburn 3089: my $src;
1.645 raeburn 3090: if ($attr->{'archive'} =~ /\.jar$/i) {
3091: &add_filetype($allfiles,$attr->{'archive'},'archive');
3092: } else {
1.1164 raeburn 3093: if ($attr->{'src'} ne '') {
3094: $src = $attr->{'src'};
3095: &add_filetype($allfiles,$src,'src');
3096: }
3097: }
3098: my $text = $p->get_trimmed_text();
3099: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3100: my @swfargs = split(/,/,$1);
3101: foreach my $item (@swfargs) {
3102: $item =~ s/["']//g;
3103: $item =~ s/^\s+//;
3104: $item =~ s/\s+$//;
3105: }
3106: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3107: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3108: push(@{$related{$swfargs[0]}},$swfargs[2]);
3109: } else {
3110: $related{$swfargs[0]} = [$swfargs[2]];
3111: }
3112: }
1.645 raeburn 3113: }
3114: }
3115: if (lc($tagname) eq 'link') {
3116: if (lc($attr->{'rel'}) eq 'stylesheet') {
3117: &add_filetype($allfiles,$attr->{'href'},'href');
3118: }
3119: }
1.640 albertel 3120: if (lc($tagname) eq 'object' ||
3121: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3122: foreach my $item (keys(%javafiles)) {
3123: $javafiles{$item} = '';
3124: }
1.1164 raeburn 3125: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3126: $lastids{lc($tagname)} = $attr->{'id'};
3127: }
1.640 albertel 3128: }
3129: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3130: my $name = lc($attr->{'name'});
3131: foreach my $item (keys(%javafiles)) {
3132: if ($name eq $item) {
3133: $javafiles{$item} = $attr->{'value'};
3134: last;
3135: }
3136: }
1.1164 raeburn 3137: my $pathfrom;
1.640 albertel 3138: foreach my $item (keys(%mediafiles)) {
3139: if ($name eq $item) {
1.1164 raeburn 3140: $pathfrom = $attr->{'value'};
3141: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3142: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3143: last;
3144: }
3145: }
1.1164 raeburn 3146: if ($name eq 'flashvars') {
3147: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3148: }
3149: if ($pathfrom ne '') {
3150: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3151: $pathfrom);
3152: }
1.640 albertel 3153: }
3154: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3155: foreach my $item (keys(%javafiles)) {
3156: if ($attr->{$item}) {
3157: $javafiles{$item} = $attr->{$item};
3158: last;
3159: }
3160: }
3161: foreach my $item (keys(%mediafiles)) {
3162: if ($attr->{$item}) {
3163: &add_filetype($allfiles,$attr->{$item},$item);
3164: last;
3165: }
3166: }
1.1164 raeburn 3167: if (lc($tagname) eq 'embed') {
3168: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3169: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3170: $attr->{'src'});
3171: }
3172: }
1.640 albertel 3173: }
1.1164 raeburn 3174: if ($t->[4] =~ m{/>$}) {
3175: pop(@state);
3176: }
1.640 albertel 3177: } elsif ($t->[0] eq 'E') {
3178: my ($tagname) = ($t->[1]);
3179: if ($javafiles{'codebase'} ne '') {
3180: $javafiles{'codebase'} .= '/';
3181: }
3182: if (lc($tagname) eq 'applet' ||
3183: lc($tagname) eq 'object' ||
3184: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3185: ) {
3186: foreach my $item (keys(%javafiles)) {
3187: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3188: my $file=$javafiles{'codebase'}.$javafiles{$item};
3189: &add_filetype($allfiles,$file,$item);
3190: }
3191: }
3192: }
3193: pop @state;
3194: }
3195: }
1.1164 raeburn 3196: foreach my $id (sort(keys(%flashvars))) {
3197: if ($shockwave{$id} ne '') {
3198: my @pairs = split(/\&/,$flashvars{$id});
3199: foreach my $pair (@pairs) {
3200: my ($key,$value) = split(/\=/,$pair);
3201: if ($key eq 'thumb') {
3202: &add_filetype($allfiles,$value,$key);
3203: } elsif ($key eq 'content') {
3204: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3205: my ($ext) = ($value =~ /\.([^.]+)$/);
3206: if ($ext ne '') {
3207: &add_filetype($allfiles,$path.$value,$ext);
3208: }
3209: }
3210: }
3211: }
3212: }
1.637 raeburn 3213: return 'ok';
3214: }
3215:
1.639 albertel 3216: sub add_filetype {
3217: my ($allfiles,$file,$type)=@_;
3218: if (exists($allfiles->{$file})) {
3219: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3220: push(@{$allfiles->{$file}}, &escape($type));
3221: }
3222: } else {
3223: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3224: }
3225: }
3226:
1.1164 raeburn 3227: sub embedded_dependency {
3228: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3229: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3230: if (($identifier ne '') &&
3231: (ref($related->{$identifier}) eq 'ARRAY') &&
3232: ($pathfrom ne '')) {
3233: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3234: foreach my $dep (@{$related->{$identifier}}) {
3235: &add_filetype($allfiles,$path.$dep,'object');
3236: }
3237: }
3238: }
3239: return;
3240: }
3241:
1.493 albertel 3242: sub removeuploadedurl {
1.984 neumanie 3243: my ($url)=@_;
3244: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3245: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3246: }
3247:
3248: sub removeuserfile {
3249: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3250: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3251: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3252: if ($result eq 'ok') {
1.798 raeburn 3253: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3254: my $metafile = $fname.'.meta';
3255: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3256: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3257: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3258: my $sqlresult =
1.823 albertel 3259: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3260: 'portfolio_metadata',$group,
3261: 'delete');
1.798 raeburn 3262: }
3263: }
3264: return $result;
1.257 www 3265: }
1.15 www 3266:
1.530 albertel 3267: sub mkdiruserfile {
3268: my ($docuname,$docudom,$dir)=@_;
3269: my $home=&homeserver($docuname,$docudom);
3270: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3271: }
3272:
1.531 albertel 3273: sub renameuserfile {
3274: my ($docuname,$docudom,$old,$new)=@_;
3275: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3276: my $result = &reply("renameuserfile:$docudom:$docuname:".
3277: &escape("$old").':'.&escape("$new"),$home);
3278: if ($result eq 'ok') {
3279: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3280: my $oldmeta = $old.'.meta';
3281: my $newmeta = $new.'.meta';
3282: my $metaresult =
3283: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3284: my $url = "/uploaded/$docudom/$docuname/$old";
3285: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3286: my $sqlresult =
1.823 albertel 3287: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3288: 'portfolio_metadata',$group,
3289: 'delete');
1.798 raeburn 3290: }
3291: }
3292: return $result;
1.531 albertel 3293: }
3294:
1.14 www 3295: # ------------------------------------------------------------------------- Log
3296:
3297: sub log {
3298: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3299: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3300: }
3301:
3302: # ------------------------------------------------------------------ Course Log
1.352 www 3303: #
3304: # This routine flushes several buffers of non-mission-critical nature
3305: #
1.157 www 3306:
3307: sub flushcourselogs {
1.352 www 3308: &logthis('Flushing log buffers');
3309: #
3310: # course logs
3311: # This is a log of all transactions in a course, which can be used
3312: # for data mining purposes
3313: #
3314: # It also collects the courseid database, which lists last transaction
3315: # times and course titles for all courseids
3316: #
3317: my %courseidbuffer=();
1.921 raeburn 3318: foreach my $crsid (keys(%courselogs)) {
1.352 www 3319: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3320: &escape($courselogs{$crsid}),
3321: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3322: delete $courselogs{$crsid};
3323: } else {
3324: &logthis('Failed to flush log buffer for '.$crsid);
3325: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3326: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3327: " exceeded maximum size, deleting.</font>");
3328: delete $courselogs{$crsid};
3329: }
1.352 www 3330: }
1.920 raeburn 3331: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3332: 'description' => $coursedescrbuf{$crsid},
3333: 'inst_code' => $courseinstcodebuf{$crsid},
3334: 'type' => $coursetypebuf{$crsid},
3335: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3336: };
1.191 harris41 3337: }
1.352 www 3338: #
3339: # Write course id database (reverse lookup) to homeserver of courses
3340: # Is used in pickcourse
3341: #
1.840 albertel 3342: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3343: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3344: $courseidbuffer{$crs_home},
3345: $crs_home,'timeonly');
1.352 www 3346: }
3347: #
3348: # File accesses
3349: # Writes to the dynamic metadata of resources to get hit counts, etc.
3350: #
1.449 matthew 3351: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3352: if ($entry =~ /___count$/) {
3353: my ($dom,$name);
1.807 albertel 3354: ($dom,$name,undef)=
1.811 albertel 3355: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3356: if (! defined($dom) || $dom eq '' ||
3357: ! defined($name) || $name eq '') {
1.620 albertel 3358: my $cid = $env{'request.course.id'};
3359: $dom = $env{'request.'.$cid.'.domain'};
3360: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3361: }
1.450 matthew 3362: my $value = $accesshash{$entry};
3363: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3364: my %temphash=($url => $value);
1.449 matthew 3365: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3366: if ($result eq 'ok') {
3367: delete $accesshash{$entry};
3368: }
3369: } else {
1.811 albertel 3370: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3371: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3372: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3373: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3374: delete $accesshash{$entry};
3375: }
1.185 www 3376: }
1.191 harris41 3377: }
1.352 www 3378: #
3379: # Roles
3380: # Reverse lookup of user roles for course faculty/staff and co-authorship
3381: #
1.800 albertel 3382: foreach my $entry (keys(%userrolehash)) {
1.351 www 3383: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3384: split(/\:/,$entry);
3385: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3386: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3387: $rudom,$runame) eq 'ok') {
3388: delete $userrolehash{$entry};
3389: }
3390: }
1.662 raeburn 3391: #
3392: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3393: #
3394: my %domrolebuffer = ();
1.1000 raeburn 3395: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3396: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3397: if ($domrolebuffer{$rudom}) {
3398: $domrolebuffer{$rudom}.='&'.&escape($entry).
3399: '='.&escape($domainrolehash{$entry});
3400: } else {
3401: $domrolebuffer{$rudom}.=&escape($entry).
3402: '='.&escape($domainrolehash{$entry});
3403: }
3404: delete $domainrolehash{$entry};
3405: }
3406: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3407: my %servers = &get_servers($dom,'library');
3408: foreach my $tryserver (keys(%servers)) {
3409: unless (&reply('domroleput:'.$dom.':'.
3410: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3411: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3412: }
1.662 raeburn 3413: }
3414: }
1.186 www 3415: $dumpcount++;
1.157 www 3416: }
3417:
3418: sub courselog {
3419: my $what=shift;
1.158 www 3420: $what=time.':'.$what;
1.620 albertel 3421: unless ($env{'request.course.id'}) { return ''; }
3422: $coursedombuf{$env{'request.course.id'}}=
3423: $env{'course.'.$env{'request.course.id'}.'.domain'};
3424: $coursenumbuf{$env{'request.course.id'}}=
3425: $env{'course.'.$env{'request.course.id'}.'.num'};
3426: $coursehombuf{$env{'request.course.id'}}=
3427: $env{'course.'.$env{'request.course.id'}.'.home'};
3428: $coursedescrbuf{$env{'request.course.id'}}=
3429: $env{'course.'.$env{'request.course.id'}.'.description'};
3430: $courseinstcodebuf{$env{'request.course.id'}}=
3431: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3432: $courseownerbuf{$env{'request.course.id'}}=
3433: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3434: $coursetypebuf{$env{'request.course.id'}}=
3435: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3436: if (defined $courselogs{$env{'request.course.id'}}) {
3437: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3438: } else {
1.620 albertel 3439: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3440: }
1.620 albertel 3441: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3442: &flushcourselogs();
3443: }
1.158 www 3444: }
3445:
3446: sub courseacclog {
3447: my $fnsymb=shift;
1.620 albertel 3448: unless ($env{'request.course.id'}) { return ''; }
3449: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3450: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3451: $what.=':POST';
1.583 matthew 3452: # FIXME: Probably ought to escape things....
1.800 albertel 3453: foreach my $key (keys(%env)) {
3454: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3455: my $formitem = $1;
3456: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3457: $what.=':'.$formitem.'='.$env{$key};
3458: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3459: $what.=':'.$formitem.'='.$env{$key};
3460: }
1.158 www 3461: }
1.191 harris41 3462: }
1.583 matthew 3463: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3464: # FIXME: We should not be depending on a form parameter that someone
3465: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3466: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3467: $what.= ':POST';
3468: # FIXME: Probably ought to escape things....
3469: foreach my $element ('courseexp','crsfulltext','crsrelated',
3470: 'crsdiscuss') {
1.620 albertel 3471: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3472: }
3473: }
1.158 www 3474: }
3475: &courselog($what);
1.149 www 3476: }
3477:
1.185 www 3478: sub countacc {
3479: my $url=&declutter(shift);
1.458 matthew 3480: return if (! defined($url) || $url eq '');
1.620 albertel 3481: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3482: #
3483: # Mark that this url was used in this course
3484: #
1.620 albertel 3485: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3486: #
3487: # Increase the access count for this resource in this child process
3488: #
1.281 www 3489: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3490: $accesshash{$key}++;
1.185 www 3491: }
1.349 www 3492:
1.361 www 3493: sub linklog {
3494: my ($from,$to)=@_;
3495: $from=&declutter($from);
3496: $to=&declutter($to);
3497: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3498: $accesshash{$to.'___'.$from.'___goto'}=1;
3499: }
1.1160 www 3500:
3501: sub statslog {
3502: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3503: if ($users<2) { return; }
3504: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3505: 'course' => $env{'request.course.id'},
3506: 'sections' => '"all"',
3507: 'num_students' => $users,
3508: 'part' => $part,
3509: 'symb' => $symb,
3510: 'mean_tries' => $av_attempts,
3511: 'deg_of_diff' => $degdiff});
3512: foreach my $key (keys(%dynstore)) {
3513: $accesshash{$key}=$dynstore{$key};
3514: }
3515: }
1.361 www 3516:
1.349 www 3517: sub userrolelog {
3518: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3519: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3520: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3521: $userrolehash
3522: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3523: =$tend.':'.$tstart;
1.662 raeburn 3524: }
1.1169 droeschl 3525: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3526: $userrolehash
3527: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3528: =$tend.':'.$tstart;
3529: }
1.1169 droeschl 3530: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3531: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3532: $domainrolehash
3533: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3534: = $tend.':'.$tstart;
3535: }
1.351 www 3536: }
3537:
1.957 raeburn 3538: sub courserolelog {
3539: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184 raeburn 3540: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3541: my $cdom = $1;
3542: my $cnum = $2;
3543: my $sec = $3;
3544: my $namespace = 'rolelog';
3545: my %storehash = (
3546: role => $trole,
3547: start => $tstart,
3548: end => $tend,
3549: selfenroll => $selfenroll,
3550: context => $context,
3551: );
3552: if ($trole eq 'gr') {
3553: $namespace = 'groupslog';
3554: $storehash{'group'} = $sec;
3555: } else {
3556: $storehash{'section'} = $sec;
3557: }
1.1188 raeburn 3558: &write_log('course',$namespace,\%storehash,$delflag,$username,
3559: $domain,$cnum,$cdom);
1.1184 raeburn 3560: if (($trole ne 'st') || ($sec ne '')) {
3561: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957 raeburn 3562: }
3563: }
3564: return;
3565: }
3566:
1.1184 raeburn 3567: sub domainrolelog {
3568: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3569: if ($area =~ m{^/($match_domain)/$}) {
3570: my $cdom = $1;
3571: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3572: my $namespace = 'rolelog';
3573: my %storehash = (
3574: role => $trole,
3575: start => $tstart,
3576: end => $tend,
3577: context => $context,
3578: );
1.1188 raeburn 3579: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3580: $domain,$domconfiguser,$cdom);
1.1184 raeburn 3581: }
3582: return;
3583:
3584: }
3585:
3586: sub coauthorrolelog {
3587: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3588: if ($area =~ m{^/($match_domain)/($match_username)$}) {
3589: my $audom = $1;
3590: my $auname = $2;
3591: my $namespace = 'rolelog';
3592: my %storehash = (
3593: role => $trole,
3594: start => $tstart,
3595: end => $tend,
3596: context => $context,
3597: );
1.1188 raeburn 3598: &write_log('author',$namespace,\%storehash,$delflag,$username,
3599: $domain,$auname,$audom);
1.1184 raeburn 3600: }
3601: return;
3602: }
3603:
1.351 www 3604: sub get_course_adv_roles {
1.948 raeburn 3605: my ($cid,$codes) = @_;
1.620 albertel 3606: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3607: my %coursehash=&coursedescription($cid);
1.988 raeburn 3608: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3609: my %nothide=();
1.800 albertel 3610: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3611: if ($user !~ /:/) {
3612: $nothide{join(':',split(/[\@]/,$user))}=1;
3613: } else {
3614: $nothide{$user}=1;
3615: }
1.470 www 3616: }
1.351 www 3617: my %returnhash=();
3618: my %dumphash=
3619: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3620: my $now=time;
1.997 raeburn 3621: my %privileged;
1.1000 raeburn 3622: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3623: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3624: if (($tstart) && ($tstart<0)) { next; }
3625: if (($tend) && ($tend<$now)) { next; }
3626: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3627: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3628: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3629: unless (ref($privileged{$domain}) eq 'HASH') {
3630: my %dompersonnel =
1.998 raeburn 3631: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3632: $privileged{$domain} = {};
3633: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3634: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3635: foreach my $user (keys(%{$dompersonnel{$server}})) {
3636: my ($trole,$uname,$udom) = split(/:/,$user);
3637: $privileged{$udom}{$uname} = 1;
3638: }
3639: }
3640: }
3641: }
3642: if ((exists($privileged{$domain}{$username})) &&
3643: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3644: if ($role eq 'cr') { next; }
1.948 raeburn 3645: if ($codes) {
3646: if ($section) { $role .= ':'.$section; }
3647: if ($returnhash{$role}) {
3648: $returnhash{$role}.=','.$username.':'.$domain;
3649: } else {
3650: $returnhash{$role}=$username.':'.$domain;
3651: }
1.351 www 3652: } else {
1.988 raeburn 3653: my $key=&plaintext($role,$crstype);
1.973 bisitz 3654: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3655: if ($returnhash{$key}) {
3656: $returnhash{$key}.=','.$username.':'.$domain;
3657: } else {
3658: $returnhash{$key}=$username.':'.$domain;
3659: }
1.351 www 3660: }
1.948 raeburn 3661: }
1.400 www 3662: return %returnhash;
3663: }
3664:
3665: sub get_my_roles {
1.937 raeburn 3666: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3667: unless (defined($uname)) { $uname=$env{'user.name'}; }
3668: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3669: my (%dumphash,%nothide);
1.1086 raeburn 3670: if ($context eq 'userroles') {
1.1166 raeburn 3671: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 3672: } else {
3673: %dumphash=
1.400 www 3674: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3675: if ($hidepriv) {
3676: my %coursehash=&coursedescription($udom.'_'.$uname);
3677: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3678: if ($user !~ /:/) {
3679: $nothide{join(':',split(/[\@]/,$user))} = 1;
3680: } else {
3681: $nothide{$user} = 1;
3682: }
3683: }
3684: }
1.858 raeburn 3685: }
1.400 www 3686: my %returnhash=();
3687: my $now=time;
1.999 raeburn 3688: my %privileged;
1.800 albertel 3689: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3690: my ($role,$tend,$tstart);
3691: if ($context eq 'userroles') {
1.1149 raeburn 3692: next if ($entry =~ /^rolesdef/);
1.867 raeburn 3693: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3694: } else {
3695: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3696: }
1.400 www 3697: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3698: my $status = 'active';
1.939 raeburn 3699: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3700: $status = 'previous';
3701: }
3702: if (($tstart) && ($now<$tstart)) {
3703: $status = 'future';
3704: }
3705: if (ref($types) eq 'ARRAY') {
3706: if (!grep(/^\Q$status\E$/,@{$types})) {
3707: next;
3708: }
3709: } else {
3710: if ($status ne 'active') {
3711: next;
3712: }
3713: }
1.867 raeburn 3714: my ($rolecode,$username,$domain,$section,$area);
3715: if ($context eq 'userroles') {
1.1186 raeburn 3716: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867 raeburn 3717: (undef,$domain,$username,$section) = split(/\//,$area);
3718: } else {
3719: ($role,$username,$domain,$section) = split(/\:/,$entry);
3720: }
1.832 raeburn 3721: if (ref($roledoms) eq 'ARRAY') {
3722: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3723: next;
3724: }
3725: }
3726: if (ref($roles) eq 'ARRAY') {
3727: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3728: if ($role =~ /^cr\//) {
3729: if (!grep(/^cr$/,@{$roles})) {
3730: next;
3731: }
1.1104 raeburn 3732: } elsif ($role =~ /^gr\//) {
3733: if (!grep(/^gr$/,@{$roles})) {
3734: next;
3735: }
1.922 raeburn 3736: } else {
3737: next;
3738: }
1.832 raeburn 3739: }
1.867 raeburn 3740: }
1.937 raeburn 3741: if ($hidepriv) {
1.999 raeburn 3742: if ($context eq 'userroles') {
3743: if ((&privileged($username,$domain)) &&
3744: (!$nothide{$username.':'.$domain})) {
3745: next;
3746: }
3747: } else {
3748: unless (ref($privileged{$domain}) eq 'HASH') {
3749: my %dompersonnel =
3750: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3751: $privileged{$domain} = {};
3752: if (keys(%dompersonnel)) {
3753: foreach my $server (keys(%dompersonnel)) {
3754: if (ref($dompersonnel{$server}) eq 'HASH') {
3755: foreach my $user (keys(%{$dompersonnel{$server}})) {
3756: my ($trole,$uname,$udom) = split(/:/,$user);
3757: $privileged{$udom}{$uname} = $trole;
3758: }
3759: }
3760: }
3761: }
3762: }
3763: if (exists($privileged{$domain}{$username})) {
3764: if (!$nothide{$username.':'.$domain}) {
3765: next;
3766: }
3767: }
1.937 raeburn 3768: }
3769: }
1.933 raeburn 3770: if ($withsec) {
3771: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3772: $tstart.':'.$tend;
3773: } else {
3774: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3775: }
1.832 raeburn 3776: }
1.373 www 3777: return %returnhash;
1.399 www 3778: }
3779:
3780: # ----------------------------------------------------- Frontpage Announcements
3781: #
3782: #
3783:
3784: sub postannounce {
3785: my ($server,$text)=@_;
1.844 albertel 3786: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3787: unless ($text=~/\w/) { $text=''; }
3788: return &reply('setannounce:'.&escape($text),$server);
3789: }
3790:
3791: sub getannounce {
1.448 albertel 3792:
3793: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3794: my $announcement='';
1.800 albertel 3795: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3796: close($fh);
1.399 www 3797: if ($announcement=~/\w/) {
3798: return
3799: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3800: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3801: } else {
3802: return '';
3803: }
3804: } else {
3805: return '';
3806: }
1.351 www 3807: }
1.353 www 3808:
3809: # ---------------------------------------------------------- Course ID routines
3810: # Deal with domain's nohist_courseid.db files
3811: #
3812:
3813: sub courseidput {
1.921 raeburn 3814: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3815: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3816: my $outcome;
3817: if ($caller eq 'timeonly') {
3818: my $cids = '';
3819: foreach my $item (keys(%$storehash)) {
3820: $cids.=&escape($item).'&';
3821: }
3822: $cids=~s/\&$//;
3823: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3824: $coursehome);
3825: } else {
3826: my $items = '';
3827: foreach my $item (keys(%$storehash)) {
3828: $items.= &escape($item).'='.
3829: &freeze_escape($$storehash{$item}).'&';
3830: }
3831: $items=~s/\&$//;
3832: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3833: $coursehome);
1.918 raeburn 3834: }
3835: if ($outcome eq 'unknown_cmd') {
3836: my $what;
3837: foreach my $cid (keys(%$storehash)) {
3838: $what .= &escape($cid).'=';
1.921 raeburn 3839: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3840: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3841: }
3842: $what =~ s/\:$/&/;
3843: }
3844: $what =~ s/\&$//;
3845: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3846: } else {
3847: return $outcome;
3848: }
1.353 www 3849: }
3850:
3851: sub courseiddump {
1.921 raeburn 3852: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3853: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3854: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3855: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3856: my $as_hash = 1;
3857: my %returnhash;
3858: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3859: my %libserv = &all_library();
3860: foreach my $tryserver (keys(%libserv)) {
3861: if ( ( $hostidflag == 1
3862: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3863: || (!defined($hostidflag)) ) {
3864:
1.918 raeburn 3865: if (($domfilter eq '') ||
3866: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 3867: my $rep;
3868: if (grep { $_ eq $tryserver } current_machine_ids()) {
3869: $rep = LONCAPA::Lond::dump_course_id_handler(
3870: join(":", (&host_domain($tryserver), $sincefilter,
3871: &escape($descfilter), &escape($instcodefilter),
3872: &escape($ownerfilter), &escape($coursefilter),
3873: &escape($typefilter), &escape($regexp_ok),
3874: $as_hash, &escape($selfenrollonly),
3875: &escape($catfilter), $showhidden, $caller,
3876: &escape($cloner), &escape($cc_clone), $cloneonly,
3877: &escape($createdbefore), &escape($createdafter),
3878: &escape($creationcontext), $domcloner)));
3879: } else {
3880: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
3881: $sincefilter.':'.&escape($descfilter).':'.
3882: &escape($instcodefilter).':'.&escape($ownerfilter).
3883: ':'.&escape($coursefilter).':'.&escape($typefilter).
3884: ':'.&escape($regexp_ok).':'.$as_hash.':'.
3885: &escape($selfenrollonly).':'.&escape($catfilter).':'.
3886: $showhidden.':'.$caller.':'.&escape($cloner).':'.
3887: &escape($cc_clone).':'.$cloneonly.':'.
3888: &escape($createdbefore).':'.&escape($createdafter).':'.
3889: &escape($creationcontext).':'.$domcloner,
3890: $tryserver);
3891: }
3892:
1.918 raeburn 3893: my @pairs=split(/\&/,$rep);
3894: foreach my $item (@pairs) {
3895: my ($key,$value)=split(/\=/,$item,2);
3896: $key = &unescape($key);
3897: next if ($key =~ /^error: 2 /);
3898: my $result = &thaw_unescape($value);
3899: if (ref($result) eq 'HASH') {
3900: $returnhash{$key}=$result;
3901: } else {
1.921 raeburn 3902: my @responses = split(/:/,$value);
3903: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3904: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3905: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3906: }
1.1008 raeburn 3907: }
1.353 www 3908: }
3909: }
3910: }
3911: }
3912: return %returnhash;
3913: }
3914:
1.1055 raeburn 3915: sub courselastaccess {
3916: my ($cdom,$cnum,$hostidref) = @_;
3917: my %returnhash;
3918: if ($cdom && $cnum) {
3919: my $chome = &homeserver($cnum,$cdom);
3920: if ($chome ne 'no_host') {
3921: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3922: &extract_lastaccess(\%returnhash,$rep);
3923: }
3924: } else {
3925: if (!$cdom) { $cdom=''; }
3926: my %libserv = &all_library();
3927: foreach my $tryserver (keys(%libserv)) {
3928: if (ref($hostidref) eq 'ARRAY') {
3929: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3930: }
3931: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3932: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3933: &extract_lastaccess(\%returnhash,$rep);
3934: }
3935: }
3936: }
3937: return %returnhash;
3938: }
3939:
3940: sub extract_lastaccess {
3941: my ($returnhash,$rep) = @_;
3942: if (ref($returnhash) eq 'HASH') {
3943: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3944: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3945: $rep eq '') {
3946: my @pairs=split(/\&/,$rep);
3947: foreach my $item (@pairs) {
3948: my ($key,$value)=split(/\=/,$item,2);
3949: $key = &unescape($key);
3950: next if ($key =~ /^error: 2 /);
3951: $returnhash->{$key} = &thaw_unescape($value);
3952: }
3953: }
3954: }
3955: return;
3956: }
3957:
1.658 raeburn 3958: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3959:
3960: sub dcmailput {
1.685 raeburn 3961: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3962: my $status = &Apache::lonnet::critical(
1.740 www 3963: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3964: &escape($message),$server);
1.662 raeburn 3965: return $status;
3966: }
3967:
1.658 raeburn 3968: sub dcmaildump {
3969: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3970: my %returnhash=();
1.846 albertel 3971:
3972: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3973: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3974: &escape($enddate).':';
3975: my @esc_senders=map { &escape($_)} @$senders;
3976: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3977: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3978: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3979: if (($key) && ($value)) {
3980: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3981: }
3982: }
3983: }
3984: return %returnhash;
3985: }
1.662 raeburn 3986: # ---------------------------------------------------------- Domain roles
3987:
3988: sub get_domain_roles {
3989: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3990: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3991: $startdate = '.';
3992: }
1.1018 raeburn 3993: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3994: $enddate = '.';
3995: }
1.922 raeburn 3996: my $rolelist;
3997: if (ref($roles) eq 'ARRAY') {
3998: $rolelist = join(':',@{$roles});
3999: }
1.662 raeburn 4000: my %personnel = ();
1.841 albertel 4001:
4002: my %servers = &get_servers($dom,'library');
4003: foreach my $tryserver (keys(%servers)) {
4004: %{$personnel{$tryserver}}=();
4005: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4006: &escape($startdate).':'.
4007: &escape($enddate).':'.
4008: &escape($rolelist), $tryserver))) {
4009: my ($key,$value) = split(/\=/,$line,2);
4010: if (($key) && ($value)) {
4011: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4012: }
4013: }
1.662 raeburn 4014: }
4015: return %personnel;
4016: }
1.658 raeburn 4017:
1.1057 www 4018: # ----------------------------------------------------------- Interval timing
1.149 www 4019:
1.1153 www 4020: {
4021: # Caches needed for speedup of navmaps
4022: # We don't want to cache this for very long at all (5 seconds at most)
4023: #
4024: # The user for whom we cache
4025: my $cachedkey='';
4026: # The cached times for this user
4027: my %cachedtimes=();
4028: # When this was last done
4029: my $cachedtime=();
4030:
4031: sub load_all_first_access {
1.1154 raeburn 4032: my ($uname,$udom)=@_;
1.1156 www 4033: if (($cachedkey eq $uname.':'.$udom) &&
1.1174 raeburn 4034: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4035: return;
4036: }
4037: $cachedtime=time;
4038: $cachedkey=$uname.':'.$udom;
4039: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4040: }
4041:
1.504 albertel 4042: sub get_first_access {
1.1162 raeburn 4043: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4044: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4045: if ($argsymb) { $symb=$argsymb; }
4046: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4047: if ($argmap) { $map = $argmap; }
1.926 albertel 4048: if ($type eq 'course') {
4049: $res='course';
4050: } elsif ($type eq 'map') {
1.588 albertel 4051: $res=&symbread($map);
4052: } else {
4053: $res=$symb;
4054: }
1.1153 www 4055: &load_all_first_access($uname,$udom);
4056: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4057: }
4058:
4059: sub set_first_access {
1.1162 raeburn 4060: my ($type,$interval)=@_;
1.790 albertel 4061: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4062: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4063: if ($type eq 'course') {
4064: $res='course';
4065: } elsif ($type eq 'map') {
1.588 albertel 4066: $res=&symbread($map);
4067: } else {
4068: $res=$symb;
4069: }
1.1153 www 4070: $cachedkey='';
1.1162 raeburn 4071: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4072: if (!$firstaccess) {
1.1162 raeburn 4073: my $start = time;
4074: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4075: $udom,$uname);
4076: if ($putres eq 'ok') {
4077: &put('timerinterval',{"$courseid\0$res"=>$interval},
4078: $udom,$uname);
4079: &appenv(
4080: {
4081: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4082: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4083: }
4084: );
4085: }
4086: return $putres;
1.505 albertel 4087: }
4088: return 'already_set';
1.504 albertel 4089: }
1.1153 www 4090: }
1.110 www 4091: # --------------------------------------------- Set Expire Date for Spreadsheet
4092:
4093: sub expirespread {
4094: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4095: my $cid=$env{'request.course.id'};
1.110 www 4096: if ($cid) {
4097: my $now=time;
4098: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4099: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4100: $env{'course.'.$cid.'.num'}.
1.110 www 4101: ':nohist_expirationdates:'.
4102: &escape($key).'='.$now,
1.620 albertel 4103: $env{'course.'.$cid.'.home'})
1.110 www 4104: }
4105: return 'ok';
1.14 www 4106: }
4107:
1.109 www 4108: # ----------------------------------------------------- Devalidate Spreadsheets
4109:
4110: sub devalidate {
1.325 www 4111: my ($symb,$uname,$udom)=@_;
1.620 albertel 4112: my $cid=$env{'request.course.id'};
1.109 www 4113: if ($cid) {
1.391 matthew 4114: # delete the stored spreadsheets for
4115: # - the student level sheet of this user in course's homespace
4116: # - the assessment level sheet for this resource
4117: # for this user in user's homespace
1.553 albertel 4118: # - current conditional state info
1.325 www 4119: my $key=$uname.':'.$udom.':';
1.109 www 4120: my $status=
1.299 matthew 4121: &del('nohist_calculatedsheets',
1.391 matthew 4122: [$key.'studentcalc:'],
1.620 albertel 4123: $env{'course.'.$cid.'.domain'},
4124: $env{'course.'.$cid.'.num'})
1.133 albertel 4125: .' '.
4126: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4127: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4128: unless ($status eq 'ok ok') {
4129: &logthis('Could not devalidate spreadsheet '.
1.325 www 4130: $uname.' at '.$udom.' for '.
1.109 www 4131: $symb.': '.$status);
1.133 albertel 4132: }
1.553 albertel 4133: &delenv('user.state.'.$cid);
1.109 www 4134: }
4135: }
4136:
1.265 albertel 4137: sub get_scalar {
4138: my ($string,$end) = @_;
4139: my $value;
4140: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4141: $value = $1;
4142: } elsif ($$string =~ s/^([^&]*?)&//) {
4143: $value = $1;
4144: }
4145: return &unescape($value);
4146: }
4147:
4148: sub array2str {
4149: my (@array) = @_;
4150: my $result=&arrayref2str(\@array);
4151: $result=~s/^__ARRAY_REF__//;
4152: $result=~s/__END_ARRAY_REF__$//;
4153: return $result;
4154: }
4155:
1.204 albertel 4156: sub arrayref2str {
4157: my ($arrayref) = @_;
1.265 albertel 4158: my $result='__ARRAY_REF__';
1.204 albertel 4159: foreach my $elem (@$arrayref) {
1.265 albertel 4160: if(ref($elem) eq 'ARRAY') {
4161: $result.=&arrayref2str($elem).'&';
4162: } elsif(ref($elem) eq 'HASH') {
4163: $result.=&hashref2str($elem).'&';
4164: } elsif(ref($elem)) {
4165: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4166: } else {
4167: $result.=&escape($elem).'&';
4168: }
4169: }
4170: $result=~s/\&$//;
1.265 albertel 4171: $result .= '__END_ARRAY_REF__';
1.204 albertel 4172: return $result;
4173: }
4174:
1.168 albertel 4175: sub hash2str {
1.204 albertel 4176: my (%hash) = @_;
4177: my $result=&hashref2str(\%hash);
1.265 albertel 4178: $result=~s/^__HASH_REF__//;
4179: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4180: return $result;
4181: }
4182:
4183: sub hashref2str {
4184: my ($hashref)=@_;
1.265 albertel 4185: my $result='__HASH_REF__';
1.800 albertel 4186: foreach my $key (sort(keys(%$hashref))) {
4187: if (ref($key) eq 'ARRAY') {
4188: $result.=&arrayref2str($key).'=';
4189: } elsif (ref($key) eq 'HASH') {
4190: $result.=&hashref2str($key).'=';
4191: } elsif (ref($key)) {
1.265 albertel 4192: $result.='=';
1.800 albertel 4193: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4194: } else {
1.1132 raeburn 4195: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4196: }
4197:
1.800 albertel 4198: if(ref($hashref->{$key}) eq 'ARRAY') {
4199: $result.=&arrayref2str($hashref->{$key}).'&';
4200: } elsif(ref($hashref->{$key}) eq 'HASH') {
4201: $result.=&hashref2str($hashref->{$key}).'&';
4202: } elsif(ref($hashref->{$key})) {
1.265 albertel 4203: $result.='&';
1.800 albertel 4204: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4205: } else {
1.800 albertel 4206: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4207: }
4208: }
1.168 albertel 4209: $result=~s/\&$//;
1.265 albertel 4210: $result .= '__END_HASH_REF__';
1.168 albertel 4211: return $result;
4212: }
4213:
4214: sub str2hash {
1.265 albertel 4215: my ($string)=@_;
4216: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4217: return %$hash;
4218: }
4219:
4220: sub str2hashref {
1.168 albertel 4221: my ($string) = @_;
1.265 albertel 4222:
4223: my %hash;
4224:
4225: if($string !~ /^__HASH_REF__/) {
4226: if (! ($string eq '' || !defined($string))) {
4227: $hash{'error'}='Not hash reference';
4228: }
4229: return (\%hash, $string);
4230: }
4231:
4232: $string =~ s/^__HASH_REF__//;
4233:
4234: while($string !~ /^__END_HASH_REF__/) {
4235: #key
4236: my $key='';
4237: if($string =~ /^__HASH_REF__/) {
4238: ($key, $string)=&str2hashref($string);
4239: if(defined($key->{'error'})) {
4240: $hash{'error'}='Bad data';
4241: return (\%hash, $string);
4242: }
4243: } elsif($string =~ /^__ARRAY_REF__/) {
4244: ($key, $string)=&str2arrayref($string);
4245: if($key->[0] eq 'Array reference error') {
4246: $hash{'error'}='Bad data';
4247: return (\%hash, $string);
4248: }
4249: } else {
4250: $string =~ s/^(.*?)=//;
1.267 albertel 4251: $key=&unescape($1);
1.265 albertel 4252: }
4253: $string =~ s/^=//;
4254:
4255: #value
4256: my $value='';
4257: if($string =~ /^__HASH_REF__/) {
4258: ($value, $string)=&str2hashref($string);
4259: if(defined($value->{'error'})) {
4260: $hash{'error'}='Bad data';
4261: return (\%hash, $string);
4262: }
4263: } elsif($string =~ /^__ARRAY_REF__/) {
4264: ($value, $string)=&str2arrayref($string);
4265: if($value->[0] eq 'Array reference error') {
4266: $hash{'error'}='Bad data';
4267: return (\%hash, $string);
4268: }
4269: } else {
4270: $value=&get_scalar(\$string,'__END_HASH_REF__');
4271: }
4272: $string =~ s/^&//;
4273:
4274: $hash{$key}=$value;
1.204 albertel 4275: }
1.265 albertel 4276:
4277: $string =~ s/^__END_HASH_REF__//;
4278:
4279: return (\%hash, $string);
1.204 albertel 4280: }
4281:
4282: sub str2array {
1.265 albertel 4283: my ($string)=@_;
4284: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4285: return @$array;
4286: }
4287:
4288: sub str2arrayref {
1.204 albertel 4289: my ($string) = @_;
1.265 albertel 4290: my @array;
4291:
4292: if($string !~ /^__ARRAY_REF__/) {
4293: if (! ($string eq '' || !defined($string))) {
4294: $array[0]='Array reference error';
4295: }
4296: return (\@array, $string);
4297: }
4298:
4299: $string =~ s/^__ARRAY_REF__//;
4300:
4301: while($string !~ /^__END_ARRAY_REF__/) {
4302: my $value='';
4303: if($string =~ /^__HASH_REF__/) {
4304: ($value, $string)=&str2hashref($string);
4305: if(defined($value->{'error'})) {
4306: $array[0] ='Array reference error';
4307: return (\@array, $string);
4308: }
4309: } elsif($string =~ /^__ARRAY_REF__/) {
4310: ($value, $string)=&str2arrayref($string);
4311: if($value->[0] eq 'Array reference error') {
4312: $array[0] ='Array reference error';
4313: return (\@array, $string);
4314: }
4315: } else {
4316: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4317: }
4318: $string =~ s/^&//;
4319:
4320: push(@array, $value);
1.191 harris41 4321: }
1.265 albertel 4322:
4323: $string =~ s/^__END_ARRAY_REF__//;
4324:
4325: return (\@array, $string);
1.168 albertel 4326: }
4327:
1.167 albertel 4328: # -------------------------------------------------------------------Temp Store
4329:
1.168 albertel 4330: sub tmpreset {
4331: my ($symb,$namespace,$domain,$stuname) = @_;
4332: if (!$symb) {
4333: $symb=&symbread();
1.620 albertel 4334: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4335: }
4336: $symb=escape($symb);
4337:
1.620 albertel 4338: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4339: $namespace=~s/\//\_/g;
4340: $namespace=~s/\W//g;
4341:
1.620 albertel 4342: if (!$domain) { $domain=$env{'user.domain'}; }
4343: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4344: if ($domain eq 'public' && $stuname eq 'public') {
4345: $stuname=$ENV{'REMOTE_ADDR'};
4346: }
1.1117 foxr 4347: my $path=LONCAPA::tempdir();
1.168 albertel 4348: my %hash;
4349: if (tie(%hash,'GDBM_File',
4350: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4351: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4352: foreach my $key (keys(%hash)) {
1.180 albertel 4353: if ($key=~ /:$symb/) {
1.168 albertel 4354: delete($hash{$key});
4355: }
4356: }
4357: }
4358: }
4359:
1.167 albertel 4360: sub tmpstore {
1.168 albertel 4361: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4362:
4363: if (!$symb) {
4364: $symb=&symbread();
1.620 albertel 4365: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4366: }
4367: $symb=escape($symb);
4368:
4369: if (!$namespace) {
4370: # I don't think we would ever want to store this for a course.
4371: # it seems this will only be used if we don't have a course.
1.620 albertel 4372: #$namespace=$env{'request.course.id'};
1.168 albertel 4373: #if (!$namespace) {
1.620 albertel 4374: $namespace=$env{'request.state'};
1.168 albertel 4375: #}
4376: }
4377: $namespace=~s/\//\_/g;
4378: $namespace=~s/\W//g;
1.620 albertel 4379: if (!$domain) { $domain=$env{'user.domain'}; }
4380: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4381: if ($domain eq 'public' && $stuname eq 'public') {
4382: $stuname=$ENV{'REMOTE_ADDR'};
4383: }
1.168 albertel 4384: my $now=time;
4385: my %hash;
1.1117 foxr 4386: my $path=LONCAPA::tempdir();
1.168 albertel 4387: if (tie(%hash,'GDBM_File',
4388: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4389: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4390: $hash{"version:$symb"}++;
4391: my $version=$hash{"version:$symb"};
4392: my $allkeys='';
4393: foreach my $key (keys(%$storehash)) {
4394: $allkeys.=$key.':';
1.591 albertel 4395: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4396: }
4397: $hash{"$version:$symb:timestamp"}=$now;
4398: $allkeys.='timestamp';
4399: $hash{"$version:keys:$symb"}=$allkeys;
4400: if (untie(%hash)) {
4401: return 'ok';
4402: } else {
4403: return "error:$!";
4404: }
4405: } else {
4406: return "error:$!";
4407: }
4408: }
1.167 albertel 4409:
1.168 albertel 4410: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4411:
1.168 albertel 4412: sub tmprestore {
4413: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4414:
1.168 albertel 4415: if (!$symb) {
4416: $symb=&symbread();
1.620 albertel 4417: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4418: }
4419: $symb=escape($symb);
4420:
1.620 albertel 4421: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4422:
1.620 albertel 4423: if (!$domain) { $domain=$env{'user.domain'}; }
4424: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4425: if ($domain eq 'public' && $stuname eq 'public') {
4426: $stuname=$ENV{'REMOTE_ADDR'};
4427: }
1.168 albertel 4428: my %returnhash;
4429: $namespace=~s/\//\_/g;
4430: $namespace=~s/\W//g;
4431: my %hash;
1.1117 foxr 4432: my $path=LONCAPA::tempdir();
1.168 albertel 4433: if (tie(%hash,'GDBM_File',
4434: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4435: &GDBM_READER(),0640)) {
1.168 albertel 4436: my $version=$hash{"version:$symb"};
4437: $returnhash{'version'}=$version;
4438: my $scope;
4439: for ($scope=1;$scope<=$version;$scope++) {
4440: my $vkeys=$hash{"$scope:keys:$symb"};
4441: my @keys=split(/:/,$vkeys);
4442: my $key;
4443: $returnhash{"$scope:keys"}=$vkeys;
4444: foreach $key (@keys) {
1.591 albertel 4445: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4446: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4447: }
4448: }
1.168 albertel 4449: if (!(untie(%hash))) {
4450: return "error:$!";
4451: }
4452: } else {
4453: return "error:$!";
4454: }
4455: return %returnhash;
1.167 albertel 4456: }
4457:
1.9 www 4458: # ----------------------------------------------------------------------- Store
4459:
4460: sub store {
1.124 www 4461: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4462: my $home='';
4463:
1.168 albertel 4464: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4465:
1.213 www 4466: $symb=&symbclean($symb);
1.122 albertel 4467: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4468:
1.620 albertel 4469: if (!$domain) { $domain=$env{'user.domain'}; }
4470: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4471:
4472: &devalidate($symb,$stuname,$domain);
1.109 www 4473:
4474: $symb=escape($symb);
1.187 www 4475: if (!$namespace) {
1.620 albertel 4476: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4477: return '';
4478: }
4479: }
1.620 albertel 4480: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4481:
4482: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4483: $$storehash{'host'}=$perlvar{'lonHostID'};
4484:
1.12 www 4485: my $namevalue='';
1.800 albertel 4486: foreach my $key (keys(%$storehash)) {
4487: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4488: }
1.12 www 4489: $namevalue=~s/\&$//;
1.187 www 4490: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4491: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4492: }
4493:
1.47 www 4494: # -------------------------------------------------------------- Critical Store
4495:
4496: sub cstore {
1.124 www 4497: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4498: my $home='';
4499:
1.168 albertel 4500: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4501:
1.213 www 4502: $symb=&symbclean($symb);
1.122 albertel 4503: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4504:
1.620 albertel 4505: if (!$domain) { $domain=$env{'user.domain'}; }
4506: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4507:
4508: &devalidate($symb,$stuname,$domain);
1.109 www 4509:
4510: $symb=escape($symb);
1.187 www 4511: if (!$namespace) {
1.620 albertel 4512: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4513: return '';
4514: }
4515: }
1.620 albertel 4516: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4517:
4518: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4519: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4520:
1.47 www 4521: my $namevalue='';
1.800 albertel 4522: foreach my $key (keys(%$storehash)) {
4523: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4524: }
1.47 www 4525: $namevalue=~s/\&$//;
1.187 www 4526: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4527: return critical
4528: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4529: }
4530:
1.9 www 4531: # --------------------------------------------------------------------- Restore
4532:
4533: sub restore {
1.124 www 4534: my ($symb,$namespace,$domain,$stuname) = @_;
4535: my $home='';
4536:
1.168 albertel 4537: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4538:
1.122 albertel 4539: if (!$symb) {
4540: unless ($symb=escape(&symbread())) { return ''; }
4541: } else {
1.213 www 4542: $symb=&escape(&symbclean($symb));
1.122 albertel 4543: }
1.188 www 4544: if (!$namespace) {
1.620 albertel 4545: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4546: return '';
4547: }
4548: }
1.620 albertel 4549: if (!$domain) { $domain=$env{'user.domain'}; }
4550: if (!$stuname) { $stuname=$env{'user.name'}; }
4551: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4552: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4553:
1.12 www 4554: my %returnhash=();
1.800 albertel 4555: foreach my $line (split(/\&/,$answer)) {
4556: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4557: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4558: }
1.75 www 4559: my $version;
4560: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4561: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4562: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4563: }
1.75 www 4564: }
1.13 www 4565: return %returnhash;
1.34 www 4566: }
4567:
4568: # ---------------------------------------------------------- Course Description
1.1118 foxr 4569: #
4570: #
1.34 www 4571:
4572: sub coursedescription {
1.731 albertel 4573: my ($courseid,$args)=@_;
1.34 www 4574: $courseid=~s/^\///;
1.49 www 4575: $courseid=~s/\_/\//g;
1.34 www 4576: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4577: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4578: my $normalid=$cdomain.'_'.$cnum;
4579: # need to always cache even if we get errors otherwise we keep
4580: # trying and trying and trying to get the course description.
4581: my %envhash=();
4582: my %returnhash=();
1.731 albertel 4583:
4584: my $expiretime=600;
4585: if ($env{'request.course.id'} eq $normalid) {
4586: $expiretime=120;
4587: }
4588:
4589: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4590: if (!$args->{'freshen_cache'}
4591: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4592: foreach my $key (keys(%env)) {
4593: next if ($key !~ /^\Q$prefix\E(.*)/);
4594: my ($setting) = $1;
4595: $returnhash{$setting} = $env{$key};
4596: }
4597: return %returnhash;
4598: }
4599:
1.1118 foxr 4600: # get the data again
4601:
1.731 albertel 4602: if (!$args->{'one_time'}) {
4603: $envhash{'course.'.$normalid.'.last_cache'}=time;
4604: }
1.811 albertel 4605:
1.34 www 4606: if ($chome ne 'no_host') {
1.302 albertel 4607: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4608: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4609: my $username = $env{'user.name'}; # Defult username
4610: if(defined $args->{'user'}) {
4611: $username = $args->{'user'};
4612: }
1.129 albertel 4613: $returnhash{'home'}= $chome;
4614: $returnhash{'domain'} = $cdomain;
4615: $returnhash{'num'} = $cnum;
1.741 raeburn 4616: if (!defined($returnhash{'type'})) {
4617: $returnhash{'type'} = 'Course';
4618: }
1.130 albertel 4619: while (my ($name,$value) = each %returnhash) {
1.53 www 4620: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4621: }
1.270 www 4622: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4623: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4624: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4625: $envhash{'course.'.$normalid.'.home'}=$chome;
4626: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4627: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4628: }
4629: }
1.731 albertel 4630: if (!$args->{'one_time'}) {
1.949 raeburn 4631: &appenv(\%envhash);
1.731 albertel 4632: }
1.302 albertel 4633: return %returnhash;
1.461 www 4634: }
4635:
1.1080 raeburn 4636: sub update_released_required {
4637: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4638: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4639: $cid = $env{'request.course.id'};
4640: $cdom = $env{'course.'.$cid.'.domain'};
4641: $cnum = $env{'course.'.$cid.'.num'};
4642: $chome = $env{'course.'.$cid.'.home'};
4643: }
4644: if ($needsrelease) {
4645: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4646: my $needsupdate;
4647: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4648: $needsupdate = 1;
4649: } else {
4650: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4651: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4652: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4653: $needsupdate = 1;
4654: }
4655: }
4656: if ($needsupdate) {
4657: my %needshash = (
4658: 'internal.releaserequired' => $needsrelease,
4659: );
4660: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4661: if ($putresult eq 'ok') {
4662: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4663: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4664: if (ref($crsinfo{$cid}) eq 'HASH') {
4665: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4666: &courseidput($cdom,\%crsinfo,$chome,'notime');
4667: }
4668: }
4669: }
4670: }
4671: return;
4672: }
4673:
1.461 www 4674: # -------------------------------------------------See if a user is privileged
4675:
4676: sub privileged {
4677: my ($username,$domain)=@_;
1.1170 droeschl 4678:
4679: my %rolesdump = &dump("roles", $domain, $username) or return 0;
4680: my $now = time;
4681:
4682: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
4683: my ($trole, $tend, $tstart) = split(/_/, $role);
4684: if (($trole eq 'dc') || ($trole eq 'su')) {
4685: return 1 unless ($tend && $tend < $now)
4686: or ($tstart && $tstart > $now);
4687: }
1.461 www 4688: }
1.1170 droeschl 4689:
1.461 www 4690: return 0;
1.9 www 4691: }
1.1 albertel 4692:
1.103 harris41 4693: # -------------------------------------------------------- Get user privileges
1.11 www 4694:
4695: sub rolesinit {
1.1169 droeschl 4696: my ($domain, $username) = @_;
4697: my %userroles = ('user.login.time' => time);
4698: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
4699:
4700: # firstaccess and timerinterval are related to timed maps/resources.
4701: # also, blocking can be triggered by an activating timer
4702: # it's saved in the user's %env.
4703: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
4704: my %timerinterval = &dump('timerinterval', $domain, $username);
4705: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
4706: %timerintchk, %timerintenv);
4707:
1.1162 raeburn 4708: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 4709: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 4710: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
4711: }
1.1169 droeschl 4712:
1.1162 raeburn 4713: foreach my $key (keys(%timerinterval)) {
4714: my ($cid,$rest) = split(/\0/,$key);
4715: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
4716: }
1.1169 droeschl 4717:
1.11 www 4718: my %allroles=();
1.1162 raeburn 4719: my %allgroups=();
1.11 www 4720:
1.1169 droeschl 4721: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
4722: my $role = $rolesdump{$area};
4723: $area =~ s/\_\w\w$//;
4724:
4725: my ($trole, $tend, $tstart, $group_privs);
4726:
4727: if ($role =~ /^cr/) {
4728: # Custom role, defined by a user
4729: # e.g., user.role.cr/msu/smith/mynewrole
4730: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4731: $trole = $1;
4732: ($tend, $tstart) = split('_', $2);
4733: } else {
4734: $trole = $role;
4735: }
4736: } elsif ($role =~ m|^gr/|) {
4737: # Role of member in a group, defined within a course/community
4738: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
4739: ($trole, $tend, $tstart) = split(/_/, $role);
4740: next if $tstart eq '-1';
4741: ($trole, $group_privs) = split(/\//, $trole);
4742: $group_privs = &unescape($group_privs);
4743: } else {
4744: # Just a normal role, defined in roles.tab
4745: ($trole, $tend, $tstart) = split(/_/,$role);
4746: }
4747:
4748: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4749: $username);
4750: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
4751:
4752: # role expired or not available yet?
4753: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
4754: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
4755:
4756: next if $area eq '' or $trole eq '';
4757:
4758: my $spec = "$trole.$area";
4759: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
4760:
4761: if ($trole =~ /^cr\//) {
4762: # Custom role, defined by a user
4763: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4764: } elsif ($trole eq 'gr') {
4765: # Role of a member in a group, defined within a course/community
4766: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
4767: next;
4768: } else {
4769: # Normal role, defined in roles.tab
4770: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4771: }
4772:
4773: my $cid = $tdomain.'_'.$trest;
4774: unless ($firstaccchk{$cid}) {
4775: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
4776: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
4777: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
4778: $coursetimerstarts{$cid}{$item};
4779: }
4780: }
4781: $firstaccchk{$cid} = 1;
4782: }
4783: unless ($timerintchk{$cid}) {
4784: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
4785: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
4786: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
4787: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 4788: }
1.12 www 4789: }
1.1169 droeschl 4790: $timerintchk{$cid} = 1;
1.191 harris41 4791: }
1.11 www 4792: }
1.1169 droeschl 4793:
4794: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
4795: \%allroles, \%allgroups);
4796: $env{'user.adv'} = $userroles{'user.adv'};
4797:
1.1162 raeburn 4798: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 4799: }
4800:
1.567 raeburn 4801: sub set_arearole {
4802: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4803: # log the associated role with the area
4804: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4805: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4806: }
4807:
4808: sub custom_roleprivs {
4809: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4810: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4811: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4812: if (&hostname($homsvr) ne '') {
1.567 raeburn 4813: my ($rdummy,$roledef)=
4814: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4815: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4816: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4817: if (defined($syspriv)) {
1.1043 raeburn 4818: if ($trest =~ /^$match_community$/) {
4819: $syspriv =~ s/bre\&S//;
4820: }
1.567 raeburn 4821: $$allroles{'cm./'}.=':'.$syspriv;
4822: $$allroles{$spec.'./'}.=':'.$syspriv;
4823: }
4824: if ($tdomain ne '') {
4825: if (defined($dompriv)) {
4826: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4827: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4828: }
4829: if (($trest ne '') && (defined($coursepriv))) {
4830: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4831: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4832: }
4833: }
4834: }
4835: }
4836: }
4837:
1.678 raeburn 4838: sub group_roleprivs {
4839: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4840: my $access = 1;
4841: my $now = time;
4842: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4843: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4844: if ($access) {
1.811 albertel 4845: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4846: $$allgroups{$course}{$group} .=':'.$group_privs;
4847: }
4848: }
1.567 raeburn 4849:
4850: sub standard_roleprivs {
4851: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4852: if (defined($pr{$trole.':s'})) {
4853: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4854: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4855: }
4856: if ($tdomain ne '') {
4857: if (defined($pr{$trole.':d'})) {
4858: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4859: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4860: }
4861: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4862: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4863: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4864: }
4865: }
4866: }
4867:
4868: sub set_userprivs {
1.1064 raeburn 4869: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4870: my $author=0;
4871: my $adv=0;
1.678 raeburn 4872: my %grouproles = ();
4873: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4874: my @groupkeys;
1.1000 raeburn 4875: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4876: push(@groupkeys,$role);
4877: }
4878: if (ref($groups_roles) eq 'HASH') {
4879: foreach my $key (keys(%{$groups_roles})) {
4880: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4881: push(@groupkeys,$key);
4882: }
4883: }
4884: }
4885: if (@groupkeys > 0) {
4886: foreach my $role (@groupkeys) {
4887: my ($trole,$area,$sec,$extendedarea);
4888: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4889: $trole = $1;
4890: $area = $2;
4891: $sec = $3;
4892: $extendedarea = $area.$sec;
4893: if (exists($$allgroups{$area})) {
4894: foreach my $group (keys(%{$$allgroups{$area}})) {
4895: my $spec = $trole.'.'.$extendedarea;
4896: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4897: $$allgroups{$area}{$group};
1.1064 raeburn 4898: }
1.678 raeburn 4899: }
4900: }
4901: }
4902: }
4903: }
1.800 albertel 4904: foreach my $group (keys(%grouproles)) {
4905: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4906: }
1.800 albertel 4907: foreach my $role (keys(%{$allroles})) {
4908: my %thesepriv;
1.941 raeburn 4909: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4910: foreach my $item (split(/:/,$$allroles{$role})) {
4911: if ($item ne '') {
4912: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4913: if ($restrictions eq '') {
4914: $thesepriv{$privilege}='F';
4915: } elsif ($thesepriv{$privilege} ne 'F') {
4916: $thesepriv{$privilege}.=$restrictions;
4917: }
4918: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4919: }
4920: }
4921: my $thesestr='';
1.1104 raeburn 4922: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 4923: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4924: }
4925: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4926: }
4927: return ($author,$adv);
4928: }
4929:
1.994 raeburn 4930: sub role_status {
1.1104 raeburn 4931: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4932: my @pwhere = ();
4933: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4934: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4935: unless (!defined($$role) || $$role eq '') {
4936: $$where=join('.',@pwhere);
4937: $$trolecode=$$role.'.'.$$where;
4938: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4939: $$tstatus='is';
1.1104 raeburn 4940: if ($$tstart && $$tstart>$update) {
1.994 raeburn 4941: $$tstatus='future';
1.1034 raeburn 4942: if ($$tstart<$now) {
4943: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4944: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4945: my (%allroles,%allgroups,$group_privs,
4946: %groups_roles,@rolecodes);
1.1002 raeburn 4947: my %userroles = (
4948: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4949: );
1.1064 raeburn 4950: @rolecodes = ('cm');
1.1002 raeburn 4951: my $spec=$$role.'.'.$$where;
4952: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4953: if ($$role =~ /^cr\//) {
4954: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4955: push(@rolecodes,'cr');
1.1002 raeburn 4956: } elsif ($$role eq 'gr') {
1.1064 raeburn 4957: push(@rolecodes,$$role);
1.1002 raeburn 4958: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4959: $env{'user.name'});
1.1064 raeburn 4960: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4961: (undef,my $group_privs) = split(/\//,$trole);
4962: $group_privs = &unescape($group_privs);
4963: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4964: 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 4965: &get_groups_roles($tdomain,$trest,
4966: \%course_roles,\@rolecodes,
4967: \%groups_roles);
1.1002 raeburn 4968: } else {
1.1064 raeburn 4969: push(@rolecodes,$$role);
1.1002 raeburn 4970: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4971: }
1.1064 raeburn 4972: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4973: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4974: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4975: }
4976: }
1.1034 raeburn 4977: $$tstatus = 'is';
1.1002 raeburn 4978: }
1.994 raeburn 4979: }
4980: if ($$tend) {
1.1104 raeburn 4981: if ($$tend<$update) {
1.994 raeburn 4982: $$tstatus='expired';
4983: } elsif ($$tend<$now) {
4984: $$tstatus='will_not';
4985: }
4986: }
4987: }
4988: }
4989: }
4990:
1.1104 raeburn 4991: sub get_groups_roles {
4992: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4993: return unless((ref($cdom_courseroles) eq 'HASH') &&
4994: (ref($rolecodes) eq 'ARRAY') &&
4995: (ref($groups_roles) eq 'HASH'));
4996: if (keys(%{$cdom_courseroles}) > 0) {
4997: my ($cnum) = ($rest =~ /^($match_courseid)/);
4998: if ($cdom ne '' && $cnum ne '') {
4999: foreach my $key (keys(%{$cdom_courseroles})) {
5000: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5001: my $crsrole = $1;
5002: my $crssec = $2;
5003: if ($crsrole =~ /^cr/) {
5004: unless (grep(/^cr$/,@{$rolecodes})) {
5005: push(@{$rolecodes},'cr');
5006: }
5007: } else {
5008: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5009: push(@{$rolecodes},$crsrole);
5010: }
5011: }
5012: my $rolekey = "$crsrole./$cdom/$cnum";
5013: if ($crssec ne '') {
5014: $rolekey .= "/$crssec";
5015: }
5016: $rolekey .= './';
5017: $groups_roles->{$rolekey} = $rolecodes;
5018: }
5019: }
5020: }
5021: }
5022: return;
5023: }
5024:
5025: sub delete_env_groupprivs {
5026: my ($where,$courseroles,$possroles) = @_;
5027: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5028: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5029: unless (ref($courseroles->{$udom}) eq 'HASH') {
5030: %{$courseroles->{$udom}} =
5031: &get_my_roles('','','userroles',['active'],
5032: $possroles,[$udom],1);
5033: }
5034: if (ref($courseroles->{$udom}) eq 'HASH') {
5035: foreach my $item (keys(%{$courseroles->{$udom}})) {
5036: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5037: my $area = '/'.$cdom.'/'.$cnum;
5038: my $privkey = "user.priv.$crsrole.$area";
5039: if ($crssec ne '') {
5040: $privkey .= '/'.$crssec;
5041: }
5042: $privkey .= ".$area/$group";
5043: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5044: }
5045: }
5046: return;
5047: }
5048:
1.994 raeburn 5049: sub check_adhoc_privs {
1.1104 raeburn 5050: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5051: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185 raeburn 5052: my $setprivs;
1.994 raeburn 5053: if ($env{$cckey}) {
5054: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5055: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5056: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5057: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5058: $setprivs = 1;
1.994 raeburn 5059: }
5060: } else {
1.1088 raeburn 5061: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185 raeburn 5062: $setprivs = 1;
1.994 raeburn 5063: }
1.1185 raeburn 5064: return $setprivs;
1.994 raeburn 5065: }
5066:
5067: sub set_adhoc_privileges {
5068: # role can be cc or ca
1.1088 raeburn 5069: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5070: my $area = '/'.$dcdom.'/'.$pickedcourse;
5071: my $spec = $role.'.'.$area;
5072: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
5073: $env{'user.name'});
5074: my %ccrole = ();
5075: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5076: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5077: &appenv(\%userroles,[$role,'cm']);
5078: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5079: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5080: &appenv( {'request.role' => $spec,
5081: 'request.role.domain' => $dcdom,
5082: 'request.course.sec' => ''
5083: }
5084: );
5085: my $tadv=0;
5086: if (&allowed('adv') eq 'F') { $tadv=1; }
5087: &appenv({'request.role.adv' => $tadv});
5088: }
1.994 raeburn 5089: }
5090:
1.12 www 5091: # --------------------------------------------------------------- get interface
5092:
5093: sub get {
1.131 albertel 5094: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5095: my $items='';
1.800 albertel 5096: foreach my $item (@$storearr) {
5097: $items.=&escape($item).'&';
1.191 harris41 5098: }
1.12 www 5099: $items=~s/\&$//;
1.620 albertel 5100: if (!$udomain) { $udomain=$env{'user.domain'}; }
5101: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5102: my $uhome=&homeserver($uname,$udomain);
5103:
1.133 albertel 5104: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5105: my @pairs=split(/\&/,$rep);
1.273 albertel 5106: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5107: return @pairs;
5108: }
1.15 www 5109: my %returnhash=();
1.42 www 5110: my $i=0;
1.800 albertel 5111: foreach my $item (@$storearr) {
5112: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5113: $i++;
1.191 harris41 5114: }
1.15 www 5115: return %returnhash;
1.27 www 5116: }
5117:
5118: # --------------------------------------------------------------- del interface
5119:
5120: sub del {
1.133 albertel 5121: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5122: my $items='';
1.800 albertel 5123: foreach my $item (@$storearr) {
5124: $items.=&escape($item).'&';
1.191 harris41 5125: }
1.984 neumanie 5126:
1.27 www 5127: $items=~s/\&$//;
1.620 albertel 5128: if (!$udomain) { $udomain=$env{'user.domain'}; }
5129: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5130: my $uhome=&homeserver($uname,$udomain);
5131: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5132: }
5133:
5134: # -------------------------------------------------------------- dump interface
5135:
1.1180 droeschl 5136: sub unserialize {
5137: my ($rep, $escapedkeys) = @_;
5138:
5139: return {} if $rep =~ /^error/;
5140:
5141: my %returnhash=();
5142: foreach my $item (split /\&/, $rep) {
5143: my ($key, $value) = split(/=/, $item, 2);
5144: $key = unescape($key) unless $escapedkeys;
5145: next if $key =~ /^error: 2 /;
5146: $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
5147: }
5148: #return %returnhash;
5149: return \%returnhash;
5150: }
5151:
5152: # see Lond::dump_with_regexp
5153: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5154: sub dump {
1.1180 droeschl 5155: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5156: if (!$udomain) { $udomain=$env{'user.domain'}; }
5157: if (!$uname) { $uname=$env{'user.name'}; }
5158: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5159:
1.1180 droeschl 5160: my $reply;
5161: if (grep { $_ eq $uhome } current_machine_ids()) {
5162: # user is hosted on this machine
5163: $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
5164: $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
5165: return %{unserialize($reply, $escapedkeys)};
5166: }
1.755 albertel 5167: if ($regexp) {
5168: $regexp=&escape($regexp);
5169: } else {
5170: $regexp='.';
5171: }
1.1166 raeburn 5172: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5173: my @pairs=split(/\&/,$rep);
5174: my %returnhash=();
1.1098 foxr 5175: if (!($rep =~ /^error/ )) {
5176: foreach my $item (@pairs) {
5177: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5178: $key = unescape($key) unless $escapedkeys;
5179: #$key = &unescape($key);
1.1098 foxr 5180: next if ($key =~ /^error: 2 /);
5181: $returnhash{$key}=&thaw_unescape($value);
5182: }
1.755 albertel 5183: }
5184: return %returnhash;
1.407 www 5185: }
5186:
1.1098 foxr 5187:
1.717 albertel 5188: # --------------------------------------------------------- dumpstore interface
5189:
5190: sub dumpstore {
5191: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5192: # same as dump but keys must be escaped. They may contain colon separated
5193: # lists of values that may themself contain colons (e.g. symbs).
5194: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5195: }
5196:
1.407 www 5197: # -------------------------------------------------------------- keys interface
5198:
5199: sub getkeys {
5200: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5201: if (!$udomain) { $udomain=$env{'user.domain'}; }
5202: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5203: my $uhome=&homeserver($uname,$udomain);
5204: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5205: my @keyarray=();
1.800 albertel 5206: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5207: next if ($key =~ /^error: 2 /);
1.800 albertel 5208: push(@keyarray,&unescape($key));
1.407 www 5209: }
5210: return @keyarray;
1.318 matthew 5211: }
5212:
1.319 matthew 5213: # --------------------------------------------------------------- currentdump
5214: sub currentdump {
1.328 matthew 5215: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5216: $courseid = $env{'request.course.id'} if (! defined($courseid));
5217: $sdom = $env{'user.domain'} if (! defined($sdom));
5218: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5219: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5220: my $rep;
5221:
5222: if (grep { $_ eq $uhome } current_machine_ids()) {
5223: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5224: $courseid)));
5225: } else {
5226: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5227: }
5228:
1.318 matthew 5229: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5230: #
1.318 matthew 5231: my %returnhash=();
1.319 matthew 5232: #
5233: if ($rep eq "unknown_cmd") {
5234: # an old lond will not know currentdump
5235: # Do a dump and make it look like a currentdump
1.822 albertel 5236: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5237: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5238: my %hash = @tmp;
5239: @tmp=();
1.424 matthew 5240: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5241: } else {
5242: my @pairs=split(/\&/,$rep);
1.800 albertel 5243: foreach my $pair (@pairs) {
5244: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5245: my ($symb,$param) = split(/:/,$key);
5246: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5247: &thaw_unescape($value);
1.319 matthew 5248: }
1.191 harris41 5249: }
1.12 www 5250: return %returnhash;
1.424 matthew 5251: }
5252:
5253: sub convert_dump_to_currentdump{
5254: my %hash = %{shift()};
5255: my %returnhash;
5256: # Code ripped from lond, essentially. The only difference
5257: # here is the unescaping done by lonnet::dump(). Conceivably
5258: # we might run in to problems with parameter names =~ /^v\./
5259: while (my ($key,$value) = each(%hash)) {
5260: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5261: $symb = &unescape($symb);
5262: $param = &unescape($param);
1.424 matthew 5263: next if ($v eq 'version' || $symb eq 'keys');
5264: next if (exists($returnhash{$symb}) &&
5265: exists($returnhash{$symb}->{$param}) &&
5266: $returnhash{$symb}->{'v.'.$param} > $v);
5267: $returnhash{$symb}->{$param}=$value;
5268: $returnhash{$symb}->{'v.'.$param}=$v;
5269: }
5270: #
5271: # Remove all of the keys in the hashes which keep track of
5272: # the version of the parameter.
5273: while (my ($symb,$param_hash) = each(%returnhash)) {
5274: # use a foreach because we are going to delete from the hash.
5275: foreach my $key (keys(%$param_hash)) {
5276: delete($param_hash->{$key}) if ($key =~ /^v\./);
5277: }
5278: }
5279: return \%returnhash;
1.12 www 5280: }
5281:
1.627 albertel 5282: # ------------------------------------------------------ critical inc interface
5283:
5284: sub cinc {
5285: return &inc(@_,'critical');
5286: }
5287:
1.449 matthew 5288: # --------------------------------------------------------------- inc interface
5289:
5290: sub inc {
1.627 albertel 5291: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5292: if (!$udomain) { $udomain=$env{'user.domain'}; }
5293: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5294: my $uhome=&homeserver($uname,$udomain);
5295: my $items='';
5296: if (! ref($store)) {
5297: # got a single value, so use that instead
5298: $items = &escape($store).'=&';
5299: } elsif (ref($store) eq 'SCALAR') {
5300: $items = &escape($$store).'=&';
5301: } elsif (ref($store) eq 'ARRAY') {
5302: $items = join('=&',map {&escape($_);} @{$store});
5303: } elsif (ref($store) eq 'HASH') {
5304: while (my($key,$value) = each(%{$store})) {
5305: $items.= &escape($key).'='.&escape($value).'&';
5306: }
5307: }
5308: $items=~s/\&$//;
1.627 albertel 5309: if ($critical) {
5310: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5311: } else {
5312: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5313: }
1.449 matthew 5314: }
5315:
1.12 www 5316: # --------------------------------------------------------------- put interface
5317:
5318: sub put {
1.134 albertel 5319: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5320: if (!$udomain) { $udomain=$env{'user.domain'}; }
5321: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5322: my $uhome=&homeserver($uname,$udomain);
1.12 www 5323: my $items='';
1.800 albertel 5324: foreach my $item (keys(%$storehash)) {
5325: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5326: }
1.12 www 5327: $items=~s/\&$//;
1.134 albertel 5328: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5329: }
5330:
1.631 albertel 5331: # ------------------------------------------------------------ newput interface
5332:
5333: sub newput {
5334: my ($namespace,$storehash,$udomain,$uname)=@_;
5335: if (!$udomain) { $udomain=$env{'user.domain'}; }
5336: if (!$uname) { $uname=$env{'user.name'}; }
5337: my $uhome=&homeserver($uname,$udomain);
5338: my $items='';
5339: foreach my $key (keys(%$storehash)) {
5340: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5341: }
5342: $items=~s/\&$//;
5343: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5344: }
5345:
5346: # --------------------------------------------------------- putstore interface
5347:
1.524 raeburn 5348: sub putstore {
1.715 albertel 5349: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5350: if (!$udomain) { $udomain=$env{'user.domain'}; }
5351: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5352: my $uhome=&homeserver($uname,$udomain);
5353: my $items='';
1.715 albertel 5354: foreach my $key (keys(%$storehash)) {
5355: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5356: }
1.715 albertel 5357: $items=~s/\&$//;
1.716 albertel 5358: my $esc_symb=&escape($symb);
5359: my $esc_v=&escape($version);
1.715 albertel 5360: my $reply =
1.716 albertel 5361: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5362: $uhome);
5363: if ($reply eq 'unknown_cmd') {
1.716 albertel 5364: # gfall back to way things use to be done
1.715 albertel 5365: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5366: $uname);
1.524 raeburn 5367: }
1.715 albertel 5368: return $reply;
5369: }
5370:
5371: sub old_putstore {
1.716 albertel 5372: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5373: if (!$udomain) { $udomain=$env{'user.domain'}; }
5374: if (!$uname) { $uname=$env{'user.name'}; }
5375: my $uhome=&homeserver($uname,$udomain);
5376: my %newstorehash;
1.800 albertel 5377: foreach my $item (keys(%$storehash)) {
5378: my $key = $version.':'.&escape($symb).':'.$item;
5379: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5380: }
5381: my $items='';
5382: my %allitems = ();
1.800 albertel 5383: foreach my $item (keys(%newstorehash)) {
5384: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5385: my $key = $1.':keys:'.$2;
5386: $allitems{$key} .= $3.':';
5387: }
1.800 albertel 5388: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5389: }
1.800 albertel 5390: foreach my $item (keys(%allitems)) {
5391: $allitems{$item} =~ s/\:$//;
5392: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5393: }
5394: $items=~s/\&$//;
5395: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5396: }
5397:
1.47 www 5398: # ------------------------------------------------------ critical put interface
5399:
5400: sub cput {
1.134 albertel 5401: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5402: if (!$udomain) { $udomain=$env{'user.domain'}; }
5403: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5404: my $uhome=&homeserver($uname,$udomain);
1.47 www 5405: my $items='';
1.800 albertel 5406: foreach my $item (keys(%$storehash)) {
5407: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5408: }
1.47 www 5409: $items=~s/\&$//;
1.134 albertel 5410: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5411: }
5412:
5413: # -------------------------------------------------------------- eget interface
5414:
5415: sub eget {
1.133 albertel 5416: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5417: my $items='';
1.800 albertel 5418: foreach my $item (@$storearr) {
5419: $items.=&escape($item).'&';
1.191 harris41 5420: }
1.12 www 5421: $items=~s/\&$//;
1.620 albertel 5422: if (!$udomain) { $udomain=$env{'user.domain'}; }
5423: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5424: my $uhome=&homeserver($uname,$udomain);
5425: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5426: my @pairs=split(/\&/,$rep);
5427: my %returnhash=();
1.42 www 5428: my $i=0;
1.800 albertel 5429: foreach my $item (@$storearr) {
5430: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5431: $i++;
1.191 harris41 5432: }
1.12 www 5433: return %returnhash;
5434: }
5435:
1.667 albertel 5436: # ------------------------------------------------------------ tmpput interface
5437: sub tmpput {
1.802 raeburn 5438: my ($storehash,$server,$context)=@_;
1.667 albertel 5439: my $items='';
1.800 albertel 5440: foreach my $item (keys(%$storehash)) {
5441: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5442: }
5443: $items=~s/\&$//;
1.802 raeburn 5444: if (defined($context)) {
5445: $items .= ':'.&escape($context);
5446: }
1.667 albertel 5447: return &reply("tmpput:$items",$server);
5448: }
5449:
5450: # ------------------------------------------------------------ tmpget interface
5451: sub tmpget {
1.688 albertel 5452: my ($token,$server)=@_;
5453: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5454: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5455: my %returnhash;
5456: foreach my $item (split(/\&/,$rep)) {
5457: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5458: next if ($key =~ /^error: 2 /);
1.667 albertel 5459: $returnhash{&unescape($key)}=&thaw_unescape($value);
5460: }
5461: return %returnhash;
5462: }
5463:
1.1113 raeburn 5464: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5465: sub tmpdel {
5466: my ($token,$server)=@_;
5467: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5468: return &reply("tmpdel:$token",$server);
5469: }
5470:
1.765 albertel 5471: # -------------------------------------------------- portfolio access checking
5472:
5473: sub portfolio_access {
1.766 albertel 5474: my ($requrl) = @_;
1.765 albertel 5475: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5476: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 5477: if ($result) {
5478: my %setters;
5479: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5480: my ($startblock,$endblock) =
5481: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5482: if ($startblock && $endblock) {
5483: return 'B';
5484: }
5485: } else {
5486: my ($startblock,$endblock) =
5487: &Apache::loncommon::blockcheck(\%setters,'port');
5488: if ($startblock && $endblock) {
5489: return 'B';
5490: }
5491: }
5492: }
1.765 albertel 5493: if ($result eq 'ok') {
1.766 albertel 5494: return 'F';
1.765 albertel 5495: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 5496: return 'A';
1.765 albertel 5497: }
1.766 albertel 5498: return '';
1.765 albertel 5499: }
5500:
5501: sub get_portfolio_access {
1.767 albertel 5502: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5503:
5504: if (!ref($access_hash)) {
5505: my $current_perms = &get_portfile_permissions($udom,$unum);
5506: my %access_controls = &get_access_controls($current_perms,$group,
5507: $file_name);
5508: $access_hash = $access_controls{$file_name};
5509: }
5510:
1.765 albertel 5511: my ($public,$guest,@domains,@users,@courses,@groups);
5512: my $now = time;
5513: if (ref($access_hash) eq 'HASH') {
5514: foreach my $key (keys(%{$access_hash})) {
5515: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5516: if ($start > $now) {
5517: next;
5518: }
5519: if ($end && $end<$now) {
5520: next;
5521: }
5522: if ($scope eq 'public') {
5523: $public = $key;
5524: last;
5525: } elsif ($scope eq 'guest') {
5526: $guest = $key;
5527: } elsif ($scope eq 'domains') {
5528: push(@domains,$key);
5529: } elsif ($scope eq 'users') {
5530: push(@users,$key);
5531: } elsif ($scope eq 'course') {
5532: push(@courses,$key);
5533: } elsif ($scope eq 'group') {
5534: push(@groups,$key);
5535: }
5536: }
5537: if ($public) {
5538: return 'ok';
5539: }
5540: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5541: if ($guest) {
5542: return $guest;
5543: }
5544: } else {
5545: if (@domains > 0) {
5546: foreach my $domkey (@domains) {
5547: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5548: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5549: return 'ok';
5550: }
5551: }
5552: }
5553: }
5554: if (@users > 0) {
5555: foreach my $userkey (@users) {
1.865 raeburn 5556: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5557: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5558: if (ref($item) eq 'HASH') {
5559: if (($item->{'uname'} eq $env{'user.name'}) &&
5560: ($item->{'udom'} eq $env{'user.domain'})) {
5561: return 'ok';
5562: }
5563: }
5564: }
5565: }
1.765 albertel 5566: }
5567: }
5568: my %roleshash;
5569: my @courses_and_groups = @courses;
5570: push(@courses_and_groups,@groups);
5571: if (@courses_and_groups > 0) {
5572: my (%allgroups,%allroles);
5573: my ($start,$end,$role,$sec,$group);
5574: foreach my $envkey (%env) {
1.1060 raeburn 5575: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5576: my $cid = $2.'_'.$3;
5577: if ($1 eq 'gr') {
5578: $group = $4;
5579: $allgroups{$cid}{$group} = $env{$envkey};
5580: } else {
5581: if ($4 eq '') {
5582: $sec = 'none';
5583: } else {
5584: $sec = $4;
5585: }
5586: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5587: }
1.811 albertel 5588: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5589: my $cid = $2.'_'.$3;
5590: if ($4 eq '') {
5591: $sec = 'none';
5592: } else {
5593: $sec = $4;
5594: }
5595: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5596: }
5597: }
5598: if (keys(%allroles) == 0) {
5599: return;
5600: }
5601: foreach my $key (@courses_and_groups) {
5602: my %content = %{$$access_hash{$key}};
5603: my $cnum = $content{'number'};
5604: my $cdom = $content{'domain'};
5605: my $cid = $cdom.'_'.$cnum;
5606: if (!exists($allroles{$cid})) {
5607: next;
5608: }
5609: foreach my $role_id (keys(%{$content{'roles'}})) {
5610: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5611: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5612: my @status = @{$content{'roles'}{$role_id}{'access'}};
5613: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5614: foreach my $role (keys(%{$allroles{$cid}})) {
5615: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5616: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5617: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5618: if (grep/^all$/,@sections) {
5619: return 'ok';
5620: } else {
5621: if (grep/^$sec$/,@sections) {
5622: return 'ok';
5623: }
5624: }
5625: }
5626: }
5627: if (keys(%{$allgroups{$cid}}) == 0) {
5628: if (grep/^none$/,@groups) {
5629: return 'ok';
5630: }
5631: } else {
5632: if (grep/^all$/,@groups) {
5633: return 'ok';
5634: }
5635: foreach my $group (keys(%{$allgroups{$cid}})) {
5636: if (grep/^$group$/,@groups) {
5637: return 'ok';
5638: }
5639: }
5640: }
5641: }
5642: }
5643: }
5644: }
5645: }
5646: if ($guest) {
5647: return $guest;
5648: }
5649: }
5650: }
5651: return;
5652: }
5653:
5654: sub course_group_datechecker {
5655: my ($dates,$now,$status) = @_;
5656: my ($start,$end) = split(/\./,$dates);
5657: if (!$start && !$end) {
5658: return 'ok';
5659: }
5660: if (grep/^active$/,@{$status}) {
5661: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5662: return 'ok';
5663: }
5664: }
5665: if (grep/^previous$/,@{$status}) {
5666: if ($end > $now ) {
5667: return 'ok';
5668: }
5669: }
5670: if (grep/^future$/,@{$status}) {
5671: if ($start > $now) {
5672: return 'ok';
5673: }
5674: }
5675: return;
5676: }
5677:
5678: sub parse_portfolio_url {
5679: my ($url) = @_;
5680:
5681: my ($type,$udom,$unum,$group,$file_name);
5682:
1.823 albertel 5683: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5684: $type = 1;
5685: $udom = $1;
5686: $unum = $2;
5687: $file_name = $3;
1.823 albertel 5688: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5689: $type = 2;
5690: $udom = $1;
5691: $unum = $2;
5692: $group = $3;
5693: $file_name = $3.'/'.$4;
5694: }
5695: if (wantarray) {
5696: return ($type,$udom,$unum,$file_name,$group);
5697: }
5698: return $type;
5699: }
5700:
5701: sub is_portfolio_url {
5702: my ($url) = @_;
5703: return scalar(&parse_portfolio_url($url));
5704: }
5705:
1.798 raeburn 5706: sub is_portfolio_file {
5707: my ($file) = @_;
1.820 raeburn 5708: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5709: return 1;
5710: }
5711: return;
5712: }
5713:
1.976 raeburn 5714: sub usertools_access {
1.1084 raeburn 5715: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 5716: my ($access,%tools);
5717: if ($context eq '') {
5718: $context = 'tools';
5719: }
5720: if ($context eq 'requestcourses') {
5721: %tools = (
5722: official => 1,
5723: unofficial => 1,
1.1006 raeburn 5724: community => 1,
1.985 raeburn 5725: );
1.1183 raeburn 5726: } elsif ($context eq 'requestauthor') {
5727: %tools = (
5728: requestauthor => 1,
5729: );
1.985 raeburn 5730: } else {
5731: %tools = (
5732: aboutme => 1,
5733: blog => 1,
1.1177 raeburn 5734: webdav => 1,
1.985 raeburn 5735: portfolio => 1,
5736: );
5737: }
1.976 raeburn 5738: return if (!defined($tools{$tool}));
5739:
5740: if ((!defined($udom)) || (!defined($uname))) {
5741: $udom = $env{'user.domain'};
5742: $uname = $env{'user.name'};
5743: }
5744:
1.978 raeburn 5745: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5746: if ($action ne 'reload') {
1.985 raeburn 5747: if ($context eq 'requestcourses') {
5748: return $env{'environment.canrequest.'.$tool};
1.1183 raeburn 5749: } elsif ($context eq 'requestauthor') {
5750: return $env{'environment.canrequest.author'};
1.985 raeburn 5751: } else {
5752: return $env{'environment.availabletools.'.$tool};
5753: }
5754: }
1.976 raeburn 5755: }
5756:
1.1183 raeburn 5757: my ($toolstatus,$inststatus,$envkey);
5758: if ($context eq 'requestauthor') {
5759: $envkey = $context;
5760: } else {
5761: $envkey = $context.'.'.$tool;
5762: }
1.976 raeburn 5763:
1.985 raeburn 5764: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5765: ($action ne 'reload')) {
1.1183 raeburn 5766: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 5767: $inststatus = $env{'environment.inststatus'};
5768: } else {
1.1084 raeburn 5769: if (ref($userenvref) eq 'HASH') {
1.1183 raeburn 5770: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 5771: $inststatus = $userenvref->{'inststatus'};
5772: } else {
1.1183 raeburn 5773: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
5774: $toolstatus = $userenv{$envkey};
1.1084 raeburn 5775: $inststatus = $userenv{'inststatus'};
5776: }
1.976 raeburn 5777: }
5778:
5779: if ($toolstatus ne '') {
5780: if ($toolstatus) {
5781: $access = 1;
5782: } else {
5783: $access = 0;
5784: }
5785: return $access;
5786: }
5787:
1.1084 raeburn 5788: my ($is_adv,%domdef);
5789: if (ref($is_advref) eq 'HASH') {
5790: $is_adv = $is_advref->{'is_adv'};
5791: } else {
5792: $is_adv = &is_advanced_user($udom,$uname);
5793: }
5794: if (ref($domdefref) eq 'HASH') {
5795: %domdef = %{$domdefref};
5796: } else {
5797: %domdef = &get_domain_defaults($udom);
5798: }
1.976 raeburn 5799: if (ref($domdef{$tool}) eq 'HASH') {
5800: if ($is_adv) {
5801: if ($domdef{$tool}{'_LC_adv'} ne '') {
5802: if ($domdef{$tool}{'_LC_adv'}) {
5803: $access = 1;
5804: } else {
5805: $access = 0;
5806: }
5807: return $access;
5808: }
5809: }
5810: if ($inststatus ne '') {
5811: my ($hasaccess,$hasnoaccess);
5812: foreach my $affiliation (split(/:/,$inststatus)) {
5813: if ($domdef{$tool}{$affiliation} ne '') {
5814: if ($domdef{$tool}{$affiliation}) {
5815: $hasaccess = 1;
5816: } else {
5817: $hasnoaccess = 1;
5818: }
5819: }
5820: }
5821: if ($hasaccess || $hasnoaccess) {
5822: if ($hasaccess) {
5823: $access = 1;
5824: } elsif ($hasnoaccess) {
5825: $access = 0;
5826: }
5827: return $access;
5828: }
5829: } else {
5830: if ($domdef{$tool}{'default'} ne '') {
5831: if ($domdef{$tool}{'default'}) {
5832: $access = 1;
5833: } elsif ($domdef{$tool}{'default'} == 0) {
5834: $access = 0;
5835: }
5836: return $access;
5837: }
5838: }
5839: } else {
1.1177 raeburn 5840: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 5841: $access = 1;
5842: } else {
5843: $access = 0;
5844: }
1.976 raeburn 5845: return $access;
5846: }
5847: }
5848:
1.1050 raeburn 5849: sub is_course_owner {
5850: my ($cdom,$cnum,$udom,$uname) = @_;
5851: if (($udom eq '') || ($uname eq '')) {
5852: $udom = $env{'user.domain'};
5853: $uname = $env{'user.name'};
5854: }
5855: unless (($udom eq '') || ($uname eq '')) {
5856: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5857: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5858: return 1;
5859: } else {
5860: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5861: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5862: return 1;
5863: }
5864: }
5865: }
5866: }
5867: return;
5868: }
5869:
1.976 raeburn 5870: sub is_advanced_user {
5871: my ($udom,$uname) = @_;
1.1085 raeburn 5872: if ($udom ne '' && $uname ne '') {
5873: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 5874: if (wantarray) {
5875: return ($env{'user.adv'},$env{'user.author'});
5876: } else {
5877: return $env{'user.adv'};
5878: }
1.1085 raeburn 5879: }
5880: }
1.976 raeburn 5881: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5882: my %allroles;
1.1128 raeburn 5883: my ($is_adv,$is_author);
1.976 raeburn 5884: foreach my $role (keys(%roleshash)) {
5885: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5886: my $area = '/'.$tdomain.'/'.$trest;
5887: if ($sec ne '') {
5888: $area .= '/'.$sec;
5889: }
5890: if (($area ne '') && ($trole ne '')) {
5891: my $spec=$trole.'.'.$area;
5892: if ($trole =~ /^cr\//) {
5893: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5894: } elsif ($trole ne 'gr') {
5895: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5896: }
1.1128 raeburn 5897: if ($trole eq 'au') {
5898: $is_author = 1;
5899: }
1.976 raeburn 5900: }
5901: }
5902: foreach my $role (keys(%allroles)) {
5903: last if ($is_adv);
5904: foreach my $item (split(/:/,$allroles{$role})) {
5905: if ($item ne '') {
5906: my ($privilege,$restrictions)=split(/&/,$item);
5907: if ($privilege eq 'adv') {
5908: $is_adv = 1;
5909: last;
5910: }
5911: }
5912: }
5913: }
1.1128 raeburn 5914: if (wantarray) {
5915: return ($is_adv,$is_author);
5916: }
1.976 raeburn 5917: return $is_adv;
5918: }
1.798 raeburn 5919:
1.1035 raeburn 5920: sub check_can_request {
1.1036 raeburn 5921: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5922: my $canreq = 0;
5923: my ($types,$typename) = &Apache::loncommon::course_types();
5924: my @options = ('approval','validate','autolimit');
5925: my $optregex = join('|',@options);
5926: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5927: foreach my $type (@{$types}) {
5928: if (&usertools_access($env{'user.name'},
5929: $env{'user.domain'},
5930: $type,undef,'requestcourses')) {
5931: $canreq ++;
1.1036 raeburn 5932: if (ref($request_domains) eq 'HASH') {
5933: push(@{$request_domains->{$type}},$env{'user.domain'});
5934: }
1.1035 raeburn 5935: if ($dom eq $env{'user.domain'}) {
5936: $can_request->{$type} = 1;
5937: }
5938: }
5939: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5940: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5941: if (@curr > 0) {
1.1036 raeburn 5942: foreach my $item (@curr) {
5943: if (ref($request_domains) eq 'HASH') {
5944: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5945: if ($otherdom ne '') {
5946: if (ref($request_domains->{$type}) eq 'ARRAY') {
5947: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5948: push(@{$request_domains->{$type}},$otherdom);
5949: }
5950: } else {
5951: push(@{$request_domains->{$type}},$otherdom);
5952: }
5953: }
5954: }
5955: }
5956: unless($dom eq $env{'user.domain'}) {
5957: $canreq ++;
1.1035 raeburn 5958: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5959: $can_request->{$type} = 1;
5960: }
5961: }
5962: }
5963: }
5964: }
5965: }
5966: return $canreq;
5967: }
5968:
1.341 www 5969: # ---------------------------------------------- Custom access rule evaluation
5970:
5971: sub customaccess {
5972: my ($priv,$uri)=@_;
1.807 albertel 5973: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5974: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5975: $udom = &LONCAPA::clean_domain($udom);
5976: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5977: my $access=0;
1.800 albertel 5978: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5979: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5980: if ($type eq 'user') {
5981: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5982: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5983: if ($tdom) {
5984: if ($tdom ne $env{'user.domain'}) { next; }
5985: }
1.896 albertel 5986: if ($tuname) {
5987: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5988: }
5989: $access=($effect eq 'allow');
5990: last;
5991: }
5992: } else {
5993: if ($role) {
5994: if ($role ne $urole) { next; }
5995: }
5996: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5997: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5998: if ($tdom) {
5999: if ($tdom ne $udom) { next; }
6000: }
6001: if ($tcrs) {
6002: if ($tcrs ne $ucrs) { next; }
6003: }
6004: if ($tsec) {
6005: if ($tsec ne $usec) { next; }
6006: }
6007: $access=($effect eq 'allow');
6008: last;
6009: }
6010: if ($realm eq '' && $role eq '') {
6011: $access=($effect eq 'allow');
6012: }
1.402 bowersj2 6013: }
1.341 www 6014: }
6015: return $access;
6016: }
6017:
1.103 harris41 6018: # ------------------------------------------------- Check for a user privilege
1.12 www 6019:
6020: sub allowed {
1.810 raeburn 6021: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 6022: my $ver_orguri=$uri;
1.439 www 6023: $uri=&deversion($uri);
1.152 www 6024: my $orguri=$uri;
1.52 www 6025: $uri=&declutter($uri);
1.809 raeburn 6026:
1.810 raeburn 6027: if ($priv eq 'evb') {
6028: # Evade communication block restrictions for specified role in a course
6029: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6030: return $1;
6031: } else {
6032: return;
6033: }
6034: }
6035:
1.620 albertel 6036: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 6037: # Free bre access to adm and meta resources
1.775 albertel 6038: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6039: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6040: && ($priv eq 'bre')) {
1.14 www 6041: return 'F';
1.159 www 6042: }
6043:
1.545 banghart 6044: # Free bre access to user's own portfolio contents
1.714 raeburn 6045: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6046: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6047: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6048: my %setters;
6049: my ($startblock,$endblock) =
6050: &Apache::loncommon::blockcheck(\%setters,'port');
6051: if ($startblock && $endblock) {
6052: return 'B';
6053: } else {
6054: return 'F';
6055: }
1.545 banghart 6056: }
6057:
1.762 raeburn 6058: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6059: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6060: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6061: if (exists($env{'request.course.id'})) {
6062: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6063: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6064: if (($domain eq $cdom) && ($name eq $cnum)) {
6065: my $courseprivid=$env{'request.course.id'};
6066: $courseprivid=~s/\_/\//;
6067: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6068: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6069: return $1;
1.762 raeburn 6070: } else {
6071: if ($env{'request.course.sec'}) {
6072: $courseprivid.='/'.$env{'request.course.sec'};
6073: }
6074: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6075: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6076: return $2;
6077: }
1.714 raeburn 6078: }
6079: }
6080: }
6081: }
6082:
1.159 www 6083: # Free bre to public access
6084:
6085: if ($priv eq 'bre') {
1.238 www 6086: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6087: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6088: return 'F';
6089: }
1.238 www 6090: if ($copyright eq 'priv') {
6091: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6092: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6093: return '';
6094: }
6095: }
6096: if ($copyright eq 'domain') {
6097: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6098: unless (($env{'user.domain'} eq $1) ||
6099: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6100: return '';
6101: }
1.262 matthew 6102: }
1.620 albertel 6103: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6104: # Library role, so allow browsing of resources in this domain.
6105: return 'F';
1.238 www 6106: }
1.341 www 6107: if ($copyright eq 'custom') {
6108: unless (&customaccess($priv,$uri)) { return ''; }
6109: }
1.14 www 6110: }
1.264 matthew 6111: # Domain coordinator is trying to create a course
1.620 albertel 6112: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6113: # uri is the requested domain in this case.
6114: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6115: # a role of dc for the domain in question.
1.620 albertel 6116: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6117: }
1.29 www 6118:
1.52 www 6119: my $thisallowed='';
6120: my $statecond=0;
6121: my $courseprivid='';
6122:
1.1039 raeburn 6123: my $ownaccess;
1.1043 raeburn 6124: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6125: if (($priv eq 'bro') && ($env{'user.author'})) {
6126: if ($uri eq '') {
6127: $ownaccess = 1;
6128: } else {
6129: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6130: my $udom = $env{'user.domain'};
6131: my $uname = $env{'user.name'};
6132: if ($uri =~ m{^\Q$udom\E/?$}) {
6133: $ownaccess = 1;
1.1040 raeburn 6134: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6135: unless ($uri =~ m{\.\./}) {
6136: $ownaccess = 1;
6137: }
6138: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6139: my $now = time;
6140: if ($uri =~ m{^([^/]+)/?$}) {
6141: my $adom = $1;
6142: foreach my $key (keys(%env)) {
1.1042 raeburn 6143: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6144: my ($start,$end) = split('.',$env{$key});
6145: if (($now >= $start) && (!$end || $end < $now)) {
6146: $ownaccess = 1;
6147: last;
6148: }
6149: }
6150: }
6151: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6152: my $adom = $1;
6153: my $aname = $2;
1.1042 raeburn 6154: foreach my $role ('ca','aa') {
6155: if ($env{"user.role.$role./$adom/$aname"}) {
6156: my ($start,$end) =
6157: split('.',$env{"user.role.$role./$adom/$aname"});
6158: if (($now >= $start) && (!$end || $end < $now)) {
6159: $ownaccess = 1;
6160: last;
6161: }
1.1039 raeburn 6162: }
6163: }
6164: }
6165: }
6166: }
6167: }
6168: }
6169:
1.52 www 6170: # Course
6171:
1.620 albertel 6172: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6173: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6174: $thisallowed.=$1;
6175: }
1.52 www 6176: }
1.29 www 6177:
1.52 www 6178: # Domain
6179:
1.620 albertel 6180: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6181: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6182: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6183: $thisallowed.=$1;
6184: }
1.12 www 6185: }
1.52 www 6186:
1.1141 raeburn 6187: # User who is not author or co-author might still be able to edit
6188: # resource of an author in the domain (e.g., if Domain Coordinator).
6189: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6190: (&allowed('mdc',$env{'request.course.id'}))) {
6191: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6192: $thisallowed.=$1;
6193: }
6194: }
6195:
1.52 www 6196: # Course: uri itself is a course
1.66 www 6197: my $courseuri=$uri;
6198: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6199: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6200:
1.620 albertel 6201: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6202: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6203: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6204: $thisallowed.=$1;
6205: }
1.12 www 6206: }
1.29 www 6207:
1.665 albertel 6208: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6209: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6210: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6211: $thisallowed='';
1.671 raeburn 6212: my ($match)=&is_on_map($uri);
6213: if ($match) {
6214: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6215: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6216: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6217: if (@blockers > 0) {
6218: $thisallowed = 'B';
6219: } else {
6220: $thisallowed.=$1;
6221: }
1.671 raeburn 6222: }
6223: } else {
1.705 albertel 6224: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6225: if ($refuri) {
6226: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6227: $thisallowed='F';
1.671 raeburn 6228: } else {
6229: $refuri=&declutter($refuri);
6230: my ($match) = &is_on_map($refuri);
6231: if ($match) {
1.1162 raeburn 6232: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6233: if (@blockers > 0) {
6234: $thisallowed = 'B';
6235: } else {
6236: $thisallowed='F';
6237: }
1.671 raeburn 6238: }
1.669 raeburn 6239: }
1.671 raeburn 6240: }
6241: }
1.314 www 6242: }
1.492 albertel 6243:
1.766 albertel 6244: if ($priv eq 'bre'
6245: && $thisallowed ne 'F'
6246: && $thisallowed ne '2'
6247: && &is_portfolio_url($uri)) {
6248: $thisallowed = &portfolio_access($uri);
6249: }
6250:
1.52 www 6251: # Full access at system, domain or course-wide level? Exit.
1.29 www 6252: if ($thisallowed=~/F/) {
6253: return 'F';
6254: }
6255:
1.52 www 6256: # If this is generating or modifying users, exit with special codes
1.29 www 6257:
1.643 www 6258: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6259: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6260: my ($audom,$auname)=split('/',$uri);
1.643 www 6261: # no author name given, so this just checks on the general right to make a co-author in this domain
6262: unless ($auname) { return $thisallowed; }
6263: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6264: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6265: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6266: ($audom ne $env{'request.role.domain'}))) { return ''; }
6267: }
1.52 www 6268: return $thisallowed;
6269: }
6270: #
1.103 harris41 6271: # Gathered so far: system, domain and course wide privileges
1.52 www 6272: #
6273: # Course: See if uri or referer is an individual resource that is part of
6274: # the course
6275:
1.620 albertel 6276: if ($env{'request.course.id'}) {
1.232 www 6277:
1.620 albertel 6278: $courseprivid=$env{'request.course.id'};
6279: if ($env{'request.course.sec'}) {
6280: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6281: }
6282: $courseprivid=~s/\_/\//;
6283: my $checkreferer=1;
1.232 www 6284: my ($match,$cond)=&is_on_map($uri);
6285: if ($match) {
6286: $statecond=$cond;
1.620 albertel 6287: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6288: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6289: my $value = $1;
6290: if ($priv eq 'bre') {
6291: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6292: if (@blockers > 0) {
6293: $thisallowed = 'B';
6294: } else {
6295: $thisallowed.=$value;
6296: }
6297: } else {
6298: $thisallowed.=$value;
6299: }
1.52 www 6300: $checkreferer=0;
6301: }
1.29 www 6302: }
1.83 www 6303:
1.148 www 6304: if ($checkreferer) {
1.620 albertel 6305: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6306: unless ($refuri) {
1.800 albertel 6307: foreach my $key (keys(%env)) {
6308: if ($key=~/^httpref\..*\*/) {
6309: my $pattern=$key;
1.156 www 6310: $pattern=~s/^httpref\.\/res\///;
1.148 www 6311: $pattern=~s/\*/\[\^\/\]\+/g;
6312: $pattern=~s/\//\\\//g;
1.152 www 6313: if ($orguri=~/$pattern/) {
1.800 albertel 6314: $refuri=$env{$key};
1.148 www 6315: }
6316: }
1.191 harris41 6317: }
1.148 www 6318: }
1.232 www 6319:
1.148 www 6320: if ($refuri) {
1.152 www 6321: $refuri=&declutter($refuri);
1.232 www 6322: my ($match,$cond)=&is_on_map($refuri);
6323: if ($match) {
6324: my $refstatecond=$cond;
1.620 albertel 6325: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6326: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6327: my $value = $1;
6328: if ($priv eq 'bre') {
6329: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6330: if (@blockers > 0) {
6331: $thisallowed = 'B';
6332: } else {
6333: $thisallowed.=$value;
6334: }
6335: } else {
6336: $thisallowed.=$value;
6337: }
1.53 www 6338: $uri=$refuri;
6339: $statecond=$refstatecond;
1.52 www 6340: }
6341: }
1.148 www 6342: }
1.29 www 6343: }
1.52 www 6344: }
1.29 www 6345:
1.52 www 6346: #
1.103 harris41 6347: # Gathered now: all privileges that could apply, and condition number
1.52 www 6348: #
6349: #
6350: # Full or no access?
6351: #
1.29 www 6352:
1.52 www 6353: if ($thisallowed=~/F/) {
6354: return 'F';
6355: }
1.29 www 6356:
1.52 www 6357: unless ($thisallowed) {
6358: return '';
6359: }
1.29 www 6360:
1.52 www 6361: # Restrictions exist, deal with them
6362: #
6363: # C:according to course preferences
6364: # R:according to resource settings
6365: # L:unless locked
6366: # X:according to user session state
6367: #
6368:
6369: # Possibly locked functionality, check all courses
1.54 www 6370: # Locks might take effect only after 10 minutes cache expiration for other
6371: # courses, and 2 minutes for current course
1.52 www 6372:
6373: my $envkey;
6374: if ($thisallowed=~/L/) {
1.1000 raeburn 6375: foreach $envkey (keys(%env)) {
1.54 www 6376: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6377: my $courseid=$2;
6378: my $roleid=$1.'.'.$2;
1.92 www 6379: $courseid=~s/^\///;
1.54 www 6380: my $expiretime=600;
1.620 albertel 6381: if ($env{'request.role'} eq $roleid) {
1.54 www 6382: $expiretime=120;
6383: }
6384: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6385: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6386: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6387: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6388: }
1.620 albertel 6389: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6390: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6391: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6392: &log($env{'user.domain'},$env{'user.name'},
6393: $env{'user.home'},
1.57 www 6394: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6395: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6396: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6397: return '';
6398: }
6399: }
1.620 albertel 6400: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6401: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6402: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6403: &log($env{'user.domain'},$env{'user.name'},
6404: $env{'user.home'},
1.57 www 6405: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6406: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6407: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6408: return '';
6409: }
6410: }
6411: }
1.29 www 6412: }
1.52 www 6413: }
6414:
6415: #
6416: # Rest of the restrictions depend on selected course
6417: #
6418:
1.620 albertel 6419: unless ($env{'request.course.id'}) {
1.766 albertel 6420: if ($thisallowed eq 'A') {
6421: return 'A';
1.814 raeburn 6422: } elsif ($thisallowed eq 'B') {
6423: return 'B';
1.766 albertel 6424: } else {
6425: return '1';
6426: }
1.52 www 6427: }
1.29 www 6428:
1.52 www 6429: #
6430: # Now user is definitely in a course
6431: #
1.53 www 6432:
6433:
6434: # Course preferences
6435:
6436: if ($thisallowed=~/C/) {
1.620 albertel 6437: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6438: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6439: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6440: =~/\Q$rolecode\E/) {
1.1103 raeburn 6441: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6442: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6443: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6444: $env{'request.course.id'});
6445: }
1.237 www 6446: return '';
6447: }
6448:
1.620 albertel 6449: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6450: =~/\Q$unamedom\E/) {
1.1103 raeburn 6451: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6452: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6453: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6454: $env{'request.course.id'});
6455: }
1.54 www 6456: return '';
6457: }
1.53 www 6458: }
6459:
6460: # Resource preferences
6461:
6462: if ($thisallowed=~/R/) {
1.620 albertel 6463: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6464: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6465: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6466: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6467: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6468: }
6469: return '';
1.54 www 6470: }
1.53 www 6471: }
1.30 www 6472:
1.246 www 6473: # Restricted by state or randomout?
1.30 www 6474:
1.52 www 6475: if ($thisallowed=~/X/) {
1.620 albertel 6476: if ($env{'acc.randomout'}) {
1.579 albertel 6477: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 6478: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 6479: return '';
6480: }
1.247 www 6481: }
6482: if (&condval($statecond)) {
1.52 www 6483: return '2';
6484: } else {
6485: return '';
6486: }
6487: }
1.30 www 6488:
1.766 albertel 6489: if ($thisallowed eq 'A') {
6490: return 'A';
1.814 raeburn 6491: } elsif ($thisallowed eq 'B') {
6492: return 'B';
1.766 albertel 6493: }
1.52 www 6494: return 'F';
1.232 www 6495: }
1.1162 raeburn 6496:
6497: sub get_comm_blocks {
6498: my ($cdom,$cnum) = @_;
6499: if ($cdom eq '' || $cnum eq '') {
6500: return unless ($env{'request.course.id'});
6501: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6502: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6503: }
6504: my %commblocks;
6505: my $hashid=$cdom.'_'.$cnum;
6506: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
6507: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
6508: %commblocks = %{$blocksref};
6509: } else {
6510: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
6511: my $cachetime = 600;
6512: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
6513: }
6514: return %commblocks;
6515: }
6516:
6517: sub has_comm_blocking {
6518: my ($priv,$symb,$uri,$blocks) = @_;
6519: return unless ($env{'request.course.id'});
6520: return unless ($priv eq 'bre');
6521: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
6522: my %commblocks;
6523: if (ref($blocks) eq 'HASH') {
6524: %commblocks = %{$blocks};
6525: } else {
6526: %commblocks = &get_comm_blocks();
6527: }
6528: return unless (keys(%commblocks) > 0);
6529: if (!$symb) { $symb=&symbread($uri,1); }
6530: my ($map,$resid,undef)=&decode_symb($symb);
6531: my %tocheck = (
6532: maps => $map,
6533: resources => $symb,
6534: );
6535: my @blockers;
6536: my $now = time;
1.1163 raeburn 6537: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 6538: foreach my $block (keys(%commblocks)) {
6539: if ($block =~ /^(\d+)____(\d+)$/) {
6540: my ($start,$end) = ($1,$2);
6541: if ($start <= $now && $end >= $now) {
6542: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6543: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6544: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
6545: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
6546: unless (grep(/^\Q$block\E$/,@blockers)) {
6547: push(@blockers,$block);
6548: }
6549: }
6550: }
6551: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
6552: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
6553: unless (grep(/^\Q$block\E$/,@blockers)) {
6554: push(@blockers,$block);
6555: }
6556: }
6557: }
6558: }
6559: }
6560: }
6561: } elsif ($block =~ /^firstaccess____(.+)$/) {
6562: my $item = $1;
1.1163 raeburn 6563: my @to_test;
1.1162 raeburn 6564: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6565: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6566: my $check_interval;
6567: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
6568: my @interval;
6569: my $type = 'map';
6570: if ($item eq 'course') {
6571: $type = 'course';
6572: @interval=&EXT("resource.0.interval");
6573: } else {
6574: if ($item =~ /___\d+___/) {
6575: $type = 'resource';
6576: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 6577: if (ref($navmap)) {
6578: my $res = $navmap->getBySymb($item);
6579: push(@to_test,$res);
6580: }
1.1162 raeburn 6581: } else {
6582: my $mapsymb = &symbread($item,1);
6583: if ($mapsymb) {
6584: if (ref($navmap)) {
6585: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 6586: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
6587: foreach my $res (@to_test) {
1.1162 raeburn 6588: my $symb = $res->symb();
6589: next if ($symb eq $mapsymb);
6590: if ($symb ne '') {
6591: @interval=&EXT("resource.0.interval",$symb);
6592: last;
6593: }
6594: }
6595: }
6596: }
6597: }
6598: }
6599: if ($interval[0] =~ /\d+/) {
6600: my $first_access;
6601: if ($type eq 'resource') {
6602: $first_access=&get_first_access($interval[1],$item);
6603: } elsif ($type eq 'map') {
6604: $first_access=&get_first_access($interval[1],undef,$item);
6605: } else {
6606: $first_access=&get_first_access($interval[1]);
6607: }
6608: if ($first_access) {
6609: my $timesup = $first_access+$interval[0];
6610: if ($timesup > $now) {
1.1163 raeburn 6611: foreach my $res (@to_test) {
6612: if ($res->is_problem()) {
6613: if ($res->completable()) {
6614: unless (grep(/^\Q$block\E$/,@blockers)) {
6615: push(@blockers,$block);
6616: }
6617: last;
6618: }
6619: }
1.1162 raeburn 6620: }
6621: }
6622: }
6623: }
6624: }
6625: }
6626: }
6627: }
6628: }
6629: return @blockers;
6630: }
6631:
6632: sub check_docs_block {
6633: my ($docsblock,$tocheck) =@_;
6634: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
6635: return;
6636: }
6637: if (ref($docsblock->{'maps'}) eq 'HASH') {
6638: if ($tocheck->{'maps'}) {
6639: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
6640: return 1;
6641: }
6642: }
6643: }
6644: if (ref($docsblock->{'resources'}) eq 'HASH') {
6645: if ($tocheck->{'resources'}) {
6646: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
6647: return 1;
6648: }
6649: }
6650: }
6651: return;
6652: }
6653:
1.1133 foxr 6654: #
6655: # Removes the versino from a URI and
6656: # splits it in to its filename and path to the filename.
6657: # Seems like File::Basename could have done this more clearly.
6658: # Parameters:
6659: # $uri - input URI
6660: # Returns:
6661: # Two element list consisting of
6662: # $pathname - the URI up to and excluding the trailing /
6663: # $filename - The part of the URI following the last /
6664: # NOTE:
6665: # Another realization of this is simply:
6666: # use File::Basename;
6667: # ...
6668: # $uri = shift;
6669: # $filename = basename($uri);
6670: # $path = dirname($uri);
6671: # return ($filename, $path);
6672: #
6673: # The implementation below is probably faster however.
6674: #
1.710 albertel 6675: sub split_uri_for_cond {
6676: my $uri=&deversion(&declutter(shift));
6677: my @uriparts=split(/\//,$uri);
6678: my $filename=pop(@uriparts);
6679: my $pathname=join('/',@uriparts);
6680: return ($pathname,$filename);
6681: }
1.232 www 6682: # --------------------------------------------------- Is a resource on the map?
6683:
6684: sub is_on_map {
1.710 albertel 6685: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 6686: #Trying to find the conditional for the file
1.620 albertel 6687: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 6688: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 6689: if ($match) {
1.289 bowersj2 6690: return (1,$1);
6691: } else {
1.434 www 6692: return (0,0);
1.289 bowersj2 6693: }
1.12 www 6694: }
6695:
1.427 www 6696: # --------------------------------------------------------- Get symb from alias
6697:
6698: sub get_symb_from_alias {
6699: my $symb=shift;
6700: my ($map,$resid,$url)=&decode_symb($symb);
6701: # Already is a symb
6702: if ($url) { return $symb; }
6703: # Must be an alias
6704: my $aliassymb='';
6705: my %bighash;
1.620 albertel 6706: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 6707: &GDBM_READER(),0640)) {
6708: my $rid=$bighash{'mapalias_'.$symb};
6709: if ($rid) {
6710: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 6711: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6712: $resid,$bighash{'src_'.$rid});
1.427 www 6713: }
6714: untie %bighash;
6715: }
6716: return $aliassymb;
6717: }
6718:
1.12 www 6719: # ----------------------------------------------------------------- Define Role
6720:
6721: sub definerole {
6722: if (allowed('mcr','/')) {
6723: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 6724: foreach my $role (split(':',$sysrole)) {
6725: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6726: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6727: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6728: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6729: return "refused:s:$crole&$cqual";
6730: }
6731: }
1.191 harris41 6732: }
1.800 albertel 6733: foreach my $role (split(':',$domrole)) {
6734: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6735: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6736: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6737: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 6738: return "refused:d:$crole&$cqual";
6739: }
6740: }
1.191 harris41 6741: }
1.800 albertel 6742: foreach my $role (split(':',$courole)) {
6743: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6744: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6745: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6746: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6747: return "refused:c:$crole&$cqual";
6748: }
6749: }
1.191 harris41 6750: }
1.620 albertel 6751: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6752: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6753: "rolesdef_$rolename=".
6754: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 6755: return reply($command,$env{'user.home'});
1.12 www 6756: } else {
6757: return 'refused';
6758: }
1.105 harris41 6759: }
6760:
6761: # ---------------- Make a metadata query against the network of library servers
6762:
6763: sub metadata_query {
1.244 matthew 6764: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 6765: my %rhash;
1.845 albertel 6766: my %libserv = &all_library();
1.244 matthew 6767: my @server_list = (defined($server_array) ? @$server_array
6768: : keys(%libserv) );
6769: for my $server (@server_list) {
1.118 harris41 6770: unless ($custom or $customshow) {
6771: my $reply=&reply("querysend:".&escape($query),$server);
6772: $rhash{$server}=$reply;
6773: }
6774: else {
6775: my $reply=&reply("querysend:".&escape($query).':'.
6776: &escape($custom).':'.&escape($customshow),
6777: $server);
6778: $rhash{$server}=$reply;
6779: }
1.112 harris41 6780: }
1.118 harris41 6781: return \%rhash;
1.240 www 6782: }
6783:
6784: # ----------------------------------------- Send log queries and wait for reply
6785:
6786: sub log_query {
6787: my ($uname,$udom,$query,%filters)=@_;
6788: my $uhome=&homeserver($uname,$udom);
6789: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 6790: my $uhost=&hostname($uhome);
1.800 albertel 6791: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 6792: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6793: $uhome);
1.479 albertel 6794: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 6795: return get_query_reply($queryid);
6796: }
6797:
1.818 raeburn 6798: # -------------------------- Update MySQL table for portfolio file
6799:
6800: sub update_portfolio_table {
1.821 raeburn 6801: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 6802: if ($group ne '') {
6803: $file_name =~s /^\Q$group\E//;
6804: }
1.818 raeburn 6805: my $homeserver = &homeserver($uname,$udom);
6806: my $queryid=
1.821 raeburn 6807: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6808: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 6809: my $reply = &get_query_reply($queryid);
6810: return $reply;
6811: }
6812:
1.899 raeburn 6813: # -------------------------- Update MySQL allusers table
6814:
6815: sub update_allusers_table {
6816: my ($uname,$udom,$names) = @_;
6817: my $homeserver = &homeserver($uname,$udom);
6818: my $queryid=
6819: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6820: 'lastname='.&escape($names->{'lastname'}).'%%'.
6821: 'firstname='.&escape($names->{'firstname'}).'%%'.
6822: 'middlename='.&escape($names->{'middlename'}).'%%'.
6823: 'generation='.&escape($names->{'generation'}).'%%'.
6824: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6825: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 6826: return;
1.899 raeburn 6827: }
6828:
1.508 raeburn 6829: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 6830:
6831: sub fetch_enrollment_query {
1.511 raeburn 6832: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 6833: my $homeserver;
1.547 raeburn 6834: my $maxtries = 1;
1.508 raeburn 6835: if ($context eq 'automated') {
6836: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 6837: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 6838: } else {
6839: $homeserver = &homeserver($cnum,$dom);
6840: }
1.838 albertel 6841: my $host=&hostname($homeserver);
1.506 raeburn 6842: my $cmd = '';
1.1000 raeburn 6843: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 6844: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 6845: }
6846: $cmd =~ s/%%$//;
6847: $cmd = &escape($cmd);
6848: my $query = 'fetchenrollment';
1.620 albertel 6849: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 6850: unless ($queryid=~/^\Q$host\E\_/) {
6851: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6852: return 'error: '.$queryid;
6853: }
1.506 raeburn 6854: my $reply = &get_query_reply($queryid);
1.547 raeburn 6855: my $tries = 1;
6856: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6857: $reply = &get_query_reply($queryid);
6858: $tries ++;
6859: }
1.526 raeburn 6860: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 6861: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 6862: } else {
1.901 albertel 6863: my @responses = split(/:/,$reply);
1.515 raeburn 6864: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 6865: foreach my $line (@responses) {
6866: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 6867: $$replyref{$key} = $value;
6868: }
6869: } else {
1.1117 foxr 6870: my $pathname = LONCAPA::tempdir();
1.800 albertel 6871: foreach my $line (@responses) {
6872: my ($key,$value) = split(/=/,$line);
1.506 raeburn 6873: $$replyref{$key} = $value;
6874: if ($value > 0) {
1.800 albertel 6875: foreach my $item (@{$$affiliatesref{$key}}) {
6876: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 6877: my $destname = $pathname.'/'.$filename;
6878: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 6879: if ($xml_classlist =~ /^error/) {
6880: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6881: } else {
1.506 raeburn 6882: if ( open(FILE,">$destname") ) {
6883: print FILE &unescape($xml_classlist);
6884: close(FILE);
1.526 raeburn 6885: } else {
6886: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6887: }
6888: }
6889: }
6890: }
6891: }
6892: }
6893: return 'ok';
6894: }
6895: return 'error';
6896: }
6897:
1.242 www 6898: sub get_query_reply {
6899: my $queryid=shift;
1.1117 foxr 6900: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 6901: my $reply='';
6902: for (1..100) {
6903: sleep 2;
6904: if (-e $replyfile.'.end') {
1.448 albertel 6905: if (open(my $fh,$replyfile)) {
1.904 albertel 6906: $reply = join('',<$fh>);
6907: close($fh);
1.240 www 6908: } else { return 'error: reply_file_error'; }
1.242 www 6909: return &unescape($reply);
6910: }
1.240 www 6911: }
1.242 www 6912: return 'timeout:'.$queryid;
1.240 www 6913: }
6914:
6915: sub courselog_query {
1.241 www 6916: #
6917: # possible filters:
6918: # url: url or symb
6919: # username
6920: # domain
6921: # action: view, submit, grade
6922: # start: timestamp
6923: # end: timestamp
6924: #
1.240 www 6925: my (%filters)=@_;
1.620 albertel 6926: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6927: if ($filters{'url'}) {
6928: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6929: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6930: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6931: }
1.620 albertel 6932: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6933: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6934: return &log_query($cname,$cdom,'courselog',%filters);
6935: }
6936:
6937: sub userlog_query {
1.858 raeburn 6938: #
6939: # possible filters:
6940: # action: log check role
6941: # start: timestamp
6942: # end: timestamp
6943: #
1.240 www 6944: my ($uname,$udom,%filters)=@_;
6945: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6946: }
6947:
1.506 raeburn 6948: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6949:
6950: sub auto_run {
1.508 raeburn 6951: my ($cnum,$cdom) = @_;
1.876 raeburn 6952: my $response = 0;
6953: my $settings;
6954: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6955: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6956: $settings = $domconfig{'autoenroll'};
6957: if ($settings->{'run'} eq '1') {
6958: $response = 1;
6959: }
6960: } else {
1.934 raeburn 6961: my $homeserver;
6962: if (&is_course($cdom,$cnum)) {
6963: $homeserver = &homeserver($cnum,$cdom);
6964: } else {
6965: $homeserver = &domain($cdom,'primary');
6966: }
6967: if ($homeserver ne 'no_host') {
6968: $response = &reply('autorun:'.$cdom,$homeserver);
6969: }
1.876 raeburn 6970: }
1.506 raeburn 6971: return $response;
6972: }
1.776 albertel 6973:
1.506 raeburn 6974: sub auto_get_sections {
1.508 raeburn 6975: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6976: my $homeserver;
6977: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6978: $homeserver = &homeserver($cnum,$cdom);
6979: }
6980: if (!defined($homeserver)) {
6981: if ($cdom =~ /^$match_domain$/) {
6982: $homeserver = &domain($cdom,'primary');
6983: }
6984: }
6985: my @secs;
6986: if (defined($homeserver)) {
6987: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6988: unless ($response eq 'refused') {
6989: @secs = split(/:/,$response);
6990: }
1.506 raeburn 6991: }
6992: return @secs;
6993: }
1.776 albertel 6994:
1.506 raeburn 6995: sub auto_new_course {
1.1099 raeburn 6996: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6997: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 6998: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6999: return $response;
7000: }
1.776 albertel 7001:
1.506 raeburn 7002: sub auto_validate_courseID {
1.508 raeburn 7003: my ($cnum,$cdom,$inst_course_id) = @_;
7004: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 7005: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 7006: return $response;
7007: }
1.776 albertel 7008:
1.1007 raeburn 7009: sub auto_validate_instcode {
1.1020 raeburn 7010: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 7011: my ($homeserver,$response);
7012: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7013: $homeserver = &homeserver($cnum,$cdom);
7014: }
7015: if (!defined($homeserver)) {
7016: if ($cdom =~ /^$match_domain$/) {
7017: $homeserver = &domain($cdom,'primary');
7018: }
7019: }
1.1065 raeburn 7020: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7021: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 7022: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
7023: return ($outcome,$description);
1.1007 raeburn 7024: }
7025:
1.506 raeburn 7026: sub auto_create_password {
1.873 raeburn 7027: my ($cnum,$cdom,$authparam,$udom) = @_;
7028: my ($homeserver,$response);
1.506 raeburn 7029: my $create_passwd = 0;
7030: my $authchk = '';
1.873 raeburn 7031: if ($udom =~ /^$match_domain$/) {
7032: $homeserver = &domain($udom,'primary');
7033: }
7034: if ($homeserver eq '') {
7035: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7036: $homeserver = &homeserver($cnum,$cdom);
7037: }
7038: }
7039: if ($homeserver eq '') {
7040: $authchk = 'nodomain';
1.506 raeburn 7041: } else {
1.873 raeburn 7042: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7043: if ($response eq 'refused') {
7044: $authchk = 'refused';
7045: } else {
1.901 albertel 7046: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7047: }
1.506 raeburn 7048: }
7049: return ($authparam,$create_passwd,$authchk);
7050: }
7051:
1.706 raeburn 7052: sub auto_photo_permission {
7053: my ($cnum,$cdom,$students) = @_;
7054: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7055: my ($outcome,$perm_reqd,$conditions) =
7056: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7057: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7058: return (undef,undef);
7059: }
1.706 raeburn 7060: return ($outcome,$perm_reqd,$conditions);
7061: }
7062:
7063: sub auto_checkphotos {
7064: my ($uname,$udom,$pid) = @_;
7065: my $homeserver = &homeserver($uname,$udom);
7066: my ($result,$resulttype);
7067: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7068: &escape($uname).':'.&escape($pid),
7069: $homeserver));
1.709 albertel 7070: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7071: return (undef,undef);
7072: }
1.706 raeburn 7073: if ($outcome) {
7074: ($result,$resulttype) = split(/:/,$outcome);
7075: }
7076: return ($result,$resulttype);
7077: }
7078:
7079: sub auto_photochoice {
7080: my ($cnum,$cdom) = @_;
7081: my $homeserver = &homeserver($cnum,$cdom);
7082: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7083: &escape($cdom),
7084: $homeserver)));
1.709 albertel 7085: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7086: return (undef,undef);
7087: }
1.706 raeburn 7088: return ($update,$comment);
7089: }
7090:
7091: sub auto_photoupdate {
7092: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7093: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7094: my $host=&hostname($homeserver);
1.706 raeburn 7095: my $cmd = '';
7096: my $maxtries = 1;
1.800 albertel 7097: foreach my $affiliate (keys(%{$affiliatesref})) {
7098: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7099: }
7100: $cmd =~ s/%%$//;
7101: $cmd = &escape($cmd);
7102: my $query = 'institutionalphotos';
7103: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7104: unless ($queryid=~/^\Q$host\E\_/) {
7105: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7106: return 'error: '.$queryid;
7107: }
7108: my $reply = &get_query_reply($queryid);
7109: my $tries = 1;
7110: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7111: $reply = &get_query_reply($queryid);
7112: $tries ++;
7113: }
7114: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7115: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7116: } else {
7117: my @responses = split(/:/,$reply);
7118: my $outcome = shift(@responses);
7119: foreach my $item (@responses) {
7120: my ($key,$value) = split(/=/,$item);
7121: $$photo{$key} = $value;
7122: }
7123: return $outcome;
7124: }
7125: return 'error';
7126: }
7127:
1.521 raeburn 7128: sub auto_instcode_format {
1.793 albertel 7129: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7130: $cat_order) = @_;
1.521 raeburn 7131: my $courses = '';
1.772 raeburn 7132: my @homeservers;
1.521 raeburn 7133: if ($caller eq 'global') {
1.841 albertel 7134: my %servers = &get_servers($codedom,'library');
7135: foreach my $tryserver (keys(%servers)) {
7136: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7137: push(@homeservers,$tryserver);
7138: }
1.584 raeburn 7139: }
1.1022 raeburn 7140: } elsif ($caller eq 'requests') {
7141: if ($codedom =~ /^$match_domain$/) {
7142: my $chome = &domain($codedom,'primary');
7143: unless ($chome eq 'no_host') {
7144: push(@homeservers,$chome);
7145: }
7146: }
1.521 raeburn 7147: } else {
1.772 raeburn 7148: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7149: }
1.793 albertel 7150: foreach my $code (keys(%{$instcodes})) {
7151: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7152: }
7153: chop($courses);
1.772 raeburn 7154: my $ok_response = 0;
7155: my $response;
7156: while (@homeservers > 0 && $ok_response == 0) {
7157: my $server = shift(@homeservers);
7158: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7159: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7160: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7161: split(/:/,$response);
1.772 raeburn 7162: %{$codes} = (%{$codes},&str2hash($codes_str));
7163: push(@{$codetitles},&str2array($codetitles_str));
7164: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7165: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7166: $ok_response = 1;
7167: }
7168: }
7169: if ($ok_response) {
1.521 raeburn 7170: return 'ok';
1.772 raeburn 7171: } else {
7172: return $response;
1.521 raeburn 7173: }
7174: }
7175:
1.792 raeburn 7176: sub auto_instcode_defaults {
7177: my ($domain,$returnhash,$code_order) = @_;
7178: my @homeservers;
1.841 albertel 7179:
7180: my %servers = &get_servers($domain,'library');
7181: foreach my $tryserver (keys(%servers)) {
7182: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7183: push(@homeservers,$tryserver);
7184: }
1.792 raeburn 7185: }
1.841 albertel 7186:
1.792 raeburn 7187: my $response;
1.841 albertel 7188: foreach my $server (@homeservers) {
1.792 raeburn 7189: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7190: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7191:
7192: foreach my $pair (split(/\&/,$response)) {
7193: my ($name,$value)=split(/\=/,$pair);
7194: if ($name eq 'code_order') {
7195: @{$code_order} = split(/\&/,&unescape($value));
7196: } else {
7197: $returnhash->{&unescape($name)}=&unescape($value);
7198: }
7199: }
7200: return 'ok';
1.792 raeburn 7201: }
1.841 albertel 7202:
7203: return $response;
1.1003 raeburn 7204: }
7205:
7206: sub auto_possible_instcodes {
1.1007 raeburn 7207: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7208: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7209: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7210: return;
7211: }
1.1003 raeburn 7212: my (@homeservers,$uhome);
7213: if (defined(&domain($domain,'primary'))) {
7214: $uhome=&domain($domain,'primary');
7215: push(@homeservers,&domain($domain,'primary'));
7216: } else {
7217: my %servers = &get_servers($domain,'library');
7218: foreach my $tryserver (keys(%servers)) {
7219: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7220: push(@homeservers,$tryserver);
7221: }
7222: }
7223: }
7224: my $response;
7225: foreach my $server (@homeservers) {
7226: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7227: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7228: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7229: split(':',$response);
7230: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7231: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7232: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7233: my ($name,$value)=split('=',$item);
7234: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7235: }
7236: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7237: my ($name,$value)=split('=',$item);
7238: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7239: }
7240: return 'ok';
7241: }
7242: return $response;
7243: }
1.792 raeburn 7244:
1.1010 raeburn 7245: sub auto_courserequest_checks {
7246: my ($dom) = @_;
1.1020 raeburn 7247: my ($homeserver,%validations);
7248: if ($dom =~ /^$match_domain$/) {
7249: $homeserver = &domain($dom,'primary');
7250: }
7251: unless ($homeserver eq 'no_host') {
7252: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7253: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7254: my @items = split(/&/,$response);
7255: foreach my $item (@items) {
7256: my ($key,$value) = split('=',$item);
7257: $validations{&unescape($key)} = &thaw_unescape($value);
7258: }
7259: }
7260: }
1.1010 raeburn 7261: return %validations;
7262: }
7263:
1.1020 raeburn 7264: sub auto_courserequest_validation {
7265: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7266: my ($homeserver,$response);
7267: if ($dom =~ /^$match_domain$/) {
7268: $homeserver = &domain($dom,'primary');
7269: }
7270: unless ($homeserver eq 'no_host') {
1.1021 raeburn 7271:
1.1020 raeburn 7272: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7273: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 7274: ':'.&escape($instcode).':'.&escape($instseclist),
7275: $homeserver));
7276: }
7277: return $response;
7278: }
7279:
1.777 albertel 7280: sub auto_validate_class_sec {
1.918 raeburn 7281: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7282: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7283: my $ownerlist;
7284: if (ref($owners) eq 'ARRAY') {
7285: $ownerlist = join(',',@{$owners});
7286: } else {
7287: $ownerlist = $owners;
7288: }
1.773 raeburn 7289: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7290: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7291: return $response;
7292: }
7293:
1.679 raeburn 7294: # ------------------------------------------------------- Course Group routines
7295:
7296: sub get_coursegroups {
1.809 raeburn 7297: my ($cdom,$cnum,$group,$namespace) = @_;
7298: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7299: }
7300:
1.679 raeburn 7301: sub modify_coursegroup {
7302: my ($cdom,$cnum,$groupsettings) = @_;
7303: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7304: }
7305:
1.809 raeburn 7306: sub toggle_coursegroup_status {
7307: my ($cdom,$cnum,$group,$action) = @_;
7308: my ($from_namespace,$to_namespace);
7309: if ($action eq 'delete') {
7310: $from_namespace = 'coursegroups';
7311: $to_namespace = 'deleted_groups';
7312: } else {
7313: $from_namespace = 'deleted_groups';
7314: $to_namespace = 'coursegroups';
7315: }
7316: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7317: if (my $tmp = &error(%curr_group)) {
7318: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7319: return ('read error',$tmp);
7320: } else {
7321: my %savedsettings = %curr_group;
1.809 raeburn 7322: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7323: my $deloutcome;
7324: if ($result eq 'ok') {
1.809 raeburn 7325: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7326: } else {
7327: return ('write error',$result);
7328: }
7329: if ($deloutcome eq 'ok') {
7330: return 'ok';
7331: } else {
7332: return ('delete error',$deloutcome);
7333: }
7334: }
7335: }
7336:
1.679 raeburn 7337: sub modify_group_roles {
1.957 raeburn 7338: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7339: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7340: my $role = 'gr/'.&escape($userprivs);
7341: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7342: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7343: if ($result eq 'ok') {
7344: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7345: }
1.679 raeburn 7346: return $result;
7347: }
7348:
7349: sub modify_coursegroup_membership {
7350: my ($cdom,$cnum,$membership) = @_;
7351: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7352: return $result;
7353: }
7354:
1.682 raeburn 7355: sub get_active_groups {
7356: my ($udom,$uname,$cdom,$cnum) = @_;
7357: my $now = time;
7358: my %groups = ();
7359: foreach my $key (keys(%env)) {
1.811 albertel 7360: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7361: my ($start,$end) = split(/\./,$env{$key});
7362: if (($end!=0) && ($end<$now)) { next; }
7363: if (($start!=0) && ($start>$now)) { next; }
7364: if ($1 eq $cdom && $2 eq $cnum) {
7365: $groups{$3} = $env{$key} ;
7366: }
7367: }
7368: }
7369: return %groups;
7370: }
7371:
1.683 raeburn 7372: sub get_group_membership {
7373: my ($cdom,$cnum,$group) = @_;
7374: return(&dump('groupmembership',$cdom,$cnum,$group));
7375: }
7376:
7377: sub get_users_groups {
7378: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 7379: my @usersgroups;
1.683 raeburn 7380: my $cachetime=1800;
7381:
7382: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 7383: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7384: if (defined($cached)) {
1.734 albertel 7385: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 7386: } else {
7387: $grouplist = '';
1.816 raeburn 7388: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 7389: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 7390: my $access_end = $env{'course.'.$courseid.
7391: '.default_enrollment_end_date'};
7392: my $now = time;
7393: foreach my $key (keys(%roleshash)) {
7394: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7395: my $group = $1;
7396: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7397: my $start = $2;
7398: my $end = $1;
7399: if ($start == -1) { next; } # deleted from group
7400: if (($start!=0) && ($start>$now)) { next; }
7401: if (($end!=0) && ($end<$now)) {
7402: if ($access_end && $access_end < $now) {
7403: if ($access_end - $end < 86400) {
7404: push(@usersgroups,$group);
1.733 raeburn 7405: }
7406: }
1.817 raeburn 7407: next;
1.733 raeburn 7408: }
1.817 raeburn 7409: push(@usersgroups,$group);
1.683 raeburn 7410: }
7411: }
7412: }
1.817 raeburn 7413: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7414: $grouplist = join(':',@usersgroups);
7415: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 7416: }
1.733 raeburn 7417: return @usersgroups;
1.683 raeburn 7418: }
7419:
7420: sub devalidate_getgroups_cache {
7421: my ($udom,$uname,$cdom,$cnum)=@_;
7422: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 7423:
1.683 raeburn 7424: my $hashid="$udom:$uname:$courseid";
7425: &devalidate_cache_new('getgroups',$hashid);
7426: }
7427:
1.12 www 7428: # ------------------------------------------------------------------ Plain Text
7429:
7430: sub plaintext {
1.988 raeburn 7431: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 7432: if ($short =~ m{^cr/}) {
1.758 albertel 7433: return (split('/',$short))[-1];
7434: }
1.742 raeburn 7435: if (!defined($cid)) {
7436: $cid = $env{'request.course.id'};
7437: }
7438: my %rolenames = (
1.1008 raeburn 7439: Course => 'std',
7440: Community => 'alt1',
1.742 raeburn 7441: );
1.1037 raeburn 7442: if ($cid ne '') {
7443: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
7444: unless ($forcedefault) {
7445: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
7446: &Apache::lonlocal::mt_escape(\$roletext);
7447: return &Apache::lonlocal::mt($roletext);
7448: }
7449: }
7450: }
7451: if ((defined($type)) && (defined($rolenames{$type})) &&
7452: (defined($rolenames{$type})) &&
7453: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 7454: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 7455: } elsif ($cid ne '') {
7456: my $crstype = $env{'course.'.$cid.'.type'};
7457: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7458: (defined($prp{$short}{$rolenames{$crstype}}))) {
7459: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7460: }
1.742 raeburn 7461: }
1.1037 raeburn 7462: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 7463: }
7464:
7465: # ----------------------------------------------------------------- Assign Role
7466:
7467: sub assignrole {
1.957 raeburn 7468: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7469: $context)=@_;
1.21 www 7470: my $mrole;
7471: if ($role =~ /^cr\//) {
1.393 www 7472: my $cwosec=$url;
1.811 albertel 7473: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 7474: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 7475: my $refused = 1;
7476: if ($context eq 'requestcourses') {
7477: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7478: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7479: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7480: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7481: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7482: if ($crsenv{'internal.courseowner'} eq
7483: $env{'user.name'}.':'.$env{'user.domain'}) {
7484: $refused = '';
7485: }
7486: }
7487: }
7488: }
7489: }
7490: if ($refused) {
7491: &logthis('Refused custom assignrole: '.
7492: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7493: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7494: return 'refused';
7495: }
1.104 www 7496: }
1.21 www 7497: $mrole='cr';
1.678 raeburn 7498: } elsif ($role =~ /^gr\//) {
7499: my $cwogrp=$url;
1.811 albertel 7500: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 7501: unless (&allowed('mdg',$cwogrp)) {
7502: &logthis('Refused group assignrole: '.
7503: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7504: $env{'user.name'}.' at '.$env{'user.domain'});
7505: return 'refused';
7506: }
7507: $mrole='gr';
1.21 www 7508: } else {
1.82 www 7509: my $cwosec=$url;
1.811 albertel 7510: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 7511: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7512: my $refused;
7513: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7514: if (!(&allowed('c'.$role,$url))) {
7515: $refused = 1;
7516: }
7517: } else {
7518: $refused = 1;
7519: }
1.947 raeburn 7520: if ($refused) {
1.1045 raeburn 7521: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7522: if (!$selfenroll && $context eq 'course') {
7523: my %crsenv;
7524: if ($role eq 'cc' || $role eq 'co') {
7525: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7526: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7527: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7528: if ($crsenv{'internal.courseowner'} eq
7529: $env{'user.name'}.':'.$env{'user.domain'}) {
7530: $refused = '';
7531: }
7532: }
7533: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7534: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7535: if ($crsenv{'internal.courseowner'} eq
7536: $env{'user.name'}.':'.$env{'user.domain'}) {
7537: $refused = '';
7538: }
7539: }
7540: }
7541: }
7542: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 7543: $refused = '';
1.1017 raeburn 7544: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 7545: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 7546: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 7547: my $wrongcc;
7548: if ($cnum =~ /^$match_community$/) {
7549: $wrongcc = 1 if ($role eq 'cc');
7550: } else {
7551: $wrongcc = 1 if ($role eq 'co');
7552: }
7553: unless ($wrongcc) {
7554: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7555: if ($crsenv{'internal.courseowner'} eq
7556: $env{'user.name'}.':'.$env{'user.domain'}) {
7557: $refused = '';
7558: }
1.1017 raeburn 7559: }
7560: }
1.1183 raeburn 7561: } elsif ($context eq 'requestauthor') {
7562: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7563: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
7564: if ($env{'environment.requestauthor'} eq 'automatic') {
7565: $refused = '';
7566: } else {
7567: my %domdefaults = &get_domain_defaults($udom);
7568: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
7569: my $checkbystatus;
7570: if ($env{'user.adv'}) {
7571: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
7572: if ($disposition eq 'automatic') {
7573: $refused = '';
7574: } elsif ($disposition eq '') {
7575: $checkbystatus = 1;
7576: }
7577: } else {
7578: $checkbystatus = 1;
7579: }
7580: if ($checkbystatus) {
7581: if ($env{'environment.inststatus'}) {
7582: my @inststatuses = split(/,/,$env{'environment.inststatus'});
7583: foreach my $type (@inststatuses) {
7584: if (($type ne '') &&
7585: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
7586: $refused = '';
7587: }
7588: }
7589: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
7590: $refused = '';
7591: }
7592: }
7593: }
7594: }
7595: }
1.1017 raeburn 7596: }
7597: if ($refused) {
1.947 raeburn 7598: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7599: ' '.$role.' '.$end.' '.$start.' by '.
7600: $env{'user.name'}.' at '.$env{'user.domain'});
7601: return 'refused';
7602: }
1.932 raeburn 7603: }
1.1131 raeburn 7604: } elsif ($role eq 'au') {
7605: if ($url ne '/'.$udom.'/') {
7606: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
7607: ' to assign author role for '.$uname.':'.$udom.
7608: ' in domain: '.$url.' refused (wrong domain).');
7609: return 'refused';
7610: }
1.104 www 7611: }
1.21 www 7612: $mrole=$role;
7613: }
1.620 albertel 7614: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7615: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 7616: if ($end) { $command.='_'.$end; }
1.21 www 7617: if ($start) {
7618: if ($end) {
1.81 www 7619: $command.='_'.$start;
1.21 www 7620: } else {
1.81 www 7621: $command.='_0_'.$start;
1.21 www 7622: }
7623: }
1.739 raeburn 7624: my $origstart = $start;
7625: my $origend = $end;
1.957 raeburn 7626: my $delflag;
1.357 www 7627: # actually delete
7628: if ($deleteflag) {
1.373 www 7629: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 7630: # modify command to delete the role
1.620 albertel 7631: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 7632: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 7633: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 7634: # set start and finish to negative values for userrolelog
7635: $start=-1;
7636: $end=-1;
1.957 raeburn 7637: $delflag = 1;
1.357 www 7638: }
7639: }
7640: # send command
1.349 www 7641: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 7642: # log new user role if status is ok
1.349 www 7643: if ($answer eq 'ok') {
1.663 raeburn 7644: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 7645: # for course roles, perform group memberships changes triggered by role change.
7646: unless ($role =~ /^gr/) {
7647: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 7648: $origstart,$selfenroll,$context);
1.739 raeburn 7649: }
1.1184 raeburn 7650: if (($role eq 'cc') || ($role eq 'in') ||
7651: ($role eq 'ep') || ($role eq 'ad') ||
7652: ($role eq 'ta') || ($role eq 'st') ||
7653: ($role=~/^cr/) || ($role eq 'gr') ||
7654: ($role eq 'co')) {
7655: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
7656: $selfenroll,$context);
7657: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
7658: ($role eq 'au') || ($role eq 'dc')) {
7659: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
7660: $context);
7661: } elsif (($role eq 'ca') || ($role eq 'aa')) {
7662: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
7663: $context);
7664: }
1.1053 raeburn 7665: if ($role eq 'cc') {
7666: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7667: }
1.349 www 7668: }
7669: return $answer;
1.169 harris41 7670: }
7671:
1.1053 raeburn 7672: sub autoupdate_coowners {
7673: my ($url,$end,$start,$uname,$udom) = @_;
7674: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7675: if (($cdom ne '') && ($cnum ne '')) {
7676: my $now = time;
7677: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7678: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7679: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7680: my $instcode = $coursehash{'internal.coursecode'};
7681: if ($instcode ne '') {
1.1056 raeburn 7682: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7683: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 7684: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 7685: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7686: if ($result eq 'valid') {
7687: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 7688: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7689: push(@newcoowners,$coowner);
7690: }
7691: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7692: push(@newcoowners,$uname.':'.$udom);
7693: }
7694: @newcoowners = sort(@newcoowners);
7695: } else {
7696: push(@newcoowners,$uname.':'.$udom);
7697: }
7698: } else {
7699: if ($coursehash{'internal.co-owners'}) {
7700: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7701: unless ($coowner eq $uname.':'.$udom) {
7702: push(@newcoowners,$coowner);
7703: }
7704: }
7705: unless (@newcoowners > 0) {
7706: $delcoowners = 1;
7707: $coowners = '';
7708: }
7709: }
7710: }
7711: if (@newcoowners || $delcoowners) {
7712: &store_coowners($cdom,$cnum,$coursehash{'home'},
7713: $delcoowners,@newcoowners);
7714: }
7715: }
7716: }
7717: }
7718: }
7719: }
7720: }
7721:
7722: sub store_coowners {
7723: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7724: my $cid = $cdom.'_'.$cnum;
7725: my ($coowners,$delresult,$putresult);
7726: if (@newcoowners) {
7727: $coowners = join(',',@newcoowners);
7728: my %coownershash = (
7729: 'internal.co-owners' => $coowners,
7730: );
7731: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7732: if ($putresult eq 'ok') {
7733: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7734: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7735: }
7736: }
7737: }
7738: if ($delcoowners) {
7739: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7740: if ($delresult eq 'ok') {
7741: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7742: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7743: }
7744: }
7745: }
7746: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7747: my %crsinfo =
7748: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7749: if (ref($crsinfo{$cid}) eq 'HASH') {
7750: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7751: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7752: }
7753: }
7754: }
7755:
1.169 harris41 7756: # -------------------------------------------------- Modify user authentication
1.197 www 7757: # Overrides without validation
7758:
1.169 harris41 7759: sub modifyuserauth {
7760: my ($udom,$uname,$umode,$upass)=@_;
7761: my $uhome=&homeserver($uname,$udom);
1.197 www 7762: unless (&allowed('mau',$udom)) { return 'refused'; }
7763: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 7764: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7765: ' in domain '.$env{'request.role.domain'});
1.169 harris41 7766: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7767: &escape($upass),$uhome);
1.620 albertel 7768: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 7769: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7770: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7771: &log($udom,,$uname,$uhome,
1.620 albertel 7772: 'Authentication changed by '.$env{'user.domain'}.', '.
7773: $env{'user.name'}.', '.$umode.
1.197 www 7774: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 7775: unless ($reply eq 'ok') {
1.197 www 7776: &logthis('Authentication mode error: '.$reply);
1.169 harris41 7777: return 'error: '.$reply;
7778: }
1.170 harris41 7779: return 'ok';
1.80 www 7780: }
7781:
1.81 www 7782: # --------------------------------------------------------------- Modify a user
1.80 www 7783:
1.81 www 7784: sub modifyuser {
1.206 matthew 7785: my ($udom, $uname, $uid,
7786: $umode, $upass, $first,
7787: $middle, $last, $gene,
1.1058 raeburn 7788: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 7789: $udom= &LONCAPA::clean_domain($udom);
7790: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 7791: my $showcandelete = 'none';
7792: if (ref($candelete) eq 'ARRAY') {
7793: if (@{$candelete} > 0) {
7794: $showcandelete = join(', ',@{$candelete});
7795: }
7796: }
1.81 www 7797: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 7798: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 7799: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 7800: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7801: ' desiredhome not specified').
1.620 albertel 7802: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7803: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 7804: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 7805: my $newuser;
7806: if ($uhome eq 'no_host') {
7807: $newuser = 1;
7808: }
1.80 www 7809: # ----------------------------------------------------------------- Create User
1.406 albertel 7810: if (($uhome eq 'no_host') &&
7811: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 7812: my $unhome='';
1.844 albertel 7813: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 7814: $unhome = $desiredhome;
1.620 albertel 7815: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7816: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 7817: } else { # load balancing routine for determining $unhome
1.81 www 7818: my $loadm=10000000;
1.841 albertel 7819: my %servers = &get_servers($udom,'library');
7820: foreach my $tryserver (keys(%servers)) {
7821: my $answer=reply('load',$tryserver);
7822: if (($answer=~/\d+/) && ($answer<$loadm)) {
7823: $loadm=$answer;
7824: $unhome=$tryserver;
7825: }
1.80 www 7826: }
7827: }
7828: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 7829: return 'error: unable to find a home server for '.$uname.
7830: ' in domain '.$udom;
1.80 www 7831: }
7832: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7833: &escape($upass),$unhome);
7834: unless ($reply eq 'ok') {
7835: return 'error: '.$reply;
7836: }
1.230 stredwic 7837: $uhome=&homeserver($uname,$udom,'true');
1.80 www 7838: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 7839: return 'error: unable verify users home machine.';
1.80 www 7840: }
1.209 matthew 7841: } # End of creation of new user
1.80 www 7842: # ---------------------------------------------------------------------- Add ID
7843: if ($uid) {
7844: $uid=~tr/A-Z/a-z/;
7845: my %uidhash=&idrget($udom,$uname);
1.196 www 7846: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7847: && (!$forceid)) {
1.80 www 7848: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 7849: return 'error: user id "'.$uid.'" does not match '.
7850: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 7851: }
7852: } else {
7853: &idput($udom,($uname => $uid));
7854: }
7855: }
7856: # -------------------------------------------------------------- Add names, etc
1.313 matthew 7857: my @tmp=&get('environment',
1.899 raeburn 7858: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 7859: 'permanentemail','inststatus'],
1.134 albertel 7860: $udom,$uname);
1.1075 raeburn 7861: my (%names,%oldnames);
1.313 matthew 7862: if ($tmp[0] =~ m/^error:.*/) {
7863: %names=();
7864: } else {
7865: %names = @tmp;
1.1075 raeburn 7866: %oldnames = %names;
1.313 matthew 7867: }
1.388 www 7868: #
1.1058 raeburn 7869: # If name, email and/or uid are blank (e.g., because an uploaded file
7870: # of users did not contain them), do not overwrite existing values
7871: # unless field is in $candelete array ref.
7872: #
7873:
7874: my @fields = ('firstname','middlename','lastname','generation',
7875: 'permanentemail','id');
7876: my %newvalues;
7877: if (ref($candelete) eq 'ARRAY') {
7878: foreach my $field (@fields) {
7879: if (grep(/^\Q$field\E$/,@{$candelete})) {
7880: if ($field eq 'firstname') {
7881: $names{$field} = $first;
7882: } elsif ($field eq 'middlename') {
7883: $names{$field} = $middle;
7884: } elsif ($field eq 'lastname') {
7885: $names{$field} = $last;
7886: } elsif ($field eq 'generation') {
7887: $names{$field} = $gene;
7888: } elsif ($field eq 'permanentemail') {
7889: $names{$field} = $email;
7890: } elsif ($field eq 'id') {
7891: $names{$field} = $uid;
7892: }
7893: }
7894: }
7895: }
1.388 www 7896: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 7897: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 7898: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 7899: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 7900: if ($email) {
7901: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 7902: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 7903: }
1.899 raeburn 7904: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 7905: if (defined($inststatus)) {
7906: $names{'inststatus'} = '';
7907: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7908: if (ref($usertypes) eq 'HASH') {
7909: my @okstatuses;
7910: foreach my $item (split(/:/,$inststatus)) {
7911: if (defined($usertypes->{$item})) {
7912: push(@okstatuses,$item);
7913: }
7914: }
7915: if (@okstatuses) {
7916: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7917: }
7918: }
7919: }
1.1075 raeburn 7920: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 7921: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 7922: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 7923: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7924: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7925: } else {
7926: $logmsg .= ' during self creation';
7927: }
1.1075 raeburn 7928: my $changed;
7929: if ($newuser) {
7930: $changed = 1;
7931: } else {
7932: foreach my $field (@fields) {
7933: if ($names{$field} ne $oldnames{$field}) {
7934: $changed = 1;
7935: last;
7936: }
7937: }
7938: }
7939: unless ($changed) {
7940: $logmsg = 'No changes in user information needed for: '.$logmsg;
7941: &logthis($logmsg);
7942: return 'ok';
7943: }
7944: my $reply = &put('environment', \%names, $udom,$uname);
7945: if ($reply ne 'ok') {
7946: return 'error: '.$reply;
7947: }
1.1087 raeburn 7948: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7949: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7950: }
1.1075 raeburn 7951: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7952: &devalidate_cache_new('namescache',$uname.':'.$udom);
7953: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7954: &logthis($logmsg);
1.134 albertel 7955: return 'ok';
1.80 www 7956: }
7957:
1.81 www 7958: # -------------------------------------------------------------- Modify student
1.80 www 7959:
1.81 www 7960: sub modifystudent {
7961: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7962: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7963: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7964: if (!$cid) {
1.620 albertel 7965: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7966: return 'not_in_class';
7967: }
1.80 www 7968: }
7969: # --------------------------------------------------------------- Make the user
1.81 www 7970: my $reply=&modifyuser
1.209 matthew 7971: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7972: $desiredhome,$email,$inststatus);
1.80 www 7973: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7974: # This will cause &modify_student_enrollment to get the uid from the
7975: # students environment
7976: $uid = undef if (!$forceid);
1.455 albertel 7977: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7978: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7979: return $reply;
7980: }
7981:
7982: sub modify_student_enrollment {
1.957 raeburn 7983: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7984: my ($cdom,$cnum,$chome);
7985: if (!$cid) {
1.620 albertel 7986: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7987: return 'not_in_class';
7988: }
1.620 albertel 7989: $cdom=$env{'course.'.$cid.'.domain'};
7990: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7991: } else {
7992: ($cdom,$cnum)=split(/_/,$cid);
7993: }
1.620 albertel 7994: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7995: if (!$chome) {
1.457 raeburn 7996: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7997: }
1.455 albertel 7998: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7999: # Make sure the user exists
1.81 www 8000: my $uhome=&homeserver($uname,$udom);
8001: if (($uhome eq '') || ($uhome eq 'no_host')) {
8002: return 'error: no such user';
8003: }
1.297 matthew 8004: # Get student data if we were not given enough information
8005: if (!defined($first) || $first eq '' ||
8006: !defined($last) || $last eq '' ||
8007: !defined($uid) || $uid eq '' ||
8008: !defined($middle) || $middle eq '' ||
8009: !defined($gene) || $gene eq '') {
1.294 matthew 8010: # They did not supply us with enough data to enroll the student, so
8011: # we need to pick up more information.
1.297 matthew 8012: my %tmp = &get('environment',
1.294 matthew 8013: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 8014: ,$udom,$uname);
8015:
1.800 albertel 8016: #foreach my $key (keys(%tmp)) {
8017: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 8018: #}
1.294 matthew 8019: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8020: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8021: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 8022: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 8023: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8024: }
1.556 albertel 8025: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 8026: my $user = "$uname:$udom";
8027: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 8028: my $reply=cput('classlist',
1.1148 raeburn 8029: {$user =>
1.515 raeburn 8030: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 8031: $cdom,$cnum);
1.1148 raeburn 8032: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8033: &devalidate_getsection_cache($udom,$uname,$cid);
8034: } else {
1.81 www 8035: return 'error: '.$reply;
8036: }
1.297 matthew 8037: # Add student role to user
1.83 www 8038: my $uurl='/'.$cid;
1.81 www 8039: $uurl=~s/\_/\//g;
8040: if ($usec) {
8041: $uurl.='/'.$usec;
8042: }
1.1148 raeburn 8043: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8044: $selfenroll,$context);
8045: if ($result ne 'ok') {
8046: if ($old_entry{$user} ne '') {
8047: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8048: } else {
8049: $reply = &del('classlist',[$user],$cdom,$cnum);
8050: }
8051: }
8052: return $result;
1.21 www 8053: }
8054:
1.556 albertel 8055: sub format_name {
8056: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8057: my $name;
8058: if ($first ne 'lastname') {
8059: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8060: } else {
8061: if ($lastname=~/\S/) {
8062: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8063: $name=~s/\s+,/,/;
8064: } else {
8065: $name.= $firstname.' '.$middlename.' '.$generation;
8066: }
8067: }
8068: $name=~s/^\s+//;
8069: $name=~s/\s+$//;
8070: $name=~s/\s+/ /g;
8071: return $name;
8072: }
8073:
1.84 www 8074: # ------------------------------------------------- Write to course preferences
8075:
8076: sub writecoursepref {
8077: my ($courseid,%prefs)=@_;
8078: $courseid=~s/^\///;
8079: $courseid=~s/\_/\//g;
8080: my ($cdomain,$cnum)=split(/\//,$courseid);
8081: my $chome=homeserver($cnum,$cdomain);
8082: if (($chome eq '') || ($chome eq 'no_host')) {
8083: return 'error: no such course';
8084: }
8085: my $cstring='';
1.800 albertel 8086: foreach my $pref (keys(%prefs)) {
8087: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8088: }
1.84 www 8089: $cstring=~s/\&$//;
8090: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8091: }
8092:
8093: # ---------------------------------------------------------- Make/modify course
8094:
8095: sub createcourse {
1.741 raeburn 8096: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8097: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8098: $url=&declutter($url);
8099: my $cid='';
1.1028 raeburn 8100: if ($context eq 'requestcourses') {
8101: my $can_create = 0;
8102: my ($ownername,$ownerdom) = split(':',$course_owner);
8103: if ($udom eq $ownerdom) {
8104: if (&usertools_access($ownername,$ownerdom,$category,undef,
8105: $context)) {
8106: $can_create = 1;
8107: }
8108: } else {
8109: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8110: $category);
8111: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8112: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8113: if (@curr > 0) {
8114: my @options = qw(approval validate autolimit);
8115: my $optregex = join('|',@options);
8116: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8117: $can_create = 1;
8118: }
8119: }
8120: }
8121: }
8122: if ($can_create) {
8123: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8124: unless (&allowed('ccc',$udom)) {
8125: return 'refused';
8126: }
1.1017 raeburn 8127: }
8128: } else {
8129: return 'refused';
8130: }
1.1028 raeburn 8131: } elsif (!&allowed('ccc',$udom)) {
8132: return 'refused';
1.84 www 8133: }
1.1011 raeburn 8134: # --------------------------------------------------------------- Get Unique ID
8135: my $uname;
8136: if ($cnum =~ /^$match_courseid$/) {
8137: my $chome=&homeserver($cnum,$udom,'true');
8138: if (($chome eq '') || ($chome eq 'no_host')) {
8139: $uname = $cnum;
8140: } else {
1.1038 raeburn 8141: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8142: }
8143: } else {
1.1038 raeburn 8144: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8145: }
8146: return $uname if ($uname =~ /^error/);
8147: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8148: if (!defined($course_server)) {
8149: if (defined(&domain($udom,'primary'))) {
8150: $course_server = &domain($udom,'primary');
8151: } else {
8152: $course_server = $env{'user.home'};
8153: }
8154: }
8155: my %host_servers =
8156: &Apache::lonnet::get_servers($udom,'library');
8157: unless ($host_servers{$course_server}) {
8158: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8159: }
1.84 www 8160: # ------------------------------------------------------------- Make the course
8161: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8162: $course_server);
1.84 www 8163: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8164: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8165: if (($uhome eq '') || ($uhome eq 'no_host')) {
8166: return 'error: no such course';
8167: }
1.271 www 8168: # ----------------------------------------------------------------- Course made
1.516 raeburn 8169: # log existence
1.1029 raeburn 8170: my $now = time;
1.918 raeburn 8171: my $newcourse = {
8172: $udom.'_'.$uname => {
1.921 raeburn 8173: description => $description,
8174: inst_code => $inst_code,
8175: owner => $course_owner,
8176: type => $crstype,
1.1029 raeburn 8177: creator => $env{'user.name'}.':'.
8178: $env{'user.domain'},
8179: created => $now,
8180: context => $context,
1.918 raeburn 8181: },
8182: };
1.921 raeburn 8183: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8184: # set toplevel url
1.271 www 8185: my $topurl=$url;
8186: unless ($nonstandard) {
8187: # ------------------------------------------ For standard courses, make top url
8188: my $mapurl=&clutter($url);
1.278 www 8189: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8190: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8191: <map>
8192: <resource id="1" type="start"></resource>
8193: <resource id="2" src="$mapurl"></resource>
8194: <resource id="3" type="finish"></resource>
8195: <link index="1" from="1" to="2"></link>
8196: <link index="2" from="2" to="3"></link>
8197: </map>
8198: ENDINITMAP
8199: $topurl=&declutter(
1.638 albertel 8200: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8201: );
8202: }
8203: # ----------------------------------------------------------- Write preferences
1.84 www 8204: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8205: ('description' => $description,
8206: 'url' => $topurl,
8207: 'internal.creator' => $env{'user.name'}.':'.
8208: $env{'user.domain'},
8209: 'internal.created' => $now,
8210: 'internal.creationcontext' => $context)
8211: );
1.84 www 8212: return '/'.$udom.'/'.$uname;
8213: }
8214:
1.1011 raeburn 8215: # ------------------------------------------------------------------- Create ID
8216: sub generate_coursenum {
1.1038 raeburn 8217: my ($udom,$crstype) = @_;
1.1011 raeburn 8218: my $domdesc = &domain($udom);
8219: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8220: my $first;
8221: if ($crstype eq 'Community') {
8222: $first = '0';
8223: } else {
8224: $first = int(1+rand(9));
8225: }
8226: my $uname=$first.
1.1011 raeburn 8227: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8228: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8229: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8230: # ----------------------------------------------- Make sure that does not exist
8231: my $uhome=&homeserver($uname,$udom,'true');
8232: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8233: if ($crstype eq 'Community') {
8234: $first = '0';
8235: } else {
8236: $first = int(1+rand(9));
8237: }
8238: $uname=$first.
1.1011 raeburn 8239: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8240: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8241: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8242: $uhome=&homeserver($uname,$udom,'true');
8243: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8244: return 'error: unable to generate unique course-ID';
8245: }
8246: }
8247: return $uname;
8248: }
8249:
1.813 albertel 8250: sub is_course {
1.1167 droeschl 8251: my ($cdom, $cnum) = scalar(@_) == 1 ?
8252: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8253:
8254: return unless $cdom and $cnum;
8255:
8256: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8257: '.');
8258:
8259: return unless exists($courses{$cdom.'_'.$cnum});
8260: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8261: }
8262:
1.1015 raeburn 8263: sub store_userdata {
8264: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8265: my $result;
1.1016 raeburn 8266: if ($datakey ne '') {
1.1013 raeburn 8267: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8268: if ($udom eq '' || $uname eq '') {
8269: $udom = $env{'user.domain'};
8270: $uname = $env{'user.name'};
8271: }
8272: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8273: if (($uhome eq '') || ($uhome eq 'no_host')) {
8274: $result = 'error: no_host';
8275: } else {
8276: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8277: $storehash->{'host'} = $perlvar{'lonHostID'};
8278:
8279: my $namevalue='';
8280: foreach my $key (keys(%{$storehash})) {
8281: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8282: }
8283: $namevalue=~s/\&$//;
1.1105 raeburn 8284: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8285: $namevalue,$uhome);
1.1013 raeburn 8286: }
8287: } else {
8288: $result = 'error: data to store was not a hash reference';
8289: }
8290: } else {
8291: $result= 'error: invalid requestkey';
8292: }
8293: return $result;
8294: }
8295:
1.21 www 8296: # ---------------------------------------------------------- Assign Custom Role
8297:
8298: sub assigncustomrole {
1.957 raeburn 8299: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8300: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8301: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8302: }
8303:
8304: # ----------------------------------------------------------------- Revoke Role
8305:
8306: sub revokerole {
1.957 raeburn 8307: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8308: my $now=time;
1.965 raeburn 8309: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8310: }
8311:
8312: # ---------------------------------------------------------- Revoke Custom Role
8313:
8314: sub revokecustomrole {
1.957 raeburn 8315: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8316: my $now=time;
1.357 www 8317: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8318: $deleteflag,$selfenroll,$context);
1.17 www 8319: }
8320:
1.533 banghart 8321: # ------------------------------------------------------------ Disk usage
1.535 albertel 8322: sub diskusage {
1.955 raeburn 8323: my ($udom,$uname,$directorypath,$getpropath)=@_;
8324: $directorypath =~ s/\/$//;
8325: my $listing=&reply('du2:'.&escape($directorypath).':'
8326: .&escape($getpropath).':'.&escape($uname).':'
8327: .&escape($udom),homeserver($uname,$udom));
8328: if ($listing eq 'unknown_cmd') {
8329: if ($getpropath) {
8330: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8331: }
8332: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8333: }
1.514 albertel 8334: return $listing;
1.512 banghart 8335: }
8336:
1.566 banghart 8337: sub is_locked {
1.1096 raeburn 8338: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8339: my @check;
8340: my $is_locked;
1.1093 raeburn 8341: push (@check,$file_name);
1.613 albertel 8342: my %locked = &get('file_permissions',\@check,
1.620 albertel 8343: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8344: my ($tmp)=keys(%locked);
8345: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8346:
1.566 banghart 8347: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8348: $is_locked = 'false';
8349: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8350: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8351: $is_locked = 'true';
1.1096 raeburn 8352: if (ref($which) eq 'ARRAY') {
8353: push(@{$which},$entry);
8354: } else {
8355: last;
8356: }
1.745 raeburn 8357: }
8358: }
1.566 banghart 8359: } else {
8360: $is_locked = 'false';
8361: }
1.1093 raeburn 8362: return $is_locked;
1.566 banghart 8363: }
8364:
1.759 albertel 8365: sub declutter_portfile {
8366: my ($file) = @_;
1.833 albertel 8367: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 8368: return $file;
8369: }
8370:
1.559 banghart 8371: # ------------------------------------------------------------- Mark as Read Only
8372:
8373: sub mark_as_readonly {
8374: my ($domain,$user,$files,$what) = @_;
1.613 albertel 8375: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8376: my ($tmp)=keys(%current_permissions);
8377: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 8378: foreach my $file (@{$files}) {
1.759 albertel 8379: $file = &declutter_portfile($file);
1.561 banghart 8380: push(@{$current_permissions{$file}},$what);
1.559 banghart 8381: }
1.613 albertel 8382: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8383: return;
8384: }
8385:
1.572 banghart 8386: # ------------------------------------------------------------Save Selected Files
8387:
8388: sub save_selected_files {
8389: my ($user, $path, @files) = @_;
8390: my $filename = $user."savedfiles";
1.573 banghart 8391: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 8392: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 8393: foreach my $file (@files) {
1.620 albertel 8394: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 8395: }
8396: foreach my $file (@other_files) {
1.574 banghart 8397: print (OUT $file."\n");
1.572 banghart 8398: }
1.574 banghart 8399: close (OUT);
1.572 banghart 8400: return 'ok';
8401: }
8402:
1.574 banghart 8403: sub clear_selected_files {
8404: my ($user) = @_;
8405: my $filename = $user."savedfiles";
1.1117 foxr 8406: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 8407: print (OUT undef);
8408: close (OUT);
8409: return ("ok");
8410: }
8411:
1.572 banghart 8412: sub files_in_path {
8413: my ($user, $path) = @_;
8414: my $filename = $user."savedfiles";
8415: my %return_files;
1.1117 foxr 8416: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 8417: while (my $line_in = <IN>) {
1.574 banghart 8418: chomp ($line_in);
8419: my @paths_and_file = split (m!/!, $line_in);
8420: my $file_part = pop (@paths_and_file);
8421: my $path_part = join ('/', @paths_and_file);
1.573 banghart 8422: $path_part.='/';
8423: my $path_and_file = $path_part.$file_part;
8424: if ($path_part eq $path) {
8425: $return_files{$file_part}= 'selected';
8426: }
8427: }
1.574 banghart 8428: close (IN);
8429: return (\%return_files);
1.572 banghart 8430: }
8431:
8432: # called in portfolio select mode, to show files selected NOT in current directory
8433: sub files_not_in_path {
8434: my ($user, $path) = @_;
8435: my $filename = $user."savedfiles";
8436: my @return_files;
8437: my $path_part;
1.1117 foxr 8438: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 8439: while (my $line = <IN>) {
1.572 banghart 8440: #ok, I know it's clunky, but I want it to work
1.800 albertel 8441: my @paths_and_file = split(m|/|, $line);
8442: my $file_part = pop(@paths_and_file);
8443: chomp($file_part);
8444: my $path_part = join('/', @paths_and_file);
1.572 banghart 8445: $path_part .= '/';
8446: my $path_and_file = $path_part.$file_part;
8447: if ($path_part ne $path) {
1.800 albertel 8448: push(@return_files, ($path_and_file));
1.572 banghart 8449: }
8450: }
1.800 albertel 8451: close(OUT);
1.574 banghart 8452: return (@return_files);
1.572 banghart 8453: }
8454:
1.745 raeburn 8455: #----------------------------------------------Get portfolio file permissions
1.629 banghart 8456:
1.745 raeburn 8457: sub get_portfile_permissions {
8458: my ($domain,$user) = @_;
1.613 albertel 8459: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8460: my ($tmp)=keys(%current_permissions);
8461: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8462: return \%current_permissions;
8463: }
8464:
8465: #---------------------------------------------Get portfolio file access controls
8466:
1.749 raeburn 8467: sub get_access_controls {
1.745 raeburn 8468: my ($current_permissions,$group,$file) = @_;
1.769 albertel 8469: my %access;
8470: my $real_file = $file;
8471: $file =~ s/\.meta$//;
1.745 raeburn 8472: if (defined($file)) {
1.749 raeburn 8473: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
8474: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 8475: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 8476: }
8477: }
1.745 raeburn 8478: } else {
1.749 raeburn 8479: foreach my $key (keys(%{$current_permissions})) {
8480: if ($key =~ /\0accesscontrol$/) {
8481: if (defined($group)) {
8482: if ($key !~ m-^\Q$group\E/-) {
8483: next;
8484: }
8485: }
8486: my ($fullpath) = split(/\0/,$key);
8487: if (ref($$current_permissions{$key}) eq 'HASH') {
8488: foreach my $control (keys(%{$$current_permissions{$key}})) {
8489: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
8490: }
8491: }
8492: }
8493: }
8494: }
8495: return %access;
8496: }
8497:
8498: sub modify_access_controls {
8499: my ($file_name,$changes,$domain,$user)=@_;
8500: my ($outcome,$deloutcome);
8501: my %store_permissions;
8502: my %new_values;
8503: my %new_control;
8504: my %translation;
8505: my @deletions = ();
8506: my $now = time;
8507: if (exists($$changes{'activate'})) {
8508: if (ref($$changes{'activate'}) eq 'HASH') {
8509: my @newitems = sort(keys(%{$$changes{'activate'}}));
8510: my $numnew = scalar(@newitems);
8511: for (my $i=0; $i<$numnew; $i++) {
8512: my $newkey = $newitems[$i];
8513: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 8514: if ($newkey =~ /^\d+:/) {
8515: $newkey =~ s/^(\d+)/$newid/;
8516: $translation{$1} = $newid;
8517: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
8518: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
8519: $translation{$1} = $newid;
8520: }
1.749 raeburn 8521: $new_values{$file_name."\0".$newkey} =
8522: $$changes{'activate'}{$newitems[$i]};
8523: $new_control{$newkey} = $now;
8524: }
8525: }
8526: }
8527: my %todelete;
8528: my %changed_items;
8529: foreach my $action ('delete','update') {
8530: if (exists($$changes{$action})) {
8531: if (ref($$changes{$action}) eq 'HASH') {
8532: foreach my $key (keys(%{$$changes{$action}})) {
8533: my ($itemnum) = ($key =~ /^([^:]+):/);
8534: if ($action eq 'delete') {
8535: $todelete{$itemnum} = 1;
8536: } else {
8537: $changed_items{$itemnum} = $key;
8538: }
8539: }
1.745 raeburn 8540: }
8541: }
1.749 raeburn 8542: }
8543: # get lock on access controls for file.
8544: my $lockhash = {
8545: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8546: ':'.$env{'user.domain'},
8547: };
8548: my $tries = 0;
8549: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8550:
8551: while (($gotlock ne 'ok') && $tries <3) {
8552: $tries ++;
8553: sleep 1;
8554: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8555: }
8556: if ($gotlock eq 'ok') {
8557: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8558: my ($tmp)=keys(%curr_permissions);
8559: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8560: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8561: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8562: if (ref($curr_controls) eq 'HASH') {
8563: foreach my $control_item (keys(%{$curr_controls})) {
8564: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8565: if (defined($todelete{$itemnum})) {
8566: push(@deletions,$file_name."\0".$control_item);
8567: } else {
8568: if (defined($changed_items{$itemnum})) {
8569: $new_control{$changed_items{$itemnum}} = $now;
8570: push(@deletions,$file_name."\0".$control_item);
8571: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8572: } else {
8573: $new_control{$control_item} = $$curr_controls{$control_item};
8574: }
8575: }
1.745 raeburn 8576: }
8577: }
8578: }
1.970 raeburn 8579: my ($group);
8580: if (&is_course($domain,$user)) {
8581: ($group,my $file) = split(/\//,$file_name,2);
8582: }
1.749 raeburn 8583: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8584: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8585: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8586: # remove lock
8587: my @del_lock = ($file_name."\0".'locked_access_records');
8588: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 8589: my $sqlresult =
1.970 raeburn 8590: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 8591: $group);
1.749 raeburn 8592: } else {
8593: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 8594: }
1.749 raeburn 8595: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 8596: }
8597:
1.827 raeburn 8598: sub make_public_indefinitely {
8599: my ($requrl) = @_;
8600: my $now = time;
8601: my $action = 'activate';
8602: my $aclnum = 0;
8603: if (&is_portfolio_url($requrl)) {
8604: my (undef,$udom,$unum,$file_name,$group) =
8605: &parse_portfolio_url($requrl);
8606: my $current_perms = &get_portfile_permissions($udom,$unum);
8607: my %access_controls = &get_access_controls($current_perms,
8608: $group,$file_name);
8609: foreach my $key (keys(%{$access_controls{$file_name}})) {
8610: my ($num,$scope,$end,$start) =
8611: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8612: if ($scope eq 'public') {
8613: if ($start <= $now && $end == 0) {
8614: $action = 'none';
8615: } else {
8616: $action = 'update';
8617: $aclnum = $num;
8618: }
8619: last;
8620: }
8621: }
8622: if ($action eq 'none') {
8623: return 'ok';
8624: } else {
8625: my %changes;
8626: my $newend = 0;
8627: my $newstart = $now;
8628: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8629: $changes{$action}{$newkey} = {
8630: type => 'public',
8631: time => {
8632: start => $newstart,
8633: end => $newend,
8634: },
8635: };
8636: my ($outcome,$deloutcome,$new_values,$translation) =
8637: &modify_access_controls($file_name,\%changes,$udom,$unum);
8638: return $outcome;
8639: }
8640: } else {
8641: return 'invalid';
8642: }
8643: }
8644:
1.745 raeburn 8645: #------------------------------------------------------Get Marked as Read Only
8646:
8647: sub get_marked_as_readonly {
8648: my ($domain,$user,$what,$group) = @_;
8649: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 8650: my @readonly_files;
1.629 banghart 8651: my $cmp1=$what;
8652: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 8653: while (my ($file_name,$value) = each(%{$current_permissions})) {
8654: if (defined($group)) {
8655: if ($file_name !~ m-^\Q$group\E/-) {
8656: next;
8657: }
8658: }
1.561 banghart 8659: if (ref($value) eq "ARRAY"){
8660: foreach my $stored_what (@{$value}) {
1.629 banghart 8661: my $cmp2=$stored_what;
1.759 albertel 8662: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 8663: $cmp2=join('',@{$stored_what});
1.745 raeburn 8664: }
1.629 banghart 8665: if ($cmp1 eq $cmp2) {
1.561 banghart 8666: push(@readonly_files, $file_name);
1.745 raeburn 8667: last;
1.563 banghart 8668: } elsif (!defined($what)) {
8669: push(@readonly_files, $file_name);
1.745 raeburn 8670: last;
1.561 banghart 8671: }
8672: }
1.745 raeburn 8673: }
1.561 banghart 8674: }
8675: return @readonly_files;
8676: }
1.577 banghart 8677: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 8678:
1.577 banghart 8679: sub get_marked_as_readonly_hash {
1.745 raeburn 8680: my ($current_permissions,$group,$what) = @_;
1.577 banghart 8681: my %readonly_files;
1.745 raeburn 8682: while (my ($file_name,$value) = each(%{$current_permissions})) {
8683: if (defined($group)) {
8684: if ($file_name !~ m-^\Q$group\E/-) {
8685: next;
8686: }
8687: }
1.577 banghart 8688: if (ref($value) eq "ARRAY"){
8689: foreach my $stored_what (@{$value}) {
1.745 raeburn 8690: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 8691: foreach my $lock_descriptor(@{$stored_what}) {
8692: if ($lock_descriptor eq 'graded') {
8693: $readonly_files{$file_name} = 'graded';
8694: } elsif ($lock_descriptor eq 'handback') {
8695: $readonly_files{$file_name} = 'handback';
8696: } else {
8697: if (!exists($readonly_files{$file_name})) {
8698: $readonly_files{$file_name} = 'locked';
8699: }
8700: }
1.745 raeburn 8701: }
1.750 banghart 8702: }
1.577 banghart 8703: }
8704: }
8705: }
8706: return %readonly_files;
8707: }
1.559 banghart 8708: # ------------------------------------------------------------ Unmark as Read Only
8709:
8710: sub unmark_as_readonly {
1.629 banghart 8711: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8712: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 8713: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 8714: $file_name = &declutter_portfile($file_name);
1.634 albertel 8715: my $symb_crs = $what;
8716: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 8717: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 8718: my ($tmp)=keys(%current_permissions);
8719: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8720: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 8721: foreach my $file (@readonly_files) {
1.759 albertel 8722: my $clean_file = &declutter_portfile($file);
8723: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 8724: my $current_locks = $current_permissions{$file};
1.563 banghart 8725: my @new_locks;
8726: my @del_keys;
8727: if (ref($current_locks) eq "ARRAY"){
8728: foreach my $locker (@{$current_locks}) {
1.632 albertel 8729: my $compare=$locker;
1.749 raeburn 8730: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 8731: $compare=join('',@{$locker});
1.746 raeburn 8732: if ($compare ne $symb_crs) {
8733: push(@new_locks, $locker);
8734: }
1.563 banghart 8735: }
8736: }
1.650 albertel 8737: if (scalar(@new_locks) > 0) {
1.563 banghart 8738: $current_permissions{$file} = \@new_locks;
8739: } else {
8740: push(@del_keys, $file);
1.613 albertel 8741: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 8742: delete($current_permissions{$file});
1.563 banghart 8743: }
8744: }
1.561 banghart 8745: }
1.613 albertel 8746: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8747: return;
8748: }
1.512 banghart 8749:
1.17 www 8750: # ------------------------------------------------------------ Directory lister
8751:
8752: sub dirlist {
1.955 raeburn 8753: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 8754: $uri=~s/^\///;
8755: $uri=~s/\/$//;
1.253 stredwic 8756: my ($udom, $uname);
1.955 raeburn 8757: if ($getuserdir) {
1.253 stredwic 8758: $udom = $userdomain;
8759: $uname = $username;
1.955 raeburn 8760: } else {
8761: (undef,$udom,$uname)=split(/\//,$uri);
8762: if(defined($userdomain)) {
8763: $udom = $userdomain;
8764: }
8765: if(defined($username)) {
8766: $uname = $username;
8767: }
1.253 stredwic 8768: }
1.955 raeburn 8769: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 8770:
1.955 raeburn 8771: $dirRoot = $perlvar{'lonDocRoot'};
8772: if (defined($getpropath)) {
8773: $dirRoot = &propath($udom,$uname);
1.253 stredwic 8774: $dirRoot =~ s/\/$//;
1.955 raeburn 8775: } elsif (defined($getuserdir)) {
8776: my $subdir=$uname.'__';
8777: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8778: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8779: ."/$udom/$subdir/$uname";
8780: } elsif (defined($alternateRoot)) {
8781: $dirRoot = $alternateRoot;
1.751 banghart 8782: }
1.253 stredwic 8783:
8784: if($udom) {
8785: if($uname) {
1.1135 raeburn 8786: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 8787: if ($uhome eq 'no_host') {
8788: return ([],'no_host');
8789: }
1.955 raeburn 8790: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 8791: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 8792: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 8793: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8794: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 8795: } else {
8796: @listing_results = map { &unescape($_); } split(/:/,$listing);
8797: }
1.605 matthew 8798: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8799: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 8800: @listing_results = split(/:/,$listing);
8801: } else {
8802: @listing_results = map { &unescape($_); } split(/:/,$listing);
8803: }
1.1135 raeburn 8804: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 8805: ($listing eq 'rejected') || ($listing eq 'refused') ||
8806: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8807: return ([],$listing);
8808: } else {
8809: return (\@listing_results);
1.1135 raeburn 8810: }
1.955 raeburn 8811: } elsif(!$alternateRoot) {
1.1136 raeburn 8812: my (%allusers,%listerror);
1.841 albertel 8813: my %servers = &get_servers($udom,'library');
1.955 raeburn 8814: foreach my $tryserver (keys(%servers)) {
8815: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8816: &escape($udom),$tryserver);
8817: if ($listing eq 'unknown_cmd') {
8818: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8819: $udom, $tryserver);
8820: } else {
8821: @listing_results = map { &unescape($_); } split(/:/,$listing);
8822: }
1.841 albertel 8823: if ($listing eq 'unknown_cmd') {
8824: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8825: $udom, $tryserver);
8826: @listing_results = split(/:/,$listing);
8827: } else {
8828: @listing_results =
8829: map { &unescape($_); } split(/:/,$listing);
8830: }
1.1136 raeburn 8831: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8832: ($listing eq 'rejected') || ($listing eq 'refused') ||
8833: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8834: $listerror{$tryserver} = $listing;
8835: } else {
1.841 albertel 8836: foreach my $line (@listing_results) {
8837: my ($entry) = split(/&/,$line,2);
8838: $allusers{$entry} = 1;
8839: }
8840: }
1.253 stredwic 8841: }
1.1136 raeburn 8842: my @alluserslist=();
1.800 albertel 8843: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 8844: push(@alluserslist,$user.'&user');
1.253 stredwic 8845: }
1.1136 raeburn 8846: return (\@alluserslist);
1.253 stredwic 8847: } else {
1.1136 raeburn 8848: return ([],'missing username');
1.253 stredwic 8849: }
1.955 raeburn 8850: } elsif(!defined($getpropath)) {
1.1136 raeburn 8851: my $path = $perlvar{'lonDocRoot'}.'/res/';
8852: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
8853: return (\@all_domains);
1.955 raeburn 8854: } else {
1.1136 raeburn 8855: return ([],'missing domain');
1.275 stredwic 8856: }
8857: }
8858:
8859: # --------------------------------------------- GetFileTimestamp
8860: # This function utilizes dirlist and returns the date stamp for
8861: # when it was last modified. It will also return an error of -1
8862: # if an error occurs
8863:
8864: sub GetFileTimestamp {
1.955 raeburn 8865: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 8866: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8867: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 8868: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
8869: undef,$getuserdir);
8870: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8871: return -1;
8872: }
8873: if (ref($fileref) eq 'ARRAY') {
8874: my @stats = split('&',$fileref->[0]);
1.375 matthew 8875: # @stats contains first the filename, then the stat output
8876: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 8877: } else {
8878: return -1;
1.253 stredwic 8879: }
1.26 www 8880: }
8881:
1.712 albertel 8882: sub stat_file {
8883: my ($uri) = @_;
1.787 albertel 8884: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 8885:
1.955 raeburn 8886: my ($udom,$uname,$file);
1.712 albertel 8887: if ($uri =~ m-^/(uploaded|editupload)/-) {
8888: ($udom,$uname,$file) =
1.811 albertel 8889: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 8890: $file = 'userfiles/'.$file;
8891: }
8892: if ($uri =~ m-^/res/-) {
8893: ($udom,$uname) =
1.807 albertel 8894: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 8895: $file = $uri;
8896: }
8897:
8898: if (!$udom || !$uname || !$file) {
8899: # unable to handle the uri
8900: return ();
8901: }
1.956 raeburn 8902: my $getpropath;
8903: if ($file =~ /^userfiles\//) {
8904: $getpropath = 1;
8905: }
1.1136 raeburn 8906: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
8907: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8908: return ();
8909: } else {
8910: if (ref($listref) eq 'ARRAY') {
8911: my @stats = split('&',$listref->[0]);
8912: shift(@stats); #filename is first
8913: return @stats;
8914: }
1.712 albertel 8915: }
8916: return ();
8917: }
8918:
1.26 www 8919: # -------------------------------------------------------- Value of a Condition
8920:
1.713 albertel 8921: # gets the value of a specific preevaluated condition
8922: # stored in the string $env{user.state.<cid>}
8923: # or looks up a condition reference in the bighash and if if hasn't
8924: # already been evaluated recurses into docondval to get the value of
8925: # the condition, then memoizing it to
8926: # $env{user.state.<cid>.<condition>}
1.40 www 8927: sub directcondval {
8928: my $number=shift;
1.620 albertel 8929: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 8930: &Apache::lonuserstate::evalstate();
8931: }
1.713 albertel 8932: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8933: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8934: } elsif ($number =~ /^_/) {
8935: my $sub_condition;
8936: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8937: &GDBM_READER(),0640)) {
8938: $sub_condition=$bighash{'conditions'.$number};
8939: untie(%bighash);
8940: }
8941: my $value = &docondval($sub_condition);
1.949 raeburn 8942: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 8943: return $value;
8944: }
1.620 albertel 8945: if ($env{'user.state.'.$env{'request.course.id'}}) {
8946: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 8947: } else {
8948: return 2;
8949: }
8950: }
8951:
1.713 albertel 8952: # get the collection of conditions for this resource
1.26 www 8953: sub condval {
8954: my $condidx=shift;
1.54 www 8955: my $allpathcond='';
1.713 albertel 8956: foreach my $cond (split(/\|/,$condidx)) {
8957: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8958: $allpathcond.=
8959: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8960: }
1.191 harris41 8961: }
1.54 www 8962: $allpathcond=~s/\|$//;
1.713 albertel 8963: return &docondval($allpathcond);
8964: }
8965:
8966: #evaluates an expression of conditions
8967: sub docondval {
8968: my ($allpathcond) = @_;
8969: my $result=0;
8970: if ($env{'request.course.id'}
8971: && defined($allpathcond)) {
8972: my $operand='|';
8973: my @stack;
8974: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8975: if ($chunk eq '(') {
8976: push @stack,($operand,$result);
8977: } elsif ($chunk eq ')') {
8978: my $before=pop @stack;
8979: if (pop @stack eq '&') {
8980: $result=$result>$before?$before:$result;
8981: } else {
8982: $result=$result>$before?$result:$before;
8983: }
8984: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8985: $operand=$chunk;
8986: } else {
8987: my $new=directcondval($chunk);
8988: if ($operand eq '&') {
8989: $result=$result>$new?$new:$result;
8990: } else {
8991: $result=$result>$new?$result:$new;
8992: }
8993: }
8994: }
1.26 www 8995: }
8996: return $result;
1.421 albertel 8997: }
8998:
8999: # ---------------------------------------------------- Devalidate courseresdata
9000:
9001: sub devalidatecourseresdata {
9002: my ($coursenum,$coursedomain)=@_;
9003: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9004: &devalidate_cache_new('courseres',$hashid);
1.28 www 9005: }
9006:
1.763 www 9007:
1.200 www 9008: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 9009: #
9010: # Parameters:
9011: # $coursenum - Number of the course.
9012: # $coursedomain - Domain at which the course was created.
9013: # Returns:
9014: # A hash of the course parameters along (I think) with timestamps
9015: # and version info.
1.877 foxr 9016:
1.624 albertel 9017: sub get_courseresdata {
9018: my ($coursenum,$coursedomain)=@_;
1.200 www 9019: my $coursehom=&homeserver($coursenum,$coursedomain);
9020: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 9021: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 9022: my %dumpreply;
1.417 albertel 9023: unless (defined($cached)) {
1.624 albertel 9024: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 9025: $result=\%dumpreply;
1.251 albertel 9026: my ($tmp) = keys(%dumpreply);
9027: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 9028: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 9029: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9030: return $tmp;
1.416 albertel 9031: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 9032: $result=undef;
1.599 albertel 9033: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 9034: }
9035: }
1.624 albertel 9036: return $result;
9037: }
9038:
1.633 albertel 9039: sub devalidateuserresdata {
9040: my ($uname,$udom)=@_;
9041: my $hashid="$udom:$uname";
9042: &devalidate_cache_new('userres',$hashid);
9043: }
9044:
1.624 albertel 9045: sub get_userresdata {
9046: my ($uname,$udom)=@_;
9047: #most student don\'t have any data set, check if there is some data
9048: if (&EXT_cache_status($udom,$uname)) { return undef; }
9049:
9050: my $hashid="$udom:$uname";
9051: my ($result,$cached)=&is_cached_new('userres',$hashid);
9052: if (!defined($cached)) {
9053: my %resourcedata=&dump('resourcedata',$udom,$uname);
9054: $result=\%resourcedata;
9055: &do_cache_new('userres',$hashid,$result,600);
9056: }
9057: my ($tmp)=keys(%$result);
9058: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9059: return $result;
9060: }
9061: #error 2 occurs when the .db doesn't exist
9062: if ($tmp!~/error: 2 /) {
1.672 albertel 9063: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9064: " Trying to get resource data for ".
9065: $uname." at ".$udom.": ".
9066: $tmp."</font>");
9067: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9068: #&EXT_cache_set($udom,$uname);
9069: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9070: undef($tmp); # not really an error so don't send it back
1.624 albertel 9071: }
9072: return $tmp;
9073: }
1.879 foxr 9074: #----------------------------------------------- resdata - return resource data
9075: # Purpose:
9076: # Return resource data for either users or for a course.
9077: # Parameters:
9078: # $name - Course/user name.
9079: # $domain - Name of the domain the user/course is registered on.
9080: # $type - Type of thing $name is (must be 'course' or 'user'
9081: # @which - Array of names of resources desired.
9082: # Returns:
9083: # The value of the first reasource in @which that is found in the
9084: # resource hash.
9085: # Exceptional Conditions:
9086: # If the $type passed in is not valid (not the string 'course' or
9087: # 'user', an undefined reference is returned.
9088: # If none of the resources are found, an undef is returned
1.624 albertel 9089: sub resdata {
9090: my ($name,$domain,$type,@which)=@_;
9091: my $result;
9092: if ($type eq 'course') {
9093: $result=&get_courseresdata($name,$domain);
9094: } elsif ($type eq 'user') {
9095: $result=&get_userresdata($name,$domain);
9096: }
9097: if (!ref($result)) { return $result; }
1.251 albertel 9098: foreach my $item (@which) {
1.927 albertel 9099: if (defined($result->{$item->[0]})) {
9100: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9101: }
1.250 albertel 9102: }
1.291 albertel 9103: return undef;
1.200 www 9104: }
9105:
1.379 matthew 9106: #
9107: # EXT resource caching routines
9108: #
9109:
9110: sub clear_EXT_cache_status {
1.383 albertel 9111: &delenv('cache.EXT.');
1.379 matthew 9112: }
9113:
9114: sub EXT_cache_status {
9115: my ($target_domain,$target_user) = @_;
1.383 albertel 9116: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9117: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9118: # We know already the user has no data
9119: return 1;
9120: } else {
9121: return 0;
9122: }
9123: }
9124:
9125: sub EXT_cache_set {
9126: my ($target_domain,$target_user) = @_;
1.383 albertel 9127: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9128: #&appenv({$cachename => time});
1.379 matthew 9129: }
9130:
1.28 www 9131: # --------------------------------------------------------- Value of a Variable
1.58 www 9132: sub EXT {
1.715 albertel 9133:
1.395 albertel 9134: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 9135: unless ($varname) { return ''; }
1.218 albertel 9136: #get real user name/domain, courseid and symb
9137: my $courseid;
1.359 albertel 9138: my $publicuser;
1.427 www 9139: if ($symbparm) {
9140: $symbparm=&get_symb_from_alias($symbparm);
9141: }
1.218 albertel 9142: if (!($uname && $udom)) {
1.790 albertel 9143: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9144: if (!$symbparm) { $symbparm=$cursymb; }
9145: } else {
1.620 albertel 9146: $courseid=$env{'request.course.id'};
1.218 albertel 9147: }
1.48 www 9148: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9149: my $rest;
1.320 albertel 9150: if (defined($therest[0])) {
1.48 www 9151: $rest=join('.',@therest);
9152: } else {
9153: $rest='';
9154: }
1.320 albertel 9155:
1.57 www 9156: my $qualifierrest=$qualifier;
9157: if ($rest) { $qualifierrest.='.'.$rest; }
9158: my $spacequalifierrest=$space;
9159: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9160: if ($realm eq 'user') {
1.48 www 9161: # --------------------------------------------------------------- user.resource
9162: if ($space eq 'resource') {
1.651 albertel 9163: if ( (defined($Apache::lonhomework::parsing_a_problem)
9164: || defined($Apache::lonhomework::parsing_a_task))
9165: &&
1.744 albertel 9166: ($symbparm eq &symbread()) ) {
9167: # if we are in the middle of processing the resource the
9168: # get the value we are planning on committing
9169: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9170: return $Apache::lonhomework::results{$qualifierrest};
9171: } else {
9172: return $Apache::lonhomework::history{$qualifierrest};
9173: }
1.335 albertel 9174: } else {
1.359 albertel 9175: my %restored;
1.620 albertel 9176: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9177: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9178: } else {
9179: %restored=&restore($symbparm,$courseid,$udom,$uname);
9180: }
1.335 albertel 9181: return $restored{$qualifierrest};
9182: }
1.48 www 9183: # ----------------------------------------------------------------- user.access
9184: } elsif ($space eq 'access') {
1.218 albertel 9185: # FIXME - not supporting calls for a specific user
1.48 www 9186: return &allowed($qualifier,$rest);
9187: # ------------------------------------------ user.preferences, user.environment
9188: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9189: if (($uname eq $env{'user.name'}) &&
9190: ($udom eq $env{'user.domain'})) {
9191: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9192: } else {
1.359 albertel 9193: my %returnhash;
9194: if (!$publicuser) {
9195: %returnhash=&userenvironment($udom,$uname,
9196: $qualifierrest);
9197: }
1.218 albertel 9198: return $returnhash{$qualifierrest};
9199: }
1.48 www 9200: # ----------------------------------------------------------------- user.course
9201: } elsif ($space eq 'course') {
1.218 albertel 9202: # FIXME - not supporting calls for a specific user
1.620 albertel 9203: return $env{join('.',('request.course',$qualifier))};
1.48 www 9204: # ------------------------------------------------------------------- user.role
9205: } elsif ($space eq 'role') {
1.218 albertel 9206: # FIXME - not supporting calls for a specific user
1.620 albertel 9207: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9208: if ($qualifier eq 'value') {
9209: return $role;
9210: } elsif ($qualifier eq 'extent') {
9211: return $where;
9212: }
9213: # ----------------------------------------------------------------- user.domain
9214: } elsif ($space eq 'domain') {
1.218 albertel 9215: return $udom;
1.48 www 9216: # ------------------------------------------------------------------- user.name
9217: } elsif ($space eq 'name') {
1.218 albertel 9218: return $uname;
1.48 www 9219: # ---------------------------------------------------- Any other user namespace
1.29 www 9220: } else {
1.359 albertel 9221: my %reply;
9222: if (!$publicuser) {
9223: %reply=&get($space,[$qualifierrest],$udom,$uname);
9224: }
9225: return $reply{$qualifierrest};
1.48 www 9226: }
1.236 www 9227: } elsif ($realm eq 'query') {
9228: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9229: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9230: [$spacequalifierrest]);
1.620 albertel 9231: return $env{'form.'.$spacequalifierrest};
1.236 www 9232: } elsif ($realm eq 'request') {
1.48 www 9233: # ------------------------------------------------------------- request.browser
9234: if ($space eq 'browser') {
1.1145 bisitz 9235: return $env{'browser.'.$qualifier};
1.57 www 9236: # ------------------------------------------------------------ request.filename
9237: } else {
1.620 albertel 9238: return $env{'request.'.$spacequalifierrest};
1.29 www 9239: }
1.28 www 9240: } elsif ($realm eq 'course') {
1.48 www 9241: # ---------------------------------------------------------- course.description
1.620 albertel 9242: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9243: } elsif ($realm eq 'resource') {
1.165 www 9244:
1.620 albertel 9245: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9246: if (!$symbparm) { $symbparm=&symbread(); }
9247: }
1.693 albertel 9248:
9249: if ($space eq 'title') {
9250: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9251: return &gettitle($symbparm);
9252: }
9253:
9254: if ($space eq 'map') {
9255: my ($map) = &decode_symb($symbparm);
9256: return &symbread($map);
9257: }
1.905 albertel 9258: if ($space eq 'filename') {
9259: if ($symbparm) {
9260: return &clutter((&decode_symb($symbparm))[2]);
9261: }
9262: return &hreflocation('',$env{'request.filename'});
9263: }
1.693 albertel 9264:
9265: my ($section, $group, @groups);
1.593 albertel 9266: my ($courselevelm,$courselevel);
1.539 albertel 9267: if ($symbparm && defined($courseid) &&
1.620 albertel 9268: $courseid eq $env{'request.course.id'}) {
1.165 www 9269:
1.218 albertel 9270: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9271:
1.60 www 9272: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9273: my $symbp=$symbparm;
1.735 albertel 9274: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9275:
9276: my $symbparm=$symbp.'.'.$spacequalifierrest;
9277: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9278:
1.620 albertel 9279: if (($env{'user.name'} eq $uname) &&
9280: ($env{'user.domain'} eq $udom)) {
9281: $section=$env{'request.course.sec'};
1.733 raeburn 9282: @groups = split(/:/,$env{'request.course.groups'});
9283: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9284: } else {
1.539 albertel 9285: if (! defined($usection)) {
1.551 albertel 9286: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9287: } else {
9288: $section = $usection;
9289: }
1.733 raeburn 9290: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9291: }
9292:
9293: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9294: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9295: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9296:
1.593 albertel 9297: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9298: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9299: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9300:
1.60 www 9301: # ----------------------------------------------------------- first, check user
1.624 albertel 9302:
9303: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9304: ([$courselevelr,'resource'],
9305: [$courselevelm,'map' ],
9306: [$courselevel, 'course' ]));
1.931 albertel 9307: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9308:
1.594 albertel 9309: # ------------------------------------------------ second, check some of course
1.684 raeburn 9310: my $coursereply;
1.691 raeburn 9311: if (@groups > 0) {
9312: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9313: $mapparm,$spacequalifierrest);
1.927 albertel 9314: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9315: }
1.96 www 9316:
1.684 raeburn 9317: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9318: $env{'course.'.$courseid.'.domain'},
9319: 'course',
9320: ([$seclevelr, 'resource'],
9321: [$seclevelm, 'map' ],
9322: [$seclevel, 'course' ],
9323: [$courselevelr,'resource']));
9324: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 9325:
1.60 www 9326: # ------------------------------------------------------ third, check map parms
1.218 albertel 9327: my %parmhash=();
9328: my $thisparm='';
9329: if (tie(%parmhash,'GDBM_File',
1.620 albertel 9330: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 9331: &GDBM_READER(),0640)) {
1.218 albertel 9332: $thisparm=$parmhash{$symbparm};
9333: untie(%parmhash);
9334: }
1.927 albertel 9335: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 9336: }
1.594 albertel 9337: # ------------------------------------------ fourth, look in resource metadata
1.71 www 9338:
1.218 albertel 9339: $spacequalifierrest=~s/\./\_/;
1.282 albertel 9340: my $filename;
9341: if (!$symbparm) { $symbparm=&symbread(); }
9342: if ($symbparm) {
1.409 www 9343: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 9344: } else {
1.620 albertel 9345: $filename=$env{'request.filename'};
1.282 albertel 9346: }
9347: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 9348: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 9349: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 9350: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 9351:
1.927 albertel 9352: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 9353: if ($symbparm && defined($courseid) &&
1.620 albertel 9354: $courseid eq $env{'request.course.id'}) {
1.624 albertel 9355: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9356: $env{'course.'.$courseid.'.domain'},
9357: 'course',
1.927 albertel 9358: ([$courselevelm,'map' ],
9359: [$courselevel, 'course']));
9360: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 9361: }
1.145 www 9362: # ------------------------------------------------------------------ Cascade up
1.218 albertel 9363: unless ($space eq '0') {
1.336 albertel 9364: my @parts=split(/_/,$space);
9365: my $id=pop(@parts);
9366: my $part=join('_',@parts);
9367: if ($part eq '') { $part='0'; }
1.927 albertel 9368: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 9369: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 9370: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 9371: }
1.395 albertel 9372: if ($recurse) { return undef; }
9373: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 9374: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 9375: # ---------------------------------------------------- Any other user namespace
9376: } elsif ($realm eq 'environment') {
9377: # ----------------------------------------------------------------- environment
1.620 albertel 9378: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9379: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 9380: } else {
1.770 albertel 9381: if ($uname eq 'anonymous' && $udom eq '') {
9382: return '';
9383: }
1.219 albertel 9384: my %returnhash=&userenvironment($udom,$uname,
9385: $spacequalifierrest);
9386: return $returnhash{$spacequalifierrest};
9387: }
1.28 www 9388: } elsif ($realm eq 'system') {
1.48 www 9389: # ----------------------------------------------------------------- system.time
9390: if ($space eq 'time') {
9391: return time;
9392: }
1.696 albertel 9393: } elsif ($realm eq 'server') {
9394: # ----------------------------------------------------------------- system.time
9395: if ($space eq 'name') {
9396: return $ENV{'SERVER_NAME'};
9397: }
1.28 www 9398: }
1.48 www 9399: return '';
1.61 www 9400: }
9401:
1.927 albertel 9402: sub get_reply {
9403: my ($reply_value) = @_;
1.940 raeburn 9404: if (ref($reply_value) eq 'ARRAY') {
9405: if (wantarray) {
9406: return @$reply_value;
9407: }
9408: return $reply_value->[0];
9409: } else {
9410: return $reply_value;
1.927 albertel 9411: }
9412: }
9413:
1.691 raeburn 9414: sub check_group_parms {
9415: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
9416: my @groupitems = ();
9417: my $resultitem;
1.927 albertel 9418: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 9419: foreach my $group (@{$groups}) {
9420: foreach my $level (@levels) {
1.927 albertel 9421: my $item = $courseid.'.['.$group.'].'.$level->[0];
9422: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 9423: }
9424: }
9425: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
9426: $env{'course.'.$courseid.'.domain'},
9427: 'course',@groupitems);
9428: return $coursereply;
9429: }
9430:
9431: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 9432: my ($courseid,@groups) = @_;
9433: @groups = sort(@groups);
1.691 raeburn 9434: return @groups;
9435: }
9436:
1.395 albertel 9437: sub packages_tab_default {
9438: my ($uri,$varname)=@_;
9439: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 9440:
9441: my (@extension,@specifics,$do_default);
9442: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 9443: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 9444: if ($pack_type eq 'default') {
9445: $do_default=1;
9446: } elsif ($pack_type eq 'extension') {
9447: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 9448: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 9449: # only look at packages defaults for packages that this id is
1.738 albertel 9450: push(@specifics,[$package,$pack_type,$pack_part]);
9451: }
9452: }
9453: # first look for a package that matches the requested part id
9454: foreach my $package (@specifics) {
9455: my (undef,$pack_type,$pack_part)=@{$package};
9456: next if ($pack_part ne $part);
9457: if (defined($packagetab{"$pack_type&$name&default"})) {
9458: return $packagetab{"$pack_type&$name&default"};
9459: }
9460: }
9461: # look for any possible matching non extension_ package
9462: foreach my $package (@specifics) {
9463: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 9464: if (defined($packagetab{"$pack_type&$name&default"})) {
9465: return $packagetab{"$pack_type&$name&default"};
9466: }
1.585 albertel 9467: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 9468: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
9469: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 9470: }
9471: }
1.738 albertel 9472: # look for any posible extension_ match
9473: foreach my $package (@extension) {
9474: my ($package,$pack_type)=@{$package};
9475: if (defined($packagetab{"$pack_type&$name&default"})) {
9476: return $packagetab{"$pack_type&$name&default"};
9477: }
9478: if (defined($packagetab{$package."&$name&default"})) {
9479: return $packagetab{$package."&$name&default"};
9480: }
9481: }
9482: # look for a global default setting
9483: if ($do_default && defined($packagetab{"default&$name&default"})) {
9484: return $packagetab{"default&$name&default"};
9485: }
1.395 albertel 9486: return undef;
9487: }
9488:
1.334 albertel 9489: sub add_prefix_and_part {
9490: my ($prefix,$part)=@_;
9491: my $keyroot;
9492: if (defined($prefix) && $prefix !~ /^__/) {
9493: # prefix that has a part already
9494: $keyroot=$prefix;
9495: } elsif (defined($prefix)) {
9496: # prefix that is missing a part
9497: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
9498: } else {
9499: # no prefix at all
9500: if (defined($part)) { $keyroot='_'.$part; }
9501: }
9502: return $keyroot;
9503: }
9504:
1.71 www 9505: # ---------------------------------------------------------------- Get metadata
9506:
1.599 albertel 9507: my %metaentry;
1.1070 www 9508: my %importedpartids;
1.71 www 9509: sub metadata {
1.176 www 9510: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 9511: $uri=&declutter($uri);
1.288 albertel 9512: # if it is a non metadata possible uri return quickly
1.529 albertel 9513: if (($uri eq '') ||
9514: (($uri =~ m|^/*adm/|) &&
1.698 albertel 9515: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108 raeburn 9516: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 9517: return undef;
9518: }
1.1140 www 9519: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 9520: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 9521: return undef;
1.288 albertel 9522: }
1.73 www 9523: my $filename=$uri;
9524: $uri=~s/\.meta$//;
1.172 www 9525: #
9526: # Is the metadata already cached?
1.177 www 9527: # Look at timestamp of caching
1.172 www 9528: # Everything is cached by the main uri, libraries are never directly cached
9529: #
1.428 albertel 9530: if (!defined($liburi)) {
1.599 albertel 9531: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 9532: if (defined($cached)) { return $result->{':'.$what}; }
9533: }
9534: {
1.1069 www 9535: # Imported parts would go here
1.1070 www 9536: my %importedids=();
9537: my @origfileimportpartids=();
1.1069 www 9538: my $importedparts=0;
1.172 www 9539: #
9540: # Is this a recursive call for a library?
9541: #
1.599 albertel 9542: # if (! exists($metacache{$uri})) {
9543: # $metacache{$uri}={};
9544: # }
1.924 albertel 9545: my $cachetime = 60*60;
1.171 www 9546: if ($liburi) {
9547: $liburi=&declutter($liburi);
9548: $filename=$liburi;
1.401 bowersj2 9549: } else {
1.599 albertel 9550: &devalidate_cache_new('meta',$uri);
9551: undef(%metaentry);
1.401 bowersj2 9552: }
1.140 www 9553: my %metathesekeys=();
1.73 www 9554: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 9555: my $metastring;
1.1140 www 9556: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 9557: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 9558: $metastring =
1.929 albertel 9559: &Apache::lonnet::ssi_body($which,
1.924 albertel 9560: ('grade_target' => 'meta'));
9561: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 9562: } elsif (($uri !~ m -^(editupload)/-) &&
9563: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 9564: my $file=&filelocation('',&clutter($filename));
1.599 albertel 9565: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 9566: $metastring=&getfile($file);
1.489 albertel 9567: }
1.208 albertel 9568: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 9569: my $token;
1.140 www 9570: undef %metathesekeys;
1.71 www 9571: while ($token=$parser->get_token) {
1.339 albertel 9572: if ($token->[0] eq 'S') {
9573: if (defined($token->[2]->{'package'})) {
1.172 www 9574: #
9575: # This is a package - get package info
9576: #
1.339 albertel 9577: my $package=$token->[2]->{'package'};
9578: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9579: if (defined($token->[2]->{'id'})) {
9580: $keyroot.='_'.$token->[2]->{'id'};
9581: }
1.599 albertel 9582: if ($metaentry{':packages'}) {
9583: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 9584: } else {
1.599 albertel 9585: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 9586: }
1.736 albertel 9587: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 9588: my $part=$keyroot;
9589: $part=~s/^\_//;
1.736 albertel 9590: if ($pack_entry=~/^\Q$package\E\&/ ||
9591: $pack_entry=~/^\Q$package\E_0\&/) {
9592: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 9593: # ignore package.tab specified default values
9594: # here &package_tab_default() will fetch those
9595: if ($subp eq 'default') { next; }
1.736 albertel 9596: my $value=$packagetab{$pack_entry};
1.432 albertel 9597: my $unikey;
9598: if ($pack =~ /_0$/) {
9599: $unikey='parameter_0_'.$name;
9600: $part=0;
9601: } else {
9602: $unikey='parameter'.$keyroot.'_'.$name;
9603: }
1.339 albertel 9604: if ($subp eq 'display') {
9605: $value.=' [Part: '.$part.']';
9606: }
1.599 albertel 9607: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 9608: $metathesekeys{$unikey}=1;
1.599 albertel 9609: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9610: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 9611: }
1.599 albertel 9612: if (defined($metaentry{':'.$unikey.'.default'})) {
9613: $metaentry{':'.$unikey}=
9614: $metaentry{':'.$unikey.'.default'};
1.356 albertel 9615: }
1.339 albertel 9616: }
9617: }
9618: } else {
1.172 www 9619: #
9620: # This is not a package - some other kind of start tag
1.339 albertel 9621: #
9622: my $entry=$token->[1];
1.1068 www 9623: my $unikey='';
1.175 www 9624:
1.339 albertel 9625: if ($entry eq 'import') {
1.175 www 9626: #
9627: # Importing a library here
1.339 albertel 9628: #
1.1067 www 9629: my $location=$parser->get_text('/import');
9630: my $dir=$filename;
9631: $dir=~s|[^/]*$||;
9632: $location=&filelocation($dir,$location);
1.1069 www 9633:
1.1068 www 9634: my $importmode=$token->[2]->{'importmode'};
9635: if ($importmode eq 'problem') {
1.1069 www 9636: # Import as problem/response
1.1068 www 9637: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9638: } elsif ($importmode eq 'part') {
9639: # Import as part(s)
1.1069 www 9640: $importedparts=1;
9641: # We need to get the original file and the imported file to get the part order correct
9642: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9643: # Load and inspect original file
1.1070 www 9644: if ($#origfileimportpartids<0) {
9645: undef(%importedpartids);
9646: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9647: my $origfile=&getfile($origfilelocation);
9648: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9649: }
9650:
1.1069 www 9651: # Load and inspect imported file
9652: my $impfile=&getfile($location);
9653: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9654: if ($#impfilepartids>=0) {
9655: # This problem had parts
1.1070 www 9656: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 9657: } else {
9658: # Importing by turning a single problem into a problem part
9659: # It gets the import-tags ID as part-ID
9660: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 9661: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 9662: }
1.1068 www 9663: } else {
9664: # Normal import
9665: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9666: if (defined($token->[2]->{'id'})) {
9667: $unikey.='_'.$token->[2]->{'id'};
9668: }
1.1067 www 9669: }
9670:
1.339 albertel 9671: if ($depthcount<20) {
1.736 albertel 9672: my $metadata =
9673: &metadata($uri,'keys', $location,$unikey,
9674: $depthcount+1);
9675: foreach my $meta (split(',',$metadata)) {
9676: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9677: $metathesekeys{$meta}=1;
1.339 albertel 9678: }
1.1068 www 9679:
9680: }
1.1067 www 9681: } else {
9682: #
9683: # Not importing, some other kind of non-package, non-library start tag
9684: #
9685: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9686: if (defined($token->[2]->{'id'})) {
9687: $unikey.='_'.$token->[2]->{'id'};
9688: }
1.339 albertel 9689: if (defined($token->[2]->{'name'})) {
9690: $unikey.='_'.$token->[2]->{'name'};
9691: }
9692: $metathesekeys{$unikey}=1;
1.736 albertel 9693: foreach my $param (@{$token->[3]}) {
9694: $metaentry{':'.$unikey.'.'.$param} =
9695: $token->[2]->{$param};
1.339 albertel 9696: }
9697: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 9698: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 9699: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9700: # only ws inside the tag, and not in default, so use default
9701: # as value
1.599 albertel 9702: $metaentry{':'.$unikey}=$default;
1.908 albertel 9703: } elsif ( $internaltext =~ /\S/ ) {
9704: # something interesting inside the tag
9705: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 9706: } else {
1.908 albertel 9707: # no interesting values, don't set a default
1.339 albertel 9708: }
1.172 www 9709: # end of not-a-package not-a-library import
1.339 albertel 9710: }
1.172 www 9711: # end of not-a-package start tag
1.339 albertel 9712: }
1.172 www 9713: # the next is the end of "start tag"
1.339 albertel 9714: }
9715: }
1.483 albertel 9716: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 9717: $extension = lc($extension);
9718: if ($extension eq 'htm') { $extension='html'; }
9719:
1.737 albertel 9720: foreach my $key (keys(%packagetab)) {
1.483 albertel 9721: #no specific packages #how's our extension
9722: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 9723: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 9724: \%metathesekeys);
9725: }
1.883 albertel 9726:
9727: if (!exists($metaentry{':packages'})
9728: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 9729: foreach my $key (keys(%packagetab)) {
1.483 albertel 9730: #no specific packages well let's get default then
9731: if ($key!~/^default&/) { next; }
1.488 albertel 9732: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 9733: \%metathesekeys);
9734: }
9735: }
1.338 www 9736: # are there custom rights to evaluate
1.599 albertel 9737: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 9738:
1.338 www 9739: #
9740: # Importing a rights file here
1.339 albertel 9741: #
9742: unless ($depthcount) {
1.599 albertel 9743: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 9744: my $dir=$filename;
9745: $dir=~s|[^/]*$||;
9746: $location=&filelocation($dir,$location);
1.736 albertel 9747: my $rights_metadata =
9748: &metadata($uri,'keys',$location,'_rights',
9749: $depthcount+1);
9750: foreach my $rights (split(',',$rights_metadata)) {
9751: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9752: $metathesekeys{$rights}=1;
1.339 albertel 9753: }
9754: }
9755: }
1.737 albertel 9756: # uniqifiy package listing
9757: my %seen;
9758: my @uniq_packages =
9759: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9760: $metaentry{':packages'} = join(',',@uniq_packages);
9761:
1.1070 www 9762: if ($importedparts) {
9763: # We had imported parts and need to rebuild partorder
9764: $metaentry{':partorder'}='';
9765: $metathesekeys{'partorder'}=1;
9766: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9767: if ($origfileimportpartids[$index] eq 'part') {
9768: # original part, part of the problem
9769: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9770: } else {
9771: # we have imported parts at this position
9772: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9773: }
9774: }
9775: $metaentry{':partorder'}=~s/^\,//;
9776: }
9777:
1.737 albertel 9778: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 9779: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9780: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 9781: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 9782: # this is the end of "was not already recently cached
1.71 www 9783: }
1.599 albertel 9784: return $metaentry{':'.$what};
1.261 albertel 9785: }
9786:
1.488 albertel 9787: sub metadata_create_package_def {
1.483 albertel 9788: my ($uri,$key,$package,$metathesekeys)=@_;
9789: my ($pack,$name,$subp)=split(/\&/,$key);
9790: if ($subp eq 'default') { next; }
9791:
1.599 albertel 9792: if (defined($metaentry{':packages'})) {
9793: $metaentry{':packages'}.=','.$package;
1.483 albertel 9794: } else {
1.599 albertel 9795: $metaentry{':packages'}=$package;
1.483 albertel 9796: }
9797: my $value=$packagetab{$key};
9798: my $unikey;
9799: $unikey='parameter_0_'.$name;
1.599 albertel 9800: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 9801: $$metathesekeys{$unikey}=1;
1.599 albertel 9802: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9803: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 9804: }
1.599 albertel 9805: if (defined($metaentry{':'.$unikey.'.default'})) {
9806: $metaentry{':'.$unikey}=
9807: $metaentry{':'.$unikey.'.default'};
1.483 albertel 9808: }
9809: }
9810:
1.261 albertel 9811: sub metadata_generate_part0 {
9812: my ($metadata,$metacache,$uri) = @_;
9813: my %allnames;
1.737 albertel 9814: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 9815: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 9816: my $part=$$metacache{':'.$metakey.'.part'};
9817: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 9818: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 9819: $allnames{$name}=$part;
9820: }
9821: }
9822: }
9823: foreach my $name (keys(%allnames)) {
9824: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 9825: my $key=":parameter_0_$name";
1.261 albertel 9826: $$metacache{"$key.part"}='0';
9827: $$metacache{"$key.name"}=$name;
1.428 albertel 9828: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 9829: $allnames{$name}.'_'.$name.
9830: '.type'};
1.428 albertel 9831: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 9832: '.display'};
1.644 www 9833: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 9834: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 9835: $$metacache{"$key.display"}=$olddis;
9836: }
1.71 www 9837: }
9838:
1.764 albertel 9839: # ------------------------------------------------------ Devalidate title cache
9840:
9841: sub devalidate_title_cache {
9842: my ($url)=@_;
9843: if (!$env{'request.course.id'}) { return; }
9844: my $symb=&symbread($url);
9845: if (!$symb) { return; }
9846: my $key=$env{'request.course.id'}."\0".$symb;
9847: &devalidate_cache_new('title',$key);
9848: }
9849:
1.1014 droeschl 9850: # ------------------------------------------------- Get the title of a course
9851:
9852: sub current_course_title {
9853: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9854: }
1.301 www 9855: # ------------------------------------------------- Get the title of a resource
9856:
9857: sub gettitle {
9858: my $urlsymb=shift;
9859: my $symb=&symbread($urlsymb);
1.534 albertel 9860: if ($symb) {
1.620 albertel 9861: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 9862: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 9863: if (defined($cached)) {
9864: return $result;
9865: }
1.534 albertel 9866: my ($map,$resid,$url)=&decode_symb($symb);
9867: my $title='';
1.907 albertel 9868: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9869: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9870: } else {
9871: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9872: &GDBM_READER(),0640)) {
9873: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9874: $title=$bighash{'title_'.$mapid.'.'.$resid};
9875: untie(%bighash);
9876: }
1.534 albertel 9877: }
9878: $title=~s/\&colon\;/\:/gs;
9879: if ($title) {
1.1159 www 9880: # Remember both $symb and $title for dynamic metadata
9881: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 9882: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 9883: # Cache this title and then return it
1.599 albertel 9884: return &do_cache_new('title',$key,$title,600);
1.534 albertel 9885: }
9886: $urlsymb=$url;
9887: }
9888: my $title=&metadata($urlsymb,'title');
9889: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9890: return $title;
1.301 www 9891: }
1.613 albertel 9892:
1.614 albertel 9893: sub get_slot {
9894: my ($which,$cnum,$cdom)=@_;
9895: if (!$cnum || !$cdom) {
1.790 albertel 9896: (undef,my $courseid)=&whichuser();
1.620 albertel 9897: $cdom=$env{'course.'.$courseid.'.domain'};
9898: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 9899: }
1.703 albertel 9900: my $key=join("\0",'slots',$cdom,$cnum,$which);
9901: my %slotinfo;
9902: if (exists($remembered{$key})) {
9903: $slotinfo{$which} = $remembered{$key};
9904: } else {
9905: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9906: &Apache::lonhomework::showhash(%slotinfo);
9907: my ($tmp)=keys(%slotinfo);
9908: if ($tmp=~/^error:/) { return (); }
9909: $remembered{$key} = $slotinfo{$which};
9910: }
1.616 albertel 9911: if (ref($slotinfo{$which}) eq 'HASH') {
9912: return %{$slotinfo{$which}};
9913: }
9914: return $slotinfo{$which};
1.614 albertel 9915: }
1.1150 raeburn 9916:
9917: sub get_reservable_slots {
9918: my ($cnum,$cdom,$uname,$udom) = @_;
9919: my $now = time;
9920: my $reservable_info;
9921: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
9922: if (exists($remembered{$key})) {
9923: $reservable_info = $remembered{$key};
9924: } else {
9925: my %resv;
9926: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
9927: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
9928: $reservable_info = \%resv;
9929: $remembered{$key} = $reservable_info;
9930: }
9931: return $reservable_info;
9932: }
9933:
9934: sub get_course_slots {
9935: my ($cnum,$cdom) = @_;
9936: my $hashid=$cnum.':'.$cdom;
9937: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
9938: if (defined($cached)) {
9939: if (ref($result) eq 'HASH') {
9940: return %{$result};
9941: }
9942: } else {
9943: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
9944: my ($tmp) = keys(%slots);
9945: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9946: &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
9947: return %slots;
9948: }
9949: }
9950: return;
9951: }
9952:
9953: sub devalidate_slots_cache {
9954: my ($cnum,$cdom)=@_;
9955: my $hashid=$cnum.':'.$cdom;
9956: &devalidate_cache_new('allslots',$hashid);
9957: }
9958:
1.1181 raeburn 9959: sub get_coursechange {
9960: my ($cdom,$cnum) = @_;
9961: if ($cdom eq '' || $cnum eq '') {
9962: return unless ($env{'request.course.id'});
9963: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9964: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9965: }
9966: my $hashid=$cdom.'_'.$cnum;
9967: my ($change,$cached)=&is_cached_new('crschange',$hashid);
9968: if ((defined($cached)) && ($change ne '')) {
9969: return $change;
9970: } else {
9971: my %crshash;
9972: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
9973: if ($crshash{'internal.contentchange'} eq '') {
9974: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
9975: if ($change eq '') {
9976: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
9977: $change = $crshash{'internal.created'};
9978: }
9979: } else {
9980: $change = $crshash{'internal.contentchange'};
9981: }
9982: my $cachetime = 600;
9983: &do_cache_new('crschange',$hashid,$change,$cachetime);
9984: }
9985: return $change;
9986: }
9987:
9988: sub devalidate_coursechange_cache {
9989: my ($cnum,$cdom)=@_;
9990: my $hashid=$cnum.':'.$cdom;
9991: &devalidate_cache_new('crschange',$hashid);
9992: }
9993:
1.31 www 9994: # ------------------------------------------------- Update symbolic store links
9995:
9996: sub symblist {
9997: my ($mapname,%newhash)=@_;
1.438 www 9998: $mapname=&deversion(&declutter($mapname));
1.31 www 9999: my %hash;
1.620 albertel 10000: if (($env{'request.course.fn'}) && (%newhash)) {
10001: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10002: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 10003: foreach my $url (keys(%newhash)) {
1.711 albertel 10004: next if ($url eq 'last_known'
10005: && $env{'form.no_update_last_known'});
10006: $hash{declutter($url)}=&encode_symb($mapname,
10007: $newhash{$url}->[1],
10008: $newhash{$url}->[0]);
1.191 harris41 10009: }
1.31 www 10010: if (untie(%hash)) {
10011: return 'ok';
10012: }
10013: }
10014: }
10015: return 'error';
1.212 www 10016: }
10017:
10018: # --------------------------------------------------------------- Verify a symb
10019:
10020: sub symbverify {
1.510 www 10021: my ($symb,$thisurl)=@_;
10022: my $thisfn=$thisurl;
1.439 www 10023: $thisfn=&declutter($thisfn);
1.215 www 10024: # direct jump to resource in page or to a sequence - will construct own symbs
10025: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10026: # check URL part
1.409 www 10027: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 10028:
1.431 www 10029: unless ($url eq $thisfn) { return 0; }
1.213 www 10030:
1.216 www 10031: $symb=&symbclean($symb);
1.510 www 10032: $thisurl=&deversion($thisurl);
1.439 www 10033: $thisfn=&deversion($thisfn);
1.213 www 10034:
10035: my %bighash;
10036: my $okay=0;
1.431 www 10037:
1.620 albertel 10038: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10039: &GDBM_READER(),0640)) {
1.1032 raeburn 10040: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10041: $thisurl =~ s/\?.+$//;
10042: }
1.510 www 10043: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102 raeburn 10044: unless ($ids) {
10045: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10046: $ids=$bighash{$idkey};
1.216 www 10047: }
10048: if ($ids) {
10049: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 10050: foreach my $id (split(/\,/,$ids)) {
10051: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 10052: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10053: $symb =~ s/\?.+$//;
10054: }
1.216 www 10055: if (
10056: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10057: eq $symb) {
1.620 albertel 10058: if (($env{'request.role.adv'}) ||
1.1101 raeburn 10059: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10060: ($thisurl eq '/adm/navmaps')) {
1.582 albertel 10061: $okay=1;
10062: }
10063: }
1.216 www 10064: }
10065: }
1.213 www 10066: untie(%bighash);
10067: }
10068: return $okay;
1.31 www 10069: }
10070:
1.210 www 10071: # --------------------------------------------------------------- Clean-up symb
10072:
10073: sub symbclean {
10074: my $symb=shift;
1.568 albertel 10075: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10076: # remove version from map
10077: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10078:
1.210 www 10079: # remove version from URL
10080: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10081:
1.507 www 10082: # remove wrapper
10083:
1.510 www 10084: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10085: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10086: return $symb;
1.409 www 10087: }
10088:
10089: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10090:
10091: sub encode_symb {
10092: my ($map,$resid,$url)=@_;
10093: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10094: }
1.409 www 10095:
10096: sub decode_symb {
1.568 albertel 10097: my $symb=shift;
10098: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10099: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10100: return (&fixversion($map),$resid,&fixversion($url));
10101: }
10102:
10103: sub fixversion {
10104: my $fn=shift;
1.609 banghart 10105: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10106: my %bighash;
10107: my $uri=&clutter($fn);
1.620 albertel 10108: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10109: # is this cached?
1.599 albertel 10110: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10111: if (defined($cached)) { return $result; }
10112: # unfortunately not cached, or expired
1.620 albertel 10113: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10114: &GDBM_READER(),0640)) {
10115: if ($bighash{'version_'.$uri}) {
10116: my $version=$bighash{'version_'.$uri};
1.444 www 10117: unless (($version eq 'mostrecent') ||
10118: ($version==&getversion($uri))) {
1.440 www 10119: $uri=~s/\.(\w+)$/\.$version\.$1/;
10120: }
10121: }
10122: untie %bighash;
1.413 www 10123: }
1.599 albertel 10124: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10125: }
10126:
10127: sub deversion {
10128: my $url=shift;
10129: $url=~s/\.\d+\.(\w+)$/\.$1/;
10130: return $url;
1.210 www 10131: }
10132:
1.31 www 10133: # ------------------------------------------------------ Return symb list entry
10134:
10135: sub symbread {
1.249 www 10136: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 10137: my $cache_str='request.symbread.cached.'.$thisfn;
1.1179 raeburn 10138: if (defined($env{$cache_str})) {
10139: if (($thisfn) || ($env{$cache_str} ne '')) {
10140: return $env{$cache_str};
10141: }
10142: }
1.242 www 10143: # no filename provided? try from environment
1.44 www 10144: unless ($thisfn) {
1.620 albertel 10145: if ($env{'request.symb'}) {
10146: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 10147: }
1.620 albertel 10148: $thisfn=$env{'request.filename'};
1.44 www 10149: }
1.569 albertel 10150: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10151: # is that filename actually a symb? Verify, clean, and return
10152: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10153: if (&symbverify($thisfn,$1)) {
1.620 albertel 10154: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10155: }
1.242 www 10156: }
1.44 www 10157: $thisfn=declutter($thisfn);
1.31 www 10158: my %hash;
1.37 www 10159: my %bighash;
10160: my $syval='';
1.620 albertel 10161: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10162: my $targetfn = $thisfn;
1.609 banghart 10163: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10164: $targetfn = 'adm/wrapper/'.$thisfn;
10165: }
1.687 albertel 10166: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10167: $targetfn=$1;
10168: }
1.620 albertel 10169: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10170: &GDBM_READER(),0640)) {
1.481 raeburn 10171: $syval=$hash{$targetfn};
1.37 www 10172: untie(%hash);
10173: }
10174: # ---------------------------------------------------------- There was an entry
10175: if ($syval) {
1.601 albertel 10176: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10177: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10178: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10179: #return $env{$cache_str}='';
1.601 albertel 10180: #}
10181: #$syval.=$1;
10182: #}
1.37 www 10183: } else {
10184: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10185: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10186: &GDBM_READER(),0640)) {
1.37 www 10187: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10188: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10189: unless ($ids) {
10190: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10191: }
10192: unless ($ids) {
10193: # alias?
10194: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10195: }
1.37 www 10196: if ($ids) {
10197: # ------------------------------------------------------------------- Has ID(s)
10198: my @possibilities=split(/\,/,$ids);
1.39 www 10199: if ($#possibilities==0) {
10200: # ----------------------------------------------- There is only one possibility
1.37 www 10201: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10202: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10203: $resid,$thisfn);
1.249 www 10204: } elsif (!$donotrecurse) {
1.39 www 10205: # ------------------------------------------ There is more than one possibility
10206: my $realpossible=0;
1.800 albertel 10207: foreach my $id (@possibilities) {
10208: my $file=$bighash{'src_'.$id};
1.39 www 10209: if (&allowed('bre',$file)) {
1.800 albertel 10210: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10211: if ($bighash{'map_type_'.$mapid} ne 'page') {
10212: $realpossible++;
1.626 albertel 10213: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10214: $resid,$thisfn);
1.39 www 10215: }
10216: }
1.191 harris41 10217: }
1.39 www 10218: if ($realpossible!=1) { $syval=''; }
1.249 www 10219: } else {
10220: $syval='';
1.37 www 10221: }
10222: }
10223: untie(%bighash)
1.481 raeburn 10224: }
1.31 www 10225: }
1.62 www 10226: if ($syval) {
1.620 albertel 10227: return $env{$cache_str}=$syval;
1.62 www 10228: }
1.31 www 10229: }
1.949 raeburn 10230: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10231: return $env{$cache_str}='';
1.31 www 10232: }
10233:
10234: # ---------------------------------------------------------- Return random seed
10235:
1.32 www 10236: sub numval {
10237: my $txt=shift;
10238: $txt=~tr/A-J/0-9/;
10239: $txt=~tr/a-j/0-9/;
10240: $txt=~tr/K-T/0-9/;
10241: $txt=~tr/k-t/0-9/;
10242: $txt=~tr/U-Z/0-5/;
10243: $txt=~tr/u-z/0-5/;
10244: $txt=~s/\D//g;
1.564 albertel 10245: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10246: return int($txt);
1.368 albertel 10247: }
10248:
1.484 albertel 10249: sub numval2 {
10250: my $txt=shift;
10251: $txt=~tr/A-J/0-9/;
10252: $txt=~tr/a-j/0-9/;
10253: $txt=~tr/K-T/0-9/;
10254: $txt=~tr/k-t/0-9/;
10255: $txt=~tr/U-Z/0-5/;
10256: $txt=~tr/u-z/0-5/;
10257: $txt=~s/\D//g;
10258: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10259: my $total;
10260: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10261: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10262: return int($total);
10263: }
10264:
1.575 albertel 10265: sub numval3 {
10266: use integer;
10267: my $txt=shift;
10268: $txt=~tr/A-J/0-9/;
10269: $txt=~tr/a-j/0-9/;
10270: $txt=~tr/K-T/0-9/;
10271: $txt=~tr/k-t/0-9/;
10272: $txt=~tr/U-Z/0-5/;
10273: $txt=~tr/u-z/0-5/;
10274: $txt=~s/\D//g;
10275: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10276: my $total;
10277: foreach my $val (@txts) { $total+=$val; }
10278: if ($_64bit) { $total=(($total<<32)>>32); }
10279: return $total;
10280: }
10281:
1.675 albertel 10282: sub digest {
10283: my ($data)=@_;
10284: my $digest=&Digest::MD5::md5($data);
10285: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10286: my ($e,$f);
10287: {
10288: use integer;
10289: $e=($a+$b);
10290: $f=($c+$d);
10291: if ($_64bit) {
10292: $e=(($e<<32)>>32);
10293: $f=(($f<<32)>>32);
10294: }
10295: }
10296: if (wantarray) {
10297: return ($e,$f);
10298: } else {
10299: my $g;
10300: {
10301: use integer;
10302: $g=($e+$f);
10303: if ($_64bit) {
10304: $g=(($g<<32)>>32);
10305: }
10306: }
10307: return $g;
10308: }
10309: }
10310:
1.368 albertel 10311: sub latest_rnd_algorithm_id {
1.675 albertel 10312: return '64bit5';
1.366 albertel 10313: }
1.32 www 10314:
1.503 albertel 10315: sub get_rand_alg {
10316: my ($courseid)=@_;
1.790 albertel 10317: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 10318: if ($courseid) {
1.620 albertel 10319: return $env{"course.$courseid.rndseed"};
1.503 albertel 10320: }
10321: return &latest_rnd_algorithm_id();
10322: }
10323:
1.562 albertel 10324: sub validCODE {
10325: my ($CODE)=@_;
10326: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10327: return 0;
10328: }
10329:
1.491 albertel 10330: sub getCODE {
1.620 albertel 10331: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 10332: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10333: defined($Apache::lonhomework::parsing_a_task) ) &&
10334: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 10335: return $Apache::lonhomework::history{'resource.CODE'};
10336: }
10337: return undef;
10338: }
1.1133 foxr 10339: #
10340: # Determines the random seed for a specific context:
10341: #
10342: # parameters:
10343: # symb - in course context the symb for the seed.
10344: # course_id - The course id of the form domain_coursenum.
10345: # domain - Domain for the user.
10346: # course - Course for the user.
10347: # cenv - environment of the course.
10348: #
10349: # NOTE:
10350: # All parameters are picked out of the environment if missing
10351: # or not defined.
10352: # If a symb cannot be determined the current time is used instead.
10353: #
10354: # For a given well defined symb, courside, domain, username,
10355: # and course environment, the seed is reproducible.
10356: #
1.31 www 10357: sub rndseed {
1.1133 foxr 10358: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 10359: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 10360: if (!defined($symb)) {
1.366 albertel 10361: unless ($symb=$wsymb) { return time; }
10362: }
1.1146 foxr 10363: if (!defined $courseid) {
10364: $courseid=$wcourseid;
10365: }
10366: if (!defined $domain) { $domain=$wdomain; }
10367: if (!defined $username) { $username=$wusername }
1.1133 foxr 10368:
10369: my $which;
10370: if (defined($cenv->{'rndseed'})) {
10371: $which = $cenv->{'rndseed'};
10372: } else {
10373: $which =&get_rand_alg($courseid);
10374: }
1.491 albertel 10375: if (defined(&getCODE())) {
1.1133 foxr 10376:
1.675 albertel 10377: if ($which eq '64bit5') {
10378: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10379: } elsif ($which eq '64bit4') {
1.575 albertel 10380: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10381: } else {
10382: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10383: }
1.675 albertel 10384: } elsif ($which eq '64bit5') {
10385: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 10386: } elsif ($which eq '64bit4') {
10387: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 10388: } elsif ($which eq '64bit3') {
10389: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 10390: } elsif ($which eq '64bit2') {
10391: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 10392: } elsif ($which eq '64bit') {
10393: return &rndseed_64bit($symb,$courseid,$domain,$username);
10394: }
10395: return &rndseed_32bit($symb,$courseid,$domain,$username);
10396: }
10397:
10398: sub rndseed_32bit {
10399: my ($symb,$courseid,$domain,$username)=@_;
10400: {
10401: use integer;
10402: my $symbchck=unpack("%32C*",$symb) << 27;
10403: my $symbseed=numval($symb) << 22;
10404: my $namechck=unpack("%32C*",$username) << 17;
10405: my $nameseed=numval($username) << 12;
10406: my $domainseed=unpack("%32C*",$domain) << 7;
10407: my $courseseed=unpack("%32C*",$courseid);
10408: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 10409: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10410: #&logthis("rndseed :$num:$symb");
1.564 albertel 10411: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 10412: return $num;
10413: }
10414: }
10415:
10416: sub rndseed_64bit {
10417: my ($symb,$courseid,$domain,$username)=@_;
10418: {
10419: use integer;
10420: my $symbchck=unpack("%32S*",$symb) << 21;
10421: my $symbseed=numval($symb) << 10;
10422: my $namechck=unpack("%32S*",$username);
10423:
10424: my $nameseed=numval($username) << 21;
10425: my $domainseed=unpack("%32S*",$domain) << 10;
10426: my $courseseed=unpack("%32S*",$courseid);
10427:
10428: my $num1=$symbchck+$symbseed+$namechck;
10429: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10430: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10431: #&logthis("rndseed :$num:$symb");
1.564 albertel 10432: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 10433: return "$num1,$num2";
1.155 albertel 10434: }
1.366 albertel 10435: }
10436:
1.443 albertel 10437: sub rndseed_64bit2 {
10438: my ($symb,$courseid,$domain,$username)=@_;
10439: {
10440: use integer;
10441: # strings need to be an even # of cahracters long, it it is odd the
10442: # last characters gets thrown away
10443: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10444: my $symbseed=numval($symb) << 10;
10445: my $namechck=unpack("%32S*",$username.' ');
10446:
10447: my $nameseed=numval($username) << 21;
1.501 albertel 10448: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10449: my $courseseed=unpack("%32S*",$courseid.' ');
10450:
10451: my $num1=$symbchck+$symbseed+$namechck;
10452: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10453: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10454: #&logthis("rndseed :$num:$symb");
1.803 albertel 10455: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 10456: return "$num1,$num2";
10457: }
10458: }
10459:
10460: sub rndseed_64bit3 {
10461: my ($symb,$courseid,$domain,$username)=@_;
10462: {
10463: use integer;
10464: # strings need to be an even # of cahracters long, it it is odd the
10465: # last characters gets thrown away
10466: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10467: my $symbseed=numval2($symb) << 10;
10468: my $namechck=unpack("%32S*",$username.' ');
10469:
10470: my $nameseed=numval2($username) << 21;
1.443 albertel 10471: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10472: my $courseseed=unpack("%32S*",$courseid.' ');
10473:
10474: my $num1=$symbchck+$symbseed+$namechck;
10475: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10476: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10477: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 10478: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 10479:
1.503 albertel 10480: return "$num1:$num2";
1.443 albertel 10481: }
10482: }
10483:
1.575 albertel 10484: sub rndseed_64bit4 {
10485: my ($symb,$courseid,$domain,$username)=@_;
10486: {
10487: use integer;
10488: # strings need to be an even # of cahracters long, it it is odd the
10489: # last characters gets thrown away
10490: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10491: my $symbseed=numval3($symb) << 10;
10492: my $namechck=unpack("%32S*",$username.' ');
10493:
10494: my $nameseed=numval3($username) << 21;
10495: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10496: my $courseseed=unpack("%32S*",$courseid.' ');
10497:
10498: my $num1=$symbchck+$symbseed+$namechck;
10499: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10500: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10501: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 10502: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 10503:
1.575 albertel 10504: return "$num1:$num2";
10505: }
10506: }
10507:
1.675 albertel 10508: sub rndseed_64bit5 {
10509: my ($symb,$courseid,$domain,$username)=@_;
10510: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10511: return "$num1:$num2";
10512: }
10513:
1.366 albertel 10514: sub rndseed_CODE_64bit {
10515: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 10516: {
1.366 albertel 10517: use integer;
1.443 albertel 10518: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 10519: my $symbseed=numval2($symb);
1.491 albertel 10520: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10521: my $CODEseed=numval(&getCODE());
1.443 albertel 10522: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 10523: my $num1=$symbseed+$CODEchck;
10524: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 10525: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10526: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 10527: if ($_64bit) { $num1=(($num1<<32)>>32); }
10528: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 10529: return "$num1:$num2";
1.366 albertel 10530: }
10531: }
10532:
1.575 albertel 10533: sub rndseed_CODE_64bit4 {
10534: my ($symb,$courseid,$domain,$username)=@_;
10535: {
10536: use integer;
10537: my $symbchck=unpack("%32S*",$symb.' ') << 16;
10538: my $symbseed=numval3($symb);
10539: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10540: my $CODEseed=numval3(&getCODE());
10541: my $courseseed=unpack("%32S*",$courseid.' ');
10542: my $num1=$symbseed+$CODEchck;
10543: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 10544: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10545: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 10546: if ($_64bit) { $num1=(($num1<<32)>>32); }
10547: if ($_64bit) { $num2=(($num2<<32)>>32); }
10548: return "$num1:$num2";
10549: }
10550: }
10551:
1.675 albertel 10552: sub rndseed_CODE_64bit5 {
10553: my ($symb,$courseid,$domain,$username)=@_;
10554: my $code = &getCODE();
10555: my ($num1,$num2)=&digest("$symb,$courseid,$code");
10556: return "$num1:$num2";
10557: }
10558:
1.366 albertel 10559: sub setup_random_from_rndseed {
10560: my ($rndseed)=@_;
1.503 albertel 10561: if ($rndseed =~/([,:])/) {
10562: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 10563: &Math::Random::random_set_seed(abs($num1),abs($num2));
10564: } else {
10565: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 10566: }
1.36 albertel 10567: }
10568:
1.474 albertel 10569: sub latest_receipt_algorithm_id {
1.835 albertel 10570: return 'receipt3';
1.474 albertel 10571: }
10572:
1.480 www 10573: sub recunique {
10574: my $fucourseid=shift;
10575: my $unique;
1.835 albertel 10576: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10577: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 10578: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 10579: } else {
10580: $unique=$perlvar{'lonReceipt'};
10581: }
10582: return unpack("%32C*",$unique);
10583: }
10584:
10585: sub recprefix {
10586: my $fucourseid=shift;
10587: my $prefix;
1.835 albertel 10588: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10589: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 10590: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 10591: } else {
10592: $prefix=$perlvar{'lonHostID'};
10593: }
10594: return unpack("%32C*",$prefix);
10595: }
10596:
1.76 www 10597: sub ireceipt {
1.474 albertel 10598: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 10599:
10600: my $return =&recprefix($fucourseid).'-';
10601:
10602: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10603: $env{'request.state'} eq 'construct') {
10604: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10605: return $return;
10606: }
10607:
1.76 www 10608: my $cuname=unpack("%32C*",$funame);
10609: my $cudom=unpack("%32C*",$fudom);
10610: my $cucourseid=unpack("%32C*",$fucourseid);
10611: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 10612: my $cunique=&recunique($fucourseid);
1.474 albertel 10613: my $cpart=unpack("%32S*",$part);
1.835 albertel 10614: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10615:
1.790 albertel 10616: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 10617:
10618: $return.= ($cunique%$cuname+
10619: $cunique%$cudom+
10620: $cusymb%$cuname+
10621: $cusymb%$cudom+
10622: $cucourseid%$cuname+
10623: $cucourseid%$cudom+
10624: $cpart%$cuname+
10625: $cpart%$cudom);
10626: } else {
10627: $return.= ($cunique%$cuname+
10628: $cunique%$cudom+
10629: $cusymb%$cuname+
10630: $cusymb%$cudom+
10631: $cucourseid%$cuname+
10632: $cucourseid%$cudom);
10633: }
10634: return $return;
1.76 www 10635: }
10636:
10637: sub receipt {
1.474 albertel 10638: my ($part)=@_;
1.790 albertel 10639: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 10640: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 10641: }
1.260 ng 10642:
1.790 albertel 10643: sub whichuser {
10644: my ($passedsymb)=@_;
10645: my ($symb,$courseid,$domain,$name,$publicuser);
10646: if (defined($env{'form.grade_symb'})) {
10647: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10648: my $allowed=&allowed('vgr',$tmp_courseid);
10649: if (!$allowed &&
10650: exists($env{'request.course.sec'}) &&
10651: $env{'request.course.sec'} !~ /^\s*$/) {
10652: $allowed=&allowed('vgr',$tmp_courseid.
10653: '/'.$env{'request.course.sec'});
10654: }
10655: if ($allowed) {
10656: ($symb)=&get_env_multiple('form.grade_symb');
10657: $courseid=$tmp_courseid;
10658: ($domain)=&get_env_multiple('form.grade_domain');
10659: ($name)=&get_env_multiple('form.grade_username');
10660: return ($symb,$courseid,$domain,$name,$publicuser);
10661: }
10662: }
10663: if (!$passedsymb) {
10664: $symb=&symbread();
10665: } else {
10666: $symb=$passedsymb;
10667: }
10668: $courseid=$env{'request.course.id'};
10669: $domain=$env{'user.domain'};
10670: $name=$env{'user.name'};
10671: if ($name eq 'public' && $domain eq 'public') {
10672: if (!defined($env{'form.username'})) {
10673: $env{'form.username'}.=time.rand(10000000);
10674: }
10675: $name.=$env{'form.username'};
10676: }
10677: return ($symb,$courseid,$domain,$name,$publicuser);
10678:
10679: }
10680:
1.36 albertel 10681: # ------------------------------------------------------------ Serves up a file
1.472 albertel 10682: # returns either the contents of the file or
10683: # -1 if the file doesn't exist
1.481 raeburn 10684: #
10685: # if the target is a file that was uploaded via DOCS,
10686: # a check will be made to see if a current copy exists on the local server,
10687: # if it does this will be served, otherwise a copy will be retrieved from
10688: # the home server for the course and stored in /home/httpd/html/userfiles on
10689: # the local server.
1.472 albertel 10690:
1.36 albertel 10691: sub getfile {
1.538 albertel 10692: my ($file) = @_;
1.609 banghart 10693: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 10694: &repcopy($file);
10695: return &readfile($file);
10696: }
10697:
10698: sub repcopy_userfile {
10699: my ($file)=@_;
1.1142 raeburn 10700: my $londocroot = $perlvar{'lonDocRoot'};
10701: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 10702: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 10703: my ($cdom,$cnum,$filename) =
1.811 albertel 10704: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 10705: my $uri="/uploaded/$cdom/$cnum/$filename";
10706: if (-e "$file") {
1.828 www 10707: # we already have a local copy, check it out
1.538 albertel 10708: my @fileinfo = stat($file);
1.828 www 10709: my $rtncode;
10710: my $info;
1.538 albertel 10711: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 10712: if ($lwpresp ne 'ok') {
1.828 www 10713: # there is no such file anymore, even though we had a local copy
1.482 albertel 10714: if ($rtncode eq '404') {
1.538 albertel 10715: unlink($file);
1.482 albertel 10716: }
10717: return -1;
10718: }
10719: if ($info < $fileinfo[9]) {
1.828 www 10720: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 10721: return 'ok';
1.828 www 10722: } else {
10723: # the file is outdated, get rid of it
10724: unlink($file);
1.482 albertel 10725: }
1.828 www 10726: }
10727: # one way or the other, at this point, we don't have the file
10728: # construct the correct path for the file
10729: my @parts = ($cdom,$cnum);
10730: if ($filename =~ m|^(.+)/[^/]+$|) {
10731: push @parts, split(/\//,$1);
10732: }
10733: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10734: foreach my $part (@parts) {
10735: $path .= '/'.$part;
10736: if (!-e $path) {
10737: mkdir($path,0770);
1.482 albertel 10738: }
10739: }
1.828 www 10740: # now the path exists for sure
10741: # get a user agent
10742: my $ua=new LWP::UserAgent;
10743: my $transferfile=$file.'.in.transfer';
10744: # FIXME: this should flock
10745: if (-e $transferfile) { return 'ok'; }
10746: my $request;
10747: $uri=~s/^\///;
1.980 raeburn 10748: my $homeserver = &homeserver($cnum,$cdom);
10749: my $protocol = $protocol{$homeserver};
10750: $protocol = 'http' if ($protocol ne 'https');
10751: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 10752: my $response=$ua->request($request,$transferfile);
10753: # did it work?
10754: if ($response->is_error()) {
10755: unlink($transferfile);
10756: &logthis("Userfile repcopy failed for $uri");
10757: return -1;
10758: }
10759: # worked, rename the transfer file
10760: rename($transferfile,$file);
1.607 raeburn 10761: return 'ok';
1.481 raeburn 10762: }
10763:
1.517 albertel 10764: sub tokenwrapper {
10765: my $uri=shift;
1.980 raeburn 10766: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 10767: $uri=~s|^/||;
1.620 albertel 10768: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 10769: my $token=$1;
1.552 albertel 10770: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10771: if ($udom && $uname && $file) {
10772: $file=~s|(\?\.*)*$||;
1.949 raeburn 10773: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 10774: my $homeserver = &homeserver($uname,$udom);
10775: my $protocol = $protocol{$homeserver};
10776: $protocol = 'http' if ($protocol ne 'https');
10777: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 10778: (($uri=~/\?/)?'&':'?').'token='.$token.
10779: '&tokenissued='.$perlvar{'lonHostID'};
10780: } else {
10781: return '/adm/notfound.html';
10782: }
10783: }
10784:
1.828 www 10785: # call with reqtype HEAD: get last modification time
10786: # call with reqtype GET: get the file contents
10787: # Do not call this with reqtype GET for large files! It loads everything into memory
10788: #
1.481 raeburn 10789: sub getuploaded {
10790: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10791: $uri=~s/^\///;
1.980 raeburn 10792: my $homeserver = &homeserver($cnum,$cdom);
10793: my $protocol = $protocol{$homeserver};
10794: $protocol = 'http' if ($protocol ne 'https');
10795: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 10796: my $ua=new LWP::UserAgent;
10797: my $request=new HTTP::Request($reqtype,$uri);
10798: my $response=$ua->request($request);
10799: $$rtncode = $response->code;
1.482 albertel 10800: if (! $response->is_success()) {
10801: return 'failed';
10802: }
10803: if ($reqtype eq 'HEAD') {
1.486 www 10804: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 10805: } elsif ($reqtype eq 'GET') {
10806: $$info = $response->content;
1.472 albertel 10807: }
1.482 albertel 10808: return 'ok';
1.36 albertel 10809: }
10810:
1.481 raeburn 10811: sub readfile {
10812: my $file = shift;
10813: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10814: my $fh;
10815: open($fh,"<$file");
10816: my $a='';
1.800 albertel 10817: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 10818: return $a;
10819: }
10820:
1.36 albertel 10821: sub filelocation {
1.590 banghart 10822: my ($dir,$file) = @_;
10823: my $location;
10824: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 10825:
10826: if ($file =~ m-^/adm/-) {
10827: $file=~s-^/adm/wrapper/-/-;
10828: $file=~s-^/adm/coursedocs/showdoc/-/-;
10829: }
1.882 albertel 10830:
1.1139 www 10831: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 10832: $location = $file;
1.609 banghart 10833: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 10834: my ($udom,$uname,$filename)=
1.811 albertel 10835: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 10836: my $home=&homeserver($uname,$udom);
10837: my $is_me=0;
10838: my @ids=¤t_machine_ids();
10839: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10840: if ($is_me) {
1.1117 foxr 10841: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 10842: } else {
10843: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10844: $udom.'/'.$uname.'/'.$filename;
10845: }
1.882 albertel 10846: } elsif ($file =~ m-^/adm/-) {
10847: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 10848: } else {
10849: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 10850: $file=~s:^/(res|priv)/:/:;
10851: my $space=$1;
1.590 banghart 10852: if ( !( $file =~ m:^/:) ) {
10853: $location = $dir. '/'.$file;
10854: } else {
1.1142 raeburn 10855: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 10856: }
1.59 albertel 10857: }
1.590 banghart 10858: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 10859: while ($location=~m{/\.\./}) {
10860: if ($location =~ m{/[^/]+/\.\./}) {
10861: $location=~ s{/[^/]+/\.\./}{/}g;
10862: } else {
10863: $location=~ s{/\.\./}{/}g;
10864: }
10865: } #remove dir/..
1.590 banghart 10866: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10867: return $location;
1.46 www 10868: }
1.36 albertel 10869:
1.46 www 10870: sub hreflocation {
10871: my ($dir,$file)=@_;
1.980 raeburn 10872: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 10873: $file=filelocation($dir,$file);
1.700 albertel 10874: } elsif ($file=~m-^/adm/-) {
10875: $file=~s-^/adm/wrapper/-/-;
10876: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 10877: }
10878: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10879: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10880: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 10881: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10882: {/uploaded/$1/$2/}x;
1.46 www 10883: }
1.913 albertel 10884: if ($file=~ m{^/userfiles/}) {
10885: $file =~ s{^/userfiles/}{/uploaded/};
10886: }
1.462 albertel 10887: return $file;
1.465 albertel 10888: }
10889:
1.1139 www 10890:
10891:
10892:
10893:
1.465 albertel 10894: sub current_machine_domains {
1.853 albertel 10895: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10896: }
10897:
10898: sub machine_domains {
10899: my ($hostname) = @_;
1.465 albertel 10900: my @domains;
1.838 albertel 10901: my %hostname = &all_hostnames();
1.465 albertel 10902: while( my($id, $name) = each(%hostname)) {
1.467 matthew 10903: # &logthis("-$id-$name-$hostname-");
1.465 albertel 10904: if ($hostname eq $name) {
1.844 albertel 10905: push(@domains,&host_domain($id));
1.465 albertel 10906: }
10907: }
10908: return @domains;
10909: }
10910:
10911: sub current_machine_ids {
1.853 albertel 10912: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10913: }
10914:
10915: sub machine_ids {
10916: my ($hostname) = @_;
10917: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 10918: my @ids;
1.888 albertel 10919: my %name_to_host = &all_names();
1.889 albertel 10920: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10921: return @{ $name_to_host{$hostname} };
10922: }
10923: return;
1.31 www 10924: }
10925:
1.824 raeburn 10926: sub additional_machine_domains {
10927: my @domains;
10928: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10929: while( my $line = <$fh>) {
10930: $line =~ s/\s//g;
10931: push(@domains,$line);
10932: }
10933: return @domains;
10934: }
10935:
10936: sub default_login_domain {
10937: my $domain = $perlvar{'lonDefDomain'};
10938: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10939: foreach my $posdom (¤t_machine_domains(),
10940: &additional_machine_domains()) {
10941: if (lc($posdom) eq lc($testdomain)) {
10942: $domain=$posdom;
10943: last;
10944: }
10945: }
10946: return $domain;
10947: }
10948:
1.31 www 10949: # ------------------------------------------------------------- Declutters URLs
10950:
10951: sub declutter {
10952: my $thisfn=shift;
1.569 albertel 10953: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 10954: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 10955: $thisfn=~s/^\///;
1.697 albertel 10956: $thisfn=~s|^adm/wrapper/||;
10957: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 10958: $thisfn=~s/^res\///;
1.1172 bisitz 10959: $thisfn=~s/^priv\///;
1.1032 raeburn 10960: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10961: $thisfn=~s/\?.+$//;
10962: }
1.268 www 10963: return $thisfn;
10964: }
10965:
10966: # ------------------------------------------------------------- Clutter up URLs
10967:
10968: sub clutter {
10969: my $thisfn='/'.&declutter(shift);
1.887 albertel 10970: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 10971: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 10972: $thisfn='/res'.$thisfn;
10973: }
1.1031 raeburn 10974: if ($thisfn !~m|^/adm|) {
10975: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 10976: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 10977: } else {
10978: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10979: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 10980: if ($embstyle eq 'ssi'
10981: || ($embstyle eq 'hdn')
10982: || ($embstyle eq 'rat')
10983: || ($embstyle eq 'prv')
10984: || ($embstyle eq 'ign')) {
10985: #do nothing with these
10986: } elsif (($embstyle eq 'img')
1.695 albertel 10987: || ($embstyle eq 'emb')
10988: || ($embstyle eq 'wrp')) {
10989: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 10990: } elsif ($embstyle eq 'unk'
10991: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 10992: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 10993: } else {
1.718 www 10994: # &logthis("Got a blank emb style");
1.695 albertel 10995: }
1.694 albertel 10996: }
10997: }
1.31 www 10998: return $thisfn;
1.12 www 10999: }
11000:
1.787 albertel 11001: sub clutter_with_no_wrapper {
11002: my $uri = &clutter(shift);
11003: if ($uri =~ m-^/adm/-) {
11004: $uri =~ s-^/adm/wrapper/-/-;
11005: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11006: }
11007: return $uri;
11008: }
11009:
1.557 albertel 11010: sub freeze_escape {
11011: my ($value)=@_;
11012: if (ref($value)) {
11013: $value=&nfreeze($value);
11014: return '__FROZEN__'.&escape($value);
11015: }
11016: return &escape($value);
11017: }
11018:
1.11 www 11019:
1.557 albertel 11020: sub thaw_unescape {
11021: my ($value)=@_;
11022: if ($value =~ /^__FROZEN__/) {
11023: substr($value,0,10,undef);
11024: $value=&unescape($value);
11025: return &thaw($value);
11026: }
11027: return &unescape($value);
11028: }
11029:
1.436 albertel 11030: sub correct_line_ends {
11031: my ($result)=@_;
11032: $$result =~s/\r\n/\n/mg;
11033: $$result =~s/\r/\n/mg;
1.415 albertel 11034: }
1.1 albertel 11035: # ================================================================ Main Program
11036:
1.184 www 11037: sub goodbye {
1.204 albertel 11038: &logthis("Starting Shut down");
1.443 albertel 11039: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 11040: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 11041: #converted
1.599 albertel 11042: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 11043: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11044: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11045: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 11046: #1.1 only
1.870 albertel 11047: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11048: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11049: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11050: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11051: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 11052: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11053: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11054: &flushcourselogs();
11055: &logthis("Shutting down");
11056: }
11057:
1.852 albertel 11058: sub get_dns {
1.869 albertel 11059: my ($url,$func,$ignore_cache) = @_;
11060: if (!$ignore_cache) {
11061: my ($content,$cached)=
11062: &Apache::lonnet::is_cached_new('dns',$url);
11063: if ($cached) {
11064: &$func($content);
11065: return;
11066: }
11067: }
11068:
11069: my %alldns;
1.852 albertel 11070: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11071: foreach my $dns (<$config>) {
11072: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11073: my $line = $1;
11074: my ($host,$protocol) = split(/:/,$line);
11075: if ($protocol ne 'https') {
11076: $protocol = 'http';
11077: }
11078: $alldns{$host} = $protocol;
1.869 albertel 11079: }
11080: while (%alldns) {
11081: my ($dns) = keys(%alldns);
1.852 albertel 11082: my $ua=new LWP::UserAgent;
1.1134 raeburn 11083: $ua->timeout(30);
1.979 raeburn 11084: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11085: my $response=$ua->request($request);
1.979 raeburn 11086: delete($alldns{$dns});
1.852 albertel 11087: next if ($response->is_error());
11088: my @content = split("\n",$response->content);
1.869 albertel 11089: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 11090: &$func(\@content);
1.869 albertel 11091: return;
1.852 albertel 11092: }
11093: close($config);
1.871 albertel 11094: my $which = (split('/',$url))[3];
11095: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11096: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11097: my @content = <$config>;
11098: &$func(\@content);
11099: return;
1.852 albertel 11100: }
1.327 albertel 11101: # ------------------------------------------------------------ Read domain file
11102: {
1.852 albertel 11103: my $loaded;
1.846 albertel 11104: my %domain;
11105:
1.852 albertel 11106: sub parse_domain_tab {
11107: my ($lines) = @_;
11108: foreach my $line (@$lines) {
11109: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11110:
1.846 albertel 11111: chomp($line);
1.852 albertel 11112: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11113: my %this_domain;
11114: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11115: 'lang_def', 'city', 'longi', 'lati',
11116: 'primary') {
11117: $this_domain{$field} = shift(@elements);
11118: }
11119: $domain{$name} = \%this_domain;
1.852 albertel 11120: }
11121: }
1.864 albertel 11122:
11123: sub reset_domain_info {
11124: undef($loaded);
11125: undef(%domain);
11126: }
11127:
1.852 albertel 11128: sub load_domain_tab {
1.869 albertel 11129: my ($ignore_cache) = @_;
11130: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11131: my $fh;
11132: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11133: my @lines = <$fh>;
11134: &parse_domain_tab(\@lines);
1.448 albertel 11135: }
1.852 albertel 11136: close($fh);
11137: $loaded = 1;
1.327 albertel 11138: }
1.846 albertel 11139:
11140: sub domain {
1.852 albertel 11141: &load_domain_tab() if (!$loaded);
11142:
1.846 albertel 11143: my ($name,$what) = @_;
11144: return if ( !exists($domain{$name}) );
11145:
11146: if (!$what) {
11147: return $domain{$name}{'description'};
11148: }
11149: return $domain{$name}{$what};
11150: }
1.974 raeburn 11151:
11152: sub domain_info {
11153: &load_domain_tab() if (!$loaded);
11154: return %domain;
11155: }
11156:
1.327 albertel 11157: }
11158:
11159:
1.1 albertel 11160: # ------------------------------------------------------------- Read hosts file
11161: {
1.838 albertel 11162: my %hostname;
1.844 albertel 11163: my %hostdom;
1.845 albertel 11164: my %libserv;
1.852 albertel 11165: my $loaded;
1.888 albertel 11166: my %name_to_host;
1.1074 raeburn 11167: my %internetdom;
1.1107 raeburn 11168: my %LC_dns_serv;
1.852 albertel 11169:
11170: sub parse_hosts_tab {
11171: my ($file) = @_;
11172: foreach my $configline (@$file) {
11173: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11174: chomp($configline);
11175: if ($configline =~ /^\^/) {
11176: if ($configline =~ /^\^([\w.\-]+)/) {
11177: $LC_dns_serv{$1} = 1;
11178: }
11179: next;
11180: }
1.1074 raeburn 11181: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11182: $name=~s/\s//g;
11183: if ($id && $domain && $role && $name) {
11184: $hostname{$id}=$name;
1.888 albertel 11185: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11186: $hostdom{$id}=$domain;
11187: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11188: if (defined($protocol)) {
11189: if ($protocol eq 'https') {
11190: $protocol{$id} = $protocol;
11191: } else {
11192: $protocol{$id} = 'http';
11193: }
1.968 raeburn 11194: } else {
1.969 raeburn 11195: $protocol{$id} = 'http';
1.968 raeburn 11196: }
1.1074 raeburn 11197: if (defined($intdom)) {
11198: $internetdom{$id} = $intdom;
11199: }
1.852 albertel 11200: }
11201: }
11202: }
1.864 albertel 11203:
11204: sub reset_hosts_info {
1.897 albertel 11205: &purge_remembered();
1.864 albertel 11206: &reset_domain_info();
11207: &reset_hosts_ip_info();
1.892 albertel 11208: undef(%name_to_host);
1.864 albertel 11209: undef(%hostname);
11210: undef(%hostdom);
11211: undef(%libserv);
11212: undef($loaded);
11213: }
1.1 albertel 11214:
1.852 albertel 11215: sub load_hosts_tab {
1.869 albertel 11216: my ($ignore_cache) = @_;
11217: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11218: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11219: my @config = <$config>;
11220: &parse_hosts_tab(\@config);
11221: close($config);
11222: $loaded=1;
1.1 albertel 11223: }
1.852 albertel 11224:
1.838 albertel 11225: sub hostname {
1.852 albertel 11226: &load_hosts_tab() if (!$loaded);
11227:
1.838 albertel 11228: my ($lonid) = @_;
11229: return $hostname{$lonid};
11230: }
1.845 albertel 11231:
1.838 albertel 11232: sub all_hostnames {
1.852 albertel 11233: &load_hosts_tab() if (!$loaded);
11234:
1.838 albertel 11235: return %hostname;
11236: }
1.845 albertel 11237:
1.888 albertel 11238: sub all_names {
11239: &load_hosts_tab() if (!$loaded);
11240:
11241: return %name_to_host;
11242: }
11243:
1.974 raeburn 11244: sub all_host_domain {
11245: &load_hosts_tab() if (!$loaded);
11246: return %hostdom;
11247: }
11248:
1.845 albertel 11249: sub is_library {
1.852 albertel 11250: &load_hosts_tab() if (!$loaded);
11251:
1.845 albertel 11252: return exists($libserv{$_[0]});
11253: }
11254:
11255: sub all_library {
1.852 albertel 11256: &load_hosts_tab() if (!$loaded);
11257:
1.845 albertel 11258: return %libserv;
11259: }
11260:
1.1062 droeschl 11261: sub unique_library {
11262: #2x reverse removes all hostnames that appear more than once
11263: my %unique = reverse &all_library();
11264: return reverse %unique;
11265: }
11266:
1.841 albertel 11267: sub get_servers {
1.852 albertel 11268: &load_hosts_tab() if (!$loaded);
11269:
1.841 albertel 11270: my ($domain,$type) = @_;
11271: my %possible_hosts = ($type eq 'library') ? %libserv
11272: : %hostname;
11273: my %result;
1.842 albertel 11274: if (ref($domain) eq 'ARRAY') {
11275: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 11276: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 11277: $result{$host} = $hostname;
11278: }
11279: }
11280: } else {
11281: while ( my ($host,$hostname) = each(%possible_hosts)) {
11282: if ($hostdom{$host} eq $domain) {
11283: $result{$host} = $hostname;
11284: }
1.841 albertel 11285: }
11286: }
11287: return %result;
11288: }
1.845 albertel 11289:
1.1062 droeschl 11290: sub get_unique_servers {
11291: my %unique = reverse &get_servers(@_);
11292: return reverse %unique;
11293: }
11294:
1.844 albertel 11295: sub host_domain {
1.852 albertel 11296: &load_hosts_tab() if (!$loaded);
11297:
1.844 albertel 11298: my ($lonid) = @_;
11299: return $hostdom{$lonid};
11300: }
11301:
1.841 albertel 11302: sub all_domains {
1.852 albertel 11303: &load_hosts_tab() if (!$loaded);
11304:
1.841 albertel 11305: my %seen;
11306: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11307: return @uniq;
11308: }
1.1074 raeburn 11309:
11310: sub internet_dom {
11311: &load_hosts_tab() if (!$loaded);
11312:
11313: my ($lonid) = @_;
11314: return $internetdom{$lonid};
11315: }
1.1107 raeburn 11316:
11317: sub is_LC_dns {
11318: &load_hosts_tab() if (!$loaded);
11319:
11320: my ($hostname) = @_;
11321: return exists($LC_dns_serv{$hostname});
11322: }
11323:
1.1 albertel 11324: }
11325:
1.847 albertel 11326: {
11327: my %iphost;
1.856 albertel 11328: my %name_to_ip;
11329: my %lonid_to_ip;
1.869 albertel 11330:
1.847 albertel 11331: sub get_hosts_from_ip {
11332: my ($ip) = @_;
11333: my %iphosts = &get_iphost();
11334: if (ref($iphosts{$ip})) {
11335: return @{$iphosts{$ip}};
11336: }
11337: return;
1.839 albertel 11338: }
1.864 albertel 11339:
11340: sub reset_hosts_ip_info {
11341: undef(%iphost);
11342: undef(%name_to_ip);
11343: undef(%lonid_to_ip);
11344: }
1.856 albertel 11345:
11346: sub get_host_ip {
11347: my ($lonid) = @_;
11348: if (exists($lonid_to_ip{$lonid})) {
11349: return $lonid_to_ip{$lonid};
11350: }
11351: my $name=&hostname($lonid);
11352: my $ip = gethostbyname($name);
11353: return if (!$ip || length($ip) ne 4);
11354: $ip=inet_ntoa($ip);
11355: $name_to_ip{$name} = $ip;
11356: $lonid_to_ip{$lonid} = $ip;
11357: return $ip;
11358: }
1.847 albertel 11359:
11360: sub get_iphost {
1.869 albertel 11361: my ($ignore_cache) = @_;
1.894 albertel 11362:
1.869 albertel 11363: if (!$ignore_cache) {
11364: if (%iphost) {
11365: return %iphost;
11366: }
11367: my ($ip_info,$cached)=
11368: &Apache::lonnet::is_cached_new('iphost','iphost');
11369: if ($cached) {
11370: %iphost = %{$ip_info->[0]};
11371: %name_to_ip = %{$ip_info->[1]};
11372: %lonid_to_ip = %{$ip_info->[2]};
11373: return %iphost;
11374: }
11375: }
1.894 albertel 11376:
11377: # get yesterday's info for fallback
11378: my %old_name_to_ip;
11379: my ($ip_info,$cached)=
11380: &Apache::lonnet::is_cached_new('iphost','iphost');
11381: if ($cached) {
11382: %old_name_to_ip = %{$ip_info->[1]};
11383: }
11384:
1.888 albertel 11385: my %name_to_host = &all_names();
11386: foreach my $name (keys(%name_to_host)) {
1.847 albertel 11387: my $ip;
11388: if (!exists($name_to_ip{$name})) {
11389: $ip = gethostbyname($name);
11390: if (!$ip || length($ip) ne 4) {
1.894 albertel 11391: if (defined($old_name_to_ip{$name})) {
11392: $ip = $old_name_to_ip{$name};
11393: &logthis("Can't find $name defaulting to old $ip");
11394: } else {
11395: &logthis("Name $name no IP found");
11396: next;
11397: }
11398: } else {
11399: $ip=inet_ntoa($ip);
1.847 albertel 11400: }
11401: $name_to_ip{$name} = $ip;
11402: } else {
11403: $ip = $name_to_ip{$name};
1.653 albertel 11404: }
1.888 albertel 11405: foreach my $id (@{ $name_to_host{$name} }) {
11406: $lonid_to_ip{$id} = $ip;
11407: }
11408: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 11409: }
1.869 albertel 11410: &Apache::lonnet::do_cache_new('iphost','iphost',
11411: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 11412: 48*60*60);
1.869 albertel 11413:
1.847 albertel 11414: return %iphost;
1.598 albertel 11415: }
11416:
1.992 raeburn 11417: #
11418: # Given a DNS returns the loncapa host name for that DNS
11419: #
11420: sub host_from_dns {
11421: my ($dns) = @_;
11422: my @hosts;
11423: my $ip;
11424:
1.993 raeburn 11425: if (exists($name_to_ip{$dns})) {
1.992 raeburn 11426: $ip = $name_to_ip{$dns};
11427: }
11428: if (!$ip) {
11429: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11430: if (length($ip) == 4) {
11431: $ip = &IO::Socket::inet_ntoa($ip);
11432: }
11433: }
11434: if ($ip) {
11435: @hosts = get_hosts_from_ip($ip);
11436: return $hosts[0];
11437: }
11438: return undef;
1.986 foxr 11439: }
1.992 raeburn 11440:
1.1074 raeburn 11441: sub get_internet_names {
11442: my ($lonid) = @_;
11443: return if ($lonid eq '');
11444: my ($idnref,$cached)=
11445: &Apache::lonnet::is_cached_new('internetnames',$lonid);
11446: if ($cached) {
11447: return $idnref;
11448: }
11449: my $ip = &get_host_ip($lonid);
11450: my @hosts = &get_hosts_from_ip($ip);
11451: my %iphost = &get_iphost();
11452: my (@idns,%seen);
11453: foreach my $id (@hosts) {
11454: my $dom = &host_domain($id);
11455: my $prim_id = &domain($dom,'primary');
11456: my $prim_ip = &get_host_ip($prim_id);
11457: next if ($seen{$prim_ip});
11458: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11459: foreach my $id (@{$iphost{$prim_ip}}) {
11460: my $intdom = &internet_dom($id);
11461: unless (grep(/^\Q$intdom\E$/,@idns)) {
11462: push(@idns,$intdom);
11463: }
11464: }
11465: }
11466: $seen{$prim_ip} = 1;
11467: }
11468: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11469: }
11470:
1.986 foxr 11471: }
11472:
1.1079 raeburn 11473: sub all_loncaparevs {
11474: 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);
11475: }
11476:
1.862 albertel 11477: BEGIN {
11478:
11479: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11480: unless ($readit) {
11481: {
11482: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11483: %perlvar = (%perlvar,%{$configvars});
11484: }
11485:
11486:
1.1 albertel 11487: # ------------------------------------------------------ Read spare server file
11488: {
1.448 albertel 11489: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 11490:
11491: while (my $configline=<$config>) {
11492: chomp($configline);
1.284 matthew 11493: if ($configline) {
1.784 albertel 11494: my ($host,$type) = split(':',$configline,2);
1.785 albertel 11495: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 11496: push(@{ $spareid{$type} }, $host);
1.1 albertel 11497: }
11498: }
1.448 albertel 11499: close($config);
1.1 albertel 11500: }
1.11 www 11501: # ------------------------------------------------------------ Read permissions
11502: {
1.448 albertel 11503: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 11504:
11505: while (my $configline=<$config>) {
1.448 albertel 11506: chomp($configline);
11507: if ($configline) {
11508: my ($role,$perm)=split(/ /,$configline);
11509: if ($perm ne '') { $pr{$role}=$perm; }
11510: }
1.11 www 11511: }
1.448 albertel 11512: close($config);
1.11 www 11513: }
11514:
11515: # -------------------------------------------- Read plain texts for permissions
11516: {
1.448 albertel 11517: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 11518:
11519: while (my $configline=<$config>) {
1.448 albertel 11520: chomp($configline);
11521: if ($configline) {
1.742 raeburn 11522: my ($short,@plain)=split(/:/,$configline);
11523: %{$prp{$short}} = ();
11524: if (@plain > 0) {
11525: $prp{$short}{'std'} = $plain[0];
11526: for (my $i=1; $i<@plain; $i++) {
11527: $prp{$short}{'alt'.$i} = $plain[$i];
11528: }
11529: }
1.448 albertel 11530: }
1.135 www 11531: }
1.448 albertel 11532: close($config);
1.135 www 11533: }
11534:
11535: # ---------------------------------------------------------- Read package table
11536: {
1.448 albertel 11537: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 11538:
11539: while (my $configline=<$config>) {
1.483 albertel 11540: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 11541: chomp($configline);
11542: my ($short,$plain)=split(/:/,$configline);
11543: my ($pack,$name)=split(/\&/,$short);
11544: if ($plain ne '') {
11545: $packagetab{$pack.'&'.$name.'&name'}=$name;
11546: $packagetab{$short}=$plain;
11547: }
1.11 www 11548: }
1.448 albertel 11549: close($config);
1.329 matthew 11550: }
11551:
1.1073 raeburn 11552: # ---------------------------------------------------------- Read loncaparev table
11553: {
11554: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11555: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11556: while (my $configline=<$config>) {
11557: chomp($configline);
11558: my ($hostid,$loncaparev)=split(/:/,$configline);
11559: $loncaparevs{$hostid}=$loncaparev;
11560: }
11561: close($config);
11562: }
11563: }
11564: }
11565:
1.1074 raeburn 11566: # ---------------------------------------------------------- Read serverhostID table
11567: {
11568: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11569: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11570: while (my $configline=<$config>) {
11571: chomp($configline);
11572: my ($name,$id)=split(/:/,$configline);
11573: $serverhomeIDs{$name}=$id;
11574: }
11575: close($config);
11576: }
11577: }
11578: }
11579:
1.1079 raeburn 11580: {
11581: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11582: if (-e $file) {
11583: my $parser = HTML::LCParser->new($file);
11584: while (my $token = $parser->get_token()) {
11585: if ($token->[0] eq 'S') {
11586: my $item = $token->[1];
11587: my $name = $token->[2]{'name'};
11588: my $value = $token->[2]{'value'};
11589: if ($item ne '' && $name ne '' && $value ne '') {
11590: my $release = $parser->get_text();
11591: $release =~ s/(^\s*|\s*$ )//gx;
11592: $needsrelease{$item.':'.$name.':'.$value} = $release;
11593: }
11594: }
11595: }
11596: }
1.1073 raeburn 11597: }
11598:
1.1138 raeburn 11599: # ---------------------------------------------------------- Read managers table
11600: {
11601: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11602: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11603: while (my $configline=<$config>) {
11604: chomp($configline);
11605: next if ($configline =~ /^\#/);
11606: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11607: $managerstab{$configline} = 1;
11608: }
11609: }
11610: close($config);
11611: }
11612: }
11613: }
11614:
1.329 matthew 11615: # ------------- set up temporary directory
11616: {
1.1117 foxr 11617: $tmpdir = LONCAPA::tempdir();
1.329 matthew 11618:
1.11 www 11619: }
11620:
1.794 albertel 11621: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
11622: 'compress_threshold'=> 20_000,
11623: });
1.185 www 11624:
1.281 www 11625: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 11626: $dumpcount=0;
1.958 www 11627: $locknum=0;
1.22 www 11628:
1.163 harris41 11629: &logtouch();
1.672 albertel 11630: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 11631: $readit=1;
1.564 albertel 11632: {
11633: use integer;
11634: my $test=(2**32)+1;
1.568 albertel 11635: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 11636: &logthis(" Detected 64bit platform ($_64bit)");
11637: }
1.195 www 11638: }
1.1 albertel 11639: }
1.179 www 11640:
1.1 albertel 11641: 1;
1.191 harris41 11642: __END__
11643:
1.243 albertel 11644: =pod
11645:
1.191 harris41 11646: =head1 NAME
11647:
1.243 albertel 11648: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 11649:
11650: =head1 SYNOPSIS
11651:
1.243 albertel 11652: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 11653:
11654: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11655:
1.243 albertel 11656: Common parameters:
11657:
11658: =over 4
11659:
11660: =item *
11661:
11662: $uname : an internal username (if $cname expecting a course Id specifically)
11663:
11664: =item *
11665:
11666: $udom : a domain (if $cdom expecting a course's domain specifically)
11667:
11668: =item *
11669:
11670: $symb : a resource instance identifier
11671:
11672: =item *
11673:
11674: $namespace : the name of a .db file that contains the data needed or
11675: being set.
11676:
11677: =back
11678:
1.394 bowersj2 11679: =head1 OVERVIEW
1.191 harris41 11680:
1.394 bowersj2 11681: lonnet provides subroutines which interact with the
11682: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11683: about classes, users, and resources.
1.243 albertel 11684:
11685: For many of these objects you can also use this to store data about
11686: them or modify them in various ways.
1.191 harris41 11687:
1.394 bowersj2 11688: =head2 Symbs
1.191 harris41 11689:
1.394 bowersj2 11690: To identify a specific instance of a resource, LON-CAPA uses symbols
11691: or "symbs"X<symb>. These identifiers are built from the URL of the
11692: map, the resource number of the resource in the map, and the URL of
11693: the resource itself. The latter is somewhat redundant, but might help
11694: if maps change.
11695:
11696: An example is
11697:
11698: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11699:
11700: The respective map entry is
11701:
11702: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11703: title="Problem 2">
11704: </resource>
11705:
11706: Symbs are used by the random number generator, as well as to store and
11707: restore data specific to a certain instance of for example a problem.
11708:
11709: =head2 Storing And Retrieving Data
11710:
11711: X<store()>X<cstore()>X<restore()>Three of the most important functions
11712: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11713: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11714: is is the non-critical message twin of cstore. These functions are for
11715: handlers to store a perl hash to a user's permanent data space in an
11716: easy manner, and to retrieve it again on another call. It is expected
11717: that a handler would use this once at the beginning to retrieve data,
11718: and then again once at the end to send only the new data back.
11719:
11720: The data is stored in the user's data directory on the user's
11721: homeserver under the ID of the course.
11722:
11723: The hash that is returned by restore will have all of the previous
11724: value for all of the elements of the hash.
11725:
11726: Example:
11727:
11728: #creating a hash
11729: my %hash;
11730: $hash{'foo'}='bar';
11731:
11732: #storing it
11733: &Apache::lonnet::cstore(\%hash);
11734:
11735: #changing a value
11736: $hash{'foo'}='notbar';
11737:
11738: #adding a new value
11739: $hash{'bar'}='foo';
11740: &Apache::lonnet::cstore(\%hash);
11741:
11742: #retrieving the hash
11743: my %history=&Apache::lonnet::restore();
11744:
11745: #print the hash
11746: foreach my $key (sort(keys(%history))) {
11747: print("\%history{$key} = $history{$key}");
11748: }
11749:
11750: Will print out:
1.191 harris41 11751:
1.394 bowersj2 11752: %history{1:foo} = bar
11753: %history{1:keys} = foo:timestamp
11754: %history{1:timestamp} = 990455579
11755: %history{2:bar} = foo
11756: %history{2:foo} = notbar
11757: %history{2:keys} = foo:bar:timestamp
11758: %history{2:timestamp} = 990455580
11759: %history{bar} = foo
11760: %history{foo} = notbar
11761: %history{timestamp} = 990455580
11762: %history{version} = 2
11763:
11764: Note that the special hash entries C<keys>, C<version> and
11765: C<timestamp> were added to the hash. C<version> will be equal to the
11766: total number of versions of the data that have been stored. The
11767: C<timestamp> attribute will be the UNIX time the hash was
11768: stored. C<keys> is available in every historical section to list which
11769: keys were added or changed at a specific historical revision of a
11770: hash.
11771:
11772: B<Warning>: do not store the hash that restore returns directly. This
11773: will cause a mess since it will restore the historical keys as if the
11774: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 11775:
1.394 bowersj2 11776: Calling convention:
1.191 harris41 11777:
1.394 bowersj2 11778: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11779: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 11780:
1.394 bowersj2 11781: For more detailed information, see lonnet specific documentation.
1.191 harris41 11782:
1.394 bowersj2 11783: =head1 RETURN MESSAGES
1.191 harris41 11784:
1.394 bowersj2 11785: =over 4
1.191 harris41 11786:
1.394 bowersj2 11787: =item * B<con_lost>: unable to contact remote host
1.191 harris41 11788:
1.394 bowersj2 11789: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11790: when the connection is brought back up
1.191 harris41 11791:
1.394 bowersj2 11792: =item * B<con_failed>: unable to contact remote host and unable to save message
11793: for later delivery
1.191 harris41 11794:
1.967 bisitz 11795: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 11796:
1.394 bowersj2 11797: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 11798: that was requested
1.191 harris41 11799:
1.243 albertel 11800: =back
1.191 harris41 11801:
1.243 albertel 11802: =head1 PUBLIC SUBROUTINES
1.191 harris41 11803:
1.243 albertel 11804: =head2 Session Environment Functions
1.191 harris41 11805:
1.243 albertel 11806: =over 4
1.191 harris41 11807:
1.394 bowersj2 11808: =item *
11809: X<appenv()>
1.949 raeburn 11810: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 11811: the user envirnoment file, and will be restored for each access this
1.620 albertel 11812: user makes during this session, also modifies the %env for the current
1.949 raeburn 11813: process. Optional rolesarrayref - if defined contains a reference to an array
11814: of roles which are exempt from the restriction on modifying user.role entries
11815: in the user's environment.db and in %env.
1.191 harris41 11816:
11817: =item *
1.394 bowersj2 11818: X<delenv()>
1.987 raeburn 11819: B<delenv($delthis,$regexp)>: removes all items from the session
11820: environment file that begin with $delthis. If the
11821: optional second arg - $regexp - is true, $delthis is treated as a
11822: regular expression, otherwise \Q$delthis\E is used.
11823: The values are also deleted from the current processes %env.
1.191 harris41 11824:
1.795 albertel 11825: =item * get_env_multiple($name)
11826:
11827: gets $name from the %env hash, it seemlessly handles the cases where multiple
11828: values may be defined and end up as an array ref.
11829:
11830: returns an array of values
11831:
1.243 albertel 11832: =back
11833:
11834: =head2 User Information
1.191 harris41 11835:
1.243 albertel 11836: =over 4
1.191 harris41 11837:
11838: =item *
1.394 bowersj2 11839: X<queryauthenticate()>
11840: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 11841: authentication scheme
11842:
11843: =item *
1.394 bowersj2 11844: X<authenticate()>
1.1073 raeburn 11845: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 11846: authenticate user from domain's lib servers (first use the current
11847: one). C<$upass> should be the users password.
1.1073 raeburn 11848: $checkdefauth is optional (value is 1 if a check should be made to
11849: authenticate user using default authentication method, and allow
11850: account creation if username does not have account in the domain).
11851: $clientcancheckhost is optional (value is 1 if checking whether the
11852: server can host will occur on the client side in lonauth.pm).
1.191 harris41 11853:
11854: =item *
1.394 bowersj2 11855: X<homeserver()>
11856: B<homeserver($uname,$udom)>: find the server which has
11857: the user's directory and files (there must be only one), this caches
11858: the answer, and also caches if there is a borken connection.
1.191 harris41 11859:
11860: =item *
1.394 bowersj2 11861: X<idget()>
11862: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11863: (IDs are a unique resource in a domain, there must be only 1 ID per
11864: username, and only 1 username per ID in a specific domain) (returns
11865: hash: id=>name,id=>name)
1.191 harris41 11866:
11867: =item *
1.394 bowersj2 11868: X<idrget()>
11869: B<idrget($udom,@unames)>: find the IDs behind a list of
11870: usernames (returns hash: name=>id,name=>id)
1.191 harris41 11871:
11872: =item *
1.394 bowersj2 11873: X<idput()>
11874: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 11875:
11876: =item *
1.394 bowersj2 11877: X<rolesinit()>
1.1169 droeschl 11878: B<rolesinit($udom,$username)>: get user privileges.
11879: returns user role, first access and timer interval hashes
1.243 albertel 11880:
11881: =item *
1.1171 droeschl 11882: X<privileged()>
11883: B<privileged($username,$domain)>: returns a true if user has a
11884: privileged and active role (i.e. su or dc), false otherwise.
11885:
11886: =item *
1.551 albertel 11887: X<getsection()>
11888: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 11889: course $cname, return section name/number or '' for "not in course"
11890: and '-1' for "no section"
11891:
11892: =item *
1.394 bowersj2 11893: X<userenvironment()>
11894: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 11895: passed in @what from the requested user's environment, returns a hash
11896:
1.858 raeburn 11897: =item *
11898: X<userlog_query()>
1.859 albertel 11899: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11900: activity.log file. %filters defines filters applied when parsing the
11901: log file. These can be start or end timestamps, or the type of action
11902: - log to look for Login or Logout events, check for Checkin or
11903: Checkout, role for role selection. The response is in the form
11904: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11905: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 11906:
1.243 albertel 11907: =back
11908:
11909: =head2 User Roles
11910:
11911: =over 4
11912:
11913: =item *
11914:
1.810 raeburn 11915: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 11916: F: full access
11917: U,I,K: authentication modes (cxx only)
11918: '': forbidden
11919: 1: user needs to choose course
11920: 2: browse allowed
1.766 albertel 11921: A: passphrase authentication needed
1.243 albertel 11922:
11923: =item *
11924:
11925: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11926: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11927: and course level
11928:
11929: =item *
11930:
1.988 raeburn 11931: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11932: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 11933: $type is Course (default) or Community.
1.988 raeburn 11934: If $forcedefault evaluates to true, text returned will be default
11935: text for $type. Otherwise, if this is a course, the text returned
11936: will be a custom name for the role (if defined in the course's
11937: environment). If no custom name is defined the default is returned.
11938:
1.832 raeburn 11939: =item *
11940:
1.935 raeburn 11941: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 11942: All arguments are optional. Returns a hash of a roles, either for
11943: co-author/assistant author roles for a user's Construction Space
1.906 albertel 11944: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 11945: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11946: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11947: For each key, value is set to colon-separated start and end times for
11948: the role. If no username and domain are specified, will default to
1.934 raeburn 11949: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 11950: of role statuses (active, future or previous), roles
11951: (e.g., cc,in, st etc.) and domains of the roles which can be used
11952: to restrict the list of roles reported. If no array ref is
11953: provided for types, will default to return only active roles.
1.834 albertel 11954:
1.243 albertel 11955: =back
11956:
11957: =head2 User Modification
11958:
11959: =over 4
11960:
11961: =item *
11962:
1.957 raeburn 11963: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 11964: user for the level given by URL. Optional start and end dates (leave empty
11965: string or zero for "no date")
1.191 harris41 11966:
11967: =item *
11968:
1.243 albertel 11969: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11970: change a users, password, possible return values are: ok,
11971: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11972: refused
1.191 harris41 11973:
11974: =item *
11975:
1.243 albertel 11976: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 11977:
11978: =item *
11979:
1.1058 raeburn 11980: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11981: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11982:
11983: will update user information (firstname,middlename,lastname,generation,
11984: permanentemail), and if forceid is true, student/employee ID also.
11985: A user's institutional affiliation(s) can also be updated.
11986: User information fields will not be overwritten with empty entries
11987: unless the field is included in the $candelete array reference.
11988: This array is included when a single user is modified via "Manage Users",
11989: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 11990:
11991: =item *
11992:
1.286 matthew 11993: modifystudent
11994:
1.957 raeburn 11995: modify a student's enrollment and identification information.
1.286 matthew 11996: The course id is resolved based on the current users environment.
11997: This means the envoking user must be a course coordinator or otherwise
11998: associated with a course.
11999:
1.297 matthew 12000: This call is essentially a wrapper for lonnet::modifyuser and
12001: lonnet::modify_student_enrollment
1.286 matthew 12002:
12003: Inputs:
12004:
12005: =over 4
12006:
1.957 raeburn 12007: =item B<$udom> Student's loncapa domain
1.286 matthew 12008:
1.957 raeburn 12009: =item B<$uname> Student's loncapa login name
1.286 matthew 12010:
1.964 bisitz 12011: =item B<$uid> Student/Employee ID
1.286 matthew 12012:
1.957 raeburn 12013: =item B<$umode> Student's authentication mode
1.286 matthew 12014:
1.957 raeburn 12015: =item B<$upass> Student's password
1.286 matthew 12016:
1.957 raeburn 12017: =item B<$first> Student's first name
1.286 matthew 12018:
1.957 raeburn 12019: =item B<$middle> Student's middle name
1.286 matthew 12020:
1.957 raeburn 12021: =item B<$last> Student's last name
1.286 matthew 12022:
1.957 raeburn 12023: =item B<$gene> Student's generation
1.286 matthew 12024:
1.957 raeburn 12025: =item B<$usec> Student's section in course
1.286 matthew 12026:
12027: =item B<$end> Unix time of the roles expiration
12028:
12029: =item B<$start> Unix time of the roles start date
12030:
12031: =item B<$forceid> If defined, allow $uid to be changed
12032:
12033: =item B<$desiredhome> server to use as home server for student
12034:
1.957 raeburn 12035: =item B<$email> Student's permanent e-mail address
12036:
12037: =item B<$type> Type of enrollment (auto or manual)
12038:
1.963 raeburn 12039: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12040:
12041: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 12042:
1.963 raeburn 12043: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 12044:
1.963 raeburn 12045: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 12046:
1.963 raeburn 12047: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 12048:
1.286 matthew 12049: =back
1.297 matthew 12050:
12051: =item *
12052:
12053: modify_student_enrollment
12054:
12055: Change a students enrollment status in a class. The environment variable
12056: 'role.request.course' must be defined for this function to proceed.
12057:
12058: Inputs:
12059:
12060: =over 4
12061:
12062: =item $udom, students domain
12063:
12064: =item $uname, students name
12065:
12066: =item $uid, students user id
12067:
12068: =item $first, students first name
12069:
12070: =item $middle
12071:
12072: =item $last
12073:
12074: =item $gene
12075:
12076: =item $usec
12077:
12078: =item $end
12079:
12080: =item $start
12081:
1.957 raeburn 12082: =item $type
12083:
12084: =item $locktype
12085:
12086: =item $cid
12087:
12088: =item $selfenroll
12089:
12090: =item $context
12091:
1.297 matthew 12092: =back
12093:
1.191 harris41 12094:
12095: =item *
12096:
1.243 albertel 12097: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12098: custom role; give a custom role to a user for the level given by URL. Specify
12099: name and domain of role author, and role name
1.191 harris41 12100:
12101: =item *
12102:
1.243 albertel 12103: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12104:
12105: =item *
12106:
1.243 albertel 12107: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12108:
12109: =back
12110:
12111: =head2 Course Infomation
12112:
12113: =over 4
1.191 harris41 12114:
12115: =item *
12116:
1.1118 foxr 12117: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12118: specified course id, including all environment settings for the
12119: course, the description of the course will be in the hash under the
12120: key 'description'
1.191 harris41 12121:
1.1118 foxr 12122: $options is an optional parameter that if supplied is a hash reference that controls
12123: what how this function works. It has the following key/values:
12124:
12125: =over 4
12126:
12127: =item freshen_cache
12128:
12129: If defined, and the environment cache for the course is valid, it is
12130: returned in the returned hash.
12131:
12132: =item one_time
12133:
12134: If defined, the last cache time is set to _now_
12135:
12136: =item user
12137:
12138: If defined, the supplied username is used instead of the current user.
12139:
12140:
12141: =back
12142:
1.191 harris41 12143: =item *
12144:
1.624 albertel 12145: resdata($name,$domain,$type,@which) : request for current parameter
12146: setting for a specific $type, where $type is either 'course' or 'user',
12147: @what should be a list of parameters to ask about. This routine caches
12148: answers for 5 minutes.
1.243 albertel 12149:
1.877 foxr 12150: =item *
12151:
12152: get_courseresdata($courseid, $domain) : dump the entire course resource
12153: data base, returning a hash that is keyed by the resource name and has
12154: values that are the resource value. I believe that the timestamps and
12155: versions are also returned.
12156:
12157:
1.243 albertel 12158: =back
12159:
12160: =head2 Course Modification
12161:
12162: =over 4
1.191 harris41 12163:
12164: =item *
12165:
1.243 albertel 12166: writecoursepref($courseid,%prefs) : write preferences (environment
12167: database) for a course
1.191 harris41 12168:
12169: =item *
12170:
1.1011 raeburn 12171: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12172:
12173: =item *
12174:
1.1038 raeburn 12175: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 12176:
1.1167 droeschl 12177: =item *
12178:
12179: is_course($courseid), is_course($cdom, $cnum)
12180:
12181: Accepts either a combined $courseid (in the form of domain_courseid) or the
12182: two component version $cdom, $cnum. It checks if the specified course exists.
12183:
12184: Returns:
12185: undef if the course doesn't exist, otherwise
12186: in scalar context the combined courseid.
12187: in list context the two components of the course identifier, domain and
12188: courseid.
12189:
1.243 albertel 12190: =back
12191:
12192: =head2 Resource Subroutines
12193:
12194: =over 4
1.191 harris41 12195:
12196: =item *
12197:
1.243 albertel 12198: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 12199:
12200: =item *
12201:
1.243 albertel 12202: repcopy($filename) : subscribes to the requested file, and attempts to
12203: replicate from the owning library server, Might return
1.607 raeburn 12204: 'unavailable', 'not_found', 'forbidden', 'ok', or
12205: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 12206: resource. Expects the local filesystem pathname
12207: (/home/httpd/html/res/....)
12208:
12209: =back
12210:
12211: =head2 Resource Information
12212:
12213: =over 4
1.191 harris41 12214:
12215: =item *
12216:
1.243 albertel 12217: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12218: a vairety of different possible values, $varname should be a request
12219: string, and the other parameters can be used to specify who and what
12220: one is asking about.
12221:
12222: Possible values for $varname are environment.lastname (or other item
12223: from the envirnment hash), user.name (or someother aspect about the
12224: user), resource.0.maxtries (or some other part and parameter of a
12225: resource)
1.204 albertel 12226:
12227: =item *
12228:
1.243 albertel 12229: directcondval($number) : get current value of a condition; reads from a state
12230: string
1.204 albertel 12231:
12232: =item *
12233:
1.243 albertel 12234: condval($condidx) : value of condition index based on state
1.204 albertel 12235:
12236: =item *
12237:
1.243 albertel 12238: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12239: resource's metadata, $what should be either a specific key, or either
12240: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12241: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12242:
12243: this function automatically caches all requests
1.191 harris41 12244:
12245: =item *
12246:
1.243 albertel 12247: metadata_query($query,$custom,$customshow) : make a metadata query against the
12248: network of library servers; returns file handle of where SQL and regex results
12249: will be stored for query
1.191 harris41 12250:
12251: =item *
12252:
1.243 albertel 12253: symbread($filename) : return symbolic list entry (filename argument optional);
12254: returns the data handle
1.191 harris41 12255:
12256: =item *
12257:
1.243 albertel 12258: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 12259: a possible symb for the URL in $thisfn, and if is an encryypted
12260: resource that the user accessed using /enc/ returns a 1 on success, 0
12261: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 12262: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 12263:
1.191 harris41 12264:
12265: =item *
12266:
1.243 albertel 12267: symbclean($symb) : removes versions numbers from a symb, returns the
12268: cleaned symb
1.191 harris41 12269:
12270: =item *
12271:
1.243 albertel 12272: is_on_map($uri) : checks if the $uri is somewhere on the current
12273: course map, user must be in a course for it to work.
1.191 harris41 12274:
12275: =item *
12276:
1.243 albertel 12277: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 12278:
12279: =item *
12280:
1.243 albertel 12281: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12282: a random seed, all arguments are optional, if they aren't sent it uses the
12283: environment to derive them. Note: if symb isn't sent and it can't get one
12284: from &symbread it will use the current time as its return value
1.191 harris41 12285:
12286: =item *
12287:
1.243 albertel 12288: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12289: unfakeable, receipt
1.191 harris41 12290:
12291: =item *
12292:
1.620 albertel 12293: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 12294:
12295: =item *
12296:
1.243 albertel 12297: countacc($url) : count the number of accesses to a given URL
1.191 harris41 12298:
12299: =item *
12300:
1.243 albertel 12301: 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 12302:
12303: =item *
12304:
1.243 albertel 12305: 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 12306:
12307: =item *
12308:
1.243 albertel 12309: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 12310:
12311: =item *
12312:
1.243 albertel 12313: devalidate($symb) : devalidate temporary spreadsheet calculations,
12314: forcing spreadsheet to reevaluate the resource scores next time.
12315:
12316: =back
12317:
12318: =head2 Storing/Retreiving Data
12319:
12320: =over 4
1.191 harris41 12321:
12322: =item *
12323:
1.243 albertel 12324: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12325: for this url; hashref needs to be given and should be a \%hashname; the
12326: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 12327: be derived from the env
1.191 harris41 12328:
12329: =item *
12330:
1.243 albertel 12331: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12332: uses critical subroutine
1.191 harris41 12333:
12334: =item *
12335:
1.243 albertel 12336: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12337: all args are optional
1.191 harris41 12338:
12339: =item *
12340:
1.717 albertel 12341: dumpstore($namespace,$udom,$uname,$regexp,$range) :
12342: dumps the complete (or key matching regexp) namespace into a hash
12343: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12344: normally &store()ed into
12345:
12346: $range should be either an integer '100' (give me the first 100
12347: matching records)
12348: or be two integers sperated by a - with no spaces
12349: '30-50' (give me the 30th through the 50th matching
12350: records)
12351:
12352:
12353: =item *
12354:
12355: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12356: replaces a &store() version of data with a replacement set of data
12357: for a particular resource in a namespace passed in the $storehash hash
12358: reference
12359:
12360: =item *
12361:
1.243 albertel 12362: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12363: works very similar to store/cstore, but all data is stored in a
12364: temporary location and can be reset using tmpreset, $storehash should
12365: be a hash reference, returns nothing on success
1.191 harris41 12366:
12367: =item *
12368:
1.243 albertel 12369: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12370: similar to restore, but all data is stored in a temporary location and
12371: can be reset using tmpreset. Returns a hash of values on success,
12372: error string otherwise.
1.191 harris41 12373:
12374: =item *
12375:
1.243 albertel 12376: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12377: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 12378:
12379: =item *
12380:
1.243 albertel 12381: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12382: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 12383:
12384: =item *
12385:
1.243 albertel 12386: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12387: namesp ($udom and $uname are optional)
1.191 harris41 12388:
12389: =item *
12390:
1.702 albertel 12391: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 12392: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 12393: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 12394:
1.702 albertel 12395: $range should be either an integer '100' (give me the first 100
12396: matching records)
12397: or be two integers sperated by a - with no spaces
12398: '30-50' (give me the 30th through the 50th matching
12399: records)
1.449 matthew 12400: =item *
12401:
12402: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12403: $store can be a scalar, an array reference, or if the amount to be
12404: incremented is > 1, a hash reference.
12405:
12406: ($udom and $uname are optional)
1.191 harris41 12407:
12408: =item *
12409:
1.243 albertel 12410: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12411: ($udom and $uname are optional)
1.191 harris41 12412:
12413: =item *
12414:
1.243 albertel 12415: cput($namespace,$storehash,$udom,$uname) : critical put
12416: ($udom and $uname are optional)
1.191 harris41 12417:
12418: =item *
12419:
1.748 albertel 12420: newput($namespace,$storehash,$udom,$uname) :
12421:
12422: Attempts to store the items in the $storehash, but only if they don't
12423: currently exist, if this succeeds you can be certain that you have
12424: successfully created a new key value pair in the $namespace db.
12425:
12426:
12427: Args:
12428: $namespace: name of database to store values to
12429: $storehash: hashref to store to the db
12430: $udom: (optional) domain of user containing the db
12431: $uname: (optional) name of user caontaining the db
12432:
12433: Returns:
12434: 'ok' -> succeeded in storing all keys of $storehash
12435: 'key_exists: <key>' -> failed to anything out of $storehash, as at
12436: least <key> already existed in the db (other
12437: requested keys may also already exist)
1.967 bisitz 12438: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 12439: 'con_lost' -> unable to contact request server
12440: 'refused' -> action was not allowed by remote machine
12441:
12442:
12443: =item *
12444:
1.243 albertel 12445: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12446: reference filled in from namesp (encrypts the return communication)
12447: ($udom and $uname are optional)
1.191 harris41 12448:
12449: =item *
12450:
1.243 albertel 12451: log($udom,$name,$home,$message) : write to permanent log for user; use
12452: critical subroutine
12453:
1.806 raeburn 12454: =item *
12455:
1.860 raeburn 12456: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12457: array reference filled in from namespace found in domain level on either
12458: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 12459:
12460: =item *
12461:
1.860 raeburn 12462: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
12463: domain level either on specified domain server ($uhome) or primary domain
12464: server ($udom and $uhome are optional)
1.806 raeburn 12465:
1.943 raeburn 12466: =item *
12467:
12468: get_domain_defaults($target_domain) : returns hash with defaults for
12469: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12470: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12471: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12472: Values are retrieved from cache (if current), or from domain's configuration.db
12473: (if available), or lastly from values in lonTabs/dns_domain,tab,
12474: or lonTabs/domain.tab.
12475:
12476: %domdefaults = &get_auth_defaults($target_domain);
12477:
1.243 albertel 12478: =back
12479:
12480: =head2 Network Status Functions
12481:
12482: =over 4
1.191 harris41 12483:
12484: =item *
12485:
1.1137 raeburn 12486: dirlist() : return directory list based on URI (first arg).
12487:
12488: Inputs: 1 required, 5 optional.
12489:
12490: =over
12491:
12492: =item
12493: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12494:
12495: =item
12496: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
12497:
12498: =item
12499: $username - username of user/course to be listed. Extracted from $uri if absent.
12500:
12501: =item
12502: $getpropath - boolean: 1 if prepend path using &propath().
12503:
12504: =item
12505: $getuserdir - boolean: 1 if prepend path for "userfiles".
12506:
12507: =item
12508: $alternateRoot - path to prepend in place of path from $uri.
12509:
12510: =back
12511:
12512: Returns: Array of up to two items.
12513:
12514: =over
12515:
12516: a reference to an array of files/subdirectories
12517:
12518: =over
12519:
12520: Each element in the array of files/subdirectories is a & separated list of
12521: item name and the result of running stat on the item. If dirlist was requested
12522: for a file instead of a directory, the item name will be ''. For a directory
12523: listing, if the item is a metadata file, the element will end &N&M
12524: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12525: default copyright set (1).
12526:
12527: =back
12528:
12529: a scalar containing error condition (if encountered).
12530:
12531: =over
12532:
12533: =item
12534: no_host (no homeserver identified for $username:$domain).
12535:
12536: =item
12537: no_such_host (server contacted for listing not identified as valid host).
12538:
12539: =item
12540: con_lost (connection to remote server failed).
12541:
12542: =item
12543: refused (invalid $username:$domain received on lond side).
12544:
12545: =item
12546: no_such_dir (directory at specified path on lond side does not exist).
12547:
12548: =item
12549: empty (directory at specified path on lond side is empty).
12550:
12551: =over
12552:
12553: This is currently not encountered because the &ls3, &ls2,
12554: &ls (_handler) routines on the lond side do not filter out
12555: . and .. from a directory listing.
12556:
12557: =back
12558:
12559: =back
12560:
12561: =back
1.191 harris41 12562:
12563: =item *
12564:
1.243 albertel 12565: spareserver() : find server with least workload from spare.tab
12566:
1.986 foxr 12567:
12568: =item *
12569:
12570: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12571: if there is no corresponding loncapa host.
12572:
1.243 albertel 12573: =back
12574:
1.986 foxr 12575:
1.243 albertel 12576: =head2 Apache Request
12577:
12578: =over 4
1.191 harris41 12579:
12580: =item *
12581:
1.243 albertel 12582: ssi($url,%hash) : server side include, does a complete request cycle on url to
12583: localhost, posts hash
12584:
12585: =back
12586:
12587: =head2 Data to String to Data
12588:
12589: =over 4
1.191 harris41 12590:
12591: =item *
12592:
1.243 albertel 12593: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12594: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 12595:
12596: =item *
12597:
1.243 albertel 12598: hashref2str($hashref) : convert a hashref into a string complete with
12599: escaping and '=' and '&' separators, supports elements that are
12600: arrayrefs and hashrefs
1.191 harris41 12601:
12602: =item *
12603:
1.243 albertel 12604: arrayref2str($arrayref) : convert an arrayref into a string complete
12605: with escaping and '&' separators, supports elements that are arrayrefs
12606: and hashrefs
1.191 harris41 12607:
12608: =item *
12609:
1.243 albertel 12610: str2hash($string) : convert string to hash using unescaping and
12611: splitting on '=' and '&', supports elements that are arrayrefs and
12612: hashrefs
1.191 harris41 12613:
12614: =item *
12615:
1.243 albertel 12616: str2array($string) : convert string to hash using unescaping and
12617: splitting on '&', supports elements that are arrayrefs and hashrefs
12618:
12619: =back
12620:
12621: =head2 Logging Routines
12622:
12623:
12624: These routines allow one to make log messages in the lonnet.log and
12625: lonnet.perm logfiles.
1.191 harris41 12626:
1.1119 foxr 12627: =over 4
12628:
1.191 harris41 12629: =item *
12630:
1.243 albertel 12631: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 12632:
12633: =item *
12634:
1.243 albertel 12635: logthis() : append message to the normal lonnet.log file, it gets
12636: preiodically rolled over and deleted.
1.191 harris41 12637:
12638: =item *
12639:
1.243 albertel 12640: logperm() : append a permanent message to lonnet.perm.log, this log
12641: file never gets deleted by any automated portion of the system, only
12642: messages of critical importance should go in here.
12643:
1.1119 foxr 12644:
1.243 albertel 12645: =back
12646:
12647: =head2 General File Helper Routines
12648:
12649: =over 4
1.191 harris41 12650:
12651: =item *
12652:
1.481 raeburn 12653: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12654: (a) files in /uploaded
12655: (i) If a local copy of the file exists -
12656: compares modification date of local copy with last-modified date for
12657: definitive version stored on home server for course. If local copy is
12658: stale, requests a new version from the home server and stores it.
12659: If the original has been removed from the home server, then local copy
12660: is unlinked.
12661: (ii) If local copy does not exist -
12662: requests the file from the home server and stores it.
12663:
12664: If $caller is 'uploadrep':
12665: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12666: for request for files originally uploaded via DOCS.
12667: - returns 'ok' if fresh local copy now available, -1 otherwise.
12668:
12669: Otherwise:
12670: This indicates a call from the content generation phase of the request.
12671: - returns the entire contents of the file or -1.
12672:
12673: (b) files in /res
12674: - returns the entire contents of a file or -1;
12675: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 12676:
1.712 albertel 12677:
12678: =item *
12679:
12680: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12681: reference
12682:
12683: returns either a stat() list of data about the file or an empty list
12684: if the file doesn't exist or couldn't find out about it (connection
12685: problems or user unknown)
12686:
1.191 harris41 12687: =item *
12688:
1.243 albertel 12689: filelocation($dir,$file) : returns file system location of a file
12690: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12691: directory that relative $file lookups are to looked in ($dir of /a/dir
12692: and a file of ../bob will become /a/bob)
1.191 harris41 12693:
12694: =item *
12695:
12696: hreflocation($dir,$file) : returns file system location or a URL; same as
12697: filelocation except for hrefs
12698:
12699: =item *
12700:
12701: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12702:
1.243 albertel 12703: =back
12704:
1.608 albertel 12705: =head2 Usererfile file routines (/uploaded*)
12706:
12707: =over 4
12708:
12709: =item *
12710:
12711: userfileupload(): main rotine for putting a file in a user or course's
12712: filespace, arguments are,
12713:
1.620 albertel 12714: formname - required - this is the name of the element in $env where the
1.608 albertel 12715: filename, and the contents of the file to create/modifed exist
1.620 albertel 12716: the filename is in $env{'form.'.$formname.'.filename'} and the
12717: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 12718: context - if coursedoc, store the file in the course of the active role
12719: of the current user;
12720: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12721: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 12722: subdir - required - subdirectory to put the file in under ../userfiles/
12723: if undefined, it will be placed in "unknown"
12724:
12725: (This routine calls clean_filename() to remove any dangerous
12726: characters from the filename, and then calls finuserfileupload() to
12727: complete the transaction)
12728:
12729: returns either the url of the uploaded file (/uploaded/....) if successful
12730: and /adm/notfound.html if unsuccessful
12731:
12732: =item *
12733:
12734: clean_filename(): routine for cleaing a filename up for storage in
12735: userfile space, argument is:
12736:
12737: filename - proposed filename
12738:
12739: returns: the new clean filename
12740:
12741: =item *
12742:
1.1090 raeburn 12743: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 12744: userspace, probably shouldn't be called directly
12745:
12746: docuname: username or courseid of destination for the file
12747: docudom: domain of user/course of destination for the file
12748: formname: same as for userfileupload()
1.1090 raeburn 12749: fname: filename (including subdirectories) for the file
12750: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12751: allfiles: reference to hash used to store objects found by parser
12752: codebase: reference to hash used for codebases of java objects found by parser
12753: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12754: thumbheight: height (pixels) of thumbnail to be created for uploaded image
12755: resizewidth: width to be used to resize image using resizeImage from ImageMagick
12756: resizeheight: height to be used to resize image using resizeImage from ImageMagick
12757: context: if 'overwrite', will move the uploaded file from its temporary location to
12758: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 12759: mimetype: reference to scalar to accommodate mime type determined
12760: from File::MMagic if $parser = parse.
1.608 albertel 12761:
12762: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 12763: and /adm/notfound.html if unsuccessful (or an error message if context
12764: was 'overwrite').
12765:
1.608 albertel 12766:
12767: =item *
12768:
12769: renameuserfile(): renames an existing userfile to a new name
12770:
12771: Args:
12772: docuname: username or courseid of destination for the file
12773: docudom: domain of user/course of destination for the file
12774: old: current file name (including any subdirs under userfiles)
12775: new: desired file name (including any subdirs under userfiles)
12776:
12777: =item *
12778:
12779: mkdiruserfile(): creates a directory is a userfiles dir
12780:
12781: Args:
12782: docuname: username or courseid of destination for the file
12783: docudom: domain of user/course of destination for the file
12784: dir: dir to create (including any subdirs under userfiles)
12785:
12786: =item *
12787:
12788: removeuserfile(): removes a file that exists in userfiles
12789:
12790: Args:
12791: docuname: username or courseid of destination for the file
12792: docudom: domain of user/course of destination for the file
12793: fname: filname to delete (including any subdirs under userfiles)
12794:
12795: =item *
12796:
12797: removeuploadedurl(): convience function for removeuserfile()
12798:
12799: Args:
12800: url: a full /uploaded/... url to delete
12801:
1.747 albertel 12802: =item *
12803:
12804: get_portfile_permissions():
12805: Args:
12806: domain: domain of user or course contain the portfolio files
12807: user: name of user or num of course contain the portfolio files
12808: Returns:
12809: hashref of a dump of the proper file_permissions.db
12810:
12811:
12812: =item *
12813:
12814: get_access_controls():
12815:
12816: Args:
12817: current_permissions: the hash ref returned from get_portfile_permissions()
12818: group: (optional) the group you want the files associated with
12819: file: (optional) the file you want access info on
12820:
12821: Returns:
1.749 raeburn 12822: a hash (keys are file names) of hashes containing
12823: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12824: values are XML containing access control settings (see below)
1.747 albertel 12825:
12826: Internal notes:
12827:
1.749 raeburn 12828: access controls are stored in file_permissions.db as key=value pairs.
12829: key -> path to file/file_name\0uniqueID:scope_end_start
12830: where scope -> public,guest,course,group,domains or users.
12831: end -> UNIX time for end of access (0 -> no end date)
12832: start -> UNIX time for start of access
12833:
12834: value -> XML description of access control
12835: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12836: <start></start>
12837: <end></end>
12838:
12839: <password></password> for scope type = guest
12840:
12841: <domain></domain> for scope type = course or group
12842: <number></number>
12843: <roles id="">
12844: <role></role>
12845: <access></access>
12846: <section></section>
12847: <group></group>
12848: </roles>
12849:
12850: <dom></dom> for scope type = domains
12851:
12852: <users> for scope type = users
12853: <user>
12854: <uname></uname>
12855: <udom></udom>
12856: </user>
12857: </users>
12858: </scope>
12859:
12860: Access data is also aggregated for each file in an additional key=value pair:
12861: key -> path to file/file_name\0accesscontrol
12862: value -> reference to hash
12863: hash contains key = value pairs
12864: where key = uniqueID:scope_end_start
12865: value = UNIX time record was last updated
12866:
12867: Used to improve speed of look-ups of access controls for each file.
12868:
12869: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12870:
12871: modify_access_controls():
12872:
12873: Modifies access controls for a portfolio file
12874: Args
12875: 1. file name
12876: 2. reference to hash of required changes,
12877: 3. domain
12878: 4. username
12879: where domain,username are the domain of the portfolio owner
12880: (either a user or a course)
12881:
12882: Returns:
12883: 1. result of additions or updates ('ok' or 'error', with error message).
12884: 2. result of deletions ('ok' or 'error', with error message).
12885: 3. reference to hash of any new or updated access controls.
12886: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12887: key = integer (inbound ID)
12888: value = uniqueID
1.747 albertel 12889:
1.608 albertel 12890: =back
12891:
1.243 albertel 12892: =head2 HTTP Helper Routines
12893:
12894: =over 4
12895:
1.191 harris41 12896: =item *
12897:
12898: escape() : unpack non-word characters into CGI-compatible hex codes
12899:
12900: =item *
12901:
12902: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12903:
1.243 albertel 12904: =back
12905:
12906: =head1 PRIVATE SUBROUTINES
12907:
12908: =head2 Underlying communication routines (Shouldn't call)
12909:
12910: =over 4
12911:
12912: =item *
12913:
12914: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12915:
12916: =item *
12917:
12918: reply() : uses subreply to send a message to remote machine, logs all failures
12919:
12920: =item *
12921:
12922: critical() : passes a critical message to another server; if cannot
12923: get through then place message in connection buffer directory and
12924: returns con_delayed, if incapable of saving message, returns
12925: con_failed
12926:
12927: =item *
12928:
12929: reconlonc() : tries to reconnect lonc client processes.
12930:
12931: =back
12932:
12933: =head2 Resource Access Logging
12934:
12935: =over 4
12936:
12937: =item *
12938:
12939: flushcourselogs() : flush (save) buffer logs and access logs
12940:
12941: =item *
12942:
12943: courselog($what) : save message for course in hash
12944:
12945: =item *
12946:
12947: courseacclog($what) : save message for course using &courselog(). Perform
12948: special processing for specific resource types (problems, exams, quizzes, etc).
12949:
1.191 harris41 12950: =item *
12951:
12952: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12953: as a PerlChildExitHandler
1.243 albertel 12954:
12955: =back
12956:
12957: =head2 Other
12958:
12959: =over 4
12960:
12961: =item *
12962:
12963: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 12964:
12965: =back
12966:
12967: =cut
1.877 foxr 12968:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>